@contello/store 4.5.0 → 4.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/fragments.d.ts +0 -2
- package/dist/fragments.d.ts.map +1 -1
- package/dist/fragments.js +1 -2
- package/dist/index.cjs +75 -57
- package/dist/index.d.cts +0 -22
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.ts +0 -22
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +75 -57
- package/dist/index.js.map +1 -1
- package/package.json +7 -7
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["mapFile","mapAsset","storeSchema","storeSchema","storeSchema","storeSchema","storeSchema"],"sources":["../src/generated/graphql.ts","../src/telemetry.ts","../src/utils.ts","../src/write-buffer.ts","../src/assets.ts","../src/dependency-collector.ts","../src/collection.ts","../src/i18n.ts","../src/lru.ts","../src/lazy-assets.ts","../src/lazy-collection.ts","../src/route-path.ts","../src/routes-mapping.ts","../src/lazy-routes.ts","../src/model-resolver.ts","../src/routes.ts","../src/singleton.ts","../src/watcher.ts","../src/store.ts"],"sourcesContent":["/* eslint-disable */\n// @ts-nocheck\n/* this file is generated by contello-client — do not edit */\n\nimport type { SourceDef } from '@contello/client';\n\nexport type ContelloAssetKind = 'AUDIO' | 'DOCUMENT' | 'IMAGE' | 'OTHER' | 'VIDEO';\nexport type ContelloAssetRetentionPolicy = 'deleteIfNotUsed' | 'retain';\nexport type ContelloBatchOperationStatus = 'error' | 'success';\nexport type ContelloContentDispositionEnum = 'ATTACHMENT' | 'AUTOMATIC' | 'INLINE';\nexport type ContelloDictionaryType = 'ENTITY' | 'STATIC';\nexport type ContelloMutationType = 'CREATE' | 'DELETE' | 'UPDATE';\nexport type ContelloRouteTargetTypeEnum = 'ENTITY' | 'FILE' | 'REDIRECT' | 'SITEMAP' | 'TEXT_RESPONSE';\n\nexport type ContelloAnnotationFilterInput = {\n key?: string | undefined;\n value?: string | undefined;\n};\n\nexport type ContelloAssetAnnotationInput = {\n key: string;\n value: string;\n};\n\nexport type ContelloAssetRequestInput = {\n id?: string | undefined;\n};\n\nexport type ContelloAssetsFilterInput = {\n annotations?: (ContelloAnnotationFilterInput | undefined)[] | undefined;\n collectionReferences?: (string | undefined)[] | undefined;\n ids?: (string | undefined)[] | undefined;\n kinds?: (ContelloAssetKind | undefined)[] | undefined;\n};\n\nexport type ContelloAssetsPaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type ContelloAssetUpdateInput = {\n annotations?: ContelloAssetAnnotationInput[] | undefined;\n collectionIds?: string[] | undefined;\n collectionReferenceNames?: string[] | undefined;\n id: string;\n name?: string | undefined;\n retentionPolicy?: ContelloAssetRetentionPolicy | undefined;\n tags?: string[] | undefined;\n};\n\nexport type ContelloEntityRouteInput = {\n path: string;\n};\n\nexport type ContelloI18nMessageInput = {\n description?: string | undefined;\n example?: string | undefined;\n initialTranslations?: ContelloI18nMessageTranslationValueInput[] | undefined;\n token: string;\n translations?: ContelloI18nMessageTranslationValueInput[] | undefined;\n variables?: ContelloI18nMessageVariableInput[] | undefined;\n};\n\nexport type ContelloI18nMessagePaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type ContelloI18nMessageTranslationValueInput = {\n language: string;\n message: string;\n};\n\nexport type ContelloI18nMessageVariableInput = {\n description?: string | undefined;\n example?: string | undefined;\n name: string;\n};\n\nexport type ContelloRouteHeaderInput = {\n name: string;\n value: string;\n};\n\nexport type ContelloRouteInput = {\n customHeaders?: (ContelloRouteHeaderInput | undefined)[] | undefined;\n path: string;\n targetEntityConfig?: TargetEntityConfigInput | undefined;\n targetFileConfig?: TargetFileConfig | undefined;\n targetRedirectConfig?: TargetRedirectConfig | undefined;\n targetSitemapConfig?: TargetSitemapConfig | undefined;\n targetTextResponseConfig?: TargetTextResponseConfig | undefined;\n targetType: ContelloRouteTargetTypeEnum;\n};\n\nexport type ContelloRouteRequestInput = {\n id?: string | undefined;\n path?: string | undefined;\n};\n\nexport type ContelloRoutesRequestInput = {\n ids?: (string | undefined)[] | undefined;\n paths?: (string | undefined)[] | undefined;\n targetType?: ContelloRouteTargetTypeEnum | undefined;\n};\n\nexport type CreateDummyEntityInput = {\n attributes: DummyAttributesInput;\n createdAt?: string | undefined;\n id?: string | undefined;\n route?: ContelloEntityRouteInput | undefined;\n updatedAt?: string | undefined;\n};\n\nexport type CreateDummyRequestInput = {\n entity: CreateDummyEntityInput;\n};\n\nexport type DateTimeFilterInput = {\n between?: DateTimeRangeInput | undefined;\n equal?: string | undefined;\n exists?: boolean | undefined;\n greaterThan?: string | undefined;\n greaterThanEqual?: string | undefined;\n lessThan?: string | undefined;\n lessThanEqual?: string | undefined;\n notEqual?: string | undefined;\n};\n\nexport type DateTimeRangeInput = {\n from: string;\n to: string;\n};\n\nexport type DeleteEntityByIdInput = {\n force?: boolean | undefined;\n id: string;\n};\n\nexport type DeleteEntityByIdsInput = {\n ids: string[];\n};\n\nexport type DummiesFilterInput = {\n created?: DateTimeFilterInput | undefined;\n ids?: (string | undefined)[] | undefined;\n name?: StringFilterInput | undefined;\n route?: StringFilterInput | undefined;\n updated?: DateTimeFilterInput | undefined;\n};\n\nexport type DummiesRequestInput = {\n filter?: DummiesFilterInput | undefined;\n pagination?: PaginationInput | undefined;\n};\n\nexport type DummyAttributesInput = {\n dummy?: string | undefined;\n};\n\nexport type GetEntityByIdInput = {\n id: string;\n};\n\nexport type PaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type StringFilterInput = {\n contains?: string | undefined;\n endsWith?: string | undefined;\n equal?: string | undefined;\n exists?: boolean | undefined;\n in?: string[] | undefined;\n notEqual?: string | undefined;\n notIn?: string[] | undefined;\n startsWith?: string | undefined;\n};\n\nexport type TargetEntityConfigInput = {\n entityId: string;\n entityModelId: string;\n};\n\nexport type TargetFileConfig = {\n assetId: string;\n contentDisposition: ContelloContentDispositionEnum;\n};\n\nexport type TargetRedirectConfig = {\n location: string;\n responseCode: number;\n};\n\nexport type TargetSitemapConfig = {\n sitemapId: string;\n};\n\nexport type TargetTextResponseConfig = {\n content: string;\n mimeType: string;\n};\n\nexport type UpdateDummyEntityInput = {\n attributes: DummyAttributesInput;\n createdAt?: string | undefined;\n id: string;\n route?: ContelloEntityRouteInput | undefined;\n updatedAt?: string | undefined;\n};\n\nexport type UpdateDummyRequestInput = {\n entity: UpdateDummyEntityInput;\n};\n\nexport type ContelloAsset = {\n __typename?: 'ContelloAsset' | undefined;\n annotations: ContelloAssetAnnotation[];\n createdAt: string;\n id: string;\n optimized: ContelloOptimizedFile[];\n original: ContelloFile;\n preview?: ContelloFile | undefined;\n updatedAt: string;\n};\n\nexport type ContelloAssetAnnotation = {\n __typename?: 'ContelloAssetAnnotation' | undefined;\n key: string;\n value: string;\n};\n\nexport type ContelloAssetDeleteResponse = {\n __typename?: 'ContelloAssetDeleteResponse' | undefined;\n id: string;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloBatchOperationResponse = {\n __typename?: 'ContelloBatchOperationResponse' | undefined;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloDictionary = {\n __typename?: 'ContelloDictionary' | undefined;\n createdAt: string;\n description?: string | undefined;\n id: string;\n items?: (string | undefined)[] | undefined;\n name: string;\n referenceName: string;\n type: ContelloDictionaryType;\n updatedAt: string;\n};\n\nexport type ContelloEntityDeleteResponse = {\n __typename?: 'ContelloEntityDeleteResponse' | undefined;\n id: string;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloEntityModel = {\n __typename?: 'ContelloEntityModel' | undefined;\n description: string;\n id: string;\n isRoutable: boolean;\n name: string;\n referenceName: string;\n};\n\nexport type ContelloI18nMessage = {\n __typename?: 'ContelloI18nMessage' | undefined;\n collectionId: string;\n createdAt: string;\n deprecated: boolean;\n description?: string | undefined;\n example?: string | undefined;\n id: string;\n token: string;\n translations: ContelloI18nMessageTranslation[];\n updatedAt: string;\n variables?: ContelloI18nMessageVariable[] | undefined;\n};\n\nexport type ContelloI18nMessagePagination = {\n __typename?: 'ContelloI18nMessagePagination' | undefined;\n limit: number;\n offset: number;\n total: number;\n};\n\nexport type ContelloI18nMessageRegisterResponse = {\n __typename?: 'ContelloI18nMessageRegisterResponse' | undefined;\n ids: string[];\n};\n\nexport type ContelloI18nMessagesResponse = {\n __typename?: 'ContelloI18nMessagesResponse' | undefined;\n items: ContelloI18nMessage[];\n pagination: ContelloI18nMessagePagination;\n};\n\nexport type ContelloI18nMessageTranslation = {\n __typename?: 'ContelloI18nMessageTranslation' | undefined;\n language: string;\n value: string;\n};\n\nexport type ContelloI18nMessageUpdate = {\n __typename?: 'ContelloI18nMessageUpdate' | undefined;\n message: ContelloI18nMessage;\n mutation: ContelloMutation;\n};\n\nexport type ContelloI18nMessageVariable = {\n __typename?: 'ContelloI18nMessageVariable' | undefined;\n description?: string | undefined;\n example?: string | undefined;\n name: string;\n};\n\nexport type ContelloImageMetadata = {\n __typename?: 'ContelloImageMetadata' | undefined;\n height: number;\n width: number;\n};\n\nexport type ContelloImageOptimizationConfig = {\n __typename?: 'ContelloImageOptimizationConfig' | undefined;\n name: string;\n};\n\nexport type ContelloMutation = {\n __typename?: 'ContelloMutation' | undefined;\n type: ContelloMutationType;\n};\n\nexport type ContelloOptimizedFile = {\n __typename?: 'ContelloOptimizedFile' | undefined;\n fileName: string;\n metadata?: ContelloFileMetadata | undefined;\n mimeType: string;\n optimizationConfig?: ContelloOptimizationConfig | undefined;\n uid: string;\n};\n\nexport type ContelloProject = {\n __typename?: 'ContelloProject' | undefined;\n description: string;\n id: string;\n name: string;\n referenceName: string;\n};\n\nexport type ContelloRoute = {\n __typename?: 'ContelloRoute' | undefined;\n createdAt: string;\n customHeaders: ContelloRouteHeader[];\n id: string;\n path: string;\n target: ContelloRouteTarget;\n updatedAt: string;\n};\n\nexport type ContelloRouteHeader = {\n __typename?: 'ContelloRouteHeader' | undefined;\n name: string;\n value: string;\n};\n\nexport type ContelloRouteTargetAsset = {\n __typename?: 'ContelloRouteTargetAsset' | undefined;\n asset: ContelloAsset;\n contentDisposition: ContelloContentDispositionEnum;\n};\n\nexport type ContelloRouteTargetEntity = {\n __typename?: 'ContelloRouteTargetEntity' | undefined;\n entity?: ContelloEntityBase | undefined;\n};\n\nexport type ContelloRouteTargetRedirect = {\n __typename?: 'ContelloRouteTargetRedirect' | undefined;\n location: string;\n responseCode: number;\n};\n\nexport type ContelloRouteTargetSitemap = {\n __typename?: 'ContelloRouteTargetSitemap' | undefined;\n displayName: string;\n sitemapId: string;\n};\n\nexport type ContelloRouteTargetText = {\n __typename?: 'ContelloRouteTargetText' | undefined;\n content: string;\n mimeType: string;\n};\n\nexport type ContelloRouteUpdate = {\n __typename?: 'ContelloRouteUpdate' | undefined;\n mutation: ContelloMutation;\n route: ContelloRoute;\n};\n\nexport type ContelloUpdateBatch = {\n __typename?: 'ContelloUpdateBatch' | undefined;\n events: ContelloUpdateEvent[];\n};\n\nexport type ContelloUpdateEvent = {\n __typename?: 'ContelloUpdateEvent' | undefined;\n mutation: ContelloMutation;\n prev?: ContelloUpdatePrev | undefined;\n target: ContelloUpdateTarget;\n};\n\nexport type ContelloVideoMetadata = {\n __typename?: 'ContelloVideoMetadata' | undefined;\n height: number;\n width: number;\n};\n\nexport type ContelloVideoOptimizationConfig = {\n __typename?: 'ContelloVideoOptimizationConfig' | undefined;\n name: string;\n};\n\nexport type DummiesResponseCollection = {\n __typename?: 'DummiesResponseCollection' | undefined;\n entities: DummyEntity[];\n pagination: Pagination;\n};\n\nexport type DummyAttributes = {\n __typename?: 'DummyAttributes' | undefined;\n dummy?: string | undefined;\n};\n\nexport type DummyEntity = {\n __typename?: 'DummyEntity' | undefined;\n __model?: 'dummy' | undefined;\n attributes: DummyAttributes;\n createdAt: string;\n id: string;\n internalName: string;\n modelId: string;\n routes: ContelloRoute[];\n updatedAt: string;\n};\n\nexport type DummyEntityUpdate = {\n __typename?: 'DummyEntityUpdate' | undefined;\n entity: DummyEntity;\n mutation: ContelloMutation;\n};\n\nexport type Pagination = {\n __typename?: 'Pagination' | undefined;\n limit: number;\n offset: number;\n total: number;\n};\n\nexport type PingResult = {\n __typename?: 'PingResult' | undefined;\n response: string;\n};\n\nexport type RootMutation = {\n __typename?: 'RootMutation' | undefined;\n createContelloRoute?: ContelloRoute | undefined;\n createContelloRoutes?: ContelloRoute[] | undefined;\n createDummies?: DummyEntity[] | undefined;\n createDummy?: DummyEntity | undefined;\n deleteContelloAsset: ContelloAssetDeleteResponse;\n deleteContelloRoute: string;\n deleteDummies?: ContelloEntityDeleteResponse[] | undefined;\n deleteDummy: ContelloEntityDeleteResponse;\n registerContelloI18nMessages?: ContelloI18nMessageRegisterResponse | undefined;\n truncateContelloRoutes?: ContelloBatchOperationResponse | undefined;\n truncateDummies?: ContelloBatchOperationResponse | undefined;\n updateContelloAsset?: ContelloAsset | undefined;\n updateContelloRoute?: ContelloRoute | undefined;\n updateDummies?: DummyEntity[] | undefined;\n updateDummy?: DummyEntity | undefined;\n};\n\nexport type RootQuery = {\n __typename?: 'RootQuery' | undefined;\n contelloAsset?: ContelloAsset | undefined;\n contelloAssets?: (ContelloAsset | undefined)[] | undefined;\n contelloDictionaries?: (ContelloDictionary | undefined)[] | undefined;\n contelloEntityModels?: (ContelloEntityModel | undefined)[] | undefined;\n contelloI18nMessages?: ContelloI18nMessagesResponse | undefined;\n contelloPing: PingResult;\n contelloProject?: ContelloProject | undefined;\n contelloRoute?: ContelloRoute | undefined;\n contelloRoutes?: (ContelloRoute | undefined)[] | undefined;\n dummies: DummiesResponseCollection;\n dummy?: DummyEntity | undefined;\n};\n\nexport type RootSubscription = {\n __typename?: 'RootSubscription' | undefined;\n contelloAssets?: ContelloAsset | undefined;\n contelloAssetsBatch: ContelloAsset[];\n contelloI18nMessages?: ContelloI18nMessage | undefined;\n contelloI18nMessagesBatch: ContelloI18nMessage[];\n contelloI18nMessageUpdates?: ContelloI18nMessageUpdate | undefined;\n contelloRoutes?: ContelloRoute | undefined;\n contelloRoutesBatch: ContelloRoute[];\n contelloRouteUpdates?: ContelloRouteUpdate | undefined;\n contelloUpdates?: ContelloUpdateEvent | undefined;\n contelloUpdatesBatch?: ContelloUpdateBatch | undefined;\n dummies?: DummyEntity | undefined;\n dummiesBatch: DummyEntity[];\n dummyUpdates?: DummyEntityUpdate | undefined;\n};\n\nexport type ContelloEntityBase = {\n __typename?: string | undefined;\n createdAt: string;\n id: string;\n updatedAt: string;\n};\n\nexport type ContelloFile = {\n __typename?: string | undefined;\n fileName: string;\n metadata?: ContelloFileMetadata | undefined;\n mimeType: string;\n uid: string;\n};\n\nexport type ContelloEntity = DummyEntity;\nexport type ContelloFileMetadata = ContelloImageMetadata | ContelloVideoMetadata;\nexport type ContelloOptimizationConfig = ContelloImageOptimizationConfig | ContelloVideoOptimizationConfig;\nexport type ContelloRouteTarget = ContelloRouteTargetAsset | ContelloRouteTargetEntity | ContelloRouteTargetRedirect | ContelloRouteTargetSitemap | ContelloRouteTargetText;\nexport type ContelloUpdatePrev = ContelloRoute;\nexport type ContelloUpdateTarget = ContelloAsset | ContelloI18nMessage | ContelloRoute | DummyEntity;\n\nexport type MediaFileFragment = {\n uid: string;\n mimeType: string;\n metadata?: {\n __typename: 'ContelloImageMetadata';\n width: number;\n height: number;\n } | {\n __typename: 'ContelloVideoMetadata';\n width: number;\n height: number;\n } | undefined;\n};\n\nexport type MediaAssetFragment = {\n id: string;\n original: MediaFileFragment;\n preview?: MediaFileFragment | undefined;\n optimized: (MediaFileFragment & ({\n __typename: 'ContelloOptimizedFile';\n optimizationConfig?: {\n __typename: 'ContelloImageOptimizationConfig';\n name: string;\n } | undefined;\n }))[];\n};\n\nexport type StoreFileFragment = MediaFileFragment;\n\nexport type StoreAssetFragment = MediaAssetFragment;\n\nexport type StoreI18nMessageFragment = {\n id: string;\n token: string;\n description?: string | undefined;\n example?: string | undefined;\n translations: ({\n language: string;\n value: string;\n })[];\n};\n\nexport type StoreRouteFragment = {\n id: string;\n path: string;\n target: {\n __typename: 'ContelloRouteTargetEntity';\n entity?: {\n __typename: string;\n id: string;\n } | undefined;\n } | {\n __typename: 'ContelloRouteTargetAsset';\n asset: {\n id: string;\n original: {\n uid: string;\n mimeType: string;\n };\n };\n contentDisposition: ContelloContentDispositionEnum;\n } | {\n __typename: 'ContelloRouteTargetRedirect';\n location: string;\n responseCode: number;\n } | {\n __typename: 'ContelloRouteTargetText';\n content: string;\n mimeType: string;\n } | {\n __typename: 'ContelloRouteTargetSitemap';\n sitemapId: string;\n };\n customHeaders: ({\n name: string;\n value: string;\n })[];\n};\n\nexport type StoreRegisterI18nMessagesMutation = {\n registerContelloI18nMessages?: {\n ids: string[];\n } | undefined;\n};\n\nexport type StoreRegisterI18nMessagesMutationVariables = {\n collection: string;\n messages: ContelloI18nMessageInput[];\n};\n\nexport type StoreWatchUpdatesSubscription = {\n contelloUpdatesBatch?: {\n events: ({\n target: {\n id: string;\n } & ({\n __typename: 'ContelloRoute';\n } & StoreRouteFragment | {\n __typename: 'ContelloAsset';\n id: string;\n } | {\n __typename: 'ContelloI18nMessage';\n id: string;\n token: string;\n });\n prev?: {\n __typename: 'ContelloRoute';\n } & StoreRouteFragment | undefined;\n mutation: {\n type: ContelloMutationType;\n };\n })[];\n } | undefined;\n};\n\nexport type StoreWatchUpdatesSubscriptionVariables = Record<string, never>;\n\nconst MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {\n id\n original {\n ...MediaFile\n }\n preview {\n ...MediaFile\n }\n optimized {\n ...MediaFile\n ... on ContelloOptimizedFile {\n optimizationConfig {\n ... on ContelloImageOptimizationConfig {\n name\n }\n }\n }\n }\n}`;\nconst MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {\n uid\n mimeType\n metadata {\n ... on ContelloImageMetadata {\n width\n height\n }\n ... on ContelloVideoMetadata {\n width\n height\n }\n }\n}`;\nconst StoreAssetFragmentSchema = `fragment StoreAsset on ContelloAsset {\n ...MediaAsset\n}`;\nconst StoreFileFragmentSchema = `fragment StoreFile on ContelloFile {\n ...MediaFile\n}`;\nconst StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nMessage {\n id\n token\n description\n example\n translations {\n language\n value\n }\n}`;\nconst StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {\n id\n path\n target {\n __typename\n ... on ContelloRouteTargetEntity {\n entity {\n __typename\n ... on ContelloEntityBase {\n id\n }\n }\n }\n ... on ContelloRouteTargetAsset {\n asset {\n id\n original {\n uid\n mimeType\n }\n }\n contentDisposition\n }\n ... on ContelloRouteTargetRedirect {\n location\n responseCode\n }\n ... on ContelloRouteTargetText {\n content\n mimeType\n }\n ... on ContelloRouteTargetSitemap {\n sitemapId\n }\n }\n customHeaders {\n name\n value\n }\n}`;\n\nexport const storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {\n registerContelloI18nMessages(\n collectionReferenceName: $collection\n messages: $messages\n deprecateUnmentioned: true\n ) {\n ids\n }\n}`;\nexport const storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}\nsubscription StoreWatchUpdates {\n contelloUpdatesBatch {\n events {\n target {\n __typename\n ... on ContelloEntityBase {\n id\n }\n ... on ContelloRoute {\n ...StoreRoute\n }\n ... on ContelloAsset {\n id\n }\n ... on ContelloI18nMessage {\n id\n token\n }\n }\n prev {\n __typename\n ... on ContelloRoute {\n ...StoreRoute\n }\n }\n mutation {\n type\n }\n }\n }\n}`;\n\nexport type Operations = {\n storeRegisterI18nMessages: {\n document: string;\n kind: 'mutation';\n __result?: StoreRegisterI18nMessagesMutation | undefined;\n __variables?: StoreRegisterI18nMessagesMutationVariables | undefined;\n };\n storeWatchUpdates: {\n document: string;\n kind: 'subscription';\n __result?: StoreWatchUpdatesSubscription | undefined;\n __variables?: StoreWatchUpdatesSubscriptionVariables | undefined;\n };\n};\n\nexport type Sources = {\n storeAsset: SourceDef<'storeAsset', 'asset', StoreAssetFragment, { update: ContelloAssetUpdateInput; delete: { id: string } }>;\n storeI18nMessage: SourceDef<'storeI18nMessage', 'i18nMessage', StoreI18nMessageFragment>;\n storeRoute: SourceDef<'storeRoute', 'route', StoreRouteFragment, { create: ContelloRouteInput; update: ContelloRouteInput; delete: { id: string } }>;\n};\n\nconst operations: Operations = {\n storeRegisterI18nMessages: { document: storeRegisterI18nMessagesDocument, kind: 'mutation' },\n storeWatchUpdates: { document: storeWatchUpdatesDocument, kind: 'subscription' },\n};\n\nconst sources: Sources = {\n storeAsset: {\n document: `${MediaFileFragmentSchema}\\n${MediaAssetFragmentSchema}\\n${StoreAssetFragmentSchema}`,\n fragment: 'StoreAsset',\n subscription: 'contelloAssetsBatch',\n mutations: {\n update: { field: 'updateContelloAsset', arguments: [{ name: 'request', type: 'ContelloAssetUpdateInput!', from: 'input' }], result: 'entity' },\n delete: { field: 'deleteContelloAsset', arguments: [{ name: 'id', type: 'String!', from: 'id' }], result: 'idObject' },\n },\n __model: 'storeAsset',\n __cardinality: 'asset',\n },\n storeI18nMessage: {\n document: StoreI18nMessageFragmentSchema,\n fragment: 'StoreI18nMessage',\n subscription: 'contelloI18nMessagesBatch',\n __model: 'storeI18nMessage',\n __cardinality: 'i18nMessage',\n },\n storeRoute: {\n document: StoreRouteFragmentSchema,\n fragment: 'StoreRoute',\n subscription: 'contelloRoutesBatch',\n mutations: {\n create: { field: 'createContelloRoute', arguments: [{ name: 'route', type: 'ContelloRouteInput!', from: 'input' }], result: 'entity' },\n update: { field: 'updateContelloRoute', arguments: [{ name: 'route', type: 'ContelloRouteInput!', from: 'input' }], result: 'entity' },\n delete: { field: 'deleteContelloRoute', arguments: [{ name: 'id', type: 'String', from: 'id' }], result: 'idScalar' },\n },\n __model: 'storeRoute',\n __cardinality: 'route',\n },\n};\n\nconst models = {\n dummy: 'DummyEntity',\n} as const;\n\nexport const schema = { operations, sources, models };\nexport type Schema = typeof schema;","import { createOperationTelemetry } from '@contello/opentelemetry';\n\nexport const { wrap } = createOperationTelemetry('@contello/store');\n","import { type AsyncIterableSubject, createAsyncIterableSubject, retryWithBackoff } from '@entwico/dash/async';\n\n/**\n * default `cache.ttl` applied across all store kinds. eager stores (collections, singletons)\n * use it as the interval for a periodic full refresh; lazy stores use it as the per-item\n * LRU eviction window. 3 hours.\n */\nexport const DEFAULT_TTL_MS = 3 * 60 * 60 * 1000;\n\n/**\n * default `cache.max` (LRU capacity) for lazy stores — the maximum number of items kept\n * before least-recently-used eviction.\n */\nexport const DEFAULT_LRU_MAX = 1000;\n\n/**\n * resolves the consumer-supplied `ttl` (number | false | undefined) into a runtime\n * value: undefined → default, false or 0 → disabled (undefined), positive → as-is.\n */\nexport function resolveTtl(ttl: number | false | undefined): number | undefined {\n if (ttl === undefined) return DEFAULT_TTL_MS;\n if (ttl === false || ttl <= 0) return undefined;\n\n return ttl;\n}\n\n/**\n * creates a coalescing refresh scheduler with exponential-backoff retry on failure.\n *\n * at most one refresh runs at a time. if a new refresh is requested while one is in-flight,\n * it is queued as pending — the queued slot keeps the latest `kind` passed via\n * scheduleRefresh. once the in-flight refresh completes, at most one queued refresh\n * starts, with that latest kind — collapsing any number of intermediate requests into one.\n *\n * on error, retries indefinitely with exponential backoff. the projected value keeps serving\n * the stale cached value throughout (SWR). the `onRefreshed` callback receives the kind that\n * triggered the just-completed refresh.\n */\nexport function createRefresher<K>(\n fn: () => Promise<unknown>,\n onRefreshed: (kind: K) => void,\n onStart: () => void,\n): (kind: K) => void {\n let refreshing = false;\n let inFlightKind: K | undefined;\n let pendingKind: { kind: K } | undefined;\n\n function scheduleRefresh(kind: K): void {\n if (refreshing) {\n pendingKind = { kind };\n\n return;\n }\n\n refreshing = true;\n inFlightKind = kind;\n onStart?.();\n\n void retryWithBackoff(fn).then(() => {\n const finished = inFlightKind as K;\n\n refreshing = false;\n inFlightKind = undefined;\n onRefreshed(finished);\n\n if (!pendingKind) {\n return;\n }\n\n const { kind: next } = pendingKind;\n\n pendingKind = undefined;\n scheduleRefresh(next);\n });\n }\n\n return scheduleRefresh;\n}\n\n/**\n * Refresh channel: bundles the `refresh$` multicast stream and the `onRefresh` callback\n * so both fire on every emission. Used by every eager and lazy store that exposes refresh\n * events.\n */\nexport type RefreshChannel<TEvent> = {\n readonly stream$: AsyncIterableSubject<TEvent>;\n emit(event: TEvent): void;\n complete(): void;\n};\n\nexport function createRefreshChannel<TEvent>(\n onRefresh?: ((event: TEvent) => void) | undefined,\n): RefreshChannel<TEvent> {\n const stream$ = createAsyncIterableSubject<TEvent>();\n\n return {\n stream$,\n emit(event) {\n stream$.next(event);\n onRefresh?.(event);\n },\n complete() {\n stream$.complete();\n },\n };\n}\n\n/**\n * TTL orchestrator: owns the safety-net timer for eager stores. Calls into `run` after\n * `ttl` ms have passed since the last `mark()` (or `reset()`); `run` is responsible for\n * actually fetching + re-arming via another `mark()` once it succeeds. `clear()` cancels\n * the timer on destroy. When `ttl` is undefined the orchestrator is a no-op.\n */\nexport type TtlOrchestrator = {\n /** start (or restart) the timer. consumers call this on first successful full fetch and after every later one. */\n mark(): void;\n /** cancel any pending timer; for destroy. */\n clear(): void;\n};\n\nexport function createTtlOrchestrator(options: { ttl: number | undefined; run: () => void }): TtlOrchestrator {\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n return {\n mark() {\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n\n if (options.ttl === undefined) {\n return;\n }\n\n timer = setTimeout(options.run, options.ttl);\n },\n clear() {\n if (timer === undefined) {\n return;\n }\n\n clearTimeout(timer);\n timer = undefined;\n },\n };\n}\n\n/**\n * FIFO queue for ttl-fired refreshes on eager stores.\n * Concurrency is fixed at 1 to avoid DDOSing the server\n */\nexport type RefreshByTtlQueue = {\n enqueue(task: () => Promise<unknown>): void;\n};\n\nexport function createRefreshByTtlQueue(): RefreshByTtlQueue {\n const waiting: (() => Promise<unknown>)[] = [];\n let running = false;\n\n function next(): void {\n if (running) return;\n\n const task = waiting.shift();\n\n if (!task) return;\n\n running = true;\n\n void (async () => {\n try {\n await task();\n } catch {\n // misbehaving task — keep the queue draining\n } finally {\n running = false;\n next();\n }\n })();\n }\n\n return {\n enqueue(task) {\n waiting.push(task);\n next();\n },\n };\n}\n","/**\n * Entities answered by a write, parked until the refresh that write schedules takes them into the\n * cache. A write mutation selects the source's fragment, so it comes back in exactly the shape the\n * subscription yields and the refresh can be served from here instead of going over the wire — the\n * entity still travels the one path that maps it, collects its dependencies, sorts and freezes it.\n *\n * A parked entity is a shortcut, never an authority. `ProjectedMap` debounces and coalesces partial\n * refreshes, so a refresh that some *other* change scheduled can be the one that consumes it —\n * answering an upstream event out of the local write and silently dropping the remote change until\n * the next full refresh. `awaitingUpstream` closes that window from both sides: it drops what is\n * already parked for those ids and refuses to park them again until the upstream refresh settles,\n * whichever of the two arrives first.\n *\n * `release` covers the rest: an id that was deleted, and a write whose own refresh failed — which\n * would otherwise leave the entity here to answer some unrelated partial refresh much later.\n */\nexport type WriteBuffer<T> = {\n /** Parks a written entity — ignored while an upstream refresh for that id is outstanding. */\n park(id: string, entity: T): void;\n release(ids: Iterable<string>): void;\n clear(): void;\n /** Splits requested ids into what this buffer answers (consuming it) and what must be fetched. */\n take(ids: readonly string[]): { written: T[]; missing: string[] };\n /**\n * Marks ids whose server version is being refetched, so nothing local answers that refresh.\n * Returns the function that unmarks them once it has settled.\n */\n awaitingUpstream(ids: readonly string[]): () => void;\n};\n\nexport function createWriteBuffer<T>(): WriteBuffer<T> {\n const parked = new Map<string, T>();\n // refresh counts, not flags — refreshes for the same id can overlap and must each unmark once\n const awaited = new Map<string, number>();\n\n return {\n park(id, entity) {\n if (!awaited.has(id)) {\n parked.set(id, entity);\n }\n },\n\n release(ids) {\n for (const id of ids) {\n parked.delete(id);\n }\n },\n\n clear() {\n parked.clear();\n },\n\n take(ids) {\n const written: T[] = [];\n const missing: string[] = [];\n\n for (const id of ids) {\n const entity = parked.get(id);\n\n if (entity === undefined) {\n missing.push(id);\n } else {\n parked.delete(id);\n written.push(entity);\n }\n }\n\n return { written, missing };\n },\n\n awaitingUpstream(ids) {\n for (const id of ids) {\n parked.delete(id);\n awaited.set(id, (awaited.get(id) ?? 0) + 1);\n }\n\n return () => {\n for (const id of ids) {\n const count = awaited.get(id) ?? 0;\n\n if (count > 1) {\n awaited.set(id, count - 1);\n } else {\n awaited.delete(id);\n }\n }\n };\n },\n };\n}\n","import {\n BUILT_IN_MUTATIONS,\n type ContelloClient,\n type DownloadResult,\n type ProxyResult,\n type SourceMutationKind,\n type SourceMutationValues,\n type UploadData,\n type UploadMetadata,\n type UploadOptions,\n createSourceMutation,\n createSourceMutationVariables,\n createSourceSubscription,\n} from '@contello/client';\nimport type { MaybePromise, ReadonlyDeep } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync, retryWithBackoff } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\n\nimport { type StoreAssetFragment, type StoreFileFragment, schema as storeSchema } from './generated/graphql';\nimport type { StoreAsset, StoreFile } from './lazy-assets';\nimport { wrap } from './telemetry';\nimport type { CacheOptions, CollectionWrites, Created, RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\nimport { createWriteBuffer } from './write-buffer';\n\nexport type AssetsOptions = {\n cache?: CacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type AssetsSyncOptions = {\n cache?: SyncCacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\n/**\n * There is no `create`: an asset comes into being through `upload()`, which is the transport, not\n * a mutation. `update` patches the mutable metadata — fields left out keep their value.\n */\nexport type Assets<TWrites = unknown> = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): MaybePromise<ReadonlyDeep<StoreAsset> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreAsset>>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n} & CollectionWrites<StoreAsset, TWrites>;\n\nexport type AssetsSync<TWrites = unknown> = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): ReadonlyDeep<StoreAsset> | undefined;\n get(ids: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreAsset>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n} & CollectionWrites<StoreAsset, TWrites>;\n\nfunction mapFile(raw: StoreFileFragment): StoreFile {\n return {\n uid: raw.uid,\n mimeType: raw.mimeType,\n metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : undefined,\n };\n}\n\nfunction mapAsset(raw: StoreAssetFragment): StoreAsset {\n return {\n id: raw.id,\n original: mapFile(raw.original),\n preview: raw.preview ? mapFile(raw.preview) : undefined,\n optimized: raw.optimized.map((file) => mapFile(file)),\n };\n}\n\nexport function createAssetsCollection(\n options: AssetsOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Assets> {\n const opts = options ?? {};\n const cache = {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n } as const;\n\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh('ttl') });\n let loaded = false;\n\n // the built-in asset source plus its fixed write bindings — `mutations` is constant for every\n // Contello schema, so the store carries it rather than depending on a regenerated bundle\n const assetSource = { ...storeSchema.sources.storeAsset, mutations: BUILT_IN_MUTATIONS.asset };\n const assetsSourceDoc = createSourceSubscription(assetSource);\n\n const writeBuffer = createWriteBuffer<StoreAssetFragment>();\n\n function fetchAssets(ids: string[] | undefined): Promise<StoreAssetFragment[]> {\n return concatAsync(\n mapAsync(\n client.subscribe<{ source: StoreAssetFragment[] }>(assetsSourceDoc, { ids }),\n (data) => data.source,\n ),\n );\n }\n\n async function fetchOrTakeWritten(ids: string[] | undefined): Promise<StoreAssetFragment[]> {\n if (ids === undefined) {\n writeBuffer.clear();\n\n return fetchAssets(undefined);\n }\n\n const { written, missing } = writeBuffer.take(ids);\n\n if (missing.length === 0) {\n return written;\n }\n\n const fetched = await fetchAssets(missing);\n\n return written.length === 0 ? fetched : [...written, ...fetched];\n }\n\n const projected = new ProjectedMap<string, StoreAsset>({\n key: (asset) => asset.id,\n values: (ids) =>\n wrap('assets', async () => {\n const rawItems = await fetchOrTakeWritten(ids);\n const items = rawItems.map((item) => mapAsset(item));\n\n if (ids === undefined && !loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((a) => a.id));\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(\n () => retryWithBackoff(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n // upstream is authoritative for these until the refetch lands — no local write may answer it\n const settled = writeBuffer.awaitingUpstream(refreshIds);\n\n void retryWithBackoff(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n }).finally(settled);\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded || batch.asset.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.asset) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (cache.eviction === 'clear') {\n writeBuffer.clear();\n projected.clear();\n\n return;\n }\n\n writeBuffer.release(deleted);\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n async function runMutation(kind: SourceMutationKind, values: SourceMutationValues): Promise<unknown> {\n const binding = assetSource.mutations?.[kind];\n\n if (!binding) {\n throw new Error(`@contello/store: assets cannot ${kind} — the schema exposes no ${kind} mutation for assets`);\n }\n\n const response = await client.execute<{ result: unknown }>(\n createSourceMutation(assetSource, kind),\n createSourceMutationVariables(binding, values),\n );\n\n if (response?.result === undefined || response.result === null) {\n throw new Error(`@contello/store: ${kind} on assets returned nothing`);\n }\n\n return response.result;\n }\n\n const writes = {\n async update(input: unknown): Promise<ReadonlyDeep<StoreAsset>> {\n const raw = (await runMutation('update', { input })) as StoreAssetFragment;\n\n writeBuffer.park(raw.id, raw);\n\n let map;\n\n try {\n map = await projected.refresh([raw.id]);\n } finally {\n writeBuffer.release([raw.id]);\n }\n\n emit([raw.id], 'write');\n\n const asset = map.get(raw.id);\n\n if (!asset) {\n throw new Error(\n `@contello/store: wrote asset \"${raw.id}\" but it is not in the cache — ` +\n `a concurrent full refresh did not return it`,\n );\n }\n\n return asset;\n },\n\n async delete(id: string): Promise<void> {\n await runMutation('delete', { input: { id }, id });\n\n writeBuffer.release([id]);\n projected.delete([id]);\n emit([id], 'write');\n },\n };\n\n const instance: Assets = {\n ...writes,\n refresh$: channel.stream$,\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n upload(data, meta, options) {\n return client.upload(data, meta, options);\n },\n\n download(fileId) {\n return client.download(fileId);\n },\n\n proxyHls(path, signal) {\n return client.proxyHls(path, signal);\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createAssetsSyncCollection(\n options: AssetsSyncOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): Created<AssetsSync> {\n const { instance: base, destroy } = createAssetsCollection(options, client, updates$, refreshByTtl);\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`assets.${method}() is not initialized yet — call assets.load() first`);\n }\n\n return value;\n }\n\n return {\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n },\n destroy,\n };\n}\n","import type { ModelResolver } from './model-resolver';\nimport type { UpdateEvent } from './watcher';\n\ntype NonEntityTarget = Exclude<UpdateEvent['target'], 'entity'>;\n\n/**\n * passed to `map()` so the mapper can declare which external entities this item depends on.\n * calls are collected during mapping and indexed once the item key is known.\n * designed to be destructurable: `map(raw, { track, trackRoute }) => ...`\n *\n * `track()` inspects `__typename` to auto-detect the dependency type:\n * - `ContelloAsset` → asset dep\n * - `ContelloRoute` → route dep\n * - `*Entity` → entity dep\n * - anything else → throws\n *\n * explicit methods (`trackEntity`, `trackAsset`, `trackRoute`) are available\n * for cases where only an id is known without the full GraphQL object.\n */\nexport type MapperContext<TModels extends string = string> = {\n track(obj: { __typename: string; id: string }): void;\n trackEntity(typename: TModels, id: string): void;\n trackAsset(id: string): void;\n trackRoute(id: string): void;\n};\n\n// shared empty result so the hot path (an event no item depends on) allocates\n// nothing — callers only ever iterate or read `.size`, never mutate.\nconst EMPTY_KEYS: ReadonlySet<never> = new Set();\n\n// dep key for non-entity targets (route, asset) — `${target}\\0${id}`\nfunction createDependencyKey(target: NonEntityTarget, id: string): string {\n return `${target}\\0${id}`;\n}\n\n// dep key for entity deps — prefixed with `entity\\0` to avoid collisions with other targets\n// e.g. a model named 'route' would otherwise collide with ref.route() deps\nfunction createEntityDependencyKey(typename: string, id: string): string {\n return `entity\\0${typename}\\0${id}`;\n}\n\n// key used to register and look up route-target interest deps.\n// separate from createDependencyKey because the value is a compound (typename \\0 id) pair itself.\nfunction createRouteTargetKey(typename: string, id: string): string {\n return `routeTarget\\0${typename}\\0${id}`;\n}\n\n/**\n * bidirectional dependency index for a single collection.\n *\n * during each map cycle, `createContext` is called per item. it creates a `MapperContext` the mapper\n * uses to declare cross-entity dependencies, and a `register(key)` function the caller invokes\n * once the item key is known. `register` flushes the collected deps into two maps:\n *\n * forwardIndex: item key -> set of dep keys it declared\n * reverseIndex: dep key -> set of item keys that declared it\n *\n * the reverse map is the hot path: given an update event (typename + id), `getAffectedKeys()`\n * looks up the dep key and returns all item keys that need to be invalidated.\n *\n * lifecycle per map cycle:\n * 1. createContext(fn) — allocates deps array, creates MapperContext, calls fn(ctx, register)\n * 2. fn calls map(raw, ctx) — mapper runs, calls track methods, fills deps array\n * 3. fn calls register(key) — real item key is known, deps written into both maps\n */\nexport class DependencyCollector<TKey, TModels extends string = string> {\n /** dep key -> item keys that declared a dependency on it */\n private reverseIndex = new Map<string, Set<TKey>>();\n /** item key -> dep keys it currently declares */\n private forwardIndex = new Map<TKey, Set<string>>();\n\n constructor(\n /** the model name of the owning collection, used to form route-target dep keys */\n private readonly model: string,\n /** resolver for mapping between model names and __typename */\n private readonly resolver: ModelResolver,\n ) {}\n\n private mergeRouteTargetKeys(\n existing: Set<TKey> | undefined,\n entityType: string,\n entityId: string,\n ): Set<TKey> | undefined {\n const items = this.reverseIndex.get(createRouteTargetKey(entityType, entityId));\n\n if (!items) {\n return existing;\n }\n\n return existing ? existing.union(items) : items;\n }\n\n private warnIfUnknownModel(model: string): void {\n if (!this.resolver.hasModel(model)) {\n console.warn(\n `[contello/store] tracking model \"${model}\" which is not in models — updates for this model will be ignored`,\n );\n }\n }\n\n /**\n * removes all index entries for one item key.\n * cleans up the forward entry and removes the item from every reverse set it appeared in.\n * if a reverse set becomes empty after removal, it is deleted to avoid memory leaks.\n */\n private clearItem(key: TKey): void {\n const existingDeps = this.forwardIndex.get(key);\n\n if (!existingDeps) {\n return;\n }\n\n for (const dk of existingDeps) {\n const set = this.reverseIndex.get(dk);\n\n if (!set) {\n continue;\n }\n\n set.delete(key);\n\n if (set.size === 0) {\n this.reverseIndex.delete(dk);\n }\n }\n\n this.forwardIndex.delete(key);\n }\n\n /**\n * creates a scoped MapperContext for one item and runs `fn` with it.\n * `fn` receives the context (for declaring deps during mapping) and a `register(key)` function\n * that must be called once the item key is known — it writes all declared deps into the index.\n * returns whatever `fn` returns, preserving MaybePromise semantics.\n */\n createContext<T>(fn: (ctx: MapperContext<TModels>, register: (key: TKey) => void) => T): T {\n const deps: string[] = [];\n\n const ctx: MapperContext<TModels> = {\n track: (obj) => {\n if (!obj.id) {\n throw new Error(`track(): object with __typename \"${obj.__typename}\" has no \"id\" field`);\n }\n\n switch (obj.__typename) {\n case 'ContelloAsset': {\n deps.push(createDependencyKey('asset', obj.id));\n break;\n }\n case 'ContelloRoute': {\n deps.push(createDependencyKey('route', obj.id));\n break;\n }\n default: {\n const model = this.resolver.getModel(obj.__typename);\n\n if (!model) {\n throw new Error(\n `track(): unexpected __typename \"${obj.__typename}\" — expected ContelloAsset, ContelloRoute, or a known entity model`,\n );\n }\n\n deps.push(createEntityDependencyKey(model, obj.id));\n }\n }\n },\n trackEntity: (model, id) => {\n this.warnIfUnknownModel(model);\n deps.push(createEntityDependencyKey(model, id));\n },\n trackAsset: (id) => {\n deps.push(createDependencyKey('asset', id));\n },\n trackRoute: (id) => {\n deps.push(createDependencyKey('route', id));\n },\n };\n\n const register = (key: TKey) => {\n this.clearItem(key);\n\n deps.push(createRouteTargetKey(this.model, String(key)));\n\n const fwd = new Set<string>();\n\n for (const dk of deps) {\n fwd.add(dk);\n\n let set = this.reverseIndex.get(dk);\n\n if (!set) {\n set = new Set();\n this.reverseIndex.set(dk, set);\n }\n\n set.add(key);\n }\n\n if (fwd.size > 0) {\n this.forwardIndex.set(key, fwd);\n }\n };\n\n return fn(ctx, register);\n }\n\n /**\n * looks up which item keys are affected by an update event.\n * for route events, checks route-target deps for both the new and previous entity targets.\n */\n getAffectedKeys(event: UpdateEvent): ReadonlySet<TKey> {\n if (event.target === 'entity') {\n return this.reverseIndex.get(createEntityDependencyKey(event.model, event.id)) ?? EMPTY_KEYS;\n }\n\n let affected = this.reverseIndex.get(createDependencyKey(event.target, event.id));\n\n if (event.target === 'route') {\n if ('after' in event && event.after.type === 'entity') {\n affected = this.mergeRouteTargetKeys(affected, event.after.model, event.after.entityId);\n }\n\n if ('before' in event && event.before.type === 'entity') {\n affected = this.mergeRouteTargetKeys(affected, event.before.model, event.before.entityId);\n }\n }\n\n return affected ?? EMPTY_KEYS;\n }\n\n /** removes all recorded deps for a single item (called on eviction) */\n removeItem(key: TKey): void {\n this.clearItem(key);\n }\n\n /** drops all recorded deps — used when clearing the entire cache */\n clear(): void {\n this.reverseIndex.clear();\n this.forwardIndex.clear();\n }\n\n /**\n * removes index entries for any item key NOT present in `keys`.\n * called after a full re-fetch to prune refs from items that were deleted upstream.\n */\n retainOnly(keys: Set<TKey>): void {\n for (const key of this.forwardIndex.keys()) {\n if (!keys.has(key)) {\n this.clearItem(key);\n }\n }\n }\n}\n","import {\n type ContelloClient,\n type SourceDef,\n type SourceMutationKind,\n type SourceMutationValues,\n createSourceMutation,\n createSourceMutationVariables,\n createSourceSubscription,\n} from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeAll, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync, retryWithBackoff } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\nimport { DependencyCollector } from './dependency-collector';\nimport type { ModelResolver } from './model-resolver';\nimport { wrap } from './telemetry';\nimport type {\n Collection,\n CollectionOptions,\n CollectionSync,\n CollectionSyncOptions,\n CollectionWrites,\n Created,\n ExtractSourceResult,\n ExtractSourceWrites,\n RefreshEvent,\n RefreshKind,\n} from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\nimport { createWriteBuffer } from './write-buffer';\n\nfunction fetchCollection<S extends SourceDef<string, 'entity'>>(\n source: S,\n client: ContelloClient<any>,\n ids: string[] | undefined,\n): Promise<ExtractSourceResult<S>[]> {\n return concatAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<S>[] }>(createSourceSubscription(source), { ids }),\n (r) => r.source,\n ),\n );\n}\n\n/**\n * Runs one write mutation of the source. A create/update selects the source's fragment, so the\n * answer is a raw entity in exactly the shape the source subscription yields — the cache takes it\n * from there. A delete only carries an id.\n */\nasync function runMutation<TRaw extends { id: string }>(\n source: SourceDef<string, 'entity'>,\n client: ContelloClient<any>,\n name: string,\n kind: SourceMutationKind,\n values: SourceMutationValues,\n): Promise<TRaw> {\n const binding = source.mutations?.[kind];\n\n if (!binding) {\n throw new Error(\n `@contello/store: collection \"${name}\" cannot ${kind} — the schema exposes no ${kind} mutation ` +\n `for model \"${source.__model}\"`,\n );\n }\n\n const document = createSourceMutation(source, kind);\n const response = await client.execute<{ result: TRaw | undefined }>(\n document,\n createSourceMutationVariables(binding, values),\n );\n\n if (!response?.result) {\n throw new Error(`@contello/store: ${kind} on collection \"${name}\" returned no entity`);\n }\n\n return response.result;\n}\n\nexport function createCollection<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: CollectionOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Collection<TMapped, ExtractSourceWrites<TSource>>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n },\n };\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runFullRefresh('ttl') });\n let loaded = false;\n\n const writeBuffer = createWriteBuffer<ExtractSourceResult<TSource>>();\n\n function fetchOrTakeWritten(ids: string[] | undefined): MaybePromise<ExtractSourceResult<TSource>[]> {\n if (ids === undefined) {\n writeBuffer.clear();\n\n return fetchCollection(source, client, undefined);\n }\n\n const { written, missing } = writeBuffer.take(ids);\n\n if (missing.length === 0) {\n return written;\n }\n\n if (written.length === 0) {\n return fetchCollection(source, client, missing);\n }\n\n return maybeThen(fetchCollection(source, client, missing), (fetched) => [...written, ...fetched]);\n }\n\n const projected = new ProjectedMap<string, TMapped>({\n key: (item) => item.id,\n values: (ids) =>\n wrap(\n `collection:${_def.name}`,\n () => maybeThen(fetchOrTakeWritten(ids), async (rawItems) => {\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const items = await maybeAll(\n rawItems.map(\n (item) => dependencyCollector.createContext(\n (ref, register) => maybeThen(mapFn(item, ref), (mapped) => {\n register(mapped.id);\n\n return mapped;\n }),\n ),\n ),\n );\n\n if (ids === undefined) {\n dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));\n\n // start tracking refresh by ttl on first successful full fetch\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((item) => item.id));\n }\n } else {\n const returnedIds = new Set(items.map((item) => item.id));\n\n for (const id of ids) {\n if (!returnedIds.has(id)) {\n dependencyCollector.removeItem(id);\n }\n }\n }\n\n return items;\n }),\n ),\n sort: opts.sort,\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(\n () => retryWithBackoff(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n // upstream is authoritative for these until the refetch lands — no local write may answer it\n const settled = writeBuffer.awaitingUpstream(refreshIds);\n\n void retryWithBackoff(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n }).finally(settled);\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n const ownEvents = batch.entity.get(_def.model) ?? [];\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of ownEvents) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n const depAffected = new Set<string>();\n\n for (const event of batch.events) {\n for (const id of dependencyCollector.getAffectedKeys(event)) {\n depAffected.add(id);\n }\n }\n\n if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) {\n return;\n }\n\n if (_def.cache.eviction === 'clear') {\n dependencyCollector.clear();\n writeBuffer.clear();\n projected.clear();\n\n return;\n }\n\n writeBuffer.release(deleted);\n\n for (const id of deleted) {\n dependencyCollector.removeItem(id);\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n const refreshIds = upserted.union(depAffected);\n\n for (const id of deleted) {\n refreshIds.delete(id);\n }\n\n runPartialRefresh([...refreshIds], deleted);\n });\n\n /** Puts a written entity into the cache through the normal refresh path and returns it mapped. */\n async function takeIntoCache(entity: ExtractSourceResult<TSource> & { id: string }): Promise<ReadonlyDeep<TMapped>> {\n writeBuffer.park(entity.id, entity);\n\n let map;\n\n try {\n map = await projected.refresh([entity.id]);\n } finally {\n writeBuffer.release([entity.id]);\n }\n\n emit([entity.id], 'write');\n\n const item = map.get(entity.id);\n\n if (!item) {\n throw new Error(\n `@contello/store: collection \"${_def.name}\" wrote entity \"${entity.id}\" but it is not in the cache — ` +\n `a concurrent full refresh did not return it`,\n );\n }\n\n return item;\n }\n\n /**\n * One method per mutation the source binds — a model the schema exposes no `createX` for has\n * no `create`, matching what `CollectionWrites` types. Permission is not decided here: the\n * server rejects a write the token may not run.\n */\n function createWrites(): CollectionWrites<TMapped, ExtractSourceWrites<TSource>> {\n const out: Record<string, unknown> = {};\n\n if (source.mutations?.create) {\n out['create'] = async (input: unknown) =>\n takeIntoCache(await runMutation(source, client, _def.name, 'create', { input }));\n }\n\n if (source.mutations?.update) {\n out['update'] = async (input: unknown) =>\n takeIntoCache(await runMutation(source, client, _def.name, 'update', { input }));\n }\n\n if (source.mutations?.delete) {\n out['delete'] = async (id: string, options?: Record<string, unknown> | undefined) => {\n await runMutation(source, client, _def.name, 'delete', { input: { ...options, id }, id });\n\n writeBuffer.release([id]);\n dependencyCollector.removeItem(id);\n projected.delete([id]);\n emit([id], 'write');\n };\n }\n\n return out as CollectionWrites<TMapped, ExtractSourceWrites<TSource>>;\n }\n\n const instance: Collection<TMapped, ExtractSourceWrites<TSource>> = {\n name: _def.name,\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n getAll(): MaybePromise<ReadonlyArray<ReadonlyDeep<TMapped>>> {\n return projected.getAll();\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n\n ...createWrites(),\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createCollectionSync<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: CollectionSyncOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<CollectionSync<TMapped, ExtractSourceWrites<TSource>>> {\n const { instance: base, destroy } = createCollection<TSource, TMapped, TModels>(\n source,\n options,\n client,\n updates$,\n resolver,\n refreshByTtl,\n );\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`collection \"${base.name}\".${method}() is not initialized yet — call collection.load() first`);\n }\n\n return value;\n }\n\n return {\n // the write half passes through untouched — a mutation is a round trip either way\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n getAll(): ReadonlyArray<ReadonlyDeep<TMapped>> {\n return assertSync(base.getAll(), 'getAll');\n },\n } as unknown as CollectionSync<TMapped, ExtractSourceWrites<TSource>>,\n destroy,\n };\n}\n","import { type ContelloClient, createSourceSubscription } from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync, retryWithBackoff } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\nimport {\n type ContelloI18nMessageInput,\n type StoreI18nMessageFragment,\n type StoreRegisterI18nMessagesMutation,\n storeRegisterI18nMessagesDocument,\n schema as storeSchema,\n} from './generated/graphql';\nimport { wrap } from './telemetry';\nimport type { RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\n\nimport {\n type RefreshByTtlQueue,\n createRefreshChannel,\n createRefresher,\n createTtlOrchestrator,\n resolveTtl,\n} from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type I18nTranslation = {\n language: string;\n value: string;\n};\n\nexport type I18nVariableInput = {\n name: string;\n description: string;\n example: string;\n};\n\nexport type I18nInitialTranslation = {\n language: string;\n message: string;\n};\n\nexport type I18nMessageRegistrationDefinition = {\n token: string;\n example?: string | undefined;\n description?: string | undefined;\n variables?: I18nVariableInput[] | undefined;\n /** always overwrites existing translations for this token */\n translations?: I18nInitialTranslation[] | undefined;\n /** only applied when the token is newly registered (existing translations are preserved) */\n initialTranslations?: I18nInitialTranslation[] | undefined;\n};\n\nexport type I18nMessageDef = {\n collection: string;\n cache?: SyncCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type I18nMessage = {\n id: string;\n token: string;\n translations: Map<string, string>;\n};\n\nexport type I18nMessages = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): MaybePromise<ReadonlyDeep<I18nMessage> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyDeep<I18nMessage[]>>;\n getAll(): MaybePromise<ReadonlyDeep<I18nMessage[]>>;\n register(messages: I18nMessageRegistrationDefinition[]): Promise<void>;\n refresh(): void;\n /** Completes refresh$ and detaches from the watcher — called by `Store.destroy()`. */\n destroy(): void;\n};\n\nfunction toGqlMessageInput(msg: I18nMessageRegistrationDefinition): ContelloI18nMessageInput {\n return {\n token: msg.token,\n example: msg.example,\n description: msg.description,\n variables: msg.variables?.map((v) => ({ name: v.name, description: v.description, example: v.example })),\n translations: msg.translations?.map((t) => ({ language: t.language, message: t.message })),\n initialTranslations: msg.initialTranslations?.map((t) => ({ language: t.language, message: t.message })),\n };\n}\n\nexport function createI18nMessagesCollection(\n def: I18nMessageDef,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): I18nMessages {\n const channel = createRefreshChannel<RefreshEvent>(def.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: resolveTtl(def.cache?.ttl), run: () => runTtlRefresh() });\n let loaded = false;\n\n const i18nSourceDoc = createSourceSubscription(storeSchema.sources.storeI18nMessage);\n\n const projected = new ProjectedMap<string, I18nMessage>({\n key: (msg) => msg.id,\n values: (ids) =>\n wrap(`i18n:${def.collection}`, async () => {\n const msgs = await concatAsync(\n mapAsync(\n client.subscribe<{ source: StoreI18nMessageFragment[] }>(i18nSourceDoc, {\n collection: def.collection,\n ids,\n }),\n (data) => data.source,\n ),\n );\n const items: I18nMessage[] = msgs.map((msg) => ({\n id: msg.id,\n token: msg.token,\n translations: new Map(msg.translations.map((t) => [t.language, t.value])),\n }));\n\n // start tracking refresh by ttl on first successful full fetch\n if (ids === undefined && !loaded) {\n loaded = true;\n ttl.mark();\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function emitWithCurrentIds(kind: RefreshKind): void {\n maybeThen(projected.getAll(), (msgs) => {\n emit(\n msgs.map((m) => m.id),\n kind,\n );\n });\n }\n\n function runTtlRefresh(): void {\n refreshByTtl.enqueue(async () => {\n await retryWithBackoff(() => projected.refresh());\n emitWithCurrentIds('ttl');\n ttl.mark();\n });\n }\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n () => projected.refresh(),\n (kind) => {\n emitWithCurrentIds(kind);\n ttl.mark();\n },\n () => {},\n );\n\n function runPartialRefresh(upsertedIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...upsertedIds, ...deletedIds])];\n\n if (changedIds.length === 0) {\n return;\n }\n\n if (upsertedIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n void retryWithBackoff(async () => {\n await projected.refresh(upsertedIds);\n emit(changedIds, 'upstream-update');\n });\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n if (batch.i18nMessage.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.i18nMessage) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n return {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n getAll() {\n return projected.getAll();\n },\n\n register(messages: I18nMessageRegistrationDefinition[]) {\n return wrap(`i18n-register:${def.collection}`, async () => {\n await client.execute<StoreRegisterI18nMessagesMutation>(storeRegisterI18nMessagesDocument, {\n collection: def.collection,\n messages: messages.map((message) => toGqlMessageInput(message)),\n });\n });\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n","import type { ProjectedMapCache } from '@entwico/projected';\nimport { LRUCache } from 'lru-cache';\n\nexport type LruCache<TKey, TValue> = ProjectedMapCache<TKey, TValue> & {\n keys: () => TKey[];\n};\n\nexport function createLruCache<TKey, TValue>(options: {\n max: number;\n ttl: number | undefined;\n onEvict: ((value: TValue, key: TKey) => void) | undefined;\n}): LruCache<TKey, TValue> {\n const { max, ttl, onEvict: dispose } = options;\n\n const lru = new LRUCache<any, any>({\n max,\n ...(ttl !== undefined && { ttl, ttlAutopurge: false }),\n ...(dispose !== undefined && { dispose }),\n });\n\n return {\n has: (key) => lru.has(key),\n get: (key) => lru.get(key),\n set: (key, value) => {\n lru.set(key, value);\n },\n delete: (key) => {\n lru.delete(key);\n },\n clear: () => {\n lru.clear();\n },\n keys: () => lru.keys().toArray(),\n };\n}\n","import {\n type ContelloClient,\n type DownloadResult,\n type ProxyResult,\n type UploadData,\n type UploadMetadata,\n type UploadOptions,\n createSourceSubscription,\n} from '@contello/client';\nimport type { ReadonlyDeep } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedLazyMap } from '@entwico/projected';\nimport { type StoreAssetFragment, type StoreFileFragment, schema as storeSchema } from './generated/graphql';\nimport { createLruCache } from './lru';\nimport { wrap } from './telemetry';\nimport type { Created, LazyCacheOptions, RefreshEvent, RefreshKind } from './types';\nimport { DEFAULT_LRU_MAX, createRefreshChannel, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type StoreFileMetadata = {\n width: number;\n height: number;\n};\n\nexport type StoreFile = {\n uid: string;\n mimeType: string;\n metadata: StoreFileMetadata | undefined;\n};\n\nexport type StoreAsset = {\n id: string;\n original: StoreFile;\n preview: StoreFile | undefined;\n optimized: StoreFile[];\n};\n\nexport type LazyAssetsOptions = {\n cache?: LazyCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type LazyAssets = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): Promise<ReadonlyDeep<StoreAsset> | undefined>;\n get(ids: readonly string[]): Promise<ReadonlyDeep<StoreAsset[]>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n clear(): void;\n};\n\nfunction mapFile(raw: StoreFileFragment): StoreFile {\n return {\n uid: raw.uid,\n mimeType: raw.mimeType,\n metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : undefined,\n };\n}\n\nfunction mapAsset(raw: StoreAssetFragment): StoreAsset {\n return {\n id: raw.id,\n original: mapFile(raw.original),\n preview: raw.preview ? mapFile(raw.preview) : undefined,\n optimized: raw.optimized.map((file) => mapFile(file)),\n };\n}\n\nexport function createLazyAssetsCollection(\n def: LazyAssetsOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n): Created<LazyAssets> {\n const _def = {\n cache: {\n max: def?.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(def?.cache?.ttl),\n },\n };\n\n const cache = createLruCache<string, StoreAsset>({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: undefined });\n\n const assetsSourceDoc = createSourceSubscription(storeSchema.sources.storeAsset);\n\n const projected = new ProjectedLazyMap<string, StoreAsset>({\n key: (asset) => asset.id,\n values: (ids) =>\n wrap('assets', async () => {\n const rawItems = await concatAsync(\n mapAsync(client.subscribe<{ source: StoreAssetFragment[] }>(assetsSourceDoc, { ids }), (data) => data.source),\n );\n\n return rawItems.map((item) => mapAsset(item));\n }),\n cache,\n });\n\n const channel = createRefreshChannel<RefreshEvent>(def?.onRefresh);\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n let lastRefreshKeys: string[] = [];\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(lastRefreshKeys, kind);\n }\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (batch.asset.length === 0) return;\n\n for (const event of batch.asset) {\n projected.delete(event.id);\n }\n\n emit(\n batch.asset.map((e) => e.id),\n 'upstream-update',\n );\n });\n\n return {\n instance: {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string> {\n return client.upload(data, meta, options);\n },\n\n download(fileId: string): Promise<DownloadResult> {\n return client.download(fileId);\n },\n\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult> {\n return client.proxyHls(path, signal);\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n clear() {\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n channel.complete();\n },\n };\n}\n","import { type ContelloClient, type SourceDef, createSourceSubscription } from '@contello/client';\nimport { maybeAll, maybeThen } from '@entwico/dash';\nimport {\n type AsyncIterableSubject,\n concatAsync,\n createAsyncIterableSubject,\n mapAsync,\n} from '@entwico/dash/async';\nimport { ProjectedLazyMap } from '@entwico/projected';\nimport { DependencyCollector } from './dependency-collector';\nimport { createLruCache } from './lru';\nimport type { ModelResolver } from './model-resolver';\nimport { wrap } from './telemetry';\nimport type {\n Created,\n ExtractSourceResult,\n LazyCollection,\n LazyCollectionOptions,\n RefreshEvent,\n RefreshKind,\n} from './types';\nimport { DEFAULT_LRU_MAX, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport function createLazyCollection<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: LazyCollectionOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n): Created<LazyCollection<TMapped>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n max: opts.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(opts.cache?.ttl),\n },\n };\n\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const cache = createLruCache<string, TMapped>({\n max: _def.cache.max,\n ttl: _def.cache.ttl,\n onEvict: (_value, key) => dependencyCollector.removeItem(key),\n });\n\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const projected = new ProjectedLazyMap<string, TMapped>({\n key: (item) => item.id,\n values: (keys) =>\n wrap(\n `lazy-collection:${_def.name}`,\n () => maybeThen(\n concatAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<TSource>[] }>(createSourceSubscription(source), {\n ids: keys,\n }),\n (r) => r.source,\n ),\n ),\n (rawItems) => maybeAll(\n rawItems.map(\n (item) => dependencyCollector.createContext(\n (ref, register) => maybeThen(mapFn(item, ref), (mapped) => {\n register(mapped.id);\n\n return mapped;\n }),\n ),\n ),\n ),\n ),\n ),\n cache,\n });\n\n const refresh$ = createAsyncIterableSubject<RefreshEvent>();\n\n function emit(ids: string[], kind: RefreshKind): void {\n const event: RefreshEvent = { ids, kind };\n\n refresh$.next(event);\n opts.onRefresh?.(event);\n }\n\n let lastRefreshKeys: string[] = [];\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(lastRefreshKeys, kind);\n }\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n const evicted = new Set<string>();\n const ownModelEvents = batch.entity.get(_def.model);\n\n if (ownModelEvents) {\n for (const event of ownModelEvents) {\n evicted.add(event.id);\n }\n }\n\n for (const event of batch.events) {\n for (const key of dependencyCollector.getAffectedKeys(event)) {\n evicted.add(key);\n }\n }\n\n if (evicted.size === 0) {\n return;\n }\n\n for (const key of evicted) {\n dependencyCollector.removeItem(key);\n projected.delete(key);\n }\n\n emit([...evicted], 'upstream-update');\n });\n\n return {\n instance: {\n name: _def.name,\n refresh$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n clear() {\n dependencyCollector.clear();\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n refresh$.complete();\n },\n };\n}\n","const ESCAPES = /(?:%[\\dA-Fa-f]{2})+/g;\n\n// a character a route path cannot hold decoded: a slash is a delimiter (`/a%2Fb` and `/a/b` are\n// two routes), a percent sign could not be re-encoded, a query or fragment delimiter, a space or\n// control character has no place in a path\nconst STAYS_ENCODED = /[/%?#\\s\\p{Cc}]/u;\n\nfunction decodeRun(run: string): string {\n let decoded: string;\n\n try {\n decoded = decodeURIComponent(run);\n } catch {\n // a broken sequence is kept as it is\n return run.toUpperCase();\n }\n\n let result = '';\n\n for (const char of decoded) {\n result += STAYS_ENCODED.test(char) ? encodeURIComponent(char) : char;\n }\n\n return result;\n}\n\n/**\n * The one form a route path is stored and looked up in: percent escapes decoded and unicode\n * composed (NFC), as core normalizes it. A request arrives percent-encoded (`/%C3%BCber-uns`),\n * the stored path is decoded (`/über-uns`); both spellings must hit the same cache entry. An\n * escape of a character a path cannot hold decoded stays encoded, with uppercase hex.\n */\nexport function normalizeRoutePath(path: string): string {\n // eslint-disable-next-line unicorn/no-unsafe-string-replacement -- the replacer is a function, no `$` patterns apply\n return path.replaceAll(ESCAPES, decodeRun).normalize('NFC');\n}\n","import type { StoreRouteFragment } from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\n\nexport type StoreRouteCustomHeader = {\n name: string;\n value: string;\n};\n\nexport type StoreRoute = {\n id: string;\n path: string;\n customHeaders: StoreRouteCustomHeader[];\n} & (\n | { type: 'redirect'; location: string; status: number }\n | { type: 'text'; content: string; mimeType: string }\n | { type: 'asset'; assetId: string; fileId: string; contentDisposition: 'inline' | 'attachment'; mimeType: string }\n | { type: 'entity'; model: string; entityType: string; entityId: string }\n | { type: 'sitemap'; sitemapId: string }\n);\n\nexport function mapRoute(raw: StoreRouteFragment, resolver: ModelResolver): StoreRoute | undefined {\n const base = {\n id: raw.id,\n path: raw.path,\n customHeaders: raw.customHeaders.map((h) => ({ name: h.name, value: h.value })),\n };\n\n switch (raw.target.__typename) {\n case 'ContelloRouteTargetRedirect': {\n return {\n ...base,\n type: 'redirect',\n location: raw.target.location,\n status: raw.target.responseCode,\n };\n }\n\n case 'ContelloRouteTargetText': {\n return {\n ...base,\n type: 'text',\n content: raw.target.content,\n mimeType: raw.target.mimeType,\n };\n }\n\n case 'ContelloRouteTargetAsset': {\n return {\n ...base,\n type: 'asset',\n assetId: raw.target.asset.id,\n fileId: raw.target.asset.original.uid,\n contentDisposition: raw.target.contentDisposition === 'INLINE' ? 'inline' : 'attachment',\n mimeType: raw.target.asset.original.mimeType,\n };\n }\n\n case 'ContelloRouteTargetEntity': {\n if (!raw.target.entity) {\n return undefined;\n }\n\n const entityType = raw.target.entity.__typename;\n\n return {\n ...base,\n type: 'entity',\n model: resolver.resolveModel(entityType),\n entityType,\n entityId: raw.target.entity.id,\n };\n }\n\n case 'ContelloRouteTargetSitemap': {\n return {\n ...base,\n type: 'sitemap',\n sitemapId: raw.target.sitemapId,\n };\n }\n\n default: {\n return undefined;\n }\n }\n}\n","import { type ContelloClient, createSourceSubscription } from '@contello/client';\nimport type { ReadonlyDeep } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedLazyMap } from '@entwico/projected';\nimport { type StoreRouteFragment, schema as storeSchema } from './generated/graphql';\nimport { type LruCache, createLruCache } from './lru';\nimport type { ModelResolver } from './model-resolver';\nimport { normalizeRoutePath } from './route-path';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport { wrap } from './telemetry';\nimport type { Created, LazyCacheOptions, RefreshEvent, RefreshKind } from './types';\nimport { DEFAULT_LRU_MAX, createRefreshChannel, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type LazyRoutesOptions = {\n cache?: LazyCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type LazyRoutes = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): Promise<ReadonlyDeep<StoreRoute> | undefined>;\n get(ids: readonly string[]): Promise<ReadonlyDeep<StoreRoute[]>>;\n getByPath(path: string): Promise<ReadonlyDeep<StoreRoute> | undefined>;\n getByPath(paths: readonly string[]): Promise<ReadonlyDeep<StoreRoute[]>>;\n refresh(): void;\n clear(): void;\n};\n\n// cache key prefixes — short nullbyte-separated to allow slice(2) extraction without branching\nconst ID_PREFIX = '1\\0';\nconst PATH_PREFIX = '2\\0';\n\n// private symbol used to tag each route with the projected cache key it was requested under,\n// so the key() function can return the right prefixed key for projected to match results back\nconst CACHE_KEY = Symbol('cacheKey');\n\nfunction collectRoutes(\n rawItems: StoreRouteFragment[],\n keyFn: (route: StoreRoute) => string,\n resolver: ModelResolver,\n): StoreRoute[] {\n return rawItems.reduce<StoreRoute[]>((acc, raw) => {\n const mapped = mapRoute(raw, resolver);\n\n if (mapped) {\n (mapped as Record<symbol, string>)[CACHE_KEY] = keyFn(mapped);\n acc.push(mapped);\n }\n\n return acc;\n }, []);\n}\n\n/**\n * cache wrapper that presents a unified `ID_PREFIX + id` / `PATH_PREFIX + path` key space\n * to ProjectedLazyMap while storing entries in the underlying LRU under ID_PREFIX keys only.\n *\n * path -> id resolution is handled internally via a pathToId map kept in sync with the LRU\n * (populated on set, cleared on natural LRU eviction via onEvict, and on explicit delete).\n */\nfunction createRoutesCache(max: number, ttl: number | undefined): LruCache<string, StoreRoute> {\n const pathToId = new Map<string, string>();\n // reverse of pathToId, so a route whose path changed can have its previous\n // path entry removed (otherwise getByPath(oldPath) would resolve to the route\n // that no longer lives there)\n const idToPath = new Map<string, string>();\n\n const lru = createLruCache<string, StoreRoute>({\n max,\n ttl,\n onEvict: (route) => {\n pathToId.delete(normalizeRoutePath(route.path));\n idToPath.delete(route.id);\n },\n });\n\n function resolveKey(key: string): string {\n if (key.startsWith(PATH_PREFIX)) {\n const id = pathToId.get(key.slice(2));\n\n if (id) {\n return ID_PREFIX + id;\n }\n\n return key; // propagate cache miss if path not found\n }\n\n return key;\n }\n\n return {\n has: (key) => lru.has(resolveKey(key)),\n get: (key) => lru.get(resolveKey(key)),\n\n set: (_key, value) => {\n // always normalise to ID_PREFIX in lru\n // regardless of which key projected passes in\n const previousPath = idToPath.get(value.id);\n\n if (previousPath !== undefined && previousPath !== value.path) {\n pathToId.delete(normalizeRoutePath(previousPath));\n }\n\n pathToId.set(normalizeRoutePath(value.path), value.id);\n idToPath.set(value.id, value.path);\n lru.set(ID_PREFIX + value.id, value);\n },\n\n delete: (key) => {\n const resolved = resolveKey(key);\n const value = lru.get(resolved);\n\n if (value) {\n pathToId.delete(normalizeRoutePath(value.path));\n idToPath.delete(value.id);\n }\n\n lru.delete(resolved);\n },\n\n clear: () => {\n pathToId.clear();\n idToPath.clear();\n lru.clear();\n },\n\n keys: () => lru.keys(),\n };\n}\n\nexport function createLazyRoutesCollection(\n def: LazyRoutesOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n): Created<LazyRoutes> {\n const _def = {\n cache: {\n max: def?.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(def?.cache?.ttl),\n },\n };\n\n const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);\n\n const negatives = createLruCache<string, true>({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: undefined });\n\n const routesSourceDoc = createSourceSubscription(storeSchema.sources.storeRoute);\n\n function fetchRoutes(vars: { ids?: string[]; paths?: string[] }): Promise<StoreRouteFragment[]> {\n return concatAsync(\n mapAsync(client.subscribe<{ source: StoreRouteFragment[] }>(routesSourceDoc, vars), (data) => data.source),\n );\n }\n\n const projected = new ProjectedLazyMap<string, StoreRoute>({\n key: (route) => (route as Record<symbol, string>)[CACHE_KEY] ?? ID_PREFIX + route.id,\n values: (prefixedKeys) =>\n wrap('routes', async () => {\n const ids: string[] = [];\n const paths: string[] = [];\n\n for (const key of prefixedKeys) {\n const value = key.slice(2);\n\n if (key.startsWith(ID_PREFIX)) {\n ids.push(value);\n } else {\n paths.push(value);\n }\n }\n\n const [rawByIds, rawByPaths] = await Promise.all([\n ids.length > 0 ? fetchRoutes({ ids }) : Promise.resolve<StoreRouteFragment[]>([]),\n paths.length > 0 ? fetchRoutes({ paths }) : Promise.resolve<StoreRouteFragment[]>([]),\n ]);\n\n const byIds = collectRoutes(rawByIds, (r) => ID_PREFIX + r.id, resolver);\n const byPaths = collectRoutes(rawByPaths, (r) => PATH_PREFIX + normalizeRoutePath(r.path), resolver);\n const found = [...byIds, ...byPaths];\n const foundKeys = new Set(found.map((route) => (route as Record<symbol, string>)[CACHE_KEY]));\n\n for (const key of prefixedKeys) {\n if (!foundKeys.has(key)) {\n negatives.set(key, true);\n }\n }\n\n return found;\n }),\n cache,\n });\n\n const channel = createRefreshChannel<RefreshEvent>(def?.onRefresh);\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n let lastRefreshKeys: string[] = [];\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(\n lastRefreshKeys.map((key) => key.slice(2)),\n kind,\n );\n }\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n const evicted: string[] = [];\n\n for (const event of batch.route) {\n const idKey = ID_PREFIX + event.id;\n\n if (event.mutation === 'delete') {\n cache.delete(idKey);\n evicted.push(event.id);\n } else {\n negatives.delete(idKey);\n negatives.delete(PATH_PREFIX + normalizeRoutePath(event.after.path));\n\n if (cache.has(idKey)) {\n cache.set(idKey, event.after);\n }\n\n evicted.push(event.after.path);\n }\n }\n\n if (evicted.length > 0) {\n emit(evicted, 'upstream-update');\n }\n });\n\n function lookupOne(key: string): unknown {\n if (negatives.has(key)) {\n return undefined;\n }\n\n return projected.get(key);\n }\n\n function lookupMany(keys: string[]): unknown {\n const known = keys.filter((key) => !negatives.has(key));\n\n if (known.length === 0) {\n return [];\n }\n\n return projected.get(known);\n }\n\n return {\n instance: {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n if (Array.isArray(idOrIds)) {\n return lookupMany(idOrIds.map((id) => ID_PREFIX + id));\n }\n\n return lookupOne(ID_PREFIX + idOrIds);\n },\n\n getByPath(pathOrPaths: string | readonly string[]): any {\n if (Array.isArray(pathOrPaths)) {\n return lookupMany(pathOrPaths.map((p) => PATH_PREFIX + normalizeRoutePath(p)));\n }\n\n return lookupOne(PATH_PREFIX + normalizeRoutePath(pathOrPaths as string));\n },\n\n refresh() {\n negatives.clear();\n scheduleRefresh('on-demand');\n },\n\n clear() {\n negatives.clear();\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n channel.complete();\n },\n };\n}\n","export class ModelResolver<TModels extends string = string> {\n private _typeNames: ReadonlySet<string> | undefined;\n private _toModel: ReadonlyMap<string, TModels>;\n private _toTypeName: ReadonlyMap<TModels, string>;\n\n constructor(models?: Record<TModels, string> | undefined) {\n const toModel = new Map<string, TModels>();\n const toTypeName = new Map<TModels, string>();\n let typeNames: Set<string> | undefined;\n\n if (models) {\n typeNames = new Set<string>();\n\n for (const [model, typeName] of Object.entries<string>(models)) {\n toModel.set(typeName, model as TModels);\n toTypeName.set(model as TModels, typeName);\n typeNames.add(typeName);\n }\n }\n\n this._typeNames = typeNames;\n this._toModel = toModel;\n this._toTypeName = toTypeName;\n }\n\n hasTypeName(typeName: string): boolean {\n return !this._typeNames || this._typeNames.has(typeName);\n }\n\n getModel(typeName: string): TModels | undefined {\n return this._toModel.get(typeName);\n }\n\n getTypeName(model: TModels): string {\n return this._toTypeName.get(model) ?? model;\n }\n\n hasModel(model: string): boolean {\n return this._toTypeName.size === 0 || this._toTypeName.has(model as TModels);\n }\n\n resolveModel(typeName: string): string {\n return this._toModel.get(typeName) ?? typeName;\n }\n}\n","import {\n BUILT_IN_MUTATIONS,\n type ContelloClient,\n type SourceMutationKind,\n createSourceMutation,\n createSourceMutationVariables,\n createSourceSubscription,\n} from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync, retryWithBackoff } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\n\nimport { type StoreRouteFragment, schema as storeSchema } from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\nimport { normalizeRoutePath } from './route-path';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport { wrap } from './telemetry';\nimport type { CacheOptions, CollectionWrites, Created, RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\nimport { createWriteBuffer } from './write-buffer';\n\nexport type RoutesOptions = {\n cache?: CacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type RoutesSyncOptions = {\n cache?: SyncCacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\n/**\n * `update` is not the patch a collection's is: `updateContelloRoute` is keyed by the `path` in its\n * input — there is no id — and it replaces the route, so a field left out is cleared, not kept.\n */\nexport type Routes<TWrites = unknown> = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>>;\n getByPath(path: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined>;\n getByPath(paths: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>>;\n refresh(): void;\n} & CollectionWrites<StoreRoute, TWrites>;\n\nexport type RoutesSync<TWrites = unknown> = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): ReadonlyDeep<StoreRoute> | undefined;\n get(ids: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreRoute>>;\n getByPath(path: string): ReadonlyDeep<StoreRoute> | undefined;\n getByPath(paths: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreRoute>>;\n refresh(): void;\n} & CollectionWrites<StoreRoute, TWrites>;\n\nexport function createRoutesCollection(\n options: RoutesOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Routes> {\n const opts = options ?? {};\n const cache = {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n } as const;\n\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh('ttl') });\n\n // id ↔ path indexes — kept in sync with `projected` by the values callback.\n // any route lookup by path resolves to an id, then the value comes from `projected`.\n const pathById = new Map<string, string>();\n const idByPath = new Map<string, string>();\n let loaded = false;\n\n // the built-in route source plus its fixed write bindings — `mutations` is constant for every\n // Contello schema, so the store carries it rather than depending on a regenerated bundle\n const routeSource = { ...storeSchema.sources.storeRoute, mutations: BUILT_IN_MUTATIONS.route };\n const routesSourceDoc = createSourceSubscription(routeSource);\n\n const writeBuffer = createWriteBuffer<StoreRouteFragment>();\n\n function fetchRoutes(ids: string[] | undefined): Promise<StoreRouteFragment[]> {\n return concatAsync(\n mapAsync(\n client.subscribe<{ source: StoreRouteFragment[] }>(routesSourceDoc, { ids }),\n (data) => data.source,\n ),\n );\n }\n\n async function fetchOrTakeWritten(ids: string[] | undefined): Promise<StoreRouteFragment[]> {\n if (ids === undefined) {\n writeBuffer.clear();\n\n return fetchRoutes(undefined);\n }\n\n const { written, missing } = writeBuffer.take(ids);\n\n if (missing.length === 0) {\n return written;\n }\n\n const fetched = await fetchRoutes(missing);\n\n return written.length === 0 ? fetched : [...written, ...fetched];\n }\n\n const projected = new ProjectedMap<string, StoreRoute>({\n key: (route) => route.id,\n values: (ids) =>\n wrap('routes', async () => {\n const rawItems = await fetchOrTakeWritten(ids);\n const items = rawItems.reduce<StoreRoute[]>((acc, raw) => {\n const mapped = mapRoute(raw, resolver);\n\n if (mapped) {\n acc.push(mapped);\n }\n\n return acc;\n }, []);\n\n if (ids === undefined) {\n pathById.clear();\n idByPath.clear();\n\n for (const r of items) {\n pathById.set(r.id, r.path);\n idByPath.set(normalizeRoutePath(r.path), r.id);\n }\n\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((r) => r.id));\n }\n } else {\n const returnedIds = new Set(items.map((r) => r.id));\n\n // requested ids missing from the response = deleted; drop their path entries\n for (const id of ids) {\n if (returnedIds.has(id)) {\n continue;\n }\n\n const oldPath = pathById.get(id);\n\n if (oldPath === undefined) {\n continue;\n }\n\n idByPath.delete(normalizeRoutePath(oldPath));\n pathById.delete(id);\n }\n\n for (const r of items) {\n const oldPath = pathById.get(r.id);\n\n if (oldPath !== undefined && oldPath !== r.path) {\n idByPath.delete(normalizeRoutePath(oldPath));\n }\n\n pathById.set(r.id, r.path);\n idByPath.set(normalizeRoutePath(r.path), r.id);\n }\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(\n () => retryWithBackoff(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n // upstream is authoritative for these until the refetch lands — no local write may answer it\n const settled = writeBuffer.awaitingUpstream(refreshIds);\n\n void retryWithBackoff(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n }).finally(settled);\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded || batch.route.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.route) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (cache.eviction === 'clear') {\n pathById.clear();\n idByPath.clear();\n writeBuffer.clear();\n projected.clear();\n\n return;\n }\n\n writeBuffer.release(deleted);\n\n for (const id of deleted) {\n const oldPath = pathById.get(id);\n\n if (oldPath === undefined) {\n continue;\n }\n\n idByPath.delete(normalizeRoutePath(oldPath));\n pathById.delete(id);\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n function getByIdSingle(id: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined> {\n return projected.get(id);\n }\n\n function getByIds(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>> {\n return projected.get(ids);\n }\n\n function lookupByPathSingle(path: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined> {\n return maybeThen(ensureLoaded(), () => {\n const id = idByPath.get(normalizeRoutePath(path));\n\n return id === undefined ? undefined : projected.get(id);\n });\n }\n\n function lookupByPaths(paths: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>> {\n return maybeThen(ensureLoaded(), () => {\n const ids: string[] = [];\n\n for (const p of paths) {\n const id = idByPath.get(normalizeRoutePath(p));\n\n if (id !== undefined) {\n ids.push(id);\n }\n }\n\n return projected.get(ids);\n });\n }\n\n function ensureLoaded(): MaybePromise<void> {\n if (loaded) {\n return undefined;\n }\n\n return maybeThen(projected.getAllAsMap(), () => {});\n }\n\n async function runMutation(kind: SourceMutationKind, values: { input?: unknown; id?: string }): Promise<unknown> {\n const binding = routeSource.mutations?.[kind];\n\n if (!binding) {\n throw new Error(`@contello/store: routes cannot ${kind} — the schema exposes no ${kind} mutation for routes`);\n }\n\n const response = await client.execute<{ result: unknown }>(\n createSourceMutation(routeSource, kind),\n createSourceMutationVariables(binding, values),\n );\n\n if (response?.result === undefined || response.result === null) {\n throw new Error(`@contello/store: ${kind} on routes returned nothing`);\n }\n\n return response.result;\n }\n\n /** Takes a written route into the cache through the normal refresh path, keeping both indexes. */\n async function takeIntoCache(raw: StoreRouteFragment): Promise<ReadonlyDeep<StoreRoute>> {\n writeBuffer.park(raw.id, raw);\n\n let map;\n\n try {\n map = await projected.refresh([raw.id]);\n } finally {\n writeBuffer.release([raw.id]);\n }\n\n emit([raw.id], 'write');\n\n const route = map.get(raw.id);\n\n if (!route) {\n throw new Error(\n `@contello/store: wrote route \"${raw.id}\" but it is not in the cache — ` +\n `its target may not have resolved, or a concurrent full refresh did not return it`,\n );\n }\n\n return route;\n }\n\n const writes = {\n async create(input: unknown): Promise<ReadonlyDeep<StoreRoute>> {\n return takeIntoCache((await runMutation('create', { input })) as StoreRouteFragment);\n },\n\n async update(input: unknown): Promise<ReadonlyDeep<StoreRoute>> {\n return takeIntoCache((await runMutation('update', { input })) as StoreRouteFragment);\n },\n\n async delete(id: string): Promise<void> {\n await runMutation('delete', { input: { id }, id });\n\n writeBuffer.release([id]);\n\n const oldPath = pathById.get(id);\n\n if (oldPath !== undefined) {\n idByPath.delete(normalizeRoutePath(oldPath));\n pathById.delete(id);\n }\n\n projected.delete([id]);\n emit([id], 'write');\n },\n };\n\n const instance: Routes = {\n ...writes,\n refresh$: channel.stream$,\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n\n get(idOrIds: string | readonly string[]): any {\n return typeof idOrIds === 'string' ? getByIdSingle(idOrIds) : getByIds(idOrIds);\n },\n\n getByPath(pathOrPaths: string | readonly string[]): any {\n return typeof pathOrPaths === 'string' ? lookupByPathSingle(pathOrPaths) : lookupByPaths(pathOrPaths);\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createRoutesSyncCollection(\n options: RoutesSyncOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<RoutesSync> {\n const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`routes.${method}() is not initialized yet — call routes.load() first`);\n }\n\n return value;\n }\n\n return {\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n getByPath(pathOrPaths: string | readonly string[]): any {\n return assertSync(base.getByPath(pathOrPaths as string), 'getByPath');\n },\n },\n destroy,\n };\n}\n","import { type ContelloClient, type SourceDef, createSourceSubscription } from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, firstAsync, mapAsync, retryWithBackoff } from '@entwico/dash/async';\nimport { ProjectedValue } from '@entwico/projected';\nimport { DependencyCollector } from './dependency-collector';\nimport type { ModelResolver } from './model-resolver';\nimport { wrap } from './telemetry';\nimport type {\n Created,\n ExtractSourceResult,\n RefreshKind,\n Singleton,\n SingletonOptions,\n SingletonRefreshEvent,\n SingletonSync,\n SingletonSyncOptions,\n} from './types';\nimport {\n type RefreshByTtlQueue,\n createRefreshChannel,\n createRefresher,\n createTtlOrchestrator,\n resolveTtl,\n} from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport function createSingleton<\n TSource extends SourceDef<TModels, 'singleton'>,\n TMapped,\n TModels extends string = string,\n>(\n source: TSource,\n options: SingletonOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Singleton<TMapped>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n },\n };\n\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const itemKey = `singleton:${_def.name}`;\n const channel = createRefreshChannel<SingletonRefreshEvent>(opts.onRefresh);\n const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runTtlRefresh() });\n let loaded = false;\n\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const projected = new ProjectedValue<TMapped>({\n value: () =>\n wrap(\n `singleton:${_def.name}`,\n () => maybeThen(\n firstAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<TSource> }>(createSourceSubscription(source)),\n (r) => r.source,\n ),\n ),\n (raw) => dependencyCollector.createContext(\n (ref, register) => maybeThen(mapFn(raw, ref), (mapped) => {\n register(itemKey);\n\n // start tracking refresh by ttl on first successful full fetch\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.();\n }\n\n return mapped;\n }),\n ),\n ),\n ),\n });\n\n function emit(kind: RefreshKind): void {\n channel.emit({ kind });\n }\n\n function runTtlRefresh(): void {\n refreshByTtl.enqueue(async () => {\n await retryWithBackoff(() => projected.refresh());\n emit('ttl');\n ttl.mark();\n });\n }\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n () => projected.refresh(),\n (kind) => {\n emit(kind);\n ttl.mark();\n },\n () => {},\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n const hasOwnModel = batch.entity.has(_def.model);\n const hasAffectedRefs = batch.events.some((event) => dependencyCollector.getAffectedKeys(event).size > 0);\n\n if (!hasOwnModel && !hasAffectedRefs) {\n return;\n }\n\n if (_def.cache.eviction === 'clear') {\n dependencyCollector.clear();\n projected.clear();\n\n return;\n }\n\n scheduleRefresh('upstream-update');\n });\n\n return {\n instance: {\n name: _def.name,\n refresh$: channel.stream$,\n\n get(): MaybePromise<ReadonlyDeep<TMapped>> {\n return projected.get();\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n async load() {\n if (!loaded) {\n await projected.get();\n }\n },\n },\n destroy() {\n unsubUpdates();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createSingletonSync<\n TSource extends SourceDef<TModels, 'singleton'>,\n TMapped,\n TModels extends string = string,\n>(\n source: TSource,\n options: SingletonSyncOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<SingletonSync<TMapped>> {\n const { instance: base, destroy } = createSingleton<TSource, TMapped, TModels>(\n source,\n options,\n client,\n updates$,\n resolver,\n refreshByTtl,\n );\n\n return {\n instance: {\n ...base,\n\n get(): ReadonlyDeep<TMapped> {\n const result = base.get();\n\n if (result instanceof Promise) {\n throw new TypeError(`singleton \"${base.name}\" is not initialized yet — call singleton.load() first`);\n }\n\n return result;\n },\n },\n destroy,\n };\n}\n","import type { ContelloClient } from '@contello/client';\nimport { type AsyncIterableSubject, createAsyncIterableSubject, keepalive, mapAsync } from '@entwico/dash/async';\n\nimport {\n type ContelloMutationType,\n type StoreRouteFragment,\n type StoreWatchUpdatesSubscription,\n storeWatchUpdatesDocument,\n} from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport { wrap } from './telemetry';\n\nexport type UpdateEvent<TEntityType extends string = string> =\n | { id: string; mutation: 'create'; target: 'route'; after: StoreRoute }\n | { id: string; mutation: 'update'; target: 'route'; after: StoreRoute; before: StoreRoute }\n | { id: string; mutation: 'delete'; target: 'route' }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'asset' }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'i18nMessage'; token: string }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'entity'; model: TEntityType };\n\nexport type UpdateMutationType = UpdateEvent['mutation'];\n\nexport type UpdateEventFor<T extends UpdateEvent['target']> = Extract<UpdateEvent, { target: T }>;\n\nexport type UpdateBatch = {\n readonly events: UpdateEvent[];\n readonly route: UpdateEventFor<'route'>[];\n readonly asset: UpdateEventFor<'asset'>[];\n readonly i18nMessage: UpdateEventFor<'i18nMessage'>[];\n /** entity events grouped by model typename */\n readonly entity: Map<string, UpdateEventFor<'entity'>[]>;\n /** route events grouped by target entity model (both after and before targets for updates) */\n readonly routeByEntityModel: Map<string, UpdateEventFor<'route'>[]>;\n};\n\nfunction addRouteByModel(\n map: Map<string, UpdateEventFor<'route'>[]>,\n entityType: string,\n event: UpdateEventFor<'route'>,\n): void {\n let list = map.get(entityType);\n\n if (!list) {\n list = [];\n map.set(entityType, list);\n }\n\n list.push(event);\n}\n\ntype MutableBatch = {\n route: UpdateEventFor<'route'>[];\n asset: UpdateEventFor<'asset'>[];\n i18nMessage: UpdateEventFor<'i18nMessage'>[];\n entity: Map<string, UpdateEventFor<'entity'>[]>;\n routeByEntityModel: Map<string, UpdateEventFor<'route'>[]>;\n};\n\nfunction addEventToBatch(batch: MutableBatch, event: UpdateEvent): void {\n switch (event.target) {\n case 'route': {\n batch.route.push(event);\n\n if ('after' in event && event.after.type === 'entity') {\n addRouteByModel(batch.routeByEntityModel, event.after.model, event);\n }\n\n if ('before' in event && event.before.type === 'entity') {\n addRouteByModel(batch.routeByEntityModel, event.before.model, event);\n }\n\n break;\n }\n case 'asset': {\n batch.asset.push(event);\n break;\n }\n case 'i18nMessage': {\n batch.i18nMessage.push(event);\n break;\n }\n case 'entity': {\n let list = batch.entity.get(event.model);\n\n if (!list) {\n list = [];\n batch.entity.set(event.model, list);\n }\n\n list.push(event);\n break;\n }\n }\n}\n\nfunction createUpdateBatch(events: UpdateEvent[]): UpdateBatch {\n const batch: MutableBatch = {\n route: [],\n asset: [],\n i18nMessage: [],\n entity: new Map<string, UpdateEventFor<'entity'>[]>(),\n routeByEntityModel: new Map<string, UpdateEventFor<'route'>[]>(),\n };\n\n for (const event of events) {\n addEventToBatch(batch, event);\n }\n\n return {\n events,\n route: batch.route,\n asset: batch.asset,\n i18nMessage: batch.i18nMessage,\n entity: batch.entity,\n routeByEntityModel: batch.routeByEntityModel,\n };\n}\n\ntype RawBatch = NonNullable<StoreWatchUpdatesSubscription['contelloUpdatesBatch']>;\ntype RawEvent = RawBatch['events'][number];\n\nfunction castMutationType(type: ContelloMutationType): UpdateMutationType {\n switch (type) {\n case 'CREATE': {\n return 'create';\n }\n case 'UPDATE': {\n return 'update';\n }\n case 'DELETE': {\n return 'delete';\n }\n }\n}\n\nfunction mapEvent(raw: RawEvent, resolver: ModelResolver): UpdateEvent | undefined {\n const mutation = castMutationType(raw.mutation.type);\n const target = raw.target;\n const { id, __typename } = target;\n\n switch (__typename) {\n case 'ContelloRoute': {\n if (mutation === 'delete') {\n return { id, mutation: 'delete', target: 'route' };\n }\n\n const after = mapRoute(target as StoreRouteFragment, resolver);\n\n if (!after) {\n return undefined;\n }\n\n if (mutation === 'create') {\n return { id, mutation, target: 'route', after };\n }\n\n const before =\n raw.prev?.__typename === 'ContelloRoute'\n ? (mapRoute(raw.prev as StoreRouteFragment, resolver) ?? undefined)\n : undefined;\n\n if (!before) {\n return undefined;\n }\n\n return { id, mutation, target: 'route', after, before };\n }\n\n case 'ContelloAsset': {\n return { id, mutation, target: 'asset' };\n }\n\n case 'ContelloI18nMessage': {\n return { id, mutation, target: 'i18nMessage', token: target.token };\n }\n\n default: {\n if (!__typename || !resolver.hasTypeName(__typename)) {\n return undefined;\n }\n\n return { id, mutation, target: 'entity', model: resolver.resolveModel(__typename) };\n }\n }\n}\n\nfunction safeMapEvent(raw: RawEvent, resolver: ModelResolver): UpdateEvent | undefined {\n try {\n return mapEvent(raw, resolver);\n } catch {\n return undefined;\n }\n}\n\nexport type InternalWatcher = {\n /** Multicast stream of update batches. Internal-only; the public `Store.updates$` is the AsyncIterable view. */\n readonly updates$: AsyncIterableSubject<UpdateBatch>;\n start(): void;\n stop(): void;\n};\n\nexport function createInternalWatcher(client: ContelloClient<any>, resolver: ModelResolver): InternalWatcher {\n const updates$ = createAsyncIterableSubject<UpdateBatch>();\n let controller: AbortController | undefined;\n\n return {\n updates$,\n\n start() {\n if (controller) {\n return;\n }\n\n controller = new AbortController();\n const signal = controller.signal;\n\n wrap('watcher:start', () => {\n void (async () => {\n const source = keepalive(\n () => client.subscribe<StoreWatchUpdatesSubscription>(storeWatchUpdatesDocument),\n { signal },\n );\n\n const events = mapAsync(\n source,\n (data) => (data.contelloUpdatesBatch?.events ?? [])\n // a single malformed event must not throw out of the loop and kill\n // the watcher — skip it and keep consuming the stream\n .map((e) => safeMapEvent(e, resolver))\n .filter((e): e is UpdateEvent => e !== undefined),\n );\n\n for await (const list of events) {\n if (signal.aborted) {\n return;\n }\n\n if (list.length === 0) {\n continue;\n }\n\n try {\n updates$.next(createUpdateBatch(list));\n } catch {\n // a subscriber threw — isolate it so it can't tear down the watcher\n }\n }\n })().catch(() => {\n // keepalive only exits on abort; swallow so a terminal failure\n // never surfaces as an unhandled rejection\n });\n });\n },\n\n stop() {\n controller?.abort();\n controller = undefined;\n updates$.complete();\n },\n };\n}\n","import { type ContelloClient, type Schema, type SourceDef, createContelloClient } from '@contello/client';\n\nimport {\n type Assets,\n type AssetsOptions,\n type AssetsSync,\n type AssetsSyncOptions,\n createAssetsCollection,\n createAssetsSyncCollection,\n} from './assets';\nimport { createCollection, createCollectionSync } from './collection';\nimport { type I18nMessageDef, type I18nMessages, createI18nMessagesCollection } from './i18n';\nimport { type LazyAssets, type LazyAssetsOptions, createLazyAssetsCollection } from './lazy-assets';\nimport { createLazyCollection } from './lazy-collection';\nimport { type LazyRoutes, type LazyRoutesOptions, createLazyRoutesCollection } from './lazy-routes';\nimport { ModelResolver } from './model-resolver';\nimport {\n type Routes,\n type RoutesOptions,\n type RoutesSync,\n type RoutesSyncOptions,\n createRoutesCollection,\n createRoutesSyncCollection,\n} from './routes';\nimport { createSingleton, createSingletonSync } from './singleton';\nimport { wrap } from './telemetry';\nimport type {\n BuiltInWrites,\n Collection,\n CollectionOptions,\n CollectionSync,\n CollectionSyncOptions,\n CreateStoreOptions,\n ExtractSourceResult,\n ExtractSourceWrites,\n LazyCollection,\n LazyCollectionOptions,\n ResolveSource,\n Singleton,\n SingletonOptions,\n SingletonSync,\n SingletonSyncOptions,\n SourceKeysOf,\n} from './types';\nimport { type RefreshByTtlQueue, createRefreshByTtlQueue } from './utils';\nimport { type InternalWatcher, type UpdateBatch, createInternalWatcher } from './watcher';\n\n/** Project the model-reference-name union out of a Schema generic, falling back to `string`. */\ntype ModelsOf<TSchema> = TSchema extends { models: infer M } ? keyof M & string : string;\n\ntype CollectionArg<TSchema> = SourceKeysOf<TSchema, 'entity'> | SourceDef<ModelsOf<TSchema>, 'entity'>;\ntype SingletonArg<TSchema> = SourceKeysOf<TSchema, 'singleton'> | SourceDef<ModelsOf<TSchema>, 'singleton'>;\n\ntype CollectionRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'entity'>>\n>;\n/** The write-input shape the source carries — `unknown` for sources the generator bound no mutations to. */\ntype CollectionWritesOf<TSchema, TArg> = ExtractSourceWrites<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'entity'>>\n>;\ntype RouteWrites<TSchema> = BuiltInWrites<TSchema, 'route'>;\ntype AssetWrites<TSchema> = BuiltInWrites<TSchema, 'asset'>;\ntype SingletonRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'singleton'>>\n>;\n\nexport class Store<TSchema extends Schema | undefined = undefined> {\n private _client: ContelloClient<TSchema>;\n private _resolver: ModelResolver;\n private _watcher: InternalWatcher;\n private _schema: TSchema;\n private _cleanups: (() => void)[] = [];\n private _refreshByTtl: RefreshByTtlQueue = createRefreshByTtlQueue();\n\n /**\n * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;\n * each iteration starts an independent fan-out from the shared source.\n */\n public readonly updates$: AsyncIterable<UpdateBatch>;\n\n public ping: () => Promise<void>;\n\n constructor(options: CreateStoreOptions<TSchema>) {\n const { url, project, token, schema } = options;\n\n this._schema = schema as TSchema;\n this._client = createContelloClient<TSchema>({\n url,\n project,\n token,\n schema,\n connections: options.connections,\n onConnected: options.onConnected,\n onReconnecting: options.onReconnecting,\n onError: options.onError,\n connectionEvents: options.connectionEvents,\n });\n\n this._resolver = new ModelResolver(schema?.models);\n this._watcher = createInternalWatcher(this._client, this._resolver);\n this.updates$ = this._watcher.updates$;\n this.ping = () => this._client.ping();\n }\n\n /** Resolve a string key (looked up via `schema.sources`) or a SourceDef directly to a SourceDef. */\n private _resolveSource<T extends SourceDef>(sourceOrKey: string | T): T {\n if (typeof sourceOrKey !== 'string') {\n return sourceOrKey;\n }\n\n const sources = (this._schema as Schema | undefined)?.sources;\n const source = sources?.[sourceOrKey];\n\n if (!source) {\n throw new Error(`@contello/store: no source named \"${sourceOrKey}\" in schema.sources`);\n }\n\n return source as T;\n }\n\n public get client(): ContelloClient<TSchema> {\n return this._client;\n }\n\n public async init() {\n await wrap('store:init', () => this._client.init());\n\n this._watcher.start();\n }\n\n public async destroy() {\n for (const fn of this._cleanups.splice(0)) {\n try {\n fn();\n } catch {\n // swallow — destruction is best-effort\n }\n }\n\n this._watcher.stop();\n\n await wrap('store:destroy', () => this._client.destroy());\n }\n\n // --- singleton ---\n\n public defineSingleton<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Singleton<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'singleton'>;\n const { instance, destroy } = createSingleton(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as Singleton<TMapped>;\n }\n\n public defineSingletonSync<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonSyncOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): SingletonSync<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'singleton'>;\n const { instance, destroy } = createSingletonSync(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as SingletonSync<TMapped>;\n }\n\n // --- collection ---\n\n public defineCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Collection<TMapped, CollectionWritesOf<TSchema, TArg>> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createCollection(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as unknown as Collection<TMapped, CollectionWritesOf<TSchema, TArg>>;\n }\n\n public defineCollectionSync<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionSyncOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): CollectionSync<TMapped, CollectionWritesOf<TSchema, TArg>> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createCollectionSync(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as unknown as CollectionSync<TMapped, CollectionWritesOf<TSchema, TArg>>;\n }\n\n // --- lazy collection ---\n\n public defineLazyCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: LazyCollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): LazyCollection<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createLazyCollection(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n );\n\n this._cleanups.push(destroy);\n\n return instance as LazyCollection<TMapped>;\n }\n\n // --- assets / routes / i18n (no source — built-ins) ---\n\n // --- assets ---\n\n public defineAssets(options?: AssetsOptions | undefined): Assets<AssetWrites<TSchema>> {\n const { instance, destroy } = createAssetsCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as Assets<AssetWrites<TSchema>>;\n }\n\n public defineAssetsSync(options?: AssetsSyncOptions | undefined): AssetsSync<AssetWrites<TSchema>> {\n const { instance, destroy } = createAssetsSyncCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as AssetsSync<AssetWrites<TSchema>>;\n }\n\n public defineLazyAssets(options?: LazyAssetsOptions | undefined): LazyAssets {\n const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n // --- routes ---\n\n public defineRoutes(options?: RoutesOptions | undefined): Routes<RouteWrites<TSchema>> {\n const { instance, destroy } = createRoutesCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as Routes<RouteWrites<TSchema>>;\n }\n\n public defineRoutesSync(options?: RoutesSyncOptions | undefined): RoutesSync<RouteWrites<TSchema>> {\n const { instance, destroy } = createRoutesSyncCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as RoutesSync<RouteWrites<TSchema>>;\n }\n\n public defineLazyRoutes(options?: LazyRoutesOptions | undefined): LazyRoutes {\n const { instance, destroy } = createLazyRoutesCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineI18nMessages(def: I18nMessageDef): I18nMessages {\n const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);\n\n this._cleanups.push(result.destroy);\n\n return result;\n }\n}\n\nexport function createStore<TSchema extends Schema | undefined = undefined>(\n options: CreateStoreOptions<TSchema>,\n): Store<TSchema> {\n return new Store(options);\n}\n"],"mappings":";;;;;;;AAopBA,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;AAmBjC,MAAM,0BAA0B;;;;;;;;;;;;;;AAchC,MAAM,2BAA2B;;;AAMjC,MAAM,iCAAiC;;;;;;;;;;AAUvC,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCjC,MAAa,oCAAoC;;;;;;;;;AASjD,MAAa,4BAA4B,GAAG,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGrE,MAAa,SAAS;CAAE;EAzCtB,2BAA2B;GAAE,UAAU;GAAmC,MAAM;EAAW;EAC3F,mBAAmB;GAAE,UAAU;GAA2B,MAAM;EAAe;CAwCzD;CAAY;EApClC,YAAY;GACV,UAAU,GAAG,wBAAwB,IAAI,yBAAyB,IAAI;GACtE,UAAU;GACV,cAAc;GACd,WAAW;IACT,QAAQ;KAAE,OAAO;KAAuB,WAAW,CAAC;MAAE,MAAM;MAAW,MAAM;MAA6B,MAAM;KAAQ,CAAC;KAAG,QAAQ;IAAS;IAC7I,QAAQ;KAAE,OAAO;KAAuB,WAAW,CAAC;MAAE,MAAM;MAAM,MAAM;MAAW,MAAM;KAAK,CAAC;KAAG,QAAQ;IAAW;GACvH;GACA,SAAS;GACT,eAAe;EACjB;EACA,kBAAkB;GAChB,UAAU;GACV,UAAU;GACV,cAAc;GACd,SAAS;GACT,eAAe;EACjB;EACA,YAAY;GACV,UAAU;GACV,UAAU;GACV,cAAc;GACd,WAAW;IACT,QAAQ;KAAE,OAAO;KAAuB,WAAW,CAAC;MAAE,MAAM;MAAS,MAAM;MAAuB,MAAM;KAAQ,CAAC;KAAG,QAAQ;IAAS;IACrI,QAAQ;KAAE,OAAO;KAAuB,WAAW,CAAC;MAAE,MAAM;MAAS,MAAM;MA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E3B,OAAO;CACT;CAIA,aAAoB,SAAmE;EACrF,MAAM,EAAE,UAAU,YAAY,uBAC5B,SACA,KAAK,SACL,KAAK,SAAS,UACd,KAAK,WACL,KAAK,aACP;EAEA,KAAK,UAAU,KAAK,OAAO;EAE3B,OAAO;CACT;CAEA,iBAAwB,SAA2E;EACjG,MAAM,EAAE,UAAU,YAAY,2BAC5B,SACA,KAAK,SACL,KAAK,SAAS,UACd,KAAK,WACL,KAAK,aACP;EAEA,KAAK,UAAU,KAAK,OAAO;EAE3B,OAAO;CACT;CAEA,iBAAwB,SAAqD;EAC3E,MAAM,EAAE,UAAU,YAAY,2BAC5B,SACA,KAAK,SACL,KAAK,SAAS,UACd,KAAK,SACP;EAEA,KAAK,UAAU,KAAK,OAAO;EAE3B,OAAO;CACT;CAEA,mBAA0B,KAAmC;EAC3D,MAAM,SAAS,6BAA6B,KAAK,KAAK,SAAS,KAAK,SAAS,UAAU,KAAK,aAAa;EAEzG,KAAK,UAAU,KAAK,OAAO,OAAO;EAElC,OAAO;CACT;AACF;AAEA,SAAgB,YACd,SACgB;CAChB,OAAO,IAAI,MAAM,OAAO;AAC1B"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["mapFile","mapAsset","storeSchema","storeSchema","storeSchema","storeSchema","storeSchema"],"sources":["../src/generated/graphql.ts","../src/telemetry.ts","../src/utils.ts","../src/write-buffer.ts","../src/assets.ts","../src/dependency-collector.ts","../src/collection.ts","../src/i18n.ts","../src/lru.ts","../src/lazy-assets.ts","../src/lazy-collection.ts","../src/route-path.ts","../src/routes-mapping.ts","../src/lazy-routes.ts","../src/model-resolver.ts","../src/routes.ts","../src/singleton.ts","../src/watcher.ts","../src/store.ts"],"sourcesContent":["/* eslint-disable */\n// @ts-nocheck\n/* this file is generated by contello-client — do not edit */\n\nimport type { SourceDef } from '@contello/client';\n\nexport type ContelloAssetKind = 'AUDIO' | 'DOCUMENT' | 'IMAGE' | 'OTHER' | 'VIDEO';\nexport type ContelloAssetRetentionPolicy = 'deleteIfNotUsed' | 'retain';\nexport type ContelloBatchOperationStatus = 'error' | 'success';\nexport type ContelloContentDispositionEnum = 'ATTACHMENT' | 'AUTOMATIC' | 'INLINE';\nexport type ContelloDictionaryType = 'ENTITY' | 'STATIC';\nexport type ContelloMutationType = 'CREATE' | 'DELETE' | 'UPDATE';\nexport type ContelloRouteTargetTypeEnum = 'ENTITY' | 'FILE' | 'REDIRECT' | 'SITEMAP' | 'TEXT_RESPONSE';\n\nexport type ContelloAnnotationFilterInput = {\n key?: string | undefined;\n value?: string | undefined;\n};\n\nexport type ContelloAssetAnnotationInput = {\n key: string;\n value: string;\n};\n\nexport type ContelloAssetRequestInput = {\n id?: string | undefined;\n};\n\nexport type ContelloAssetsFilterInput = {\n annotations?: (ContelloAnnotationFilterInput | undefined)[] | undefined;\n collectionReferences?: (string | undefined)[] | undefined;\n ids?: (string | undefined)[] | undefined;\n kinds?: (ContelloAssetKind | undefined)[] | undefined;\n};\n\nexport type ContelloAssetsPaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type ContelloAssetUpdateInput = {\n annotations?: ContelloAssetAnnotationInput[] | undefined;\n collectionIds?: string[] | undefined;\n collectionReferenceNames?: string[] | undefined;\n id: string;\n name?: string | undefined;\n retentionPolicy?: ContelloAssetRetentionPolicy | undefined;\n tags?: string[] | undefined;\n};\n\nexport type ContelloEntityRouteInput = {\n path: string;\n};\n\nexport type ContelloI18nMessageInput = {\n description?: string | undefined;\n example?: string | undefined;\n initialTranslations?: ContelloI18nMessageTranslationValueInput[] | undefined;\n token: string;\n translations?: ContelloI18nMessageTranslationValueInput[] | undefined;\n variables?: ContelloI18nMessageVariableInput[] | undefined;\n};\n\nexport type ContelloI18nMessagePaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type ContelloI18nMessageTranslationValueInput = {\n language: string;\n message: string;\n};\n\nexport type ContelloI18nMessageVariableInput = {\n description?: string | undefined;\n example?: string | undefined;\n name: string;\n};\n\nexport type ContelloRouteHeaderInput = {\n name: string;\n value: string;\n};\n\nexport type ContelloRouteInput = {\n customHeaders?: (ContelloRouteHeaderInput | undefined)[] | undefined;\n path: string;\n targetEntityConfig?: TargetEntityConfigInput | undefined;\n targetFileConfig?: TargetFileConfig | undefined;\n targetRedirectConfig?: TargetRedirectConfig | undefined;\n targetSitemapConfig?: TargetSitemapConfig | undefined;\n targetTextResponseConfig?: TargetTextResponseConfig | undefined;\n targetType: ContelloRouteTargetTypeEnum;\n};\n\nexport type ContelloRouteRequestInput = {\n id?: string | undefined;\n path?: string | undefined;\n};\n\nexport type ContelloRoutesRequestInput = {\n ids?: (string | undefined)[] | undefined;\n paths?: (string | undefined)[] | undefined;\n targetType?: ContelloRouteTargetTypeEnum | undefined;\n};\n\nexport type CreateDummyEntityInput = {\n attributes: DummyAttributesInput;\n createdAt?: string | undefined;\n id?: string | undefined;\n route?: ContelloEntityRouteInput | undefined;\n updatedAt?: string | undefined;\n};\n\nexport type CreateDummyRequestInput = {\n entity: CreateDummyEntityInput;\n};\n\nexport type DateTimeFilterInput = {\n between?: DateTimeRangeInput | undefined;\n equal?: string | undefined;\n exists?: boolean | undefined;\n greaterThan?: string | undefined;\n greaterThanEqual?: string | undefined;\n lessThan?: string | undefined;\n lessThanEqual?: string | undefined;\n notEqual?: string | undefined;\n};\n\nexport type DateTimeRangeInput = {\n from: string;\n to: string;\n};\n\nexport type DeleteEntityByIdInput = {\n force?: boolean | undefined;\n id: string;\n};\n\nexport type DeleteEntityByIdsInput = {\n ids: string[];\n};\n\nexport type DummiesFilterInput = {\n created?: DateTimeFilterInput | undefined;\n ids?: (string | undefined)[] | undefined;\n name?: StringFilterInput | undefined;\n route?: StringFilterInput | undefined;\n updated?: DateTimeFilterInput | undefined;\n};\n\nexport type DummiesRequestInput = {\n filter?: DummiesFilterInput | undefined;\n pagination?: PaginationInput | undefined;\n};\n\nexport type DummyAttributesInput = {\n dummy?: string | undefined;\n};\n\nexport type GetEntityByIdInput = {\n id: string;\n};\n\nexport type PaginationInput = {\n limit?: number | undefined;\n offset?: number | undefined;\n};\n\nexport type StringFilterInput = {\n contains?: string | undefined;\n endsWith?: string | undefined;\n equal?: string | undefined;\n exists?: boolean | undefined;\n in?: string[] | undefined;\n notEqual?: string | undefined;\n notIn?: string[] | undefined;\n startsWith?: string | undefined;\n};\n\nexport type TargetEntityConfigInput = {\n entityId: string;\n entityModelId: string;\n};\n\nexport type TargetFileConfig = {\n assetId: string;\n contentDisposition: ContelloContentDispositionEnum;\n};\n\nexport type TargetRedirectConfig = {\n location: string;\n responseCode: number;\n};\n\nexport type TargetSitemapConfig = {\n sitemapId: string;\n};\n\nexport type TargetTextResponseConfig = {\n content: string;\n mimeType: string;\n};\n\nexport type UpdateDummyEntityInput = {\n attributes: DummyAttributesInput;\n createdAt?: string | undefined;\n id: string;\n route?: ContelloEntityRouteInput | undefined;\n updatedAt?: string | undefined;\n};\n\nexport type UpdateDummyRequestInput = {\n entity: UpdateDummyEntityInput;\n};\n\nexport type ContelloAsset = {\n __typename?: 'ContelloAsset' | undefined;\n annotations: ContelloAssetAnnotation[];\n createdAt: string;\n id: string;\n optimized: ContelloOptimizedFile[];\n original: ContelloFile;\n preview?: ContelloFile | undefined;\n updatedAt: string;\n};\n\nexport type ContelloAssetAnnotation = {\n __typename?: 'ContelloAssetAnnotation' | undefined;\n key: string;\n value: string;\n};\n\nexport type ContelloAssetDeleteResponse = {\n __typename?: 'ContelloAssetDeleteResponse' | undefined;\n id: string;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloBatchOperationResponse = {\n __typename?: 'ContelloBatchOperationResponse' | undefined;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloDictionary = {\n __typename?: 'ContelloDictionary' | undefined;\n createdAt: string;\n description?: string | undefined;\n id: string;\n items?: (string | undefined)[] | undefined;\n name: string;\n referenceName: string;\n type: ContelloDictionaryType;\n updatedAt: string;\n};\n\nexport type ContelloEntityDeleteResponse = {\n __typename?: 'ContelloEntityDeleteResponse' | undefined;\n id: string;\n status: ContelloBatchOperationStatus;\n};\n\nexport type ContelloEntityModel = {\n __typename?: 'ContelloEntityModel' | undefined;\n description: string;\n id: string;\n isRoutable: boolean;\n name: string;\n referenceName: string;\n};\n\nexport type ContelloI18nMessage = {\n __typename?: 'ContelloI18nMessage' | undefined;\n collectionId: string;\n createdAt: string;\n deprecated: boolean;\n description?: string | undefined;\n example?: string | undefined;\n id: string;\n token: string;\n translations: ContelloI18nMessageTranslation[];\n updatedAt: string;\n variables?: ContelloI18nMessageVariable[] | undefined;\n};\n\nexport type ContelloI18nMessagePagination = {\n __typename?: 'ContelloI18nMessagePagination' | undefined;\n limit: number;\n offset: number;\n total: number;\n};\n\nexport type ContelloI18nMessageRegisterResponse = {\n __typename?: 'ContelloI18nMessageRegisterResponse' | undefined;\n ids: string[];\n};\n\nexport type ContelloI18nMessagesResponse = {\n __typename?: 'ContelloI18nMessagesResponse' | undefined;\n items: ContelloI18nMessage[];\n pagination: ContelloI18nMessagePagination;\n};\n\nexport type ContelloI18nMessageTranslation = {\n __typename?: 'ContelloI18nMessageTranslation' | undefined;\n language: string;\n value: string;\n};\n\nexport type ContelloI18nMessageUpdate = {\n __typename?: 'ContelloI18nMessageUpdate' | undefined;\n message: ContelloI18nMessage;\n mutation: ContelloMutation;\n};\n\nexport type ContelloI18nMessageVariable = {\n __typename?: 'ContelloI18nMessageVariable' | undefined;\n description?: string | undefined;\n example?: string | undefined;\n name: string;\n};\n\nexport type ContelloImageMetadata = {\n __typename?: 'ContelloImageMetadata' | undefined;\n height: number;\n width: number;\n};\n\nexport type ContelloImageOptimizationConfig = {\n __typename?: 'ContelloImageOptimizationConfig' | undefined;\n name: string;\n};\n\nexport type ContelloMutation = {\n __typename?: 'ContelloMutation' | undefined;\n type: ContelloMutationType;\n};\n\nexport type ContelloOptimizedFile = {\n __typename?: 'ContelloOptimizedFile' | undefined;\n fileName: string;\n metadata?: ContelloFileMetadata | undefined;\n mimeType: string;\n optimizationConfig?: ContelloOptimizationConfig | undefined;\n uid: string;\n};\n\nexport type ContelloProject = {\n __typename?: 'ContelloProject' | undefined;\n description: string;\n id: string;\n name: string;\n referenceName: string;\n};\n\nexport type ContelloRoute = {\n __typename?: 'ContelloRoute' | undefined;\n createdAt: string;\n customHeaders: ContelloRouteHeader[];\n id: string;\n path: string;\n target: ContelloRouteTarget;\n updatedAt: string;\n};\n\nexport type ContelloRouteHeader = {\n __typename?: 'ContelloRouteHeader' | undefined;\n name: string;\n value: string;\n};\n\nexport type ContelloRouteTargetAsset = {\n __typename?: 'ContelloRouteTargetAsset' | undefined;\n asset: ContelloAsset;\n contentDisposition: ContelloContentDispositionEnum;\n};\n\nexport type ContelloRouteTargetEntity = {\n __typename?: 'ContelloRouteTargetEntity' | undefined;\n entity?: ContelloEntityBase | undefined;\n};\n\nexport type ContelloRouteTargetRedirect = {\n __typename?: 'ContelloRouteTargetRedirect' | undefined;\n location: string;\n responseCode: number;\n};\n\nexport type ContelloRouteTargetSitemap = {\n __typename?: 'ContelloRouteTargetSitemap' | undefined;\n displayName: string;\n sitemapId: string;\n};\n\nexport type ContelloRouteTargetText = {\n __typename?: 'ContelloRouteTargetText' | undefined;\n content: string;\n mimeType: string;\n};\n\nexport type ContelloRouteUpdate = {\n __typename?: 'ContelloRouteUpdate' | undefined;\n mutation: ContelloMutation;\n route: ContelloRoute;\n};\n\nexport type ContelloUpdateBatch = {\n __typename?: 'ContelloUpdateBatch' | undefined;\n events: ContelloUpdateEvent[];\n};\n\nexport type ContelloUpdateEvent = {\n __typename?: 'ContelloUpdateEvent' | undefined;\n mutation: ContelloMutation;\n prev?: ContelloUpdatePrev | undefined;\n target: ContelloUpdateTarget;\n};\n\nexport type ContelloVideoMetadata = {\n __typename?: 'ContelloVideoMetadata' | undefined;\n height: number;\n width: number;\n};\n\nexport type ContelloVideoOptimizationConfig = {\n __typename?: 'ContelloVideoOptimizationConfig' | undefined;\n name: string;\n};\n\nexport type DummiesResponseCollection = {\n __typename?: 'DummiesResponseCollection' | undefined;\n entities: DummyEntity[];\n pagination: Pagination;\n};\n\nexport type DummyAttributes = {\n __typename?: 'DummyAttributes' | undefined;\n dummy?: string | undefined;\n};\n\nexport type DummyEntity = {\n __typename?: 'DummyEntity' | undefined;\n __model?: 'dummy' | undefined;\n attributes: DummyAttributes;\n createdAt: string;\n id: string;\n internalName: string;\n modelId: string;\n routes: ContelloRoute[];\n updatedAt: string;\n};\n\nexport type DummyEntityUpdate = {\n __typename?: 'DummyEntityUpdate' | undefined;\n entity: DummyEntity;\n mutation: ContelloMutation;\n};\n\nexport type Pagination = {\n __typename?: 'Pagination' | undefined;\n limit: number;\n offset: number;\n total: number;\n};\n\nexport type PingResult = {\n __typename?: 'PingResult' | undefined;\n response: string;\n};\n\nexport type RootMutation = {\n __typename?: 'RootMutation' | undefined;\n createContelloRoute?: ContelloRoute | undefined;\n createContelloRoutes?: ContelloRoute[] | undefined;\n createDummies?: DummyEntity[] | undefined;\n createDummy?: DummyEntity | undefined;\n deleteContelloAsset: ContelloAssetDeleteResponse;\n deleteContelloRoute: string;\n deleteDummies?: ContelloEntityDeleteResponse[] | undefined;\n deleteDummy: ContelloEntityDeleteResponse;\n registerContelloI18nMessages?: ContelloI18nMessageRegisterResponse | undefined;\n truncateContelloRoutes?: ContelloBatchOperationResponse | undefined;\n truncateDummies?: ContelloBatchOperationResponse | undefined;\n updateContelloAsset?: ContelloAsset | undefined;\n updateContelloRoute?: ContelloRoute | undefined;\n updateDummies?: DummyEntity[] | undefined;\n updateDummy?: DummyEntity | undefined;\n};\n\nexport type RootQuery = {\n __typename?: 'RootQuery' | undefined;\n contelloAsset?: ContelloAsset | undefined;\n contelloAssets?: (ContelloAsset | undefined)[] | undefined;\n contelloDictionaries?: (ContelloDictionary | undefined)[] | undefined;\n contelloEntityModels?: (ContelloEntityModel | undefined)[] | undefined;\n contelloI18nMessages?: ContelloI18nMessagesResponse | undefined;\n contelloPing: PingResult;\n contelloProject?: ContelloProject | undefined;\n contelloRoute?: ContelloRoute | undefined;\n contelloRoutes?: (ContelloRoute | undefined)[] | undefined;\n dummies: DummiesResponseCollection;\n dummy?: DummyEntity | undefined;\n};\n\nexport type RootSubscription = {\n __typename?: 'RootSubscription' | undefined;\n contelloAssets?: ContelloAsset | undefined;\n contelloAssetsBatch: ContelloAsset[];\n contelloI18nMessages?: ContelloI18nMessage | undefined;\n contelloI18nMessagesBatch: ContelloI18nMessage[];\n contelloI18nMessageUpdates?: ContelloI18nMessageUpdate | undefined;\n contelloRoutes?: ContelloRoute | undefined;\n contelloRoutesBatch: ContelloRoute[];\n contelloRouteUpdates?: ContelloRouteUpdate | undefined;\n contelloUpdates?: ContelloUpdateEvent | undefined;\n contelloUpdatesBatch?: ContelloUpdateBatch | undefined;\n dummies?: DummyEntity | undefined;\n dummiesBatch: DummyEntity[];\n dummyUpdates?: DummyEntityUpdate | undefined;\n};\n\nexport type ContelloEntityBase = {\n __typename?: string | undefined;\n createdAt: string;\n id: string;\n updatedAt: string;\n};\n\nexport type ContelloFile = {\n __typename?: string | undefined;\n fileName: string;\n metadata?: ContelloFileMetadata | undefined;\n mimeType: string;\n uid: string;\n};\n\nexport type ContelloEntity = DummyEntity;\nexport type ContelloFileMetadata = ContelloImageMetadata | ContelloVideoMetadata;\nexport type ContelloOptimizationConfig = ContelloImageOptimizationConfig | ContelloVideoOptimizationConfig;\nexport type ContelloRouteTarget = ContelloRouteTargetAsset | ContelloRouteTargetEntity | ContelloRouteTargetRedirect | ContelloRouteTargetSitemap | ContelloRouteTargetText;\nexport type ContelloUpdatePrev = ContelloRoute;\nexport type ContelloUpdateTarget = ContelloAsset | ContelloI18nMessage | ContelloRoute | DummyEntity;\n\nexport type MediaFileFragment = {\n uid: string;\n mimeType: string;\n metadata?: {\n __typename: 'ContelloImageMetadata';\n width: number;\n height: number;\n } | {\n __typename: 'ContelloVideoMetadata';\n width: number;\n height: number;\n } | undefined;\n};\n\nexport type MediaAssetFragment = {\n id: string;\n original: MediaFileFragment;\n preview?: MediaFileFragment | undefined;\n optimized: (MediaFileFragment & ({\n __typename: 'ContelloOptimizedFile';\n optimizationConfig?: {\n __typename: 'ContelloImageOptimizationConfig';\n name: string;\n } | undefined;\n }))[];\n};\n\nexport type StoreFileFragment = MediaFileFragment;\n\nexport type StoreAssetFragment = MediaAssetFragment;\n\nexport type StoreI18nMessageFragment = {\n id: string;\n token: string;\n description?: string | undefined;\n example?: string | undefined;\n translations: ({\n language: string;\n value: string;\n })[];\n};\n\nexport type StoreRouteFragment = {\n id: string;\n path: string;\n target: {\n __typename: 'ContelloRouteTargetEntity';\n entity?: {\n __typename: string;\n id: string;\n } | undefined;\n } | {\n __typename: 'ContelloRouteTargetAsset';\n asset: {\n id: string;\n original: {\n uid: string;\n mimeType: string;\n };\n };\n contentDisposition: ContelloContentDispositionEnum;\n } | {\n __typename: 'ContelloRouteTargetRedirect';\n location: string;\n responseCode: number;\n } | {\n __typename: 'ContelloRouteTargetText';\n content: string;\n mimeType: string;\n } | {\n __typename: 'ContelloRouteTargetSitemap';\n sitemapId: string;\n };\n customHeaders: ({\n name: string;\n value: string;\n })[];\n};\n\nexport type StoreRegisterI18nMessagesMutation = {\n registerContelloI18nMessages?: {\n ids: string[];\n } | undefined;\n};\n\nexport type StoreRegisterI18nMessagesMutationVariables = {\n collection: string;\n messages: ContelloI18nMessageInput[];\n};\n\nexport type StoreWatchUpdatesSubscription = {\n contelloUpdatesBatch?: {\n events: ({\n target: {\n id: string;\n } & ({\n __typename: 'ContelloRoute';\n } & StoreRouteFragment | {\n __typename: 'ContelloAsset';\n id: string;\n } | {\n __typename: 'ContelloI18nMessage';\n id: string;\n token: string;\n });\n prev?: {\n __typename: 'ContelloRoute';\n } & StoreRouteFragment | undefined;\n mutation: {\n type: ContelloMutationType;\n };\n })[];\n } | undefined;\n};\n\nexport type StoreWatchUpdatesSubscriptionVariables = Record<string, never>;\n\nconst MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {\n id\n original {\n ...MediaFile\n }\n preview {\n ...MediaFile\n }\n optimized {\n ...MediaFile\n ... on ContelloOptimizedFile {\n optimizationConfig {\n ... on ContelloImageOptimizationConfig {\n name\n }\n }\n }\n }\n}`;\nconst MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {\n uid\n mimeType\n metadata {\n ... on ContelloImageMetadata {\n width\n height\n }\n ... on ContelloVideoMetadata {\n width\n height\n }\n }\n}`;\nconst StoreAssetFragmentSchema = `fragment StoreAsset on ContelloAsset {\n ...MediaAsset\n}`;\nconst StoreFileFragmentSchema = `fragment StoreFile on ContelloFile {\n ...MediaFile\n}`;\nconst StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nMessage {\n id\n token\n description\n example\n translations {\n language\n value\n }\n}`;\nconst StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {\n id\n path\n target {\n __typename\n ... on ContelloRouteTargetEntity {\n entity {\n __typename\n ... on ContelloEntityBase {\n id\n }\n }\n }\n ... on ContelloRouteTargetAsset {\n asset {\n id\n original {\n uid\n mimeType\n }\n }\n contentDisposition\n }\n ... on ContelloRouteTargetRedirect {\n location\n responseCode\n }\n ... on ContelloRouteTargetText {\n content\n mimeType\n }\n ... on ContelloRouteTargetSitemap {\n sitemapId\n }\n }\n customHeaders {\n name\n value\n }\n}`;\n\nexport const storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {\n registerContelloI18nMessages(\n collectionReferenceName: $collection\n messages: $messages\n deprecateUnmentioned: true\n ) {\n ids\n }\n}`;\nexport const storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}\nsubscription StoreWatchUpdates {\n contelloUpdatesBatch {\n events {\n target {\n __typename\n ... on ContelloEntityBase {\n id\n }\n ... on ContelloRoute {\n ...StoreRoute\n }\n ... on ContelloAsset {\n id\n }\n ... on ContelloI18nMessage {\n id\n token\n }\n }\n prev {\n __typename\n ... on ContelloRoute {\n ...StoreRoute\n }\n }\n mutation {\n type\n }\n }\n }\n}`;\n\nexport type Operations = {\n storeRegisterI18nMessages: {\n document: string;\n kind: 'mutation';\n __result?: StoreRegisterI18nMessagesMutation | undefined;\n __variables?: StoreRegisterI18nMessagesMutationVariables | undefined;\n };\n storeWatchUpdates: {\n document: string;\n kind: 'subscription';\n __result?: StoreWatchUpdatesSubscription | undefined;\n __variables?: StoreWatchUpdatesSubscriptionVariables | undefined;\n };\n};\n\nexport type Sources = {\n storeAsset: SourceDef<'storeAsset', 'asset', StoreAssetFragment, { update: ContelloAssetUpdateInput; delete: { id: string } }>;\n storeI18nMessage: SourceDef<'storeI18nMessage', 'i18nMessage', StoreI18nMessageFragment>;\n storeRoute: SourceDef<'storeRoute', 'route', StoreRouteFragment, { create: ContelloRouteInput; update: ContelloRouteInput; delete: { id: string } }>;\n};\n\nconst operations: Operations = {\n storeRegisterI18nMessages: { document: storeRegisterI18nMessagesDocument, kind: 'mutation' },\n storeWatchUpdates: { document: storeWatchUpdatesDocument, kind: 'subscription' },\n};\n\nconst sources: Sources = {\n storeAsset: {\n document: `${MediaFileFragmentSchema}\\n${MediaAssetFragmentSchema}\\n${StoreAssetFragmentSchema}`,\n fragment: 'StoreAsset',\n subscription: 'contelloAssetsBatch',\n mutations: {\n update: { field: 'updateContelloAsset', arguments: [{ name: 'request', type: 'ContelloAssetUpdateInput!', from: 'input' }], result: 'entity' },\n delete: { field: 'deleteContelloAsset', arguments: [{ name: 'id', type: 'String!', from: 'id' }], result: 'idObject' },\n },\n __model: 'storeAsset',\n __cardinality: 'asset',\n },\n storeI18nMessage: {\n document: StoreI18nMessageFragmentSchema,\n fragment: 'StoreI18nMessage',\n subscription: 'contelloI18nMessagesBatch',\n __model: 'storeI18nMessage',\n __cardinality: 'i18nMessage',\n },\n storeRoute: {\n document: StoreRouteFragmentSchema,\n fragment: 'StoreRoute',\n subscription: 'contelloRoutesBatch',\n mutations: {\n create: { field: 'createContelloRoute', arguments: [{ name: 'route', type: 'ContelloRouteInput!', from: 'input' }], result: 'entity' },\n update: { field: 'updateContelloRoute', arguments: [{ name: 'route', type: 'ContelloRouteInput!', from: 'input' }], result: 'entity' },\n delete: { field: 'deleteContelloRoute', arguments: [{ name: 'id', type: 'String', from: 'id' }], result: 'idScalar' },\n },\n __model: 'storeRoute',\n __cardinality: 'route',\n },\n};\n\nconst models = {\n dummy: 'DummyEntity',\n} as const;\n\nexport const schema = { operations, sources, models };\nexport type Schema = typeof schema;","import { createOperationTelemetry } from '@contello/opentelemetry';\n\nexport const { wrap } = createOperationTelemetry('@contello/store');\n","import { AsyncLocalStorage } from 'node:async_hooks';\n\nimport { type AsyncIterableSubject, createAsyncIterableSubject, retryWithBackoff } from '@entwico/dash/async';\n\n/**\n * default `cache.ttl` applied across all store kinds. eager stores (collections, singletons)\n * use it as the interval for a periodic full refresh; lazy stores use it as the per-item\n * LRU eviction window. 3 hours.\n */\nexport const DEFAULT_TTL_MS = 3 * 60 * 60 * 1000;\n\n/**\n * default `cache.max` (LRU capacity) for lazy stores — the maximum number of items kept\n * before least-recently-used eviction.\n */\nexport const DEFAULT_LRU_MAX = 1000;\n\n/**\n * resolves the consumer-supplied `ttl` (number | false | undefined) into a runtime\n * value: undefined → default, false or 0 → disabled (undefined), positive → as-is.\n */\nexport function resolveTtl(ttl: number | false | undefined): number | undefined {\n if (ttl === undefined) return DEFAULT_TTL_MS;\n if (ttl === false || ttl <= 0) return undefined;\n\n return ttl;\n}\n\n/**\n * Retries the refreshes of one store until they succeed. A source that keeps failing would\n * otherwise be retried for the life of the process, with the store it belonged to kept in memory:\n * `stop()` on destroy ends every retry that is still running.\n */\nexport type RefreshRetry = {\n /** Answers whether `fn` succeeded: `false` once the store was destroyed. */\n run(fn: () => Promise<unknown>): Promise<boolean>;\n stop(): void;\n};\n\nexport function createRefreshRetry(): RefreshRetry {\n const controller = new AbortController();\n\n return {\n async run(fn) {\n try {\n await retryWithBackoff(fn, { signal: controller.signal });\n\n return true;\n } catch {\n // retryWithBackoff gives up only when the signal aborts\n return false;\n }\n },\n stop() {\n controller.abort();\n },\n };\n}\n\n/**\n * creates a coalescing refresh scheduler with exponential-backoff retry on failure.\n *\n * at most one refresh runs at a time. if a new refresh is requested while one is in-flight,\n * it is queued as pending — the queued slot keeps the latest `kind` passed via\n * scheduleRefresh. once the in-flight refresh completes, at most one queued refresh\n * starts, with that latest kind — collapsing any number of intermediate requests into one.\n *\n * on error, retries with exponential backoff until `retry` is stopped. the projected value keeps serving\n * the stale cached value throughout (SWR). the `onRefreshed` callback receives the kind that\n * triggered the just-completed refresh.\n */\nexport function createRefresher<K>(\n fn: () => Promise<unknown>,\n onRefreshed: (kind: K) => void,\n retry: RefreshRetry,\n): (kind: K) => void {\n let refreshing = false;\n let inFlightKind: K | undefined;\n let pendingKind: { kind: K } | undefined;\n\n function scheduleRefresh(kind: K): void {\n if (refreshing) {\n pendingKind = { kind };\n\n return;\n }\n\n refreshing = true;\n inFlightKind = kind;\n\n void retry.run(fn).then((refreshed) => {\n if (!refreshed) {\n return;\n }\n\n const finished = inFlightKind as K;\n\n refreshing = false;\n inFlightKind = undefined;\n onRefreshed(finished);\n\n if (!pendingKind) {\n return;\n }\n\n const { kind: next } = pendingKind;\n\n pendingKind = undefined;\n scheduleRefresh(next);\n });\n }\n\n return scheduleRefresh;\n}\n\n/**\n * Refresh channel: bundles the `refresh$` multicast stream and the `onRefresh` callback\n * so both fire on every emission. Used by every eager and lazy store that exposes refresh\n * events.\n */\nexport type RefreshChannel<TEvent> = {\n readonly stream$: AsyncIterableSubject<TEvent>;\n emit(event: TEvent): void;\n complete(): void;\n};\n\nexport function createRefreshChannel<TEvent>(\n onRefresh?: ((event: TEvent) => void) | undefined,\n): RefreshChannel<TEvent> {\n const stream$ = createAsyncIterableSubject<TEvent>();\n\n return {\n stream$,\n emit(event) {\n stream$.next(event);\n onRefresh?.(event);\n },\n complete() {\n stream$.complete();\n },\n };\n}\n\n/**\n * TTL orchestrator: owns the safety-net timer for eager stores. Calls into `run` after\n * `ttl` ms have passed since the last `mark()` (or `reset()`); `run` is responsible for\n * actually fetching + re-arming via another `mark()` once it succeeds. `clear()` cancels\n * the timer on destroy. When `ttl` is undefined the orchestrator is a no-op.\n */\nexport type TtlOrchestrator = {\n /** start (or restart) the timer. consumers call this on first successful full fetch and after every later one. */\n mark(): void;\n /** cancel any pending timer for good; for destroy. */\n clear(): void;\n};\n\nexport function createTtlOrchestrator(options: { ttl: number | undefined; run: () => void }): TtlOrchestrator {\n // the timer is armed by whoever loads or refreshes the store, often a request. armed inside that\n // request's async context it would keep the context for as long as the store lives, and run\n // every later refresh in it\n const runInOwnContext = AsyncLocalStorage.snapshot();\n let timer: ReturnType<typeof setTimeout> | undefined;\n let cleared = false;\n\n return {\n mark() {\n // a refresh that was in flight when the store was destroyed must not arm the timer again\n if (cleared) {\n return;\n }\n\n if (timer !== undefined) {\n clearTimeout(timer);\n timer = undefined;\n }\n\n if (options.ttl === undefined) {\n return;\n }\n\n timer = runInOwnContext(() => setTimeout(options.run, options.ttl));\n },\n clear() {\n cleared = true;\n\n if (timer === undefined) {\n return;\n }\n\n clearTimeout(timer);\n timer = undefined;\n },\n };\n}\n\n/**\n * FIFO queue for ttl-fired refreshes on eager stores.\n * Concurrency is fixed at 1 to avoid DDOSing the server\n */\nexport type RefreshByTtlQueue = {\n enqueue(task: () => Promise<unknown>): void;\n};\n\nexport function createRefreshByTtlQueue(): RefreshByTtlQueue {\n const waiting: (() => Promise<unknown>)[] = [];\n let running = false;\n\n function next(): void {\n if (running) return;\n\n const task = waiting.shift();\n\n if (!task) return;\n\n running = true;\n\n void (async () => {\n try {\n await task();\n } catch {\n // misbehaving task — keep the queue draining\n } finally {\n running = false;\n next();\n }\n })();\n }\n\n return {\n enqueue(task) {\n waiting.push(task);\n next();\n },\n };\n}\n","/**\n * Entities answered by a write, parked until the refresh that write schedules takes them into the\n * cache. A write mutation selects the source's fragment, so it comes back in exactly the shape the\n * subscription yields and the refresh can be served from here instead of going over the wire — the\n * entity still travels the one path that maps it, collects its dependencies, sorts and freezes it.\n *\n * A parked entity is a shortcut, never an authority. `ProjectedMap` debounces and coalesces partial\n * refreshes, so a refresh that some *other* change scheduled can be the one that consumes it —\n * answering an upstream event out of the local write and silently dropping the remote change until\n * the next full refresh. `awaitingUpstream` closes that window from both sides: it drops what is\n * already parked for those ids and refuses to park them again until the upstream refresh settles,\n * whichever of the two arrives first.\n *\n * `release` covers the rest: an id that was deleted, and a write whose own refresh failed — which\n * would otherwise leave the entity here to answer some unrelated partial refresh much later.\n */\nexport type WriteBuffer<T> = {\n /** Parks a written entity — ignored while an upstream refresh for that id is outstanding. */\n park(id: string, entity: T): void;\n release(ids: Iterable<string>): void;\n clear(): void;\n /** Splits requested ids into what this buffer answers (consuming it) and what must be fetched. */\n take(ids: readonly string[]): { written: T[]; missing: string[] };\n /**\n * Marks ids whose server version is being refetched, so nothing local answers that refresh.\n * Returns the function that unmarks them once it has settled.\n */\n awaitingUpstream(ids: readonly string[]): () => void;\n};\n\nexport function createWriteBuffer<T>(): WriteBuffer<T> {\n const parked = new Map<string, T>();\n // refresh counts, not flags — refreshes for the same id can overlap and must each unmark once\n const awaited = new Map<string, number>();\n\n return {\n park(id, entity) {\n if (!awaited.has(id)) {\n parked.set(id, entity);\n }\n },\n\n release(ids) {\n for (const id of ids) {\n parked.delete(id);\n }\n },\n\n clear() {\n parked.clear();\n },\n\n take(ids) {\n const written: T[] = [];\n const missing: string[] = [];\n\n for (const id of ids) {\n const entity = parked.get(id);\n\n if (entity === undefined) {\n missing.push(id);\n } else {\n parked.delete(id);\n written.push(entity);\n }\n }\n\n return { written, missing };\n },\n\n awaitingUpstream(ids) {\n for (const id of ids) {\n parked.delete(id);\n awaited.set(id, (awaited.get(id) ?? 0) + 1);\n }\n\n return () => {\n for (const id of ids) {\n const count = awaited.get(id) ?? 0;\n\n if (count > 1) {\n awaited.set(id, count - 1);\n } else {\n awaited.delete(id);\n }\n }\n };\n },\n };\n}\n","import {\n BUILT_IN_MUTATIONS,\n type ContelloClient,\n type DownloadResult,\n type ProxyResult,\n type SourceMutationKind,\n type SourceMutationValues,\n type UploadData,\n type UploadMetadata,\n type UploadOptions,\n createSourceMutation,\n createSourceMutationVariables,\n createSourceSubscription,\n} from '@contello/client';\nimport type { MaybePromise, ReadonlyDeep } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\n\nimport { type StoreAssetFragment, type StoreFileFragment, schema as storeSchema } from './generated/graphql';\nimport type { StoreAsset, StoreFile } from './lazy-assets';\nimport { wrap } from './telemetry';\nimport type { CacheOptions, CollectionWrites, Created, RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createRefreshRetry, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\nimport { createWriteBuffer } from './write-buffer';\n\nexport type AssetsOptions = {\n cache?: CacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type AssetsSyncOptions = {\n cache?: SyncCacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\n/**\n * There is no `create`: an asset comes into being through `upload()`, which is the transport, not\n * a mutation. `update` patches the mutable metadata — fields left out keep their value.\n */\nexport type Assets<TWrites = unknown> = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): MaybePromise<ReadonlyDeep<StoreAsset> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreAsset>>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n} & CollectionWrites<StoreAsset, TWrites>;\n\nexport type AssetsSync<TWrites = unknown> = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): ReadonlyDeep<StoreAsset> | undefined;\n get(ids: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreAsset>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n} & CollectionWrites<StoreAsset, TWrites>;\n\nfunction mapFile(raw: StoreFileFragment): StoreFile {\n return {\n uid: raw.uid,\n mimeType: raw.mimeType,\n metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : undefined,\n };\n}\n\nfunction mapAsset(raw: StoreAssetFragment): StoreAsset {\n return {\n id: raw.id,\n original: mapFile(raw.original),\n preview: raw.preview ? mapFile(raw.preview) : undefined,\n optimized: raw.optimized.map((file) => mapFile(file)),\n };\n}\n\nexport function createAssetsCollection(\n options: AssetsOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Assets> {\n const opts = options ?? {};\n const cache = {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n } as const;\n\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const retry = createRefreshRetry();\n const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh('ttl') });\n let loaded = false;\n\n // the built-in asset source plus its fixed write bindings — `mutations` is constant for every\n // Contello schema, so the store carries it rather than depending on a regenerated bundle\n const assetSource = { ...storeSchema.sources.storeAsset, mutations: BUILT_IN_MUTATIONS.asset };\n const assetsSourceDoc = createSourceSubscription(assetSource);\n\n const writeBuffer = createWriteBuffer<StoreAssetFragment>();\n\n function fetchAssets(ids: string[] | undefined): Promise<StoreAssetFragment[]> {\n return concatAsync(\n mapAsync(\n client.subscribe<{ source: StoreAssetFragment[] }>(assetsSourceDoc, { ids }),\n (data) => data.source,\n ),\n );\n }\n\n async function fetchOrTakeWritten(ids: string[] | undefined): Promise<StoreAssetFragment[]> {\n if (ids === undefined) {\n writeBuffer.clear();\n\n return fetchAssets(undefined);\n }\n\n const { written, missing } = writeBuffer.take(ids);\n\n if (missing.length === 0) {\n return written;\n }\n\n const fetched = await fetchAssets(missing);\n\n return written.length === 0 ? fetched : [...written, ...fetched];\n }\n\n const projected = new ProjectedMap<string, StoreAsset>({\n key: (asset) => asset.id,\n values: (ids) =>\n wrap('assets', async () => {\n const rawItems = await fetchOrTakeWritten(ids);\n const items = rawItems.map((item) => mapAsset(item));\n\n if (ids === undefined && !loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((a) => a.id));\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(\n () => retry.run(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n // upstream is authoritative for these until the refetch lands — no local write may answer it\n const settled = writeBuffer.awaitingUpstream(refreshIds);\n\n void retry.run(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n }).finally(settled);\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded || batch.asset.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.asset) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (cache.eviction === 'clear') {\n writeBuffer.clear();\n projected.clear();\n\n return;\n }\n\n writeBuffer.release(deleted);\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n async function runMutation(kind: SourceMutationKind, values: SourceMutationValues): Promise<unknown> {\n const binding = assetSource.mutations?.[kind];\n\n if (!binding) {\n throw new Error(`@contello/store: assets cannot ${kind} — the schema exposes no ${kind} mutation for assets`);\n }\n\n const response = await client.execute<{ result: unknown }>(\n createSourceMutation(assetSource, kind),\n createSourceMutationVariables(binding, values),\n );\n\n if (response?.result === undefined || response.result === null) {\n throw new Error(`@contello/store: ${kind} on assets returned nothing`);\n }\n\n return response.result;\n }\n\n const writes = {\n async update(input: unknown): Promise<ReadonlyDeep<StoreAsset>> {\n const raw = (await runMutation('update', { input })) as StoreAssetFragment;\n\n writeBuffer.park(raw.id, raw);\n\n let map;\n\n try {\n map = await projected.refresh([raw.id]);\n } finally {\n writeBuffer.release([raw.id]);\n }\n\n emit([raw.id], 'write');\n\n const asset = map.get(raw.id);\n\n if (!asset) {\n throw new Error(\n `@contello/store: wrote asset \"${raw.id}\" but it is not in the cache — ` +\n `a concurrent full refresh did not return it`,\n );\n }\n\n return asset;\n },\n\n async delete(id: string): Promise<void> {\n await runMutation('delete', { input: { id }, id });\n\n writeBuffer.release([id]);\n projected.delete([id]);\n emit([id], 'write');\n },\n };\n\n const instance: Assets = {\n ...writes,\n refresh$: channel.stream$,\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n upload(data, meta, options) {\n return client.upload(data, meta, options);\n },\n\n download(fileId) {\n return client.download(fileId);\n },\n\n proxyHls(path, signal) {\n return client.proxyHls(path, signal);\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n retry.stop();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createAssetsSyncCollection(\n options: AssetsSyncOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): Created<AssetsSync> {\n const { instance: base, destroy } = createAssetsCollection(options, client, updates$, refreshByTtl);\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`assets.${method}() is not initialized yet — call assets.load() first`);\n }\n\n return value;\n }\n\n return {\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n },\n destroy,\n };\n}\n","import type { ModelResolver } from './model-resolver';\nimport type { UpdateEvent } from './watcher';\n\ntype NonEntityTarget = Exclude<UpdateEvent['target'], 'entity'>;\n\n/**\n * passed to `map()` so the mapper can declare which external entities this item depends on.\n * calls are collected during mapping and indexed once the item key is known.\n * designed to be destructurable: `map(raw, { track, trackRoute }) => ...`\n *\n * `track()` inspects `__typename` to auto-detect the dependency type:\n * - `ContelloAsset` → asset dep\n * - `ContelloRoute` → route dep\n * - `*Entity` → entity dep\n * - anything else → throws\n *\n * explicit methods (`trackEntity`, `trackAsset`, `trackRoute`) are available\n * for cases where only an id is known without the full GraphQL object.\n */\nexport type MapperContext<TModels extends string = string> = {\n track(obj: { __typename: string; id: string }): void;\n trackEntity(typename: TModels, id: string): void;\n trackAsset(id: string): void;\n trackRoute(id: string): void;\n};\n\n// shared empty result so the hot path (an event no item depends on) allocates\n// nothing — callers only ever iterate or read `.size`, never mutate.\nconst EMPTY_KEYS: ReadonlySet<never> = new Set();\n\n// dep key for non-entity targets (route, asset) — `${target}\\0${id}`\nfunction createDependencyKey(target: NonEntityTarget, id: string): string {\n return `${target}\\0${id}`;\n}\n\n// dep key for entity deps — prefixed with `entity\\0` to avoid collisions with other targets\n// e.g. a model named 'route' would otherwise collide with ref.route() deps\nfunction createEntityDependencyKey(typename: string, id: string): string {\n return `entity\\0${typename}\\0${id}`;\n}\n\n// key used to register and look up route-target interest deps.\n// separate from createDependencyKey because the value is a compound (typename \\0 id) pair itself.\nfunction createRouteTargetKey(typename: string, id: string): string {\n return `routeTarget\\0${typename}\\0${id}`;\n}\n\n/**\n * bidirectional dependency index for a single collection.\n *\n * during each map cycle, `createContext` is called per item. it creates a `MapperContext` the mapper\n * uses to declare cross-entity dependencies, and a `register(key)` function the caller invokes\n * once the item key is known. `register` flushes the collected deps into two maps:\n *\n * forwardIndex: item key -> set of dep keys it declared\n * reverseIndex: dep key -> set of item keys that declared it\n *\n * the reverse map is the hot path: given an update event (typename + id), `getAffectedKeys()`\n * looks up the dep key and returns all item keys that need to be invalidated.\n *\n * lifecycle per map cycle:\n * 1. createContext(fn) — allocates deps array, creates MapperContext, calls fn(ctx, register)\n * 2. fn calls map(raw, ctx) — mapper runs, calls track methods, fills deps array\n * 3. fn calls register(key) — real item key is known, deps written into both maps\n */\nexport class DependencyCollector<TKey, TModels extends string = string> {\n /** dep key -> item keys that declared a dependency on it */\n private reverseIndex = new Map<string, Set<TKey>>();\n /** item key -> dep keys it currently declares */\n private forwardIndex = new Map<TKey, Set<string>>();\n\n constructor(\n /** the model name of the owning collection, used to form route-target dep keys */\n private readonly model: string,\n /** resolver for mapping between model names and __typename */\n private readonly resolver: ModelResolver,\n ) {}\n\n private mergeRouteTargetKeys(\n existing: Set<TKey> | undefined,\n entityType: string,\n entityId: string,\n ): Set<TKey> | undefined {\n const items = this.reverseIndex.get(createRouteTargetKey(entityType, entityId));\n\n if (!items) {\n return existing;\n }\n\n return existing ? existing.union(items) : items;\n }\n\n private warnIfUnknownModel(model: string): void {\n if (!this.resolver.hasModel(model)) {\n console.warn(\n `[contello/store] tracking model \"${model}\" which is not in models — updates for this model will be ignored`,\n );\n }\n }\n\n /**\n * removes all index entries for one item key.\n * cleans up the forward entry and removes the item from every reverse set it appeared in.\n * if a reverse set becomes empty after removal, it is deleted to avoid memory leaks.\n */\n private clearItem(key: TKey): void {\n const existingDeps = this.forwardIndex.get(key);\n\n if (!existingDeps) {\n return;\n }\n\n for (const dk of existingDeps) {\n const set = this.reverseIndex.get(dk);\n\n if (!set) {\n continue;\n }\n\n set.delete(key);\n\n if (set.size === 0) {\n this.reverseIndex.delete(dk);\n }\n }\n\n this.forwardIndex.delete(key);\n }\n\n /**\n * creates a scoped MapperContext for one item and runs `fn` with it.\n * `fn` receives the context (for declaring deps during mapping) and a `register(key)` function\n * that must be called once the item key is known — it writes all declared deps into the index.\n * returns whatever `fn` returns, preserving MaybePromise semantics.\n */\n createContext<T>(fn: (ctx: MapperContext<TModels>, register: (key: TKey) => void) => T): T {\n const deps: string[] = [];\n\n const ctx: MapperContext<TModels> = {\n track: (obj) => {\n if (!obj.id) {\n throw new Error(`track(): object with __typename \"${obj.__typename}\" has no \"id\" field`);\n }\n\n switch (obj.__typename) {\n case 'ContelloAsset': {\n deps.push(createDependencyKey('asset', obj.id));\n break;\n }\n case 'ContelloRoute': {\n deps.push(createDependencyKey('route', obj.id));\n break;\n }\n default: {\n const model = this.resolver.getModel(obj.__typename);\n\n if (!model) {\n throw new Error(\n `track(): unexpected __typename \"${obj.__typename}\" — expected ContelloAsset, ContelloRoute, or a known entity model`,\n );\n }\n\n deps.push(createEntityDependencyKey(model, obj.id));\n }\n }\n },\n trackEntity: (model, id) => {\n this.warnIfUnknownModel(model);\n deps.push(createEntityDependencyKey(model, id));\n },\n trackAsset: (id) => {\n deps.push(createDependencyKey('asset', id));\n },\n trackRoute: (id) => {\n deps.push(createDependencyKey('route', id));\n },\n };\n\n const register = (key: TKey) => {\n this.clearItem(key);\n\n deps.push(createRouteTargetKey(this.model, String(key)));\n\n const fwd = new Set<string>();\n\n for (const dk of deps) {\n fwd.add(dk);\n\n let set = this.reverseIndex.get(dk);\n\n if (!set) {\n set = new Set();\n this.reverseIndex.set(dk, set);\n }\n\n set.add(key);\n }\n\n if (fwd.size > 0) {\n this.forwardIndex.set(key, fwd);\n }\n };\n\n return fn(ctx, register);\n }\n\n /**\n * looks up which item keys are affected by an update event.\n * for route events, checks route-target deps for both the new and previous entity targets.\n */\n getAffectedKeys(event: UpdateEvent): ReadonlySet<TKey> {\n if (event.target === 'entity') {\n return this.reverseIndex.get(createEntityDependencyKey(event.model, event.id)) ?? EMPTY_KEYS;\n }\n\n let affected = this.reverseIndex.get(createDependencyKey(event.target, event.id));\n\n if (event.target === 'route') {\n if ('after' in event && event.after.type === 'entity') {\n affected = this.mergeRouteTargetKeys(affected, event.after.model, event.after.entityId);\n }\n\n if ('before' in event && event.before.type === 'entity') {\n affected = this.mergeRouteTargetKeys(affected, event.before.model, event.before.entityId);\n }\n }\n\n return affected ?? EMPTY_KEYS;\n }\n\n /** removes all recorded deps for a single item (called on eviction) */\n removeItem(key: TKey): void {\n this.clearItem(key);\n }\n\n /** drops all recorded deps — used when clearing the entire cache */\n clear(): void {\n this.reverseIndex.clear();\n this.forwardIndex.clear();\n }\n\n /**\n * removes index entries for any item key NOT present in `keys`.\n * called after a full re-fetch to prune refs from items that were deleted upstream.\n */\n retainOnly(keys: Set<TKey>): void {\n for (const key of this.forwardIndex.keys()) {\n if (!keys.has(key)) {\n this.clearItem(key);\n }\n }\n }\n}\n","import {\n type ContelloClient,\n type SourceDef,\n type SourceMutationKind,\n type SourceMutationValues,\n createSourceMutation,\n createSourceMutationVariables,\n createSourceSubscription,\n} from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeAll, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\nimport { DependencyCollector } from './dependency-collector';\nimport type { ModelResolver } from './model-resolver';\nimport { wrap } from './telemetry';\nimport type {\n Collection,\n CollectionOptions,\n CollectionSync,\n CollectionSyncOptions,\n CollectionWrites,\n Created,\n ExtractSourceResult,\n ExtractSourceWrites,\n RefreshEvent,\n RefreshKind,\n} from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createRefreshRetry, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\nimport { createWriteBuffer } from './write-buffer';\n\nfunction fetchCollection<S extends SourceDef<string, 'entity'>>(\n source: S,\n client: ContelloClient<any>,\n ids: string[] | undefined,\n): Promise<ExtractSourceResult<S>[]> {\n return concatAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<S>[] }>(createSourceSubscription(source), { ids }),\n (r) => r.source,\n ),\n );\n}\n\n/**\n * Runs one write mutation of the source. A create/update selects the source's fragment, so the\n * answer is a raw entity in exactly the shape the source subscription yields — the cache takes it\n * from there. A delete only carries an id.\n */\nasync function runMutation<TRaw extends { id: string }>(\n source: SourceDef<string, 'entity'>,\n client: ContelloClient<any>,\n name: string,\n kind: SourceMutationKind,\n values: SourceMutationValues,\n): Promise<TRaw> {\n const binding = source.mutations?.[kind];\n\n if (!binding) {\n throw new Error(\n `@contello/store: collection \"${name}\" cannot ${kind} — the schema exposes no ${kind} mutation ` +\n `for model \"${source.__model}\"`,\n );\n }\n\n const document = createSourceMutation(source, kind);\n const response = await client.execute<{ result: TRaw | undefined }>(\n document,\n createSourceMutationVariables(binding, values),\n );\n\n if (!response?.result) {\n throw new Error(`@contello/store: ${kind} on collection \"${name}\" returned no entity`);\n }\n\n return response.result;\n}\n\nexport function createCollection<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: CollectionOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Collection<TMapped, ExtractSourceWrites<TSource>>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n },\n };\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const retry = createRefreshRetry();\n const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runFullRefresh('ttl') });\n let loaded = false;\n\n const writeBuffer = createWriteBuffer<ExtractSourceResult<TSource>>();\n\n function fetchOrTakeWritten(ids: string[] | undefined): MaybePromise<ExtractSourceResult<TSource>[]> {\n if (ids === undefined) {\n writeBuffer.clear();\n\n return fetchCollection(source, client, undefined);\n }\n\n const { written, missing } = writeBuffer.take(ids);\n\n if (missing.length === 0) {\n return written;\n }\n\n if (written.length === 0) {\n return fetchCollection(source, client, missing);\n }\n\n return maybeThen(fetchCollection(source, client, missing), (fetched) => [...written, ...fetched]);\n }\n\n const projected = new ProjectedMap<string, TMapped>({\n key: (item) => item.id,\n values: (ids) =>\n wrap(\n `collection:${_def.name}`,\n () => maybeThen(fetchOrTakeWritten(ids), async (rawItems) => {\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const items = await maybeAll(\n rawItems.map(\n (item) => dependencyCollector.createContext(\n (ref, register) => maybeThen(mapFn(item, ref), (mapped) => {\n register(mapped.id);\n\n return mapped;\n }),\n ),\n ),\n );\n\n if (ids === undefined) {\n dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));\n\n // start tracking refresh by ttl on first successful full fetch\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((item) => item.id));\n }\n } else {\n const returnedIds = new Set(items.map((item) => item.id));\n\n for (const id of ids) {\n if (!returnedIds.has(id)) {\n dependencyCollector.removeItem(id);\n }\n }\n }\n\n return items;\n }),\n ),\n sort: opts.sort,\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(\n () => retry.run(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n // upstream is authoritative for these until the refetch lands — no local write may answer it\n const settled = writeBuffer.awaitingUpstream(refreshIds);\n\n void retry.run(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n }).finally(settled);\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n const ownEvents = batch.entity.get(_def.model) ?? [];\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of ownEvents) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n const depAffected = new Set<string>();\n\n for (const event of batch.events) {\n for (const id of dependencyCollector.getAffectedKeys(event)) {\n depAffected.add(id);\n }\n }\n\n if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) {\n return;\n }\n\n if (_def.cache.eviction === 'clear') {\n dependencyCollector.clear();\n writeBuffer.clear();\n projected.clear();\n\n return;\n }\n\n writeBuffer.release(deleted);\n\n for (const id of deleted) {\n dependencyCollector.removeItem(id);\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n const refreshIds = upserted.union(depAffected);\n\n for (const id of deleted) {\n refreshIds.delete(id);\n }\n\n runPartialRefresh([...refreshIds], deleted);\n });\n\n /** Puts a written entity into the cache through the normal refresh path and returns it mapped. */\n async function takeIntoCache(entity: ExtractSourceResult<TSource> & { id: string }): Promise<ReadonlyDeep<TMapped>> {\n writeBuffer.park(entity.id, entity);\n\n let map;\n\n try {\n map = await projected.refresh([entity.id]);\n } finally {\n writeBuffer.release([entity.id]);\n }\n\n emit([entity.id], 'write');\n\n const item = map.get(entity.id);\n\n if (!item) {\n throw new Error(\n `@contello/store: collection \"${_def.name}\" wrote entity \"${entity.id}\" but it is not in the cache — ` +\n `a concurrent full refresh did not return it`,\n );\n }\n\n return item;\n }\n\n /**\n * One method per mutation the source binds — a model the schema exposes no `createX` for has\n * no `create`, matching what `CollectionWrites` types. Permission is not decided here: the\n * server rejects a write the token may not run.\n */\n function createWrites(): CollectionWrites<TMapped, ExtractSourceWrites<TSource>> {\n const out: Record<string, unknown> = {};\n\n if (source.mutations?.create) {\n out['create'] = async (input: unknown) =>\n takeIntoCache(await runMutation(source, client, _def.name, 'create', { input }));\n }\n\n if (source.mutations?.update) {\n out['update'] = async (input: unknown) =>\n takeIntoCache(await runMutation(source, client, _def.name, 'update', { input }));\n }\n\n if (source.mutations?.delete) {\n out['delete'] = async (id: string, options?: Record<string, unknown> | undefined) => {\n await runMutation(source, client, _def.name, 'delete', { input: { ...options, id }, id });\n\n writeBuffer.release([id]);\n dependencyCollector.removeItem(id);\n projected.delete([id]);\n emit([id], 'write');\n };\n }\n\n return out as CollectionWrites<TMapped, ExtractSourceWrites<TSource>>;\n }\n\n const instance: Collection<TMapped, ExtractSourceWrites<TSource>> = {\n name: _def.name,\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n getAll(): MaybePromise<ReadonlyArray<ReadonlyDeep<TMapped>>> {\n return projected.getAll();\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n\n ...createWrites(),\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n retry.stop();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createCollectionSync<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: CollectionSyncOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<CollectionSync<TMapped, ExtractSourceWrites<TSource>>> {\n const { instance: base, destroy } = createCollection<TSource, TMapped, TModels>(\n source,\n options,\n client,\n updates$,\n resolver,\n refreshByTtl,\n );\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`collection \"${base.name}\".${method}() is not initialized yet — call collection.load() first`);\n }\n\n return value;\n }\n\n return {\n // the write half passes through untouched — a mutation is a round trip either way\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n getAll(): ReadonlyArray<ReadonlyDeep<TMapped>> {\n return assertSync(base.getAll(), 'getAll');\n },\n } as unknown as CollectionSync<TMapped, ExtractSourceWrites<TSource>>,\n destroy,\n };\n}\n","import { type ContelloClient, createSourceSubscription } from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\nimport {\n type ContelloI18nMessageInput,\n type StoreI18nMessageFragment,\n type StoreRegisterI18nMessagesMutation,\n storeRegisterI18nMessagesDocument,\n schema as storeSchema,\n} from './generated/graphql';\nimport { wrap } from './telemetry';\nimport type { RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\n\nimport {\n type RefreshByTtlQueue,\n createRefreshChannel,\n createRefreshRetry,\n createRefresher,\n createTtlOrchestrator,\n resolveTtl,\n} from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type I18nTranslation = {\n language: string;\n value: string;\n};\n\nexport type I18nVariableInput = {\n name: string;\n description: string;\n example: string;\n};\n\nexport type I18nInitialTranslation = {\n language: string;\n message: string;\n};\n\nexport type I18nMessageRegistrationDefinition = {\n token: string;\n example?: string | undefined;\n description?: string | undefined;\n variables?: I18nVariableInput[] | undefined;\n /** always overwrites existing translations for this token */\n translations?: I18nInitialTranslation[] | undefined;\n /** only applied when the token is newly registered (existing translations are preserved) */\n initialTranslations?: I18nInitialTranslation[] | undefined;\n};\n\nexport type I18nMessageDef = {\n collection: string;\n cache?: SyncCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type I18nMessage = {\n id: string;\n token: string;\n translations: Map<string, string>;\n};\n\nexport type I18nMessages = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): MaybePromise<ReadonlyDeep<I18nMessage> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyDeep<I18nMessage[]>>;\n getAll(): MaybePromise<ReadonlyDeep<I18nMessage[]>>;\n register(messages: I18nMessageRegistrationDefinition[]): Promise<void>;\n refresh(): void;\n /** Completes refresh$ and detaches from the watcher — called by `Store.destroy()`. */\n destroy(): void;\n};\n\nfunction toGqlMessageInput(msg: I18nMessageRegistrationDefinition): ContelloI18nMessageInput {\n return {\n token: msg.token,\n example: msg.example,\n description: msg.description,\n variables: msg.variables?.map((v) => ({ name: v.name, description: v.description, example: v.example })),\n translations: msg.translations?.map((t) => ({ language: t.language, message: t.message })),\n initialTranslations: msg.initialTranslations?.map((t) => ({ language: t.language, message: t.message })),\n };\n}\n\nexport function createI18nMessagesCollection(\n def: I18nMessageDef,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n refreshByTtl: RefreshByTtlQueue,\n): I18nMessages {\n const channel = createRefreshChannel<RefreshEvent>(def.onRefresh);\n const retry = createRefreshRetry();\n const ttl = createTtlOrchestrator({ ttl: resolveTtl(def.cache?.ttl), run: () => runTtlRefresh() });\n let loaded = false;\n\n const i18nSourceDoc = createSourceSubscription(storeSchema.sources.storeI18nMessage);\n\n const projected = new ProjectedMap<string, I18nMessage>({\n key: (msg) => msg.id,\n values: (ids) =>\n wrap(`i18n:${def.collection}`, async () => {\n const msgs = await concatAsync(\n mapAsync(\n client.subscribe<{ source: StoreI18nMessageFragment[] }>(i18nSourceDoc, {\n collection: def.collection,\n ids,\n }),\n (data) => data.source,\n ),\n );\n const items: I18nMessage[] = msgs.map((msg) => ({\n id: msg.id,\n token: msg.token,\n translations: new Map(msg.translations.map((t) => [t.language, t.value])),\n }));\n\n // start tracking refresh by ttl on first successful full fetch\n if (ids === undefined && !loaded) {\n loaded = true;\n ttl.mark();\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function emitWithCurrentIds(kind: RefreshKind): void {\n maybeThen(projected.getAll(), (msgs) => {\n emit(\n msgs.map((m) => m.id),\n kind,\n );\n });\n }\n\n function runTtlRefresh(): void {\n refreshByTtl.enqueue(async () => {\n if (!(await retry.run(() => projected.refresh()))) {\n return;\n }\n\n emitWithCurrentIds('ttl');\n ttl.mark();\n });\n }\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n () => projected.refresh(),\n (kind) => {\n emitWithCurrentIds(kind);\n ttl.mark();\n },\n retry,\n );\n\n function runPartialRefresh(upsertedIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...upsertedIds, ...deletedIds])];\n\n if (changedIds.length === 0) {\n return;\n }\n\n if (upsertedIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n void retry.run(async () => {\n await projected.refresh(upsertedIds);\n emit(changedIds, 'upstream-update');\n });\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n if (batch.i18nMessage.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.i18nMessage) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n return {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n getAll() {\n return projected.getAll();\n },\n\n register(messages: I18nMessageRegistrationDefinition[]) {\n return wrap(`i18n-register:${def.collection}`, async () => {\n await client.execute<StoreRegisterI18nMessagesMutation>(storeRegisterI18nMessagesDocument, {\n collection: def.collection,\n messages: messages.map((message) => toGqlMessageInput(message)),\n });\n });\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n destroy() {\n unsubUpdates();\n retry.stop();\n ttl.clear();\n channel.complete();\n },\n };\n}\n","import type { ProjectedMapCache } from '@entwico/projected';\nimport { LRUCache } from 'lru-cache';\n\nexport type LruCache<TKey, TValue> = ProjectedMapCache<TKey, TValue> & {\n keys: () => TKey[];\n};\n\nexport function createLruCache<TKey, TValue>(options: {\n max: number;\n ttl: number | undefined;\n onEvict: ((value: TValue, key: TKey) => void) | undefined;\n}): LruCache<TKey, TValue> {\n const { max, ttl, onEvict: dispose } = options;\n\n const lru = new LRUCache<any, any>({\n max,\n ...(ttl !== undefined && { ttl, ttlAutopurge: false }),\n ...(dispose !== undefined && { dispose }),\n });\n\n return {\n has: (key) => lru.has(key),\n get: (key) => lru.get(key),\n set: (key, value) => {\n lru.set(key, value);\n },\n delete: (key) => {\n lru.delete(key);\n },\n clear: () => {\n lru.clear();\n },\n keys: () => lru.keys().toArray(),\n };\n}\n","import {\n type ContelloClient,\n type DownloadResult,\n type ProxyResult,\n type UploadData,\n type UploadMetadata,\n type UploadOptions,\n createSourceSubscription,\n} from '@contello/client';\nimport type { ReadonlyDeep } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedLazyMap } from '@entwico/projected';\nimport { type StoreAssetFragment, type StoreFileFragment, schema as storeSchema } from './generated/graphql';\nimport { createLruCache } from './lru';\nimport { wrap } from './telemetry';\nimport type { Created, LazyCacheOptions, RefreshEvent, RefreshKind } from './types';\nimport { DEFAULT_LRU_MAX, createRefreshChannel, createRefreshRetry, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type StoreFileMetadata = {\n width: number;\n height: number;\n};\n\nexport type StoreFile = {\n uid: string;\n mimeType: string;\n metadata: StoreFileMetadata | undefined;\n};\n\nexport type StoreAsset = {\n id: string;\n original: StoreFile;\n preview: StoreFile | undefined;\n optimized: StoreFile[];\n};\n\nexport type LazyAssetsOptions = {\n cache?: LazyCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type LazyAssets = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): Promise<ReadonlyDeep<StoreAsset> | undefined>;\n get(ids: readonly string[]): Promise<ReadonlyDeep<StoreAsset[]>>;\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string>;\n download(fileId: string): Promise<DownloadResult>;\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult>;\n refresh(): void;\n clear(): void;\n};\n\nfunction mapFile(raw: StoreFileFragment): StoreFile {\n return {\n uid: raw.uid,\n mimeType: raw.mimeType,\n metadata: raw.metadata ? { width: raw.metadata.width, height: raw.metadata.height } : undefined,\n };\n}\n\nfunction mapAsset(raw: StoreAssetFragment): StoreAsset {\n return {\n id: raw.id,\n original: mapFile(raw.original),\n preview: raw.preview ? mapFile(raw.preview) : undefined,\n optimized: raw.optimized.map((file) => mapFile(file)),\n };\n}\n\nexport function createLazyAssetsCollection(\n def: LazyAssetsOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n): Created<LazyAssets> {\n const _def = {\n cache: {\n max: def?.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(def?.cache?.ttl),\n },\n };\n\n const cache = createLruCache<string, StoreAsset>({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: undefined });\n\n const assetsSourceDoc = createSourceSubscription(storeSchema.sources.storeAsset);\n\n const projected = new ProjectedLazyMap<string, StoreAsset>({\n key: (asset) => asset.id,\n values: (ids) =>\n wrap('assets', async () => {\n const rawItems = await concatAsync(\n mapAsync(client.subscribe<{ source: StoreAssetFragment[] }>(assetsSourceDoc, { ids }), (data) => data.source),\n );\n\n return rawItems.map((item) => mapAsset(item));\n }),\n cache,\n });\n\n const channel = createRefreshChannel<RefreshEvent>(def?.onRefresh);\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n let lastRefreshKeys: string[] = [];\n\n const retry = createRefreshRetry();\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(lastRefreshKeys, kind);\n }\n },\n retry,\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (batch.asset.length === 0) return;\n\n for (const event of batch.asset) {\n projected.delete(event.id);\n }\n\n emit(\n batch.asset.map((e) => e.id),\n 'upstream-update',\n );\n });\n\n return {\n instance: {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n upload(data: UploadData, meta: UploadMetadata, options?: UploadOptions | undefined): Promise<string> {\n return client.upload(data, meta, options);\n },\n\n download(fileId: string): Promise<DownloadResult> {\n return client.download(fileId);\n },\n\n proxyHls(path: string, signal?: AbortSignal | undefined): Promise<ProxyResult> {\n return client.proxyHls(path, signal);\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n clear() {\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n retry.stop();\n channel.complete();\n },\n };\n}\n","import { type ContelloClient, type SourceDef, createSourceSubscription } from '@contello/client';\nimport { maybeAll, maybeThen } from '@entwico/dash';\nimport {\n type AsyncIterableSubject,\n concatAsync,\n createAsyncIterableSubject,\n mapAsync,\n} from '@entwico/dash/async';\nimport { ProjectedLazyMap } from '@entwico/projected';\nimport { DependencyCollector } from './dependency-collector';\nimport { createLruCache } from './lru';\nimport type { ModelResolver } from './model-resolver';\nimport { wrap } from './telemetry';\nimport type {\n Created,\n ExtractSourceResult,\n LazyCollection,\n LazyCollectionOptions,\n RefreshEvent,\n RefreshKind,\n} from './types';\nimport { DEFAULT_LRU_MAX, createRefreshRetry, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport function createLazyCollection<\n TSource extends SourceDef<TModels, 'entity'>,\n TMapped extends { id: string },\n TModels extends string = string,\n>(\n source: TSource,\n options: LazyCollectionOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n): Created<LazyCollection<TMapped>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n max: opts.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(opts.cache?.ttl),\n },\n };\n\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const cache = createLruCache<string, TMapped>({\n max: _def.cache.max,\n ttl: _def.cache.ttl,\n onEvict: (_value, key) => dependencyCollector.removeItem(key),\n });\n\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const projected = new ProjectedLazyMap<string, TMapped>({\n key: (item) => item.id,\n values: (keys) =>\n wrap(\n `lazy-collection:${_def.name}`,\n () => maybeThen(\n concatAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<TSource>[] }>(createSourceSubscription(source), {\n ids: keys,\n }),\n (r) => r.source,\n ),\n ),\n (rawItems) => maybeAll(\n rawItems.map(\n (item) => dependencyCollector.createContext(\n (ref, register) => maybeThen(mapFn(item, ref), (mapped) => {\n register(mapped.id);\n\n return mapped;\n }),\n ),\n ),\n ),\n ),\n ),\n cache,\n });\n\n const refresh$ = createAsyncIterableSubject<RefreshEvent>();\n\n function emit(ids: string[], kind: RefreshKind): void {\n const event: RefreshEvent = { ids, kind };\n\n refresh$.next(event);\n opts.onRefresh?.(event);\n }\n\n const retry = createRefreshRetry();\n let lastRefreshKeys: string[] = [];\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(lastRefreshKeys, kind);\n }\n },\n retry,\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n const evicted = new Set<string>();\n const ownModelEvents = batch.entity.get(_def.model);\n\n if (ownModelEvents) {\n for (const event of ownModelEvents) {\n evicted.add(event.id);\n }\n }\n\n for (const event of batch.events) {\n for (const key of dependencyCollector.getAffectedKeys(event)) {\n evicted.add(key);\n }\n }\n\n if (evicted.size === 0) {\n return;\n }\n\n for (const key of evicted) {\n dependencyCollector.removeItem(key);\n projected.delete(key);\n }\n\n emit([...evicted], 'upstream-update');\n });\n\n return {\n instance: {\n name: _def.name,\n refresh$,\n\n get(idOrIds: string | readonly string[]): any {\n return projected.get(idOrIds as string);\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n clear() {\n dependencyCollector.clear();\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n retry.stop();\n refresh$.complete();\n },\n };\n}\n","const ESCAPES = /(?:%[\\dA-Fa-f]{2})+/g;\n\n// a character a route path cannot hold decoded: a slash is a delimiter (`/a%2Fb` and `/a/b` are\n// two routes), a percent sign could not be re-encoded, a query or fragment delimiter, a space or\n// control character has no place in a path\nconst STAYS_ENCODED = /[/%?#\\s\\p{Cc}]/u;\n\nfunction decodeRun(run: string): string {\n let decoded: string;\n\n try {\n decoded = decodeURIComponent(run);\n } catch {\n // a broken sequence is kept as it is\n return run.toUpperCase();\n }\n\n let result = '';\n\n for (const char of decoded) {\n result += STAYS_ENCODED.test(char) ? encodeURIComponent(char) : char;\n }\n\n return result;\n}\n\n/**\n * The one form a route path is stored and looked up in: percent escapes decoded and unicode\n * composed (NFC), as core normalizes it. A request arrives percent-encoded (`/%C3%BCber-uns`),\n * the stored path is decoded (`/über-uns`); both spellings must hit the same cache entry. An\n * escape of a character a path cannot hold decoded stays encoded, with uppercase hex.\n */\nexport function normalizeRoutePath(path: string): string {\n // eslint-disable-next-line unicorn/no-unsafe-string-replacement -- the replacer is a function, no `$` patterns apply\n return path.replaceAll(ESCAPES, decodeRun).normalize('NFC');\n}\n","import type { StoreRouteFragment } from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\n\nexport type StoreRouteCustomHeader = {\n name: string;\n value: string;\n};\n\nexport type StoreRoute = {\n id: string;\n path: string;\n customHeaders: StoreRouteCustomHeader[];\n} & (\n | { type: 'redirect'; location: string; status: number }\n | { type: 'text'; content: string; mimeType: string }\n | { type: 'asset'; assetId: string; fileId: string; contentDisposition: 'inline' | 'attachment'; mimeType: string }\n | { type: 'entity'; model: string; entityType: string; entityId: string }\n | { type: 'sitemap'; sitemapId: string }\n);\n\nexport function mapRoute(raw: StoreRouteFragment, resolver: ModelResolver): StoreRoute | undefined {\n const base = {\n id: raw.id,\n path: raw.path,\n customHeaders: raw.customHeaders.map((h) => ({ name: h.name, value: h.value })),\n };\n\n switch (raw.target.__typename) {\n case 'ContelloRouteTargetRedirect': {\n return {\n ...base,\n type: 'redirect',\n location: raw.target.location,\n status: raw.target.responseCode,\n };\n }\n\n case 'ContelloRouteTargetText': {\n return {\n ...base,\n type: 'text',\n content: raw.target.content,\n mimeType: raw.target.mimeType,\n };\n }\n\n case 'ContelloRouteTargetAsset': {\n return {\n ...base,\n type: 'asset',\n assetId: raw.target.asset.id,\n fileId: raw.target.asset.original.uid,\n contentDisposition: raw.target.contentDisposition === 'INLINE' ? 'inline' : 'attachment',\n mimeType: raw.target.asset.original.mimeType,\n };\n }\n\n case 'ContelloRouteTargetEntity': {\n if (!raw.target.entity) {\n return undefined;\n }\n\n const entityType = raw.target.entity.__typename;\n\n return {\n ...base,\n type: 'entity',\n model: resolver.resolveModel(entityType),\n entityType,\n entityId: raw.target.entity.id,\n };\n }\n\n case 'ContelloRouteTargetSitemap': {\n return {\n ...base,\n type: 'sitemap',\n sitemapId: raw.target.sitemapId,\n };\n }\n\n default: {\n return undefined;\n }\n }\n}\n","import { type ContelloClient, createSourceSubscription } from '@contello/client';\nimport type { ReadonlyDeep } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedLazyMap } from '@entwico/projected';\nimport { type StoreRouteFragment, schema as storeSchema } from './generated/graphql';\nimport { type LruCache, createLruCache } from './lru';\nimport type { ModelResolver } from './model-resolver';\nimport { normalizeRoutePath } from './route-path';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport { wrap } from './telemetry';\nimport type { Created, LazyCacheOptions, RefreshEvent, RefreshKind } from './types';\nimport { DEFAULT_LRU_MAX, createRefreshChannel, createRefreshRetry, createRefresher, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport type LazyRoutesOptions = {\n cache?: LazyCacheOptions | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type LazyRoutes = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n get(id: string): Promise<ReadonlyDeep<StoreRoute> | undefined>;\n get(ids: readonly string[]): Promise<ReadonlyDeep<StoreRoute[]>>;\n getByPath(path: string): Promise<ReadonlyDeep<StoreRoute> | undefined>;\n getByPath(paths: readonly string[]): Promise<ReadonlyDeep<StoreRoute[]>>;\n refresh(): void;\n clear(): void;\n};\n\n// cache key prefixes — short nullbyte-separated to allow slice(2) extraction without branching\nconst ID_PREFIX = '1\\0';\nconst PATH_PREFIX = '2\\0';\n\n// private symbol used to tag each route with the projected cache key it was requested under,\n// so the key() function can return the right prefixed key for projected to match results back\nconst CACHE_KEY = Symbol('cacheKey');\n\nfunction collectRoutes(\n rawItems: StoreRouteFragment[],\n keyFn: (route: StoreRoute) => string,\n resolver: ModelResolver,\n): StoreRoute[] {\n return rawItems.reduce<StoreRoute[]>((acc, raw) => {\n const mapped = mapRoute(raw, resolver);\n\n if (mapped) {\n (mapped as Record<symbol, string>)[CACHE_KEY] = keyFn(mapped);\n acc.push(mapped);\n }\n\n return acc;\n }, []);\n}\n\n/**\n * cache wrapper that presents a unified `ID_PREFIX + id` / `PATH_PREFIX + path` key space\n * to ProjectedLazyMap while storing entries in the underlying LRU under ID_PREFIX keys only.\n *\n * path -> id resolution is handled internally via a pathToId map kept in sync with the LRU\n * (populated on set, cleared on natural LRU eviction via onEvict, and on explicit delete).\n */\nfunction createRoutesCache(max: number, ttl: number | undefined): LruCache<string, StoreRoute> {\n const pathToId = new Map<string, string>();\n // reverse of pathToId, so a route whose path changed can have its previous\n // path entry removed (otherwise getByPath(oldPath) would resolve to the route\n // that no longer lives there)\n const idToPath = new Map<string, string>();\n\n const lru = createLruCache<string, StoreRoute>({\n max,\n ttl,\n onEvict: (route) => {\n pathToId.delete(normalizeRoutePath(route.path));\n idToPath.delete(route.id);\n },\n });\n\n function resolveKey(key: string): string {\n if (key.startsWith(PATH_PREFIX)) {\n const id = pathToId.get(key.slice(2));\n\n if (id) {\n return ID_PREFIX + id;\n }\n\n return key; // propagate cache miss if path not found\n }\n\n return key;\n }\n\n return {\n has: (key) => lru.has(resolveKey(key)),\n get: (key) => lru.get(resolveKey(key)),\n\n set: (_key, value) => {\n // always normalise to ID_PREFIX in lru\n // regardless of which key projected passes in\n const previousPath = idToPath.get(value.id);\n\n if (previousPath !== undefined && previousPath !== value.path) {\n pathToId.delete(normalizeRoutePath(previousPath));\n }\n\n pathToId.set(normalizeRoutePath(value.path), value.id);\n idToPath.set(value.id, value.path);\n lru.set(ID_PREFIX + value.id, value);\n },\n\n delete: (key) => {\n const resolved = resolveKey(key);\n const value = lru.get(resolved);\n\n if (value) {\n pathToId.delete(normalizeRoutePath(value.path));\n idToPath.delete(value.id);\n }\n\n lru.delete(resolved);\n },\n\n clear: () => {\n pathToId.clear();\n idToPath.clear();\n lru.clear();\n },\n\n keys: () => lru.keys(),\n };\n}\n\nexport function createLazyRoutesCollection(\n def: LazyRoutesOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n): Created<LazyRoutes> {\n const _def = {\n cache: {\n max: def?.cache?.max ?? DEFAULT_LRU_MAX,\n ttl: resolveTtl(def?.cache?.ttl),\n },\n };\n\n const cache = createRoutesCache(_def.cache.max, _def.cache.ttl);\n\n const negatives = createLruCache<string, true>({ max: _def.cache.max, ttl: _def.cache.ttl, onEvict: undefined });\n\n const routesSourceDoc = createSourceSubscription(storeSchema.sources.storeRoute);\n\n function fetchRoutes(vars: { ids?: string[]; paths?: string[] }): Promise<StoreRouteFragment[]> {\n return concatAsync(\n mapAsync(client.subscribe<{ source: StoreRouteFragment[] }>(routesSourceDoc, vars), (data) => data.source),\n );\n }\n\n const projected = new ProjectedLazyMap<string, StoreRoute>({\n key: (route) => (route as Record<symbol, string>)[CACHE_KEY] ?? ID_PREFIX + route.id,\n values: (prefixedKeys) =>\n wrap('routes', async () => {\n const ids: string[] = [];\n const paths: string[] = [];\n\n for (const key of prefixedKeys) {\n const value = key.slice(2);\n\n if (key.startsWith(ID_PREFIX)) {\n ids.push(value);\n } else {\n paths.push(value);\n }\n }\n\n const [rawByIds, rawByPaths] = await Promise.all([\n ids.length > 0 ? fetchRoutes({ ids }) : Promise.resolve<StoreRouteFragment[]>([]),\n paths.length > 0 ? fetchRoutes({ paths }) : Promise.resolve<StoreRouteFragment[]>([]),\n ]);\n\n const byIds = collectRoutes(rawByIds, (r) => ID_PREFIX + r.id, resolver);\n const byPaths = collectRoutes(rawByPaths, (r) => PATH_PREFIX + normalizeRoutePath(r.path), resolver);\n const found = [...byIds, ...byPaths];\n const foundKeys = new Set(found.map((route) => (route as Record<symbol, string>)[CACHE_KEY]));\n\n for (const key of prefixedKeys) {\n if (!foundKeys.has(key)) {\n negatives.set(key, true);\n }\n }\n\n return found;\n }),\n cache,\n });\n\n const channel = createRefreshChannel<RefreshEvent>(def?.onRefresh);\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n let lastRefreshKeys: string[] = [];\n\n const retry = createRefreshRetry();\n const scheduleRefresh = createRefresher<RefreshKind>(\n async () => {\n lastRefreshKeys = cache.keys();\n\n if (lastRefreshKeys.length === 0) {\n return;\n }\n\n await projected.refresh(lastRefreshKeys);\n },\n (kind) => {\n if (lastRefreshKeys.length > 0) {\n emit(\n lastRefreshKeys.map((key) => key.slice(2)),\n kind,\n );\n }\n },\n retry,\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n const evicted: string[] = [];\n\n for (const event of batch.route) {\n const idKey = ID_PREFIX + event.id;\n\n if (event.mutation === 'delete') {\n cache.delete(idKey);\n evicted.push(event.id);\n } else {\n negatives.delete(idKey);\n negatives.delete(PATH_PREFIX + normalizeRoutePath(event.after.path));\n\n if (cache.has(idKey)) {\n cache.set(idKey, event.after);\n }\n\n evicted.push(event.after.path);\n }\n }\n\n if (evicted.length > 0) {\n emit(evicted, 'upstream-update');\n }\n });\n\n function lookupOne(key: string): unknown {\n if (negatives.has(key)) {\n return undefined;\n }\n\n return projected.get(key);\n }\n\n function lookupMany(keys: string[]): unknown {\n const known = keys.filter((key) => !negatives.has(key));\n\n if (known.length === 0) {\n return [];\n }\n\n return projected.get(known);\n }\n\n return {\n instance: {\n refresh$: channel.stream$,\n\n get(idOrIds: string | readonly string[]): any {\n if (Array.isArray(idOrIds)) {\n return lookupMany(idOrIds.map((id) => ID_PREFIX + id));\n }\n\n return lookupOne(ID_PREFIX + idOrIds);\n },\n\n getByPath(pathOrPaths: string | readonly string[]): any {\n if (Array.isArray(pathOrPaths)) {\n return lookupMany(pathOrPaths.map((p) => PATH_PREFIX + normalizeRoutePath(p)));\n }\n\n return lookupOne(PATH_PREFIX + normalizeRoutePath(pathOrPaths as string));\n },\n\n refresh() {\n negatives.clear();\n scheduleRefresh('on-demand');\n },\n\n clear() {\n negatives.clear();\n projected.clear();\n },\n },\n destroy() {\n unsubUpdates();\n retry.stop();\n channel.complete();\n },\n };\n}\n","export class ModelResolver<TModels extends string = string> {\n private _typeNames: ReadonlySet<string> | undefined;\n private _toModel: ReadonlyMap<string, TModels>;\n private _toTypeName: ReadonlyMap<TModels, string>;\n\n constructor(models?: Record<TModels, string> | undefined) {\n const toModel = new Map<string, TModels>();\n const toTypeName = new Map<TModels, string>();\n let typeNames: Set<string> | undefined;\n\n if (models) {\n typeNames = new Set<string>();\n\n for (const [model, typeName] of Object.entries<string>(models)) {\n toModel.set(typeName, model as TModels);\n toTypeName.set(model as TModels, typeName);\n typeNames.add(typeName);\n }\n }\n\n this._typeNames = typeNames;\n this._toModel = toModel;\n this._toTypeName = toTypeName;\n }\n\n hasTypeName(typeName: string): boolean {\n return !this._typeNames || this._typeNames.has(typeName);\n }\n\n getModel(typeName: string): TModels | undefined {\n return this._toModel.get(typeName);\n }\n\n getTypeName(model: TModels): string {\n return this._toTypeName.get(model) ?? model;\n }\n\n hasModel(model: string): boolean {\n return this._toTypeName.size === 0 || this._toTypeName.has(model as TModels);\n }\n\n resolveModel(typeName: string): string {\n return this._toModel.get(typeName) ?? typeName;\n }\n}\n","import {\n BUILT_IN_MUTATIONS,\n type ContelloClient,\n type SourceMutationKind,\n createSourceMutation,\n createSourceMutationVariables,\n createSourceSubscription,\n} from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, concatAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedMap } from '@entwico/projected';\n\nimport { type StoreRouteFragment, schema as storeSchema } from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\nimport { normalizeRoutePath } from './route-path';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport { wrap } from './telemetry';\nimport type { CacheOptions, CollectionWrites, Created, RefreshEvent, RefreshKind, SyncCacheOptions } from './types';\nimport { type RefreshByTtlQueue, createRefreshChannel, createRefreshRetry, createTtlOrchestrator, resolveTtl } from './utils';\nimport type { UpdateBatch } from './watcher';\nimport { createWriteBuffer } from './write-buffer';\n\nexport type RoutesOptions = {\n cache?: CacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\nexport type RoutesSyncOptions = {\n cache?: SyncCacheOptions | undefined;\n onLoad?: ((ids: string[]) => void) | undefined;\n onRefresh?: ((event: RefreshEvent) => void) | undefined;\n};\n\n/**\n * `update` is not the patch a collection's is: `updateContelloRoute` is keyed by the `path` in its\n * input — there is no id — and it replaces the route, so a field left out is cleared, not kept.\n */\nexport type Routes<TWrites = unknown> = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined>;\n get(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>>;\n getByPath(path: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined>;\n getByPath(paths: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>>;\n refresh(): void;\n} & CollectionWrites<StoreRoute, TWrites>;\n\nexport type RoutesSync<TWrites = unknown> = {\n readonly refresh$: AsyncIterable<RefreshEvent>;\n load(): Promise<void>;\n get(id: string): ReadonlyDeep<StoreRoute> | undefined;\n get(ids: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreRoute>>;\n getByPath(path: string): ReadonlyDeep<StoreRoute> | undefined;\n getByPath(paths: readonly string[]): ReadonlyArray<ReadonlyDeep<StoreRoute>>;\n refresh(): void;\n} & CollectionWrites<StoreRoute, TWrites>;\n\nexport function createRoutesCollection(\n options: RoutesOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Routes> {\n const opts = options ?? {};\n const cache = {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n } as const;\n\n const channel = createRefreshChannel<RefreshEvent>(opts.onRefresh);\n const retry = createRefreshRetry();\n const ttl = createTtlOrchestrator({ ttl: cache.ttl, run: () => runFullRefresh('ttl') });\n\n // id ↔ path indexes — kept in sync with `projected` by the values callback.\n // any route lookup by path resolves to an id, then the value comes from `projected`.\n const pathById = new Map<string, string>();\n const idByPath = new Map<string, string>();\n let loaded = false;\n\n // the built-in route source plus its fixed write bindings — `mutations` is constant for every\n // Contello schema, so the store carries it rather than depending on a regenerated bundle\n const routeSource = { ...storeSchema.sources.storeRoute, mutations: BUILT_IN_MUTATIONS.route };\n const routesSourceDoc = createSourceSubscription(routeSource);\n\n const writeBuffer = createWriteBuffer<StoreRouteFragment>();\n\n function fetchRoutes(ids: string[] | undefined): Promise<StoreRouteFragment[]> {\n return concatAsync(\n mapAsync(\n client.subscribe<{ source: StoreRouteFragment[] }>(routesSourceDoc, { ids }),\n (data) => data.source,\n ),\n );\n }\n\n async function fetchOrTakeWritten(ids: string[] | undefined): Promise<StoreRouteFragment[]> {\n if (ids === undefined) {\n writeBuffer.clear();\n\n return fetchRoutes(undefined);\n }\n\n const { written, missing } = writeBuffer.take(ids);\n\n if (missing.length === 0) {\n return written;\n }\n\n const fetched = await fetchRoutes(missing);\n\n return written.length === 0 ? fetched : [...written, ...fetched];\n }\n\n const projected = new ProjectedMap<string, StoreRoute>({\n key: (route) => route.id,\n values: (ids) =>\n wrap('routes', async () => {\n const rawItems = await fetchOrTakeWritten(ids);\n const items = rawItems.reduce<StoreRoute[]>((acc, raw) => {\n const mapped = mapRoute(raw, resolver);\n\n if (mapped) {\n acc.push(mapped);\n }\n\n return acc;\n }, []);\n\n if (ids === undefined) {\n pathById.clear();\n idByPath.clear();\n\n for (const r of items) {\n pathById.set(r.id, r.path);\n idByPath.set(normalizeRoutePath(r.path), r.id);\n }\n\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.(items.map((r) => r.id));\n }\n } else {\n const returnedIds = new Set(items.map((r) => r.id));\n\n // requested ids missing from the response = deleted; drop their path entries\n for (const id of ids) {\n if (returnedIds.has(id)) {\n continue;\n }\n\n const oldPath = pathById.get(id);\n\n if (oldPath === undefined) {\n continue;\n }\n\n idByPath.delete(normalizeRoutePath(oldPath));\n pathById.delete(id);\n }\n\n for (const r of items) {\n const oldPath = pathById.get(r.id);\n\n if (oldPath !== undefined && oldPath !== r.path) {\n idByPath.delete(normalizeRoutePath(oldPath));\n }\n\n pathById.set(r.id, r.path);\n idByPath.set(normalizeRoutePath(r.path), r.id);\n }\n }\n\n return items;\n }),\n });\n\n function emit(ids: string[], kind: RefreshKind): void {\n channel.emit({ ids, kind });\n }\n\n function runFullRefresh(kind: RefreshKind): void {\n refreshByTtl.enqueue(\n () => retry.run(async () => {\n const map = await projected.refresh();\n\n emit(map.keys().toArray(), kind);\n ttl.mark();\n }),\n );\n }\n\n function runPartialRefresh(refreshIds: string[], deletedIds: string[]): void {\n const changedIds = [...new Set([...refreshIds, ...deletedIds])];\n\n if (refreshIds.length === 0) {\n emit(changedIds, 'upstream-update');\n\n return;\n }\n\n // upstream is authoritative for these until the refetch lands — no local write may answer it\n const settled = writeBuffer.awaitingUpstream(refreshIds);\n\n void retry.run(async () => {\n await projected.refresh(refreshIds);\n emit(changedIds, 'upstream-update');\n }).finally(settled);\n }\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded || batch.route.length === 0) {\n return;\n }\n\n const deleted: string[] = [];\n const upserted = new Set<string>();\n\n for (const event of batch.route) {\n if (event.mutation === 'delete') {\n deleted.push(event.id);\n } else {\n upserted.add(event.id);\n }\n }\n\n if (cache.eviction === 'clear') {\n pathById.clear();\n idByPath.clear();\n writeBuffer.clear();\n projected.clear();\n\n return;\n }\n\n writeBuffer.release(deleted);\n\n for (const id of deleted) {\n const oldPath = pathById.get(id);\n\n if (oldPath === undefined) {\n continue;\n }\n\n idByPath.delete(normalizeRoutePath(oldPath));\n pathById.delete(id);\n }\n\n if (deleted.length > 0) {\n projected.delete(deleted);\n }\n\n runPartialRefresh([...upserted], deleted);\n });\n\n function getByIdSingle(id: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined> {\n return projected.get(id);\n }\n\n function getByIds(ids: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>> {\n return projected.get(ids);\n }\n\n function lookupByPathSingle(path: string): MaybePromise<ReadonlyDeep<StoreRoute> | undefined> {\n return maybeThen(ensureLoaded(), () => {\n const id = idByPath.get(normalizeRoutePath(path));\n\n return id === undefined ? undefined : projected.get(id);\n });\n }\n\n function lookupByPaths(paths: readonly string[]): MaybePromise<ReadonlyArray<ReadonlyDeep<StoreRoute>>> {\n return maybeThen(ensureLoaded(), () => {\n const ids: string[] = [];\n\n for (const p of paths) {\n const id = idByPath.get(normalizeRoutePath(p));\n\n if (id !== undefined) {\n ids.push(id);\n }\n }\n\n return projected.get(ids);\n });\n }\n\n function ensureLoaded(): MaybePromise<void> {\n if (loaded) {\n return undefined;\n }\n\n return maybeThen(projected.getAllAsMap(), () => {});\n }\n\n async function runMutation(kind: SourceMutationKind, values: { input?: unknown; id?: string }): Promise<unknown> {\n const binding = routeSource.mutations?.[kind];\n\n if (!binding) {\n throw new Error(`@contello/store: routes cannot ${kind} — the schema exposes no ${kind} mutation for routes`);\n }\n\n const response = await client.execute<{ result: unknown }>(\n createSourceMutation(routeSource, kind),\n createSourceMutationVariables(binding, values),\n );\n\n if (response?.result === undefined || response.result === null) {\n throw new Error(`@contello/store: ${kind} on routes returned nothing`);\n }\n\n return response.result;\n }\n\n /** Takes a written route into the cache through the normal refresh path, keeping both indexes. */\n async function takeIntoCache(raw: StoreRouteFragment): Promise<ReadonlyDeep<StoreRoute>> {\n writeBuffer.park(raw.id, raw);\n\n let map;\n\n try {\n map = await projected.refresh([raw.id]);\n } finally {\n writeBuffer.release([raw.id]);\n }\n\n emit([raw.id], 'write');\n\n const route = map.get(raw.id);\n\n if (!route) {\n throw new Error(\n `@contello/store: wrote route \"${raw.id}\" but it is not in the cache — ` +\n `its target may not have resolved, or a concurrent full refresh did not return it`,\n );\n }\n\n return route;\n }\n\n const writes = {\n async create(input: unknown): Promise<ReadonlyDeep<StoreRoute>> {\n return takeIntoCache((await runMutation('create', { input })) as StoreRouteFragment);\n },\n\n async update(input: unknown): Promise<ReadonlyDeep<StoreRoute>> {\n return takeIntoCache((await runMutation('update', { input })) as StoreRouteFragment);\n },\n\n async delete(id: string): Promise<void> {\n await runMutation('delete', { input: { id }, id });\n\n writeBuffer.release([id]);\n\n const oldPath = pathById.get(id);\n\n if (oldPath !== undefined) {\n idByPath.delete(normalizeRoutePath(oldPath));\n pathById.delete(id);\n }\n\n projected.delete([id]);\n emit([id], 'write');\n },\n };\n\n const instance: Routes = {\n ...writes,\n refresh$: channel.stream$,\n\n async load() {\n if (!loaded) {\n await projected.getAllAsMap();\n }\n },\n\n get(idOrIds: string | readonly string[]): any {\n return typeof idOrIds === 'string' ? getByIdSingle(idOrIds) : getByIds(idOrIds);\n },\n\n getByPath(pathOrPaths: string | readonly string[]): any {\n return typeof pathOrPaths === 'string' ? lookupByPathSingle(pathOrPaths) : lookupByPaths(pathOrPaths);\n },\n\n refresh() {\n runFullRefresh('on-demand');\n },\n };\n\n return {\n instance,\n destroy() {\n unsubUpdates();\n retry.stop();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createRoutesSyncCollection(\n options: RoutesSyncOptions | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<RoutesSync> {\n const { instance: base, destroy } = createRoutesCollection(options, client, updates$, resolver, refreshByTtl);\n\n function assertSync<T>(value: MaybePromise<T>, method: string): T {\n if (value instanceof Promise) {\n throw new TypeError(`routes.${method}() is not initialized yet — call routes.load() first`);\n }\n\n return value;\n }\n\n return {\n instance: {\n ...base,\n get(idOrIds: string | readonly string[]): any {\n return assertSync(base.get(idOrIds as string), 'get');\n },\n getByPath(pathOrPaths: string | readonly string[]): any {\n return assertSync(base.getByPath(pathOrPaths as string), 'getByPath');\n },\n },\n destroy,\n };\n}\n","import { type ContelloClient, type SourceDef, createSourceSubscription } from '@contello/client';\nimport { type MaybePromise, type ReadonlyDeep, maybeThen } from '@entwico/dash';\nimport { type AsyncIterableSubject, firstAsync, mapAsync } from '@entwico/dash/async';\nimport { ProjectedValue } from '@entwico/projected';\nimport { DependencyCollector } from './dependency-collector';\nimport type { ModelResolver } from './model-resolver';\nimport { wrap } from './telemetry';\nimport type {\n Created,\n ExtractSourceResult,\n RefreshKind,\n Singleton,\n SingletonOptions,\n SingletonRefreshEvent,\n SingletonSync,\n SingletonSyncOptions,\n} from './types';\nimport {\n type RefreshByTtlQueue,\n createRefreshChannel,\n createRefreshRetry,\n createRefresher,\n createTtlOrchestrator,\n resolveTtl,\n} from './utils';\nimport type { UpdateBatch } from './watcher';\n\nexport function createSingleton<\n TSource extends SourceDef<TModels, 'singleton'>,\n TMapped,\n TModels extends string = string,\n>(\n source: TSource,\n options: SingletonOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<Singleton<TMapped>> {\n const opts = options ?? {};\n const mapFn = opts.map ?? ((item: ExtractSourceResult<TSource>) => item as unknown as TMapped);\n const _def = {\n name: opts.name ?? source.__model,\n model: source.__model,\n cache: {\n ttl: resolveTtl(opts.cache?.ttl),\n eviction: opts.cache?.eviction ?? 'refresh',\n },\n };\n\n const dependencyCollector = new DependencyCollector<string, TModels>(_def.model, resolver);\n const itemKey = `singleton:${_def.name}`;\n const channel = createRefreshChannel<SingletonRefreshEvent>(opts.onRefresh);\n const retry = createRefreshRetry();\n const ttl = createTtlOrchestrator({ ttl: _def.cache.ttl, run: () => runTtlRefresh() });\n let loaded = false;\n\n // eslint-disable-next-line @eslint-react/naming-convention-context-name -- `createContext` here is DependencyCollector's method, not React's; this is a non-React module\n const projected = new ProjectedValue<TMapped>({\n value: () =>\n wrap(\n `singleton:${_def.name}`,\n () => maybeThen(\n firstAsync(\n mapAsync(\n client.subscribe<{ source: ExtractSourceResult<TSource> }>(createSourceSubscription(source)),\n (r) => r.source,\n ),\n ),\n (raw) => dependencyCollector.createContext(\n (ref, register) => maybeThen(mapFn(raw, ref), (mapped) => {\n register(itemKey);\n\n // start tracking refresh by ttl on first successful full fetch\n if (!loaded) {\n loaded = true;\n ttl.mark();\n opts.onLoad?.();\n }\n\n return mapped;\n }),\n ),\n ),\n ),\n });\n\n function emit(kind: RefreshKind): void {\n channel.emit({ kind });\n }\n\n function runTtlRefresh(): void {\n refreshByTtl.enqueue(async () => {\n if (!(await retry.run(() => projected.refresh()))) {\n return;\n }\n\n emit('ttl');\n ttl.mark();\n });\n }\n\n const scheduleRefresh = createRefresher<RefreshKind>(\n () => projected.refresh(),\n (kind) => {\n emit(kind);\n ttl.mark();\n },\n retry,\n );\n\n const unsubUpdates = updates$.subscribe((batch) => {\n if (!loaded) {\n return;\n }\n\n const hasOwnModel = batch.entity.has(_def.model);\n const hasAffectedRefs = batch.events.some((event) => dependencyCollector.getAffectedKeys(event).size > 0);\n\n if (!hasOwnModel && !hasAffectedRefs) {\n return;\n }\n\n if (_def.cache.eviction === 'clear') {\n dependencyCollector.clear();\n projected.clear();\n\n return;\n }\n\n scheduleRefresh('upstream-update');\n });\n\n return {\n instance: {\n name: _def.name,\n refresh$: channel.stream$,\n\n get(): MaybePromise<ReadonlyDeep<TMapped>> {\n return projected.get();\n },\n\n refresh() {\n scheduleRefresh('on-demand');\n },\n\n async load() {\n if (!loaded) {\n await projected.get();\n }\n },\n },\n destroy() {\n unsubUpdates();\n retry.stop();\n ttl.clear();\n channel.complete();\n },\n };\n}\n\nexport function createSingletonSync<\n TSource extends SourceDef<TModels, 'singleton'>,\n TMapped,\n TModels extends string = string,\n>(\n source: TSource,\n options: SingletonSyncOptions<ExtractSourceResult<TSource>, TMapped, TModels> | undefined,\n client: ContelloClient<any>,\n updates$: AsyncIterableSubject<UpdateBatch>,\n resolver: ModelResolver,\n refreshByTtl: RefreshByTtlQueue,\n): Created<SingletonSync<TMapped>> {\n const { instance: base, destroy } = createSingleton<TSource, TMapped, TModels>(\n source,\n options,\n client,\n updates$,\n resolver,\n refreshByTtl,\n );\n\n return {\n instance: {\n ...base,\n\n get(): ReadonlyDeep<TMapped> {\n const result = base.get();\n\n if (result instanceof Promise) {\n throw new TypeError(`singleton \"${base.name}\" is not initialized yet — call singleton.load() first`);\n }\n\n return result;\n },\n },\n destroy,\n };\n}\n","import type { ContelloClient } from '@contello/client';\nimport { type AsyncIterableSubject, createAsyncIterableSubject, keepalive, mapAsync } from '@entwico/dash/async';\n\nimport {\n type ContelloMutationType,\n type StoreRouteFragment,\n type StoreWatchUpdatesSubscription,\n storeWatchUpdatesDocument,\n} from './generated/graphql';\nimport type { ModelResolver } from './model-resolver';\nimport { type StoreRoute, mapRoute } from './routes-mapping';\nimport { wrap } from './telemetry';\n\nexport type UpdateEvent<TEntityType extends string = string> =\n | { id: string; mutation: 'create'; target: 'route'; after: StoreRoute }\n | { id: string; mutation: 'update'; target: 'route'; after: StoreRoute; before: StoreRoute }\n | { id: string; mutation: 'delete'; target: 'route' }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'asset' }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'i18nMessage'; token: string }\n | { id: string; mutation: 'create' | 'update' | 'delete'; target: 'entity'; model: TEntityType };\n\nexport type UpdateMutationType = UpdateEvent['mutation'];\n\nexport type UpdateEventFor<T extends UpdateEvent['target']> = Extract<UpdateEvent, { target: T }>;\n\nexport type UpdateBatch = {\n readonly events: UpdateEvent[];\n readonly route: UpdateEventFor<'route'>[];\n readonly asset: UpdateEventFor<'asset'>[];\n readonly i18nMessage: UpdateEventFor<'i18nMessage'>[];\n /** entity events grouped by model typename */\n readonly entity: Map<string, UpdateEventFor<'entity'>[]>;\n /** route events grouped by target entity model (both after and before targets for updates) */\n readonly routeByEntityModel: Map<string, UpdateEventFor<'route'>[]>;\n};\n\nfunction addRouteByModel(\n map: Map<string, UpdateEventFor<'route'>[]>,\n entityType: string,\n event: UpdateEventFor<'route'>,\n): void {\n let list = map.get(entityType);\n\n if (!list) {\n list = [];\n map.set(entityType, list);\n }\n\n list.push(event);\n}\n\ntype MutableBatch = {\n route: UpdateEventFor<'route'>[];\n asset: UpdateEventFor<'asset'>[];\n i18nMessage: UpdateEventFor<'i18nMessage'>[];\n entity: Map<string, UpdateEventFor<'entity'>[]>;\n routeByEntityModel: Map<string, UpdateEventFor<'route'>[]>;\n};\n\nfunction addEventToBatch(batch: MutableBatch, event: UpdateEvent): void {\n switch (event.target) {\n case 'route': {\n batch.route.push(event);\n\n if ('after' in event && event.after.type === 'entity') {\n addRouteByModel(batch.routeByEntityModel, event.after.model, event);\n }\n\n if ('before' in event && event.before.type === 'entity') {\n addRouteByModel(batch.routeByEntityModel, event.before.model, event);\n }\n\n break;\n }\n case 'asset': {\n batch.asset.push(event);\n break;\n }\n case 'i18nMessage': {\n batch.i18nMessage.push(event);\n break;\n }\n case 'entity': {\n let list = batch.entity.get(event.model);\n\n if (!list) {\n list = [];\n batch.entity.set(event.model, list);\n }\n\n list.push(event);\n break;\n }\n }\n}\n\nfunction createUpdateBatch(events: UpdateEvent[]): UpdateBatch {\n const batch: MutableBatch = {\n route: [],\n asset: [],\n i18nMessage: [],\n entity: new Map<string, UpdateEventFor<'entity'>[]>(),\n routeByEntityModel: new Map<string, UpdateEventFor<'route'>[]>(),\n };\n\n for (const event of events) {\n addEventToBatch(batch, event);\n }\n\n return {\n events,\n route: batch.route,\n asset: batch.asset,\n i18nMessage: batch.i18nMessage,\n entity: batch.entity,\n routeByEntityModel: batch.routeByEntityModel,\n };\n}\n\ntype RawBatch = NonNullable<StoreWatchUpdatesSubscription['contelloUpdatesBatch']>;\ntype RawEvent = RawBatch['events'][number];\n\nfunction castMutationType(type: ContelloMutationType): UpdateMutationType {\n switch (type) {\n case 'CREATE': {\n return 'create';\n }\n case 'UPDATE': {\n return 'update';\n }\n case 'DELETE': {\n return 'delete';\n }\n }\n}\n\nfunction mapEvent(raw: RawEvent, resolver: ModelResolver): UpdateEvent | undefined {\n const mutation = castMutationType(raw.mutation.type);\n const target = raw.target;\n const { id, __typename } = target;\n\n switch (__typename) {\n case 'ContelloRoute': {\n if (mutation === 'delete') {\n return { id, mutation: 'delete', target: 'route' };\n }\n\n const after = mapRoute(target as StoreRouteFragment, resolver);\n\n if (!after) {\n return undefined;\n }\n\n if (mutation === 'create') {\n return { id, mutation, target: 'route', after };\n }\n\n const before =\n raw.prev?.__typename === 'ContelloRoute'\n ? (mapRoute(raw.prev as StoreRouteFragment, resolver) ?? undefined)\n : undefined;\n\n if (!before) {\n return undefined;\n }\n\n return { id, mutation, target: 'route', after, before };\n }\n\n case 'ContelloAsset': {\n return { id, mutation, target: 'asset' };\n }\n\n case 'ContelloI18nMessage': {\n return { id, mutation, target: 'i18nMessage', token: target.token };\n }\n\n default: {\n if (!__typename || !resolver.hasTypeName(__typename)) {\n return undefined;\n }\n\n return { id, mutation, target: 'entity', model: resolver.resolveModel(__typename) };\n }\n }\n}\n\nfunction safeMapEvent(raw: RawEvent, resolver: ModelResolver): UpdateEvent | undefined {\n try {\n return mapEvent(raw, resolver);\n } catch {\n return undefined;\n }\n}\n\nexport type InternalWatcher = {\n /** Multicast stream of update batches. Internal-only; the public `Store.updates$` is the AsyncIterable view. */\n readonly updates$: AsyncIterableSubject<UpdateBatch>;\n start(): void;\n stop(): void;\n};\n\nexport function createInternalWatcher(client: ContelloClient<any>, resolver: ModelResolver): InternalWatcher {\n const updates$ = createAsyncIterableSubject<UpdateBatch>();\n let controller: AbortController | undefined;\n\n return {\n updates$,\n\n start() {\n if (controller) {\n return;\n }\n\n controller = new AbortController();\n const signal = controller.signal;\n\n wrap('watcher:start', () => {\n void (async () => {\n const source = keepalive(\n () => client.subscribe<StoreWatchUpdatesSubscription>(storeWatchUpdatesDocument),\n { signal },\n );\n\n const events = mapAsync(\n source,\n (data) => (data.contelloUpdatesBatch?.events ?? [])\n // a single malformed event must not throw out of the loop and kill\n // the watcher — skip it and keep consuming the stream\n .map((e) => safeMapEvent(e, resolver))\n .filter((e): e is UpdateEvent => e !== undefined),\n );\n\n for await (const list of events) {\n if (signal.aborted) {\n return;\n }\n\n if (list.length === 0) {\n continue;\n }\n\n try {\n updates$.next(createUpdateBatch(list));\n } catch {\n // a subscriber threw — isolate it so it can't tear down the watcher\n }\n }\n })().catch(() => {\n // keepalive only exits on abort; swallow so a terminal failure\n // never surfaces as an unhandled rejection\n });\n });\n },\n\n stop() {\n controller?.abort();\n controller = undefined;\n updates$.complete();\n },\n };\n}\n","import { type ContelloClient, type Schema, type SourceDef, createContelloClient } from '@contello/client';\n\nimport {\n type Assets,\n type AssetsOptions,\n type AssetsSync,\n type AssetsSyncOptions,\n createAssetsCollection,\n createAssetsSyncCollection,\n} from './assets';\nimport { createCollection, createCollectionSync } from './collection';\nimport { type I18nMessageDef, type I18nMessages, createI18nMessagesCollection } from './i18n';\nimport { type LazyAssets, type LazyAssetsOptions, createLazyAssetsCollection } from './lazy-assets';\nimport { createLazyCollection } from './lazy-collection';\nimport { type LazyRoutes, type LazyRoutesOptions, createLazyRoutesCollection } from './lazy-routes';\nimport { ModelResolver } from './model-resolver';\nimport {\n type Routes,\n type RoutesOptions,\n type RoutesSync,\n type RoutesSyncOptions,\n createRoutesCollection,\n createRoutesSyncCollection,\n} from './routes';\nimport { createSingleton, createSingletonSync } from './singleton';\nimport { wrap } from './telemetry';\nimport type {\n BuiltInWrites,\n Collection,\n CollectionOptions,\n CollectionSync,\n CollectionSyncOptions,\n CreateStoreOptions,\n ExtractSourceResult,\n ExtractSourceWrites,\n LazyCollection,\n LazyCollectionOptions,\n ResolveSource,\n Singleton,\n SingletonOptions,\n SingletonSync,\n SingletonSyncOptions,\n SourceKeysOf,\n} from './types';\nimport { type RefreshByTtlQueue, createRefreshByTtlQueue } from './utils';\nimport { type InternalWatcher, type UpdateBatch, createInternalWatcher } from './watcher';\n\n/** Project the model-reference-name union out of a Schema generic, falling back to `string`. */\ntype ModelsOf<TSchema> = TSchema extends { models: infer M } ? keyof M & string : string;\n\ntype CollectionArg<TSchema> = SourceKeysOf<TSchema, 'entity'> | SourceDef<ModelsOf<TSchema>, 'entity'>;\ntype SingletonArg<TSchema> = SourceKeysOf<TSchema, 'singleton'> | SourceDef<ModelsOf<TSchema>, 'singleton'>;\n\ntype CollectionRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'entity'>>\n>;\n/** The write-input shape the source carries — `unknown` for sources the generator bound no mutations to. */\ntype CollectionWritesOf<TSchema, TArg> = ExtractSourceWrites<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'entity'>>\n>;\ntype RouteWrites<TSchema> = BuiltInWrites<TSchema, 'route'>;\ntype AssetWrites<TSchema> = BuiltInWrites<TSchema, 'asset'>;\ntype SingletonRaw<TSchema, TArg> = ExtractSourceResult<\n Extract<ResolveSource<TSchema, TArg>, SourceDef<string, 'singleton'>>\n>;\n\nexport class Store<TSchema extends Schema | undefined = undefined> {\n private _client: ContelloClient<TSchema>;\n private _resolver: ModelResolver;\n private _watcher: InternalWatcher;\n private _schema: TSchema;\n private _cleanups: (() => void)[] = [];\n private _refreshByTtl: RefreshByTtlQueue = createRefreshByTtlQueue();\n\n /**\n * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;\n * each iteration starts an independent fan-out from the shared source.\n */\n public readonly updates$: AsyncIterable<UpdateBatch>;\n\n public ping: () => Promise<void>;\n\n constructor(options: CreateStoreOptions<TSchema>) {\n const { url, project, token, schema } = options;\n\n this._schema = schema as TSchema;\n this._client = createContelloClient<TSchema>({\n url,\n project,\n token,\n schema,\n connections: options.connections,\n onConnected: options.onConnected,\n onReconnecting: options.onReconnecting,\n onError: options.onError,\n connectionEvents: options.connectionEvents,\n });\n\n this._resolver = new ModelResolver(schema?.models);\n this._watcher = createInternalWatcher(this._client, this._resolver);\n this.updates$ = this._watcher.updates$;\n this.ping = () => this._client.ping();\n }\n\n /** Resolve a string key (looked up via `schema.sources`) or a SourceDef directly to a SourceDef. */\n private _resolveSource<T extends SourceDef>(sourceOrKey: string | T): T {\n if (typeof sourceOrKey !== 'string') {\n return sourceOrKey;\n }\n\n const sources = (this._schema as Schema | undefined)?.sources;\n const source = sources?.[sourceOrKey];\n\n if (!source) {\n throw new Error(`@contello/store: no source named \"${sourceOrKey}\" in schema.sources`);\n }\n\n return source as T;\n }\n\n public get client(): ContelloClient<TSchema> {\n return this._client;\n }\n\n public async init() {\n await wrap('store:init', () => this._client.init());\n\n this._watcher.start();\n }\n\n public async destroy() {\n for (const fn of this._cleanups.splice(0)) {\n try {\n fn();\n } catch {\n // swallow — destruction is best-effort\n }\n }\n\n this._watcher.stop();\n\n await wrap('store:destroy', () => this._client.destroy());\n }\n\n // --- singleton ---\n\n public defineSingleton<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Singleton<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'singleton'>;\n const { instance, destroy } = createSingleton(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as Singleton<TMapped>;\n }\n\n public defineSingletonSync<TArg extends SingletonArg<TSchema>, TMapped = SingletonRaw<TSchema, TArg>>(\n sourceOrKey: TArg,\n options?: SingletonSyncOptions<SingletonRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): SingletonSync<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'singleton'>;\n const { instance, destroy } = createSingletonSync(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as SingletonSync<TMapped>;\n }\n\n // --- collection ---\n\n public defineCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): Collection<TMapped, CollectionWritesOf<TSchema, TArg>> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createCollection(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as unknown as Collection<TMapped, CollectionWritesOf<TSchema, TArg>>;\n }\n\n public defineCollectionSync<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: CollectionSyncOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): CollectionSync<TMapped, CollectionWritesOf<TSchema, TArg>> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createCollectionSync(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as unknown as CollectionSync<TMapped, CollectionWritesOf<TSchema, TArg>>;\n }\n\n // --- lazy collection ---\n\n public defineLazyCollection<\n TArg extends CollectionArg<TSchema>,\n TMapped extends { id: string } = CollectionRaw<TSchema, TArg> & { id: string },\n >(\n sourceOrKey: TArg,\n options?: LazyCollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>,\n ): LazyCollection<TMapped> {\n const source = this._resolveSource(sourceOrKey as string | SourceDef) as SourceDef<string, 'entity'>;\n const { instance, destroy } = createLazyCollection(\n source,\n options as any,\n this._client,\n this._watcher.updates$,\n this._resolver,\n );\n\n this._cleanups.push(destroy);\n\n return instance as LazyCollection<TMapped>;\n }\n\n // --- assets / routes / i18n (no source — built-ins) ---\n\n // --- assets ---\n\n public defineAssets(options?: AssetsOptions | undefined): Assets<AssetWrites<TSchema>> {\n const { instance, destroy } = createAssetsCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as Assets<AssetWrites<TSchema>>;\n }\n\n public defineAssetsSync(options?: AssetsSyncOptions | undefined): AssetsSync<AssetWrites<TSchema>> {\n const { instance, destroy } = createAssetsSyncCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as AssetsSync<AssetWrites<TSchema>>;\n }\n\n public defineLazyAssets(options?: LazyAssetsOptions | undefined): LazyAssets {\n const { instance, destroy } = createLazyAssetsCollection(options, this._client, this._watcher.updates$);\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n // --- routes ---\n\n public defineRoutes(options?: RoutesOptions | undefined): Routes<RouteWrites<TSchema>> {\n const { instance, destroy } = createRoutesCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as Routes<RouteWrites<TSchema>>;\n }\n\n public defineRoutesSync(options?: RoutesSyncOptions | undefined): RoutesSync<RouteWrites<TSchema>> {\n const { instance, destroy } = createRoutesSyncCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n this._refreshByTtl,\n );\n\n this._cleanups.push(destroy);\n\n return instance as RoutesSync<RouteWrites<TSchema>>;\n }\n\n public defineLazyRoutes(options?: LazyRoutesOptions | undefined): LazyRoutes {\n const { instance, destroy } = createLazyRoutesCollection(\n options,\n this._client,\n this._watcher.updates$,\n this._resolver,\n );\n\n this._cleanups.push(destroy);\n\n return instance;\n }\n\n public defineI18nMessages(def: I18nMessageDef): I18nMessages {\n const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$, this._refreshByTtl);\n\n this._cleanups.push(result.destroy);\n\n return result;\n }\n}\n\nexport function createStore<TSchema extends Schema | undefined = undefined>(\n options: CreateStoreOptions<TSchema>,\n): Store<TSchema> {\n return new Store(options);\n}\n"],"mappings":";;;;;;;;AAopBA,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;AAmBjC,MAAM,0BAA0B;;;;;;;;;;;;;;AAchC,MAAM,2BAA2B;;;AAMjC,MAAM,iCAAiC;;;;;;;;;;AAUvC,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCjC,MAAa,oCAAoC;;;;;;;;;AASjD,MAAa,4BAA4B,GAAG,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgGrE,MAAa,SAAS;CAAE;EAzCtB,2BAA2B;GAAE,UAAU;GAAmC,MAAM;EAAW;EAC3F,mBAAmB;GAAE,UAAU;GAA2B,MAAM;EAAe;CAwCzD;CAAY;EApClC,YAAY;GACV,UAAU,GAAG,wBAAwB,IAAI,yBAAyB,IAAI;GACtE,UAAU;GACV,cAAc;GACd,WAAW;IACT,QAAQ;KAAE,OAAO;KAAuB,WAAW,CAAC;MAAE,MAAM;MAAW,MAAM;MAA6B,MAAM;KAAQ,CAAC;KAAG,QAAQ;IAAS;IAC7I,QAAQ;KAAE,OAAO;KAAuB,WAAW,CAAC;MAAE,MAAM;MAAM,MAAM;MAAW,MAAM;KAAK,CAAC;KAAG,QAAQ;IAAW;GACvH;GACA,SAAS;GACT,eAAe;EACjB;EACA,kBAAkB;GAChB,UAAU;GACV,UAAU;GACV,cAAc;GACd,SAAS;GACT,eAAe;EACjB;EACA,YAAY;GACV,UAAU;GACV,UAAU;GACV,cAAc;GACd,WAAW;IACT,QAAQ;KAAE,OAAO;KAAuB,WAAW,CAAC;MAAE,MAAM;MAAS,MAAM;MAAuB,MAAM;KAAQ,CAAC;KAAG,QAAQ;IAAS;IACrI,QAAQ;KAAE,OAAO;KAAuB,WAAW,CAAC;MAAE,MAAM;MAAS,MAAM;MAA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