@tech4good/platform-data 0.1.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BACKENDS.md +161 -0
- package/EXTRACTION-CHANGES.md +1011 -0
- package/FUTURE-WORK.md +328 -0
- package/MIGRATION.md +227 -0
- package/README.md +536 -0
- package/fesm2022/tech4good-platform-data-firestore.mjs +281 -0
- package/fesm2022/tech4good-platform-data-firestore.mjs.map +1 -0
- package/fesm2022/tech4good-platform-data-material.mjs +15 -0
- package/fesm2022/tech4good-platform-data-material.mjs.map +1 -0
- package/fesm2022/tech4good-platform-data-testing.mjs +479 -0
- package/fesm2022/tech4good-platform-data-testing.mjs.map +1 -0
- package/fesm2022/tech4good-platform-data.mjs +2190 -0
- package/fesm2022/tech4good-platform-data.mjs.map +1 -0
- package/package.json +51 -0
- package/types/tech4good-platform-data-firestore.d.ts +83 -0
- package/types/tech4good-platform-data-firestore.d.ts.map +1 -0
- package/types/tech4good-platform-data-material.d.ts +7 -0
- package/types/tech4good-platform-data-material.d.ts.map +1 -0
- package/types/tech4good-platform-data-testing.d.ts +236 -0
- package/types/tech4good-platform-data-testing.d.ts.map +1 -0
- package/types/tech4good-platform-data.d.ts +686 -0
- package/types/tech4good-platform-data.d.ts.map +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tech4good-platform-data.mjs","sources":["../../src/entity-definition.ts","../../src/timestamp.ts","../../src/data-access.ts","../../src/feedback.ts","../../src/config.ts","../../src/selectors.ts","../../src/query-descriptors.ts","../../src/stream-multiplexer.ts","../../src/cached-listeners.ts","../../src/undo.ts","../../src/entity-store.ts","../../src/batch-write.ts","../../src/public-api.ts","../../src/tech4good-platform-data.ts"],"sourcesContent":["import { DataEntity } from './model';\n\ndeclare const entityType: unique symbol;\n\n/**\n * Runtime collection identity paired with a compile-time record type.\n * Keep the definition beside its interface in *.model.ts. It contains no seeds\n * or store instances, so production code can import it without mock dependencies.\n */\nexport interface EntityDefinition<T extends DataEntity = DataEntity> {\n /** Persisted collection name, shared by the entity store and generated registry. */\n readonly collection: string;\n /** Type-only association. No entity instance or mock data is stored here. */\n readonly [entityType]?: T;\n}\n\n/** Recover the record type from a definition, as the generated AppEntityMap does. */\nexport type EntityType<D extends EntityDefinition> = D extends EntityDefinition<infer T> ? T : never;\n\n/**\n * Declare an entity for t4g-entities to discover; this does not create a database\n * collection or register Angular providers. Export a top-level const with a\n * literal collection name so discovery can read it without executing app code.\n *\n * @example\n * export const problemEntity = defineEntity<Problem>({ collection: 'problems' });\n */\nexport function defineEntity<T extends DataEntity>(definition: { collection: string }): EntityDefinition<T> {\n const name = definition.collection;\n if (!name || name.trim() !== name || name.includes('/') || name === '.' || name === '..' || /^__.*__$/.test(name)) {\n throw new Error(`Invalid entity collection name: ${JSON.stringify(name)}`);\n }\n return Object.freeze({ collection: name });\n}\n","/** A finite instant relative to 1970-01-01T00:00:00Z. No timezone or database SDK. */\nexport interface DataTimestamp {\n /** Explicit JSON-safe marker; ordinary seconds/nanoseconds objects remain ordinary data. */\n readonly __type: 'DataTimestamp';\n readonly seconds: number;\n readonly nanoseconds: number;\n}\n\n/**\n * Construct an immutable value from already-normalized parts; out-of-range\n * nanoseconds are rejected, not carried into seconds. Negative instants use\n * negative seconds and positive nanoseconds: (-1, 500000000) is 0.5s before epoch.\n */\nexport function dataTimestamp(seconds: number, nanoseconds = 0): DataTimestamp {\n if (!Number.isSafeInteger(seconds) || !Number.isInteger(nanoseconds) || nanoseconds < 0 || nanoseconds >= 1e9) {\n throw new RangeError('A DataTimestamp requires safe integer seconds and nanoseconds from 0 to 999999999.');\n }\n return Object.freeze({ __type: 'DataTimestamp', seconds: seconds === 0 ? 0 : seconds, nanoseconds: nanoseconds === 0 ? 0 : nanoseconds });\n}\n\n/** Validate the marker and numeric parts, including values read back from JSON. */\nexport function isDataTimestamp(value: unknown): value is DataTimestamp {\n if (!value || typeof value !== 'object') return false;\n const timestamp = value as Partial<DataTimestamp>;\n return timestamp.__type === 'DataTimestamp' && Number.isSafeInteger(timestamp.seconds) &&\n Number.isInteger(timestamp.nanoseconds) && timestamp.nanoseconds! >= 0 && timestamp.nanoseconds! < 1e9;\n}\n\n/** Millisecond input is rounded to the nearest nanosecond; use dataTimestamp for exact values. */\nexport function dataTimestampFromMillis(milliseconds: number): DataTimestamp {\n if (!Number.isFinite(milliseconds)) throw new RangeError('Timestamp milliseconds must be finite.');\n const seconds = Math.floor(milliseconds / 1000);\n const nanoseconds = Math.round((milliseconds - seconds * 1000) * 1e6);\n return nanoseconds === 1e9 ? dataTimestamp(seconds + 1) : dataTimestamp(seconds, nanoseconds);\n}\n\n/** Local clock estimate for optimistic records; database adapters own authoritative write times. */\nexport function dataTimestampNow(): DataTimestamp { return dataTimestampFromMillis(Date.now()); }\n/** Convert a valid Date; its timezone display does not change the represented instant. */\nexport function dataTimestampFromDate(date: Date): DataTimestamp { return dataTimestampFromMillis(date.getTime()); }\n\n/** Potentially lossy numeric conversion, intended for display and the existing load-time clock. */\nexport function dataTimestampToMillis(value: DataTimestamp): number {\n return value.seconds * 1000 + value.nanoseconds / 1e6;\n}\n\n/** Millisecond display conversion. Do not use this to round-trip database timestamps. */\nexport function dataTimestampToDate(value: DataTimestamp): Date {\n const date = new Date(dataTimestampToMillis(value));\n if (!Number.isFinite(date.getTime())) throw new RangeError('Timestamp is outside the JavaScript Date range.');\n return date;\n}\n\n/** Exact chronological comparison without floating-point epoch conversion. */\nexport function compareDataTimestamps(a: DataTimestamp, b: DataTimestamp): number {\n return a.seconds === b.seconds ? Math.sign(a.nanoseconds - b.nanoseconds) : a.seconds < b.seconds ? -1 : 1;\n}\n\n/** Compare timestamp values rather than object identity; matching null/undefined also compare equal. */\nexport function dataTimestampEquals(a: DataTimestamp | null | undefined, b: DataTimestamp | null | undefined): boolean {\n return a === b || (isDataTimestamp(a) && isDataTimestamp(b) && a.seconds === b.seconds && a.nanoseconds === b.nanoseconds);\n}\n","import { InjectionToken } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { DataEntity, NewDataEntity, QueryParams, QueryOptions } from './model';\nimport { WriteBatchI } from './batch-write';\n/**\n * Backend operations consumed by entity stores. Implementations translate\n * shared timestamps and query descriptors into their backend's representation.\n * These methods apply only the supplied filters; the store layer adds its\n * active/deleted and incremental-load filters. Authentication is app-owned.\n */\nexport interface DataAccess {\n /** Allocate an ID without persisting a record. */\n createId(): string;\n /** Observe a document, emitting null when absent; unsubscribe releases the listener. */\n streamEntity<T>(collectionName: string, id: string): Observable<T | null>;\n /** Observe complete query results on each update. */\n streamEntities<T>(collectionName, queryParams, queryOptions?): Observable<T[]>;\n /**\n * Observe added/modified/removed query members, including initial added records.\n * A removed event can mean the record left the query, not that it was deleted.\n */\n streamEntitiesChanges<T>(\n collectionName,\n queryParams,\n queryOptions?,\n ): Observable<\n {\n type: string;\n docData: T;\n }[]\n >;\n /** Read once without opening a persistent listener. */\n getEntity<T>(collectionName: string, id: string): Promise<T | null>;\n getEntities<S>(\n collectionName: string,\n queryParams: [string, string, any][],\n queryOptions?: { [index: string]: any },\n ): Promise<S[]>;\n count(\n collectionName: string,\n queryParams: QueryParams,\n queryOptions?: QueryOptions,\n ): Promise<number>;\n /** Named aggregates: { total: ['count'], averageScore: ['average', 'score'] }. */\n aggregate<S extends { [k: string]: number }>(\n collectionName: string,\n queryParams: QueryParams,\n queryOptions: QueryOptions,\n aggregateParams: { [K in keyof S]: [string] | [string, string] },\n ): Promise<{ [K in keyof S]: number | null }>;\n /** Write a record with metadata, or queue it in the supplied uncommitted batch. */\n addEntity<T extends NewDataEntity & { __id: string }>(collectionName: string, entity: T, batch?: WriteBatchI): Promise<any>;\n /** Apply changes and advance _updatedAt; a supplied batch must be committed separately. */\n updateEntity<T extends object>(\n collectionName: string,\n id: string,\n changes: Partial<T>,\n batch?: WriteBatchI,\n ): Promise<any>;\n /** Soft-delete and advance _updatedAt so incremental loads can observe the removal. */\n removeEntity(collectionName: string, id: string, batch?: WriteBatchI): Promise<any>;\n incrementEntityField(collectionName, id, field, delta): Promise<void>;\n}\n\n/** Provide the selected adapter here; core stores never inject a backend SDK. */\nexport const DATA_ACCESS = new InjectionToken<DataAccess>('PlatformDataAccess');\n/** Compatibility alias; this is the same token, not another provider. */\nexport const DATABASE_SERVICE = DATA_ACCESS;\nexport type DatabaseService = DataAccess;\n","import { InjectionToken } from '@angular/core';\nimport { EMPTY, Observable } from 'rxjs';\n\n/** UI-neutral configuration; the Material adapter accepts MatSnackBarConfig. */\nexport type FeedbackConfig = object;\n/**\n * Minimal notification interface used by write success/failure and undo flows.\n * An adapter presents the message and emits onAction when the user chooses Undo.\n * Keeping the interface here lets core run without Angular Material.\n */\nexport interface DataFeedback {\n open(message: string, action?: string, config?: FeedbackConfig): {\n onAction(): Observable<void>;\n };\n}\n/** Silent default: writes still work, but no notification or undo action is presented. */\nexport const NOOP_DATA_FEEDBACK: DataFeedback = {\n open: () => ({ onAction: () => EMPTY }),\n};\nexport const DATA_FEEDBACK = new InjectionToken<DataFeedback>('PlatformDataFeedback', {\n providedIn: 'root', factory: () => NOOP_DATA_FEEDBACK,\n});\n","import { makeEnvironmentProviders, EnvironmentProviders } from '@angular/core';\nimport { DATA_FEEDBACK, DataFeedback } from './feedback';\n\n/** Optional write-feedback integration; omitting it retains the no-op implementation. */\nexport interface PlatformDataOptions {\n feedback?: DataFeedback;\n}\n/**\n * Configure write feedback in the application's providers. App-wide diagnostic\n * logging is configured separately with providePlatformLogging from platform-logging.\n * This does not select a database: also provide a DATA_ACCESS adapter and a\n * matching batch service, using provideFirestoreData or provideMockData.\n */\nexport function providePlatformData(options: PlatformDataOptions = {}): EnvironmentProviders {\n return makeEnvironmentProviders([\n ...(options.feedback ? [{ provide: DATA_FEEDBACK, useValue: options.feedback }] : []),\n ]);\n}\n","import { isDataTimestamp } from './timestamp';\nimport { QueryOptions, QueryParams } from './model';\n\n/** Read dotted field paths; local __name__ queries refer to the record's __id. */\nexport function fieldValue(entity: any, path: string): any {\n if (path === '__name__') return entity.__id;\n return path.split('.').reduce((value, key) => value?.[key], entity);\n}\n/** Compare objects by their contents and preserve types when building cache keys. */\nfunction canonical(value: any): any {\n if (value === undefined) return ['undefined'];\n if (value === null) return ['null'];\n if (typeof value === 'number') return ['number', String(value)];\n if (typeof value !== 'object') return [typeof value, value];\n if (value instanceof Date) return ['date', value.toISOString()];\n if (isDataTimestamp(value)) {\n return ['timestamp', value.seconds, value.nanoseconds];\n }\n if (Array.isArray(value)) return ['array', value.map(canonical)];\n return ['object', Object.keys(value).sort().map(key => [key, canonical(value[key])])];\n}\n/** Stable, type-preserving keys; never mutates a query supplied by the app. */\nexport function stableQueryKey(collection: string, params: QueryParams = [], options: QueryOptions = {}): string {\n return JSON.stringify([collection, params.map(param => JSON.stringify(canonical(param))).sort(), canonical(options ?? {})]);\n}\n/** Separately created timestamps, arrays and objects can still have equal values. */\nfunction equals(a: any, b: any): boolean {\n return Object.is(a, b) || JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));\n}\n/** Order different supported types consistently, without JavaScript's type coercion. */\nfunction valueRank(value: any): number {\n if (value === null) return 0;\n if (typeof value === 'boolean') return 1;\n if (typeof value === 'number') return 2;\n if (value instanceof Date || isDataTimestamp(value)) return 3;\n if (typeof value === 'string') return 4;\n if (Array.isArray(value)) return 5;\n if (value && Object.getPrototypeOf(value) === Object.prototype) return 6;\n throw new Error('Unsupported local ordering value; validate this query with the configured data adapter.');\n}\n/** Sort by type first, then by value; timestamps keep their nanosecond precision. */\nfunction compare(a: any, b: any): number {\n if (equals(a, b)) return 0;\n const aRank = valueRank(a);\n const bRank = valueRank(b);\n if (aRank !== bRank) return Math.sign(aRank - bRank);\n if (aRank === 2) {\n if (Number.isNaN(a)) return -1;\n if (Number.isNaN(b)) return 1;\n return a < b ? -1 : a > b ? 1 : 0;\n }\n if (aRank === 3) {\n // Compare whole seconds, then the fraction within that second. Date has only\n // millisecond precision; a shared timestamp can represent finer differences.\n const tuple = (v: any) => v instanceof Date ? [Math.floor(v.getTime() / 1000), (v.getTime() % 1000 + 1000) % 1000 * 1e6] : [v.seconds, v.nanoseconds];\n const [as, an] = tuple(a);\n const [bs, bn] = tuple(b);\n return as === bs ? Math.sign(an - bn) : Math.sign(as - bs);\n }\n if (aRank === 5) {\n // The first differing element decides array order; otherwise the shorter wins.\n for (let i = 0; i < Math.min(a.length, b.length); i++) {\n const result = compare(a[i], b[i]);\n if (result) return result;\n }\n return Math.sign(a.length - b.length);\n }\n if (aRank === 6) {\n // Sort keys first so object insertion order does not affect the comparison.\n const ak = Object.keys(a).sort();\n const bk = Object.keys(b).sort();\n for (let i = 0; i < Math.min(ak.length, bk.length); i++) {\n const keyResult = compare(ak[i], bk[i]);\n if (keyResult) return keyResult;\n const valueResult = compare(a[ak[i]], b[bk[i]]);\n if (valueResult) return valueResult;\n }\n return Math.sign(ak.length - bk.length);\n }\n return a < b ? -1 : a > b ? 1 : 0;\n}\n/**\n * Apply the field filters together: if any defined filter fails, exclude the record.\n * An undefined query operand is ignored, as explained by the optional __hashtagId\n * example in runQuery. That is different from a record missing the field needed\n * to satisfy a defined filter. For example, a record without an optional tags\n * array cannot match ['tags', 'array-contains', 'algebra'].\n */\nfunction matches(entity: any, params: QueryParams): boolean {\n return (params ?? []).every(([field, operator, operand]) => {\n if (operand === undefined) return true;\n const value = fieldValue(entity, field);\n if (value === undefined) return false;\n switch (operator) {\n case '==': return equals(value, operand);\n case '!=': return !equals(value, operand);\n case '>': return compare(value, operand) > 0;\n case '>=': return compare(value, operand) >= 0;\n case '<': return compare(value, operand) < 0;\n case '<=': return compare(value, operand) <= 0;\n case 'in': return Array.isArray(operand) && operand.some(v => equals(value, v));\n case 'not-in': return Array.isArray(operand) && value !== null && !operand.includes(null) && !operand.some(v => equals(value, v));\n case 'array-contains': return Array.isArray(value) && value.some(v => equals(v, operand));\n case 'array-contains-any': return Array.isArray(value) && Array.isArray(operand) && value.some(v => operand.some(o => equals(v, o)));\n default: throw new Error(`Unsupported query operator: ${operator}`);\n }\n });\n}\n/** Normalize the three supported orderBy shapes without changing the caller's options. */\nexport function queryOrderings(options: QueryOptions = {}): [string, string][] {\n const order = options?.orderBy;\n if (!order) return [];\n if (typeof order === 'string') return [[order, 'asc']];\n return Array.isArray(order[0]) ? order as [string, string][] : [order as [string, string]];\n}\n/**\n * Filter using startAt/startAfter/endAt/endBefore in the requested sort order.\n * The original local selector only supported a single ordered field. This helper\n * also handles multiple fields: with orderBy [['group', 'asc'], ['score', 'desc']],\n * startAfter ['algebra', 5] means after algebra/5 in that combined ordering.\n * Each descending field reverses its comparison; inclusive bounds keep equal values.\n */\nfunction withinCursors(entity: any, options: QueryOptions, orders: [string, string][]): boolean {\n return (['startAt', 'startAfter', 'endAt', 'endBefore'] as const).every(key => {\n if (options?.[key] === undefined) return true;\n if (!orders.length) throw new Error('Local query cursors require orderBy.');\n const cursor = Array.isArray(options[key]) ? options[key] : [options[key]];\n if (!cursor.length || cursor.length > orders.length) throw new Error('Cursor values must match the query orderings.');\n let result = 0;\n for (let i = 0; i < cursor.length; i++) {\n result = compare(fieldValue(entity, orders[i][0]), cursor[i]) * (orders[i][1] === 'desc' ? -1 : 1);\n if (result) break;\n }\n return key === 'startAt' ? result >= 0 : key === 'startAfter' ? result > 0 : key === 'endAt' ? result <= 0 : result < 0;\n });\n}\n/**\n * Check whether the entity satisfies the query results.\n * We use this to double-check whether a 'removed' change was truly removed from\n * the backend or whether it just doesn't match the query anymore. For example,\n * a post whose authorId changes leaves the old author's query, but can still be\n * needed by another query and should not be removed from the shared store solely\n * for leaving that result set.\n *\n * This checks filters, ordered fields and cursor bounds. A single entity cannot\n * establish membership in a limited result window; that also depends on other records.\n */\nexport function entityInQueryResults<T>(entity: T, params: QueryParams = [], options: QueryOptions = {}): boolean {\n if (!entity || !matches(entity, params)) return false;\n const orders = queryOrderings(options);\n // If orderBy is provided, only return entities that have each ordered property,\n // just like Firestore. A null value is present; an undefined field is missing.\n return orders.every(([field]) => fieldValue(entity, field) !== undefined) && withinCursors(entity, options, orders);\n}\n/**\n * The selection steps shared by frontend selectors and mock database reads:\n * narrow by ID, apply the remaining filters, then order and limit the results.\n * Entity maps are keyed by the record's string __id, as required by DataEntity.\n * activeOnly hides deleted records for the frontend; the mock needs to query them.\n */\nfunction runQuery<T>(entityMap: Record<string, T>, queryParams: QueryParams, queryOptions: QueryOptions, activeOnly: boolean): T[] {\n // 1. START WITH ID FILTERS so a small ID query does not scan the whole store.\n // Note: Firestore supports setting and querying for null, but not undefined.\n // We filter out cases where the value is undefined to protect against cases\n // when people are doing a nested query and some entity does not have a\n // particular field, e.g. [['__hashtagId', '==', q.__hashtagId]] when\n // __hashtagId is an optional parameter.\n // This ignores only that filter: other filters still apply. It does not skip\n // the whole query, and a defined ID that is not loaded must still return [].\n const filters = (queryParams ?? []).filter(([, , value]) => value !== undefined);\n const selectIdEqQueries = filters.filter(([key, rel]) => key === '__id' && rel === '==');\n const uniqSelectEqIds = [...new Set(selectIdEqQueries.map(([, , id]) => id))];\n const selectIdInQueries = filters.filter(([key, rel]) => key === '__id' && rel === 'in');\n let filteredEntities: T[] = [];\n\n if (uniqSelectEqIds.length === 1) {\n // Exactly one required ID: look it up directly, even if it is not loaded.\n const id = uniqSelectEqIds[0];\n const entity = typeof id === 'string' && Object.hasOwn(entityMap, id) ? entityMap[id] : undefined;\n // Missing IDs have no matches. Do not fall through to all loaded records.\n if (!entity) return [];\n filteredEntities.push(entity);\n } else if (uniqSelectEqIds.length > 1) {\n // One record cannot have two different IDs (e.g. __id == 'a' AND __id == 'b').\n return [];\n } else if (selectIdInQueries.length > 0) {\n // Start with the first ID list, looking up each unique ID directly.\n // Empty lists match nothing; missing IDs and undefined list entries add nothing.\n const firstInIds = selectIdInQueries[0][2];\n if (!Array.isArray(firstInIds)) return [];\n filteredEntities = [...new Set(firstInIds)]\n .filter(id => typeof id === 'string' && Object.hasOwn(entityMap, id))\n .map(id => entityMap[id]);\n } else {\n // Without an ID ==/in filter, consider every record already in the map.\n filteredEntities = Object.values(entityMap);\n }\n\n // Every ID list must also match, including when the == branch supplied the record.\n // For example, __id == 'a' AND __id in ['b'] must return nothing.\n const allowedIdSets = selectIdInQueries.map(([, , ids]) => new Set(Array.isArray(ids) ? ids : []));\n filteredEntities = filteredEntities.filter(entity =>\n entity && allowedIdSets.every(ids => ids.has(entity['__id'])) &&\n (!activeOnly || !entity['_deleted']));\n\n // 2. APPLY THE REMAINING FILTERS. ID ==/in have been fully handled above.\n // The common predicate helper also checks ordered fields and cursor bounds.\n const remainingFilters = filters.filter(([key, rel]) =>\n !(key === '__id' && (rel === '==' || rel === 'in')));\n filteredEntities = filteredEntities.filter(entity =>\n entityInQueryResults(entity, remainingFilters, queryOptions));\n\n // 3. SORT BY EACH REQUESTED FIELD, using the ID to break ties consistently.\n const orders = queryOrderings(queryOptions);\n if (orders.length) {\n filteredEntities.sort((a, b) => {\n for (const [field, direction] of orders) {\n const result = compare(fieldValue(a, field), fieldValue(b, field));\n if (result) return result * (direction === 'desc' ? -1 : 1);\n }\n return compare(fieldValue(a, '__id'), fieldValue(b, '__id')) * (orders.at(-1)[1] === 'desc' ? -1 : 1);\n });\n }\n\n // 4. APPLY THE LIMIT LAST, after filtering (including deletion) and ordering.\n if (queryOptions?.limit !== undefined) {\n if (!Number.isInteger(queryOptions.limit) || queryOptions.limit < 1) throw new Error('Query limit must be a positive integer.');\n filteredEntities = filteredEntities.slice(0, queryOptions.limit);\n }\n return filteredEntities;\n}\n\n/**\n * Mock database query: use the ID-first steps in runQuery without hiding deletions.\n * In particular, the loader's _deleted == true query must return those records.\n */\nexport function queryEntities<T>(entityMap: Record<string, T>, params: QueryParams = [], options: QueryOptions = {}): T[] {\n return runQuery(entityMap, params, options, false);\n}\n/**\n * Select entities already in the store, given its entityMap and query constraints.\n * Filters out records marked _deleted even if a caller explicitly includes a\n * _deleted filter, so a frontend selector cannot expose a soft-deleted record.\n * The mock backend instead uses queryEntities: the loader needs its separate\n * _deleted == true query to return deletion markers and remove cached records.\n */\nexport function selectEntities<T>(entityMap: Record<string, T>, params: QueryParams = [], options: QueryOptions = {}): T[] {\n return runQuery(entityMap, params, options, true);\n}\n","import { DataEntity as AnyEntity, QueryParams, QueryOptions } from './model';\n/**\n * Expand child-load descriptors for parent records and execute compatible groups\n * together. Each position in the callback's returned array represents one child\n * relationship; batching also checks collection/store/callback identity before\n * combining requests. Firestore rejects an empty `in` list, so the helper skips\n * the entire descriptor containing it. Other descriptors still run, and skipping\n * a load does not clear records already held in the frontend store.\n */\nexport async function processLoadQueries<T extends { __id: string }>(entities: T[], loadQueries: (entity: T) => EntityLoadQuery<AnyEntity>[]) {\n if (entities.length > 0) {\n // create a matrix of queries, each row corresponding to a given entity\n const queriesByEntity = entities.map((entity) => loadQueries!(entity));\n\n // transpose the matrix so each row corresponds to all queries for the same query type\n const queriesByQueryType = Array.from({ length: Math.max(0, ...queriesByEntity.map(row => row.length)) }, (_, colIndex) => queriesByEntity.map(row => row[colIndex]).filter(Boolean));\n\n // Process all query types concurrently\n await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {\n // Seeing if we can optimize by collapsing equality queries into 'in' queries\n const optimizedQueries = EntityLoadQuery.optimize(queriesForOneType);\n\n // Process queries concurrently using Promise.all\n await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {\n // Firestore throws an error if an 'in' query is executed with an empty array.\n // Therefore, we skip executing any queries that have an 'in' clause with an empty array.\n // Example: ['__id', 'in', []]\n if (!query.queryParams.some((param) => Array.isArray(param[2]) && param[2].length === 0 && param[1] === 'in')) {\n await query.store.load(query.queryParams, query.queryOptions, query.loadQueries);\n }\n }));\n }));\n }\n}\n\n/**\n * Description of a nested one-shot load. Construction does not run the query;\n * processLoadQueries passes it to the owning store. Generated Load<Entity>\n * subclasses supply collection identity and the entity's domain type.\n */\nexport class EntityLoadQuery<T> {\n collection: string;\n queryParams: QueryParams;\n queryOptions: QueryOptions;\n loadQueries: (entity: T) => EntityLoadQuery<AnyEntity>[];\n store;\n\n constructor(\n collection: string,\n store,\n queryParams: QueryParams,\n queryOptions: QueryOptions,\n loadQueries?: (entity: T) => EntityLoadQuery<AnyEntity>[],\n ) {\n this.collection = collection;\n this.queryParams = queryParams;\n this.queryOptions = queryOptions;\n this.loadQueries = loadQueries;\n this.store = store;\n }\n\n // Checks if there is a single equality query of the same type\n // that could be transformed into an 'in' query\n static areBatchableEqualityQueries<T>(queries: EntityLoadQuery<T>[]): boolean {\n if (queries.length === 0) return false;\n\n // check if there is only one queryParam for each query and no queryOptions\n const hasSingleQueryParamAndNoOptions = queries.every((q) => {\n return q.queryParams.length === 1 && (!q.queryOptions || Object.keys(q.queryOptions).length === 0);\n });\n\n if (!hasSingleQueryParamAndNoOptions) return false;\n\n // Finally, verify that every query is filtering on the exact same field\n // (e.g., they are all querying '__userId') AND that they are all using the\n // exact equality operator ('=='). This ensures they can be safely collapsed\n // into a single 'in' query (e.g., '__userId in [1, 2, 3]').\n const firstField = queries[0].queryParams[0][0];\n return queries.every((q) => q.collection === queries[0].collection && q.store === queries[0].store && q.loadQueries === queries[0].loadQueries && q.queryParams[0][2] !== undefined && q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');\n }\n\n /**\n * Optimize N+1 loads: N parents requesting children with one equality filter\n * each (e.g. [['__postId', '==', x]]) would otherwise cause N separate requests.\n * With no queryOptions, compatible requests can be combined into an 'in' query;\n * load() then splits it into backend-sized chunks of at most 30 values.\n * See https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.\n *\n * Batching changes the query key when a parent is added or removed. Tracking\n * only the whole query's lastLoadTime would then lose incremental-load reuse\n * and could refetch already-loaded children. The current loader tracks cutoff\n * times per field/value and groups compatible times before chunking, retaining\n * that reuse while reducing separate backend requests.\n */\n static optimize<T>(queries: EntityLoadQuery<T>[]): EntityLoadQuery<T>[] {\n if (this.areBatchableEqualityQueries<T>(queries)) {\n // get the field we are querying against\n const collection: string = queries[0].collection;\n const field: string = queries[0].queryParams[0][0];\n const loadQs: (entity: T) => EntityLoadQuery<AnyEntity>[] = queries[0].loadQueries;\n\n // We no longer chunk into groups of 30 here. Instead, we bundle ALL IDs into a single 'in'\n // query. The `load()` method will intercept this unified query, generate a single `newLoadTime`,\n // and perform the 30-item chunking internally. This guarantees that all entities requested\n // together receive the exact same timestamp.\n const ids = queries.map((q) => q.queryParams[0][2]);\n return [new EntityLoadQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, loadQs)];\n } else {\n return queries;\n }\n }\n}\n\n/**\n * Description of a nested live query. CachedListenersService establishes the\n * listener using the caller's injector and processes further child descriptors\n * as parent records change. Constructing a descriptor alone opens no listener.\n */\nexport class EntityStreamQuery<T> {\n collection: string;\n queryParams: QueryParams;\n queryOptions: QueryOptions;\n streamQueries: (entity: T) => EntityStreamQuery<AnyEntity>[];\n store;\n\n constructor(\n collection: string,\n store,\n queryParams: QueryParams,\n queryOptions: QueryOptions,\n streamQueries?: (entity: T) => EntityStreamQuery<AnyEntity>[],\n ) {\n this.collection = collection;\n this.queryParams = queryParams;\n this.queryOptions = queryOptions;\n this.streamQueries = streamQueries;\n this.store = store;\n }\n\n // Checks if there is a single equality query of the same type\n // that could be transformed into an 'in' query\n static areBatchableEqualityQueries<T>(queries: EntityStreamQuery<T>[]): boolean {\n if (queries.length === 0) return false;\n\n // check if there is only one queryParam for each query and no queryOptions\n const hasSingleQueryParamAndNoOptions = queries.every((q) => {\n return q.queryParams.length === 1 && (!q.queryOptions || Object.keys(q.queryOptions).length === 0);\n });\n\n if (!hasSingleQueryParamAndNoOptions) return false;\n\n // Finally, verify that every query is filtering on the exact same field\n // (e.g., they are all querying '__userId') AND that they are all using the\n // exact equality operator ('=='). This ensures they can be safely collapsed\n // into a single 'in' query (e.g., '__userId in [1, 2, 3]').\n const firstField = queries[0].queryParams[0][0];\n return queries.every((q) => q.collection === queries[0].collection && q.store === queries[0].store && q.streamQueries === queries[0].streamQueries && q.queryParams[0][2] !== undefined && q.queryParams[0][0] === firstField && q.queryParams[0][1] === '==');\n }\n\n /**\n * Optimize N+1 streams: combine compatible single-equality child queries such\n * as [['__postId', '==', x]], with no queryOptions, into one descriptor. The\n * multiplexer opens 'in' listeners with at most 30 values per batch downstream.\n * See https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any.\n *\n * The pairwise diff in CachedListenersService re-evaluates nested queries only\n * for changed parents. The initial N parents can be collapsed together, while\n * later individual changes typically request a single value; the multiplexer\n * manages those sparse listeners and repacks them when appropriate.\n *\n * Batched listeners share the parent component's DestroyRef for cleanup, just\n * as individual listeners do. Batching does not give them a longer lifetime.\n */\n static optimize<T>(queries: EntityStreamQuery<T>[]): EntityStreamQuery<T>[] {\n // Keep all requested IDs in one descriptor. Listener chunking and reference\n // counting happen downstream, where component DestroyRefs are available.\n if (this.areBatchableEqualityQueries<T>(queries)) {\n // get the field we are querying against\n const collection: string = queries[0].collection;\n const field: string = queries[0].queryParams[0][0];\n const streamQs: (entity: T) => EntityStreamQuery<AnyEntity>[] = queries[0].streamQueries;\n\n const ids = queries.map((q) => q.queryParams[0][2]);\n return [new EntityStreamQuery<T>(collection, queries[0].store, [[field, 'in', ids]], {}, streamQs)];\n } else {\n return queries;\n }\n }\n}\n","import { DestroyRef } from '@angular/core';\nimport { DataAccess as DatabaseService } from './data-access';\nimport { entityInQueryResults } from './selectors';\nimport { Logger, NOOP_LOGGER } from '@tech4good/platform-logging';\nimport { QueryParams, DataEntity as AnyEntity } from './model';\n\n\n\n/**\n * Combines component requests for one store/collection/field into batched 'in'\n * queries through DataAccess. The current batch size follows Firestore's limit.\n *\n * It manages two pools of logical listeners (transport connections belong to the adapter):\n * 1. `batchedListeners`: fully packed 'in' queries (chunks of 30 IDs).\n * 2. `singleListeners`: sparse 'in' queries handling newly requested IDs.\n *\n * It balances stream connection limits with UI rendering performance by maintaining\n * sparse streams until a threshold is reached, at which point it automatically triggers\n * an `executeSmartRepack` to consolidate streams and release redundant listeners.\n *\n * It tracks component lifecycles using `DestroyRef` to gracefully tear down streams\n * when components are destroyed and their requested IDs become \"orphaned\".\n */\nexport class StreamMultiplexer<T extends AnyEntity = AnyEntity> {\n private retiring = new Set<{ ids: string[]; unsubscribe: (() => void) | null }>();\n private generation = 0;\n // Maps a unique query value ID (e.g., a specific user ID) to the set of component DestroyRefs that requested it.\n private destroyRefsById = new Map<string, Set<DestroyRef>>();\n\n // Maps a component's DestroyRef to the set of IDs it requested. This allows us to safely clean up all of a component's\n // requested IDs when it is destroyed, even if it called registerIds multiple times.\n private idsByDestroyRef = new Map<DestroyRef, Set<string>>();\n\n // Tracks optimized batches of up to 30 IDs\n private batchedListeners: Array<{ ids: string[], unsubscribe: (() => void) | null }> = [];\n\n // Tracks newly added small groups of IDs that haven't been repacked yet\n private singleListeners: Array<{ ids: string[], unsubscribe: (() => void) | null }> = [];\n\n // Threshold for determining when a batch is \"sparse\" enough to warrant evaluating a repack operation.\n private readonly MAX_ORPHANED_IDS_PER_BATCH = 10;\n\n // Threshold for determining when we have accumulated enough single listeners to warrant repacking them into a batch.\n private readonly MAX_SINGLE_LISTENERS_BEFORE_REPACK = 10;\n\n constructor(\n private collection: string,\n private field: string,\n private db: DatabaseService,\n private store: { handleStreamChanges(entitiesToAdd: T[], entitiesToModify: T[], entitiesToRemove: string[]): void }, // NgRx Signal Store with handleStreamChanges\n private queryLogger: Logger = NOOP_LOGGER,\n private onError: (error: unknown) => void = () => {},\n ) {}\n\n /**\n * Checks if an ID is currently being actively streamed by any component.\n */\n isIdActive(id: string): boolean {\n return this.destroyRefsById.has(id) && this.destroyRefsById.get(id)!.size > 0;\n }\n\n /**\n * Registers a list of query values to stream through the configured adapter.\n * Duplicate requests for the same ID are deduplicated.\n * Automatically handles teardown when the provided destroyRef fires.\n */\n registerIds(ids: string[], destroyRef: DestroyRef) {\n this.queryLogger.log(`[StreamMultiplexer] registerIds called with: [${Array.from(ids).join(', ')}]`);\n const newIds: string[] = [];\n\n // We maintain a reverse lookup from DestroyRef -> IDs to easily clean up when the component is destroyed.\n let idsForDestroyRef = this.idsByDestroyRef.get(destroyRef);\n const isFirstRegistrationForRef = !idsForDestroyRef;\n\n // Initialize the set if this is the very first time this DestroyRef is calling registerIds()\n if (!idsForDestroyRef) {\n idsForDestroyRef = new Set();\n this.idsByDestroyRef.set(destroyRef, idsForDestroyRef);\n }\n\n ids.forEach((id) => {\n // Add the requested ID to the component's tracking set so it can be safely cleaned up later\n idsForDestroyRef.add(id);\n\n // Look up if this exact ID is already being actively streamed by anyone else in the application\n let registeredSet = this.destroyRefsById.get(id);\n if (!registeredSet) {\n // First time this ID has been requested anywhere!\n // We create a new Set to track all the specific DestroyRefs that have requested it.\n registeredSet = new Set();\n this.destroyRefsById.set(id, registeredSet);\n\n // Track this as a new ID that needs to be streamed\n newIds.push(id);\n }\n registeredSet.add(destroyRef);\n });\n\n // Handle teardown when the component is destroyed\n if (isFirstRegistrationForRef) {\n destroyRef.onDestroy(() => {\n setTimeout(() => {\n let triggeredRemove = false;\n\n // Retrieve the dynamically accumulated set of IDs that were requested by this specific component's DestroyRef.\n // By pulling from this Map instead of a closed-over lexical variable, we ensure we clean up ALL IDs\n // requested across multiple calls to registerIds() by the same component.\n const idsToClean = this.idsByDestroyRef.get(destroyRef);\n if (idsToClean) {\n this.queryLogger.log(`[StreamMultiplexer] Component destroyed 5 seconds ago! Releasing its holds on IDs: [${Array.from(idsToClean).join(', ')}]`);\n idsToClean.forEach((id) => {\n const registeredSet = this.destroyRefsById.get(id);\n if (registeredSet && registeredSet.has(destroyRef)) {\n // Remove this component's claim to the ID\n registeredSet.delete(destroyRef);\n\n // If no other components are currently listening to this ID,\n // completely remove it from the globally active set.\n if (registeredSet.size === 0) {\n this.destroyRefsById.delete(id);\n triggeredRemove = true;\n }\n }\n });\n\n // Cleanup the tracking Map itself to prevent memory leaks\n this.idsByDestroyRef.delete(destroyRef);\n }\n\n if (triggeredRemove) {\n this.cleanupEmptyListeners();\n if (this.hasBatchWithTooManyOrphans()) {\n this.executeSmartRepack();\n }\n }\n }, 5000); // 5-second graceful shutdown period\n });\n }\n\n this.checkAndExecuteRepack(newIds);\n }\n\n /**\n * Evaluates whether the multiplexer should execute a repack operation.\n * A repack is executed if either:\n * 1. A new ID request pushes the projected single listener count over the MAX_SINGLE_LISTENERS_BEFORE_REPACK threshold.\n * 2. An orphaned batch cleanup check triggered this evaluation.\n *\n * If new IDs are requested but the threshold is not met, this method simply spins up\n * a single sparse stream for those IDs to prioritize immediate UI rendering speed.\n *\n * @param newIds - Array of newly requested IDs that are not yet streamed.\n */\n private checkAndExecuteRepack(newIds: string[]) {\n if (newIds.length > 0) {\n const numNewBatches = Math.ceil(newIds.length / 30);\n const projectedSingleListeners = this.singleListeners.length + numNewBatches;\n\n // If adding these new IDs would push us over the threshold, just execute a repack directly.\n // The repack logic will automatically pick up all unstreamed IDs.\n if (projectedSingleListeners >= this.MAX_SINGLE_LISTENERS_BEFORE_REPACK) {\n this.executeSmartRepack(newIds);\n } else {\n // Otherwise, spin up a new listener for the newly requested IDs\n const newChunks = this.chunkArray(newIds, 30);\n const newBatches = this.startNewBatches(newChunks, []);\n\n // We separate full batches from sparse single listeners\n newBatches.forEach((b) => {\n if (b.ids.length === 30) {\n this.batchedListeners.push(b);\n } else {\n this.singleListeners.push(b);\n }\n });\n }\n }\n }\n\n /**\n * Completely tears down all active streams and resets the multiplexer state.\n * Useful when the user logs out or the entire parent collection listener is destroyed.\n */\n teardownAll() {\n this.generation++;\n this.teardownOldListeners([...this.retiring]);\n this.retiring.clear();\n this.batchedListeners.forEach((b) => {\n if (b.unsubscribe) b.unsubscribe();\n });\n this.batchedListeners = [];\n\n this.singleListeners.forEach((s) => {\n if (s.unsubscribe) s.unsubscribe();\n });\n this.singleListeners = [];\n\n this.destroyRefsById.clear();\n this.idsByDestroyRef.clear();\n }\n\n /**\n * Identifies any listeners (both single and batched) where EVERY SINGLE ID has 0 active holds.\n * If an entire stream is completely abandoned, it is immediately unsubscribed and purged to prevent\n * dead sockets from hanging around indefinitely.\n */\n private cleanupEmptyListeners() {\n const activeIds = new Set(this.destroyRefsById.keys());\n\n const emptyBatches = this.batchedListeners.filter((b) => b.ids.every((id) => !activeIds.has(id)));\n if (emptyBatches.length > 0) {\n this.queryLogger.log(`[StreamMultiplexer] Purging ${emptyBatches.length} completely empty batched stream(s).`);\n emptyBatches.forEach((b) => {\n if (b.unsubscribe) {\n b.unsubscribe();\n b.unsubscribe = null;\n }\n });\n this.batchedListeners = this.batchedListeners.filter((b) => !emptyBatches.includes(b));\n }\n\n const emptySingles = this.singleListeners.filter((s) => s.ids.every((id) => !activeIds.has(id)));\n if (emptySingles.length > 0) {\n this.queryLogger.log(`[StreamMultiplexer] Purging ${emptySingles.length} completely empty single stream(s).`);\n emptySingles.forEach((s) => {\n if (s.unsubscribe) {\n s.unsubscribe();\n s.unsubscribe = null;\n }\n });\n this.singleListeners = this.singleListeners.filter((s) => !emptySingles.includes(s));\n }\n }\n\n /**\n * Checks if any of the currently active websocket listeners has too many \"orphaned\" IDs\n * (IDs that are being streamed from Firestore but are no longer requested by any component).\n */\n private hasBatchWithTooManyOrphans(): boolean {\n return this.batchedListeners.some((batch) => {\n const orphans = batch.ids.filter((id) => {\n const refs = this.destroyRefsById.get(id);\n return !refs || refs.size === 0;\n }).length;\n return orphans >= this.MAX_ORPHANED_IDS_PER_BATCH;\n });\n }\n\n /**\n * Consolidates sparse streams and tears down bloated batches.\n *\n * It uses a greedy mathematical algorithm to evaluate \"candidate batches\" (those with <= 25 active IDs)\n * and determine if tearing them down and bundling their active IDs with the single listeners will\n * result in a net reduction in the total number of websocket streams.\n *\n * Note: This method does not check threshold conditions before executing. Callers\n * (e.g. checkAndExecuteRepack) must verify that a repack is strictly necessary\n * before invoking this method.\n *\n * @param newIds - Array of newly requested IDs that need to be streamed.\n */\n private executeSmartRepack(newIds: string[] = []) {\n this.queryLogger.log(`[StreamMultiplexer] Smart Repack Triggered!`);\n\n const activeIds = new Set(this.destroyRefsById.keys());\n\n // 1. Gather all single listeners and new IDs into one pool\n const singleIds: string[] = [];\n this.singleListeners.forEach((s) => singleIds.push(...s.ids.filter((id) => activeIds.has(id))));\n singleIds.push(...newIds);\n\n const S = singleIds.length;\n\n // 2. Identify sparse batches (<= 25 active IDs) as candidates for mathematical reduction\n const candidateBatches = this.batchedListeners\n .map((batch) => ({\n batch,\n activeCount: batch.ids.filter((id) => activeIds.has(id)).length,\n }))\n .filter((b) => b.activeCount <= 25);\n\n // 3. Sort candidates ascending so we combine the sparsest batches first\n candidateBatches.sort((a, b) => a.activeCount - b.activeCount);\n\n // Baseline reduction: bundling all single listeners into tight chunks\n let bestReduction = S > 0 ? S - Math.ceil(S / 30) : 0;\n let bestT: Array<{ ids: string[], unsubscribe: (() => void) | null }> = [];\n\n let currentA = 0;\n const currentT: Array<{ ids: string[], unsubscribe: (() => void) | null }> = [];\n\n // 4. Greedily evaluate absorbing sparse batches to maximize stream reduction\n for (let i = 0; i < candidateBatches.length; i++) {\n currentT.push(candidateBatches[i].batch);\n currentA += candidateBatches[i].activeCount;\n\n const newBatchesCount = Math.ceil((S + currentA) / 30);\n const reduction = S + currentT.length - newBatchesCount;\n\n if (reduction > bestReduction) {\n bestReduction = reduction;\n bestT = [...currentT];\n }\n }\n\n // 5. Ensure we also forcibly tear down any bloated batches (>= 10 orphans)\n // even if they didn't mathematically reduce the total stream count.\n const bloatedBatches = this.batchedListeners.filter((batch) => {\n const orphans = batch.ids.filter((id) => !activeIds.has(id)).length;\n return orphans >= this.MAX_ORPHANED_IDS_PER_BATCH;\n });\n\n bloatedBatches.forEach((b) => {\n if (!bestT.includes(b)) {\n bestT.push(b);\n }\n });\n\n const batchesToTeardown = bestT;\n const singleListenersToTeardown = [...this.singleListeners];\n\n // 6. Collect all the actively requested IDs from the streams we are about to tear down\n const idsToChunk: string[] = [...singleIds];\n batchesToTeardown.forEach((b) => {\n idsToChunk.push(...b.ids.filter((id) => activeIds.has(id)));\n });\n\n // 7. If there's nothing left to stream, just clean up state and return\n if (idsToChunk.length === 0) {\n this.finalizeRepackState(batchesToTeardown, singleListenersToTeardown, []);\n return;\n }\n\n // 8. Break the collected IDs into optimal chunks of 30 for Firestore 'in' queries\n const newChunks = this.chunkArray(idsToChunk, 30);\n\n // 9. Spin up the new websocket streams, passing the old ones to be torn down only AFTER the new ones emit data\n const newBatches = this.startNewBatches(newChunks, [...batchesToTeardown, ...singleListenersToTeardown]);\n\n // 10. Update our internal tracking arrays to reflect the new state\n this.finalizeRepackState(batchesToTeardown, singleListenersToTeardown, newBatches);\n }\n\n /**\n * Opens new Firestore snapshot streams for the given chunks of IDs.\n *\n * @param newChunks - The fully chunked arrays of IDs to stream (max 30 per chunk).\n * @param oldBatchesToTeardown - The old websocket listeners that these new chunks are replacing.\n * They are only torn down *after* the new stream emits its first\n * payload, preventing UI flickering.\n */\n private startNewBatches(newChunks: string[][], oldBatchesToTeardown: Array<{ ids: string[], unsubscribe: (() => void) | null }>) {\n if (newChunks.length > 0) {\n this.queryLogger.log(`[StreamMultiplexer] Opening ${newChunks.length} new websocket stream(s) for chunks:`);\n newChunks.forEach((c) => this.queryLogger.log(` - [${c.join(', ')}]`));\n }\n const newBatches: Array<{ ids: string[], unsubscribe: (() => void) | null }> = [];\n\n const epoch = this.generation;\n let remaining = newChunks.length;\n oldBatchesToTeardown.forEach(batch => this.retiring.add(batch));\n for (const chunk of newChunks) {\n if (epoch !== this.generation) break;\n let isFirstEmission = true;\n const queryParams: QueryParams = chunk.length === 1 ?\n [[this.field, '==', chunk[0]]] : [[this.field, 'in', chunk]];\n const subscription = this.db.streamEntitiesChanges<T>(this.collection, queryParams, {}).subscribe({\n next: changes => {\n if (epoch !== this.generation) return;\n this.patchToStore(changes, queryParams);\n if (isFirstEmission) {\n isFirstEmission = false;\n if (--remaining === 0) this.teardownOldListeners(oldBatchesToTeardown);\n }\n },\n error: error => {\n this.onError(error);\n this.queryLogger.error('Data stream failed; a subsequent stream request can retry.', error);\n this.teardownAll();\n },\n });\n if (epoch === this.generation) newBatches.push({ ids: chunk, unsubscribe: () => subscription.unsubscribe() });\n else subscription.unsubscribe();\n }\n return newBatches;\n }\n\n /**\n * Unsubscribes from the old listener sockets to clean up the network connections.\n */\n private teardownOldListeners(oldBatches: Array<{ ids: string[], unsubscribe: (() => void) | null }>) {\n if (oldBatches.length > 0) {\n this.queryLogger.log(`[StreamMultiplexer] Tearing down ${oldBatches.length} old websocket stream(s).`);\n oldBatches.forEach((b) => {\n this.retiring.delete(b);\n this.queryLogger.log(` - [${b.ids.join(', ')}]`);\n if (b.unsubscribe) {\n b.unsubscribe();\n b.unsubscribe = null;\n }\n });\n }\n }\n\n /**\n * Cleans up the multiplexer state arrays by removing the objects for the torn down streams\n * and pushing the newly created streams into the correct `batchedListeners` or `singleListeners` array.\n */\n private finalizeRepackState(\n oldBatchesToTeardown: Array<{ ids: string[], unsubscribe: (() => void) | null }>,\n oldSingleListenersToTeardown: Array<{ ids: string[], unsubscribe: (() => void) | null }>,\n newBatches: Array<{ ids: string[], unsubscribe: (() => void) | null }>,\n ) {\n this.batchedListeners = this.batchedListeners.filter((b) => !oldBatchesToTeardown.includes(b));\n this.singleListeners = this.singleListeners.filter((s) => !oldSingleListenersToTeardown.includes(s));\n\n newBatches.forEach((b) => {\n if (b.ids.length === 30) {\n this.batchedListeners.push(b);\n } else {\n this.singleListeners.push(b);\n }\n });\n }\n\n /**\n * Utility to split an array of IDs into smaller chunks (max 30 for Firestore 'in' queries).\n */\n private chunkArray(array: string[], size: number): string[][] {\n return Array.from({ length: Math.ceil(array.length / size) }, (v, i) => array.slice(i * size, i * size + size));\n }\n\n /**\n * Takes the raw DocumentChange payload from Firestore and formats it into\n * added/modified/removed arrays that the NgRx Signal Store can easily process.\n */\n private patchToStore(fbPayload: Array<{ type: string, docData: T }>, queryParams: QueryParams) {\n const entitiesToAdd = fbPayload\n .filter((dc) => dc.type === 'added' && !dc.docData['_deleted'])\n .map((dc) => dc.docData);\n\n const entitiesToModify = fbPayload\n .filter((dc) => dc.type === 'modified' && !dc.docData['_deleted'])\n .map((dc) => dc.docData);\n\n const entitiesToRemove = fbPayload\n .filter((dc) => dc.type === 'modified' && dc.docData['_deleted'])\n .map((dc) => dc.docData['__id']);\n\n const entitiesToModify2 = fbPayload\n .filter((dc) => dc.type === 'removed' && !entityInQueryResults(dc.docData, queryParams, {}))\n .map((dc) => dc.docData);\n\n const entitiesToRemove2 = fbPayload\n .filter((dc) => dc.type === 'removed' && entityInQueryResults(dc.docData, queryParams, {}))\n .map((dc) => dc.docData['__id']);\n\n this.store.handleStreamChanges(\n entitiesToAdd,\n [...entitiesToModify, ...entitiesToModify2],\n [...entitiesToRemove, ...entitiesToRemove2],\n );\n }\n}\n","import { dataTimestampEquals, isDataTimestamp } from './timestamp';\nimport { Inject, Injectable, WritableSignal, Signal, Injector, inject, DestroyRef, computed, effect, untracked } from '@angular/core';\nimport { Subject, Observable, merge, forkJoin, of, from, pipe } from 'rxjs';\nimport { startWith, pairwise, share, tap, pluck, mergeMap, filter, takeUntil, skipUntil, buffer, skip, switchMap, map, take } from 'rxjs/operators';\nimport { setEntities, setEntity, removeEntities, SelectEntityId } from '@ngrx/signals/entities';\nimport { EntityLoadQuery, EntityStreamQuery } from './query-descriptors';\nimport { entityInQueryResults, stableQueryKey } from './selectors';\nimport { QueryParams, QueryOptions, DataEntity as AnyEntity } from './model';\nimport { DATA_ACCESS as DATABASE_SERVICE, DataAccess as DatabaseService } from './data-access';\nimport { StreamMultiplexer } from './stream-multiplexer';\nimport { injectLogger } from '@tech4good/platform-logging';\n\nconst selectId: SelectEntityId<AnyEntity> = (entity) => entity.__id;\n\nexport interface CachedConnection {\n queryKey: string;\n registeredSet: Set<DestroyRef>;\n closed?: boolean;\n}\n\n\n/** Equal timestamps are not a record revision: multiple local writes can share a clock tick. */\nfunction entityChanged(previous: Record<string, unknown>, current: Record<string, unknown>): boolean {\n if (previous === current) return false;\n const keys = Object.keys(current);\n if (keys.length !== Object.keys(previous).length) return true;\n return keys.some(key => {\n const before = previous[key];\n const after = current[key];\n return isDataTimestamp(before) && isDataTimestamp(after)\n ? !dataTimestampEquals(before, after)\n : !Object.prototype.hasOwnProperty.call(previous, key) || !Object.is(before, after);\n });\n}\n\n/**\n * CachedListenersService manages database connections and their lifecycles to\n * ensure optimal performance, prevent memory leaks, and solve the N+1 query problem.\n *\n * Responsibilities:\n * 1. **Listener Pooling**: Deduplicates active database snapshot listeners. If\n * multiple components request the exact same query, only one actual database\n * listener is opened. Components share one root store per collection, so the\n * shared listener updates the same records for all those components.\n * 2. **Reference Counting & Lifecycle Management**: Tracks which components are using\n * which stream via their Angular `DestroyRef`. When a component is destroyed, its\n * reference is removed.\n * 3. **Graceful Teardown**: Implements a 5-second grace period before fully closing a\n * database connection after its last reference drops. This prevents UI flicker and\n * unnecessary DB reads if the user navigates away and immediately back.\n * 4. **Load Time Tracking (One-shot Loads)**: Tracks `lastLoadTime` for general queries\n * and precise `entityLoadTime` for optimized batch equality queries. This enables\n * incremental (delta-only) fetching, drastically reducing bandwidth by only fetching\n * entities modified since the last load.\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class CachedListenersService {\n /** Prevent nested stream callbacks from restarting listeners after global teardown. */\n private streamGeneration = 0;\n private queryLogger = injectLogger('data');\n private streamErrors = new Subject<unknown>();\n private nestedObservers = new Set<() => void>();\n private reportStreamError(error: unknown): void {\n this.queryLogger.error('Nested data stream failed', error);\n this.streamErrors.next(error);\n }\n\n /** Dispose nested signal observers on component destruction or global listener teardown. */\n private observeNested(source: Signal<any[]>, injector: Injector): Observable<any[]> {\n return new Observable(subscriber => {\n const destroyRef = injector.get(DestroyRef);\n if (destroyRef.destroyed) { subscriber.complete(); return; }\n const watcher = effect(() => {\n try { const value = source(); untracked(() => subscriber.next(value)); }\n catch (error) { subscriber.error(error); }\n }, { injector, manualCleanup: true });\n const complete = () => subscriber.complete();\n const unregister = destroyRef.onDestroy(complete);\n this.nestedObservers.add(complete);\n return () => {\n watcher.destroy();\n unregister();\n this.nestedObservers.delete(complete);\n };\n });\n }\n\n /** Nested asynchronous failures, which cannot be returned from the initial stream call. */\n readonly errors$ = this.streamErrors.asObservable();\n\n /** Listener claims keyed by collection and canonical query. */\n private connectionByQueryKey: Record<string, CachedConnection> = {};\n\n /** Active equality multiplexers keyed by collection and field. */\n private streamMultiplexers = new Map<string, StreamMultiplexer>();\n\n /** Close connection events. */\n private closeConnection$: Subject<string> = new Subject<string>();\n\n\n /** Query cutoffs grouped by collection so resetting one store preserves the others. */\n private lastLoadTime = new Map<string, Map<string, number>>();\n\n /** Per-value equality cutoffs grouped by collection, in local-clock milliseconds. */\n private entityLoadTime = new Map<string, Map<string, number>>();\n\n getEntityLoadTime(collection: string, field: string, value: string): number {\n return this.entityLoadTime.get(collection)?.get(this.getQueryKey(collection, [[field, '==', value]], {})) ?? -1;\n }\n\n setEntityLoadTime(collection: string, field: string, value: string, time: number): void {\n let history = this.entityLoadTime.get(collection);\n if (!history) this.entityLoadTime.set(collection, history = new Map());\n history.set(this.getQueryKey(collection, [[field, '==', value]], {}), time);\n }\n\n /** Define a unique key for each connection. */\n private getQueryKey(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): string {\n return stableQueryKey(collection, queryParams, queryOptions);\n }\n\n /**\n * Tears down active adapter listeners before authentication is removed.\n * Retains records and load history so cached stores can keep loading deltas.\n * Ordinary reads/writes already in flight still finish normally.\n */\n teardownAllStreams(): void {\n this.streamGeneration++;\n for (const complete of [...this.nestedObservers]) complete();\n for (const key of Object.keys(this.connectionByQueryKey)) {\n const connection = this.connectionByQueryKey[key];\n if (connection) {\n this.closeConnection$.next(key);\n connection.registeredSet.clear();\n }\n }\n this.connectionByQueryKey = {};\n\n for (const multiplexer of this.streamMultiplexers.values()) {\n multiplexer.teardownAll();\n }\n this.streamMultiplexers.clear();\n }\n\n /** Forget all query/value cutoffs for one collection when its store is reset. */\n clearLoadHistory(collection: string): void {\n this.lastLoadTime.delete(collection);\n this.entityLoadTime.delete(collection);\n }\n\n /**\n * Explicitly close all listeners and clear every collection's load history, e.g. in tests.\n * Does not clear entity records or cancel pending reads/writes.\n */\n clearCache(): void {\n this.teardownAllStreams();\n this.lastLoadTime.clear();\n this.entityLoadTime.clear();\n }\n\n /** Return whether a stream exists for this query. */\n isStreamForQuery(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): boolean {\n const queryKey = this.getQueryKey(collection, queryParams, queryOptions);\n return !!this.connectionByQueryKey[queryKey];\n }\n\n /** Return whether a specific ID is currently being streamed by a multiplexer. */\n isIdStreamed(collection: string, field: string, id: string): boolean {\n const multiplexerKey = stableQueryKey(collection, [[field, '==', null]], {});\n const multiplexer = this.streamMultiplexers.get(multiplexerKey);\n return multiplexer ? multiplexer.isIdActive(id) : false;\n }\n\n /** Get the last load time for a particular query. */\n getLastLoadTime(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): number {\n // If there are queryOptions, we don't support saving load times\n if (queryOptions && Object.keys(queryOptions).length > 0) return -1;\n\n const queryKey = this.getQueryKey(collection, queryParams, queryOptions);\n return this.lastLoadTime.get(collection)?.get(queryKey) ?? -1;\n }\n\n /** Set the last load time for a particular query. */\n setLastLoadTime(collection: string, queryParams: QueryParams, queryOptions: QueryOptions, time: number): void {\n // If there are queryOptions, we don't support saving load times\n if (queryOptions && Object.keys(queryOptions).length > 0) return;\n\n const queryKey = this.getQueryKey(collection, queryParams, queryOptions);\n let history = this.lastLoadTime.get(collection);\n if (!history) this.lastLoadTime.set(collection, history = new Map());\n history.set(queryKey, time);\n }\n\n /** Gets a cached connection if one exists. */\n private getConnection(collection: string, queryParams: QueryParams, queryOptions: QueryOptions): CachedConnection {\n const queryKey = this.getQueryKey(collection, queryParams, queryOptions);\n return this.connectionByQueryKey[queryKey];\n }\n\n /**\n * Attach/reuse a general query listener for this store and calling component.\n * DestroyRef releases the component's claim after the navigation grace period;\n * session resets bypass that delay. Optional descriptors add nested streams.\n */\n public async processStreamQuery<T extends AnyEntity>(\n collection: string,\n store,\n queryParams: QueryParams,\n queryOptions: QueryOptions,\n injector,\n streamQueries?: (entity: T) => EntityStreamQuery<AnyEntity>[],\n options?: {\n loading?: WritableSignal<boolean>,\n },\n ): Promise<CachedConnection> {\n this.queryLogger.log(`[CachedListenersService] processStreamQuery called for collection: '${collection}', query:`, JSON.stringify(queryParams));\n // console.log(\"PROCESS QUERY: \" + this.getQueryKey(collection, queryParams, queryOptions));\n\n // Get destroyRef for the component that called processStreamQuery\n // (which will be used to determine when to trigger unsubscribe)\n const destroyRef = injector.get(DestroyRef);\n const epoch = this.streamGeneration;\n\n // get connection and process the immediate query\n let connection = this.getConnection(collection, queryParams, queryOptions);\n\n if (connection) {\n // if the connection already exists, don't need to create a new connection,\n // but may need to add the DestroyRef if it doesn't already exist\n if (!connection.registeredSet.has(destroyRef)) {\n connection.registeredSet.add(destroyRef);\n }\n } else {\n // if the connection does not exist, create it and initialize the\n // registeredSet to include destroyRef\n // this function also will subscribe and link to the store\n connection = this.createConnection<T>(collection, store, queryParams, queryOptions, destroyRef);\n if (!connection.closed) this.connectionByQueryKey[connection.queryKey] = connection;\n }\n\n // Unregister from the connection when the component is destroyed\n // Disconnects the \"virtual\" connection. If this was the only DestroyRef,\n // then actually unsubscribe\n destroyRef.onDestroy(() => {\n // Add a 5-second delay so we don't have to reconnect multiple times\n // if the next view happens to use the same stream\n setTimeout(() => {\n // If the destroyRef is not in the set, it means this connection was already\n // cleared/cleaned up (e.g., via clearCache() in tests), so we bail out.\n if (!connection.registeredSet.has(destroyRef)) {\n return;\n }\n\n connection.registeredSet.delete(destroyRef);\n if (connection.registeredSet.size === 0) {\n // Verify that this connection is still the active connection in the cache map.\n // This is essential to prevent stale callbacks (e.g. from a previous test case\n // that was cleared via clearCache()) from overwriting a new active connection\n // in the cache or triggering premature disconnections.\n if (this.connectionByQueryKey[connection.queryKey] === connection) {\n this.closeConnection$.next(connection.queryKey);\n this.connectionByQueryKey[connection.queryKey] = undefined;\n }\n }\n }, 5000);\n });\n\n // For every new entity on the stream, process the nested streamQueries\n if (streamQueries) {\n // get the entities we're streaming as a signal. we do it here rather than\n // using the firestore stream so that we can always get the latest version\n // without needing to multicast the original stream to all future components\n // querying for the stream\n const streamEntities = computed(() => {\n return store.selectEntities(queryParams, queryOptions);\n });\n\n // convert to an observable, convert to the changes, then subscribe\n // Global teardown and component destruction both dispose the underlying effect.\n this.observeNested(streamEntities, injector).pipe(\n // convert to entityMap to more easily compare\n map((entities) => {\n const entityMap = {};\n for (const entity of entities) {\n entityMap[entity.__id] = entity;\n }\n return entityMap;\n }),\n // compare current with prior including the first\n startWith({}),\n pairwise(),\n // get the changedEntities\n map(([prevEntities, currEntities]) => {\n const changedEntities = [];\n for (const key in currEntities) {\n if (!(key in prevEntities)) {\n // the entity was added\n changedEntities.push({\n type: 'added',\n doc: currEntities[key],\n });\n } else if (currEntities[key]['_deleted']) {\n // the entity was removed\n changedEntities.push({\n type: 'removed',\n doc: currEntities[key],\n });\n } else if (entityChanged(prevEntities[key], currEntities[key])) {\n // the entity was modified\n changedEntities.push({\n type: 'modified',\n doc: currEntities[key],\n });\n }\n }\n\n return changedEntities;\n }),\n // We don't need the removed ones for nested streamQueries (but I just\n // included it above for debugging purposes so we can see all changes)\n map((changes) => changes.filter((c) => c.type !== 'removed')),\n filter((changes) => changes.length > 0),\n mergeMap(async (changes) => {\n if (epoch !== this.streamGeneration || destroyRef.destroyed) return;\n // create a matrix of queries, each row corresponding to a given entity\n const queriesByEntity = changes.map((change) => streamQueries(change.doc));\n\n // transpose the matrix so each row corresponds to all queries for the same query type\n const queriesByQueryType = Array.from({ length: Math.max(0, ...queriesByEntity.map(row => row.length)) }, (_, colIndex) => queriesByEntity.map(row => row[colIndex]).filter(Boolean));\n\n // Process all query types concurrently\n await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {\n // Seeing if we can optimize by collapsing equality queries into 'in' queries\n const optimizedQueries = EntityStreamQuery.optimize(queriesForOneType);\n\n // Process queries concurrently using Promise.all\n await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {\n const isSimpleChild = (!query.queryOptions || Object.keys(query.queryOptions).length === 0) &&\n query.queryParams.length === 1 &&\n (query.queryParams[0][1] === '==' || query.queryParams[0][1] === 'in');\n\n if (isSimpleChild) {\n const childField = query.queryParams[0][0];\n const childOp = query.queryParams[0][1];\n const childVal = query.queryParams[0][2];\n const childIds = childOp === 'in' ? childVal : [childVal];\n this.queryLogger.log(`[CachedListenersService] Nested query optimized to simple stream query: ${childField} in [${childIds}]`);\n await this.processSimpleStreamQuery(query.collection, childField, childIds, query.store, injector, query.streamQueries, { loading: options?.loading });\n } else {\n this.queryLogger.log(`[CachedListenersService] Nested query falling back to standard stream query:`, JSON.stringify(query.queryParams));\n await this.processStreamQuery(query.collection, query.store, query.queryParams, query.queryOptions, injector, query.streamQueries, { loading: options?.loading });\n }\n }));\n }));\n }),\n ).subscribe({ error: error => this.reportStreamError(error) });\n } else {\n // We'll turn off the loading indicator the first time there is a query that doesn't have nested queries\n // (ideally we'd want to turn if off after each of the streams have gotten their first entities, but I\n // don't think we can do that easily and this won't be too off)\n options?.loading?.set(false);\n }\n\n return connection;\n }\n\n /**\n * Optimized fast-path for simple streaming queries (e.g., `id in [1, 2, 3]`).\n * Instead of managing distinct complex RxJS subscription chains for every component, this delegates\n * ID registration to a centralized `StreamMultiplexer` (per collection/field).\n *\n * It also handles nested `streamQueries` (e.g. streaming a post's author) by listening to changes\n * to the parent entities, diffing them (`pairwise`), and setting up streams for the new children.\n */\n public async processSimpleStreamQuery<T extends AnyEntity>(\n collection: string,\n field: string,\n ids: string[],\n store: any,\n injector: any,\n streamQueries?: (entity: T) => EntityStreamQuery<AnyEntity>[],\n options?: { loading?: WritableSignal<boolean> },\n ): Promise<void> {\n this.queryLogger.log(`[CachedListenersService] processSimpleStreamQuery called for collection: '${collection}', field: '${field}', ids: [${ids}]`);\n\n if (!ids || ids.length === 0) {\n options?.loading?.set(false);\n return;\n }\n\n const destroyRef = injector.get(DestroyRef);\n const epoch = this.streamGeneration;\n const multiplexerKey = stableQueryKey(collection, [[field, '==', null]], {});\n\n let multiplexer = this.streamMultiplexers.get(multiplexerKey);\n if (!multiplexer) {\n multiplexer = new StreamMultiplexer(collection, field, this.db, store, this.queryLogger, error => this.streamErrors.next(error));\n this.streamMultiplexers.set(multiplexerKey, multiplexer);\n }\n multiplexer.registerIds(ids, destroyRef);\n\n if (streamQueries) {\n // 1. We select the entities from the store.\n // Because the selectors in `entity-store.ts` cache identical array references, `filteredSignal` will NOT trigger\n // spurious emissions if the underlying data has not actually changed.\n const filteredSignal = computed(() => {\n return store.selectEntities([[field, 'in', ids]], {});\n });\n\n // 2. We convert the signal to an observable to perform pairwise diffing.\n // This is necessary because if a parent entity is added or modified, we need to re-evaluate\n // its nested `streamQueries` (e.g., if a post's authorId changes, we must query the new author).\n this.observeNested(filteredSignal, injector).pipe(\n map((entities) => {\n const entityMap = {};\n for (const entity of entities) {\n entityMap[entity.__id] = entity;\n }\n return entityMap;\n }),\n startWith({}),\n pairwise(),\n map(([prevEntities, currEntities]) => {\n // 3. Diff the current entities against the previous entities to determine exactly\n // what was added, removed, or modified. The _deleted flag identifies\n // deletion. Compare _updatedAt by its timestamp value, and also check\n // other fields: two writes in the same clock tick can change a post's\n // authorId without producing different _updatedAt values. Comparing\n // only timestamps would miss the new author and its nested query.\n const changedEntities = [];\n for (const key in currEntities) {\n if (!(key in prevEntities)) {\n changedEntities.push({ type: 'added', doc: currEntities[key] });\n } else if (currEntities[key]['_deleted']) {\n changedEntities.push({ type: 'removed', doc: currEntities[key] });\n } else if (entityChanged(prevEntities[key], currEntities[key])) {\n changedEntities.push({ type: 'modified', doc: currEntities[key] });\n }\n }\n return changedEntities;\n }),\n map((changes) => changes.filter((c) => c.type !== 'removed')),\n filter((changes) => changes.length > 0),\n mergeMap(async (changes) => {\n if (epoch !== this.streamGeneration || destroyRef.destroyed) return;\n // 4. For every changed entity, evaluate its nested stream queries.\n const queriesByEntity = changes.map((change) => streamQueries(change.doc));\n if (queriesByEntity.length === 0) return;\n\n // 5. Transpose the matrix so each row corresponds to all queries of the same query type.\n // This allows us to group and optimize queries (e.g., combining 5 single equality queries into 1 'in' query).\n const queriesByQueryType = Array.from({ length: Math.max(0, ...queriesByEntity.map(row => row.length)) }, (_, colIndex) => queriesByEntity.map(row => row[colIndex]).filter(Boolean));\n\n await Promise.all(queriesByQueryType.map(async (queriesForOneType) => {\n const optimizedQueries = EntityStreamQuery.optimize(queriesForOneType);\n await Promise.all(optimizedQueries.filter((q) => !!q).map(async (query) => {\n const isSimpleChild = (!query.queryOptions || Object.keys(query.queryOptions).length === 0) &&\n query.queryParams.length === 1 &&\n (query.queryParams[0][1] === '==' || query.queryParams[0][1] === 'in');\n\n if (isSimpleChild) {\n const childField = query.queryParams[0][0];\n const childOp = query.queryParams[0][1];\n const childVal = query.queryParams[0][2];\n const childIds = childOp === 'in' ? childVal : [childVal];\n this.queryLogger.log(`[CachedListenersService] Nested query optimized to simple stream query: ${childField} in [${childIds}]`);\n await this.processSimpleStreamQuery(query.collection, childField, childIds, query.store, injector, query.streamQueries, { loading: options?.loading });\n } else {\n this.queryLogger.log(`[CachedListenersService] Nested query falling back to standard stream query:`, JSON.stringify(query.queryParams));\n await this.processStreamQuery(query.collection, query.store, query.queryParams, query.queryOptions, injector, query.streamQueries, { loading: options?.loading });\n }\n }));\n }));\n }),\n ).subscribe({ error: error => this.reportStreamError(error) });\n }\n\n // We'll turn off the loading indicator right away since we don't have a good way\n // to know when all individual streams are initialized yet.\n options?.loading?.set(false);\n }\n\n private createConnection<T>(collection: string, store: any, queryParams: QueryParams, queryOptions: QueryOptions, destroyRef: DestroyRef): CachedConnection {\n // console.log(\"CONNECT \" + this.getQueryKey(collection, queryParams, queryOptions));\n\n // ------------ DEFINE OBSERVABLES FOR DISCONNECTING ------------------------------\n\n const queryKey = this.getQueryKey(collection, queryParams, queryOptions);\n const disconnectObs$ = this.closeConnection$.pipe(\n filter((qk) => qk === queryKey),\n take(1),\n // tap(a => { console.log(\"DISCONNECT: \" + queryKey) }),\n share(),\n );\n\n const connection: CachedConnection = { queryKey, registeredSet: new Set([destroyRef]) };\n\n // ------------ HANDLE PATCHING TO STORE ------------------------------------------\n\n // Handle patching to the store\n this.db.streamEntitiesChanges(collection, queryParams, queryOptions).pipe(\n takeUntil(disconnectObs$),\n ).subscribe({ next: (fbPayload: Array<{ type: string, docData: AnyEntity }>) => {\n // Handle all the added entities\n const entitiesToAdd = fbPayload\n .filter((dc) => dc.type === 'added' && !dc.docData['_deleted'])\n .map((dc) => dc.docData);\n\n // Handle all the modified entities\n const entitiesToModify = fbPayload\n .filter((dc) => dc.type === 'modified' && !dc.docData['_deleted'])\n .map((dc) => dc.docData);\n\n // Handle all the removed entities\n const entitiesToRemove = fbPayload\n .filter((dc) => dc.type === 'modified' && dc.docData['_deleted'])\n .map((dc) => dc.docData['__id']);\n\n // Handle changes of the 'removed' type. In general, firebase 'removed'\n // could be due to no longer matching the stream query rather than being\n // deleted from the DB. this is why we use soft deletes (set _deleted to true).\n // We could still get 'removed' entries if there are manual deletions in the\n // database or when firestore is syncing updates after temporarily using\n // entities cached to IndexedDB.\n const entitiesToModify2 = fbPayload\n .filter((dc) => dc.type === 'removed' && !entityInQueryResults(dc.docData, queryParams, queryOptions))\n .map((dc) => dc.docData);\n\n const entitiesToRemove2 = fbPayload\n .filter((dc) => dc.type === 'removed' && entityInQueryResults(dc.docData, queryParams, queryOptions))\n .map((dc) => dc.docData['__id']);\n\n // Patch all the changes to the store\n store.handleStreamChanges(\n entitiesToAdd,\n [...entitiesToModify, ...entitiesToModify2],\n [...entitiesToRemove, ...entitiesToRemove2],\n );\n }, error: error => {\n connection.closed = true;\n connection.registeredSet.clear();\n this.streamErrors.next(error);\n this.queryLogger.error('Data stream failed; a subsequent stream request can retry.', error);\n this.closeConnection$.next(queryKey);\n delete this.connectionByQueryKey[queryKey];\n } });\n\n return connection;\n }\n\n constructor(\n @Inject(DATABASE_SERVICE) private db: DatabaseService,\n ) { }\n}\n","import { DataFeedback, FeedbackConfig } from './feedback';\nimport { WriteBatchI } from './batch-write';\n/**\n * Present successful-write feedback with an optional compensating undo.\n * Backend restoration must succeed before local state is reverted. Inverse\n * operations run in reverse order so dependent writes unwind correctly.\n * Undo is a new write attempt, not cancellation of the original commit.\n */\nexport function openSnackBarWithUndoOption(\n snackBar: DataFeedback,\n snackBarConfig: {\n successMessage: string,\n failureMessage: string,\n undoOnAction?: boolean,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config?: FeedbackConfig,\n },\n revertFns: Array<() => void>,\n dbRevertFns: Array<() => void>,\n revertBatch?: WriteBatchI,\n) {\n const snackBarRef = snackBar.open(\n snackBarConfig.successMessage,\n snackBarConfig.undoOnAction ? 'Undo' : '',\n snackBarConfig.config,\n );\n // if there is an undo option for the snackbar, then we should\n // revert both local and database changes if the undo was clicked\n if (snackBarConfig.undoOnAction) {\n snackBarRef.onAction().subscribe(async () => {\n try {\n // first try to undo changes on the database\n // dbRevertFns will directly remove from DB if not in the batch setting.\n // if it is a batch setting, it will do revertBatch.set to prepare\n // revertBatch for a commit\n for (const dbRevertFn of [...dbRevertFns].reverse()) await dbRevertFn();\n if (revertBatch) {\n await revertBatch.commit();\n }\n // if successful, then undo changes locally too\n [...revertFns].reverse().forEach((revertFn) => revertFn());\n } catch (e) {\n console.error(e);\n snackBar.open('Failed to undo', '', {\n duration: 3000,\n });\n }\n });\n }\n}\n","import { WritableSignal, inject } from '@angular/core';\nimport { dataTimestampNow, dataTimestampFromMillis } from './timestamp';\nimport { patchState, signalStoreFeature, withMethods } from '@ngrx/signals';\nimport { removeEntities, removeEntity, setEntities, setEntity, updateEntity, withEntities, setAllEntities, SelectEntityId } from '@ngrx/signals/entities';\nimport { CachedListenersService } from './cached-listeners';\nimport { DATA_ACCESS } from './data-access';\nimport { DataEntity as AnyEntity, NewDataEntity, QueryOptions, QueryParams } from './model';\nimport { DATA_FEEDBACK, FeedbackConfig } from './feedback';\nimport { injectLogger } from '@tech4good/platform-logging';\nimport { WriteBatchI } from './batch-write';\nimport { openSnackBarWithUndoOption } from './undo';\nimport { selectEntities } from './selectors';\nimport { EntityLoadQuery, EntityStreamQuery, processLoadQueries } from './query-descriptors';\nconst selectId: SelectEntityId<AnyEntity> = (entity) => entity.__id;\n/**\n * Add in-memory entity state, stream-change application and synchronous selectors.\n * Selectors hide soft-deleted records and only inspect already-loaded state;\n * they do not query the backend. Used by frontend and mock backend stores.\n */\nexport function withEntitiesAndSelectMethods<S extends AnyEntity>() {\n return signalStoreFeature(\n withEntities<S>(),\n withMethods((store) => {\n const queryCache = new Map<string, S[]>();\n return {\n handleStreamChanges(entitiesToAdd: S[], entitiesToModify: S[], entitiesToRemove: string[]) {\n patchState(store, setEntities(entitiesToAdd, { selectId }));\n patchState(store, setEntities(entitiesToModify, { selectId }));\n patchState(store, removeEntities(entitiesToRemove));\n },\n selectEntity(id: string): S | null {\n const result = store.entityMap()[id];\n\n if (result && !result['_deleted']) {\n return result;\n } else {\n return null;\n }\n },\n selectFirst(queryParams: QueryParams, queryOptions: QueryOptions): S | null {\n // Note: selectEntities already filters out _deleted\n const entities = selectEntities<S>(store.entityMap(), queryParams, queryOptions);\n if (entities && entities.length > 0) {\n return entities[0];\n } else {\n return null;\n }\n },\n selectEntities(queryParams: QueryParams, queryOptions: QueryOptions): S[] {\n // Note: The global standalone selectEntities function already filters out entities with _deleted: true\n const result = selectEntities<S>(store.entityMap(), queryParams, queryOptions);\n const key = JSON.stringify({ queryParams, queryOptions });\n\n // CRITICAL: Angular's computed() signals rely on strict referential equality (===).\n // Because Object.values().filter() creates a brand new array reference every time it is called,\n // any computed signal that calls selectEntities() would trigger an update even if the contents\n // of the array are identical. This led to infinite loops and massive memory leaks in nested streams.\n // By memoizing the array reference here, we ensure that if the query results are strictly identical\n // (same length, same entity references in the exact same order), we return the exact same array reference.\n const lastResult = queryCache.get(key);\n if (lastResult && lastResult.length === result.length && lastResult.every((v, i) => v === result[i])) {\n return lastResult;\n }\n\n queryCache.set(key, result);\n\n // Bound retained query results to 50 keys, evicting in insertion order.\n if (queryCache.size > 50) {\n const firstKey = queryCache.keys().next().value;\n if (firstKey) queryCache.delete(firstKey);\n }\n return result;\n },\n };\n }),\n );\n}\n\n/**\n * Add collection-specific load/stream/write methods to an NgRx signal store.\n * Provide one root store per collection so components share records and listeners.\n * DATA_ACCESS selects the backend. The app ends listeners through the cache service\n * and explicitly chooses which local stores to reset during logout.\n *\n * @example\n * export const ProblemStore = signalStore(\n * { providedIn: 'root' },\n * withEntitiesAndDBMethods<Problem>(problemEntity.collection),\n * );\n */\nexport function withEntitiesAndDBMethods<S extends AnyEntity>(collectionName: string) {\n return signalStoreFeature(\n withEntitiesAndSelectMethods<S>(),\n withMethods((store, cachedLoads = inject(CachedListenersService), db = inject(DATA_ACCESS), snackBar = inject(DATA_FEEDBACK), logger = injectLogger('data')) => ({\n /** Replace local state only; no records are written to the backend. */\n init(entities: S[]) {\n patchState(store, setAllEntities<S>(entities, { selectId }));\n },\n /** Empty this collection’s records and load history; listener teardown is separate. */\n reset() {\n cachedLoads.clearLoadHistory(collectionName);\n patchState(store, setAllEntities<S>([], { selectId }));\n },\n /**\n * Keep query results current for the lifetime of the caller's injector.\n * Pass a component/route injector, not the root injector, for scoped cleanup.\n * To reduce redundant database reads, matching queries reuse cached listeners.\n * After navigating away from a container, its listener claim has a 5-second\n * grace period before release, allowing a quick return to reuse the listener.\n * The injector's DestroyRef handles this; containers do not manually disconnect IDs.\n *\n * Nested streamQueries establish child streams, with simple equality filters\n * combined by the multiplexer to avoid one listener per parent. The older\n * comment about nested queries being load-only does not describe this method:\n * use load() and loadQueries for nested one-shot reads instead.\n */\n async stream(\n queryParams: QueryParams,\n queryOptions: QueryOptions,\n injector,\n streamQueries?: (entity: S) => EntityStreamQuery<AnyEntity>[],\n options?: {\n loading?: WritableSignal<boolean>, // set to true on start, set to false once all are complete\n },\n ) {\n\n try {\n // start loading icon if available\n options?.loading?.set(true);\n\n const isSimpleEqualityQuery = (!queryOptions || Object.keys(queryOptions).length === 0) &&\n queryParams.length === 1 &&\n (queryParams[0][1] === '==' || queryParams[0][1] === 'in');\n\n if (isSimpleEqualityQuery) {\n const field = queryParams[0][0];\n const ids = queryParams[0][1] === 'in' ? queryParams[0][2] : [queryParams[0][2]];\n await cachedLoads.processSimpleStreamQuery(collectionName, field, ids, store, injector, streamQueries, options);\n } else {\n await cachedLoads.processStreamQuery(collectionName, store, queryParams, queryOptions, injector, streamQueries, options);\n }\n } catch (e) {\n logger.error(e);\n\n // stop loading icon. when no error, loading icon is stopped\n // upon the initial payload coming through the stream and the\n // loadQueries being processed\n options?.loading?.set(false);\n throw e;\n }\n },\n /**\n * Fetch once, then evaluate nested loads against all matching local records.\n * Loading reduces redundant reads in the following ways when there are no\n * queryOptions:\n * - If a matching listener already covers the data, let it keep the store current.\n * - Otherwise, load active records updated since the last load (_deleted == false).\n * - Also query for records deleted since that load (_deleted == true), so their\n * IDs can be removed from the frontend store. The active query cannot report them.\n * - Calculate loadQueries from the matching entities in the store, including\n * both the newly fetched changes and records loaded earlier. A delta response\n * alone would miss unchanged parents whose related data still needs loading.\n *\n * Ordering/limits/cursors disable delta caching because adding a time filter\n * would change the requested result window. A first load has no previous cutoff.\n */\n async load(\n queryParams: QueryParams,\n queryOptions: QueryOptions,\n loadQueries?: (entity: S) => EntityLoadQuery<AnyEntity>[],\n options?: {\n loading?: WritableSignal<boolean>,\n },\n ) {\n\n try {\n // start loading icon if available\n options?.loading?.set(true);\n\n const isBatchableEqualityOrIn =\n (!queryOptions || Object.keys(queryOptions).length === 0) &&\n queryParams.length === 1 &&\n (queryParams[0][1] === '==' || queryParams[0][1] === 'in');\n\n if (!isBatchableEqualityOrIn) {\n // ---------------------------------------------------------\n // LEGACY PATH: Non-equality queries use full query-string tracking\n // ---------------------------------------------------------\n // only load if there is not already a listener for the same query\n if (!cachedLoads.isStreamForQuery(collectionName, queryParams, queryOptions)) {\n // get the last load time and next load time\n const lastLoadTime = cachedLoads.getLastLoadTime(collectionName, queryParams, queryOptions);\n const newLoadTime = Date.now();\n\n // load entities since last load that are not deleted\n // note that we always load all entities if there exist queryOptions since adding\n // the _updatedAt filter will change queries with limit\n let queryParamsWithTime;\n if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {\n queryParamsWithTime = [...queryParams, ['_deleted', '==', false]];\n } else {\n queryParamsWithTime = [\n ...queryParams,\n ['_updatedAt', '>', dataTimestampFromMillis(lastLoadTime)],\n ['_deleted', '==', false],\n ];\n }\n\n // get entities that have been added or updated since last load\n const entitiesDelta: S[] = await db.getEntities(\n collectionName,\n queryParamsWithTime,\n queryOptions,\n );\n\n patchState(store, setEntities<S>(entitiesDelta, { selectId }));\n\n // delete any new deleted entities\n if (lastLoadTime === -1 || (queryOptions && Object.keys(queryOptions).length > 0)) {\n const entitiesDeletedDelta: S[] = await db.getEntities(\n collectionName,\n [...queryParams, ['_deleted', '==', true]],\n queryOptions,\n );\n\n patchState(store, removeEntities(\n entitiesDeletedDelta.map((e) => e.__id),\n ));\n } else {\n const entitiesDeletedDelta: S[] = await db.getEntities(\n collectionName,\n [...queryParams,\n ['_updatedAt', '>', dataTimestampFromMillis(lastLoadTime)],\n ['_deleted', '==', true]],\n queryOptions,\n );\n\n patchState(store, removeEntities(\n entitiesDeletedDelta.map((e) => e.__id),\n ));\n }\n\n // save a new lastLoadTime for this query\n cachedLoads.setLastLoadTime(collectionName, queryParams, queryOptions, newLoadTime);\n }\n } else {\n // ---------------------------------------------------------\n // OPTIMIZED PATH: Per-entity tracking for == and in queries\n // ---------------------------------------------------------\n const field = queryParams[0][0] as string;\n const operator = queryParams[0][1];\n const rawValues = operator === '==' ? [queryParams[0][2] as string] : queryParams[0][2] as string[];\n\n // 1. Remove IDs already covered by active streams\n const valuesToLoad = rawValues.filter((v) => {\n // Check if it's covered by a multiplexer stream\n if (cachedLoads.isIdStreamed(collectionName, field, v)) return false;\n return true;\n });\n\n if (valuesToLoad.length > 0) {\n const newLoadTime = Date.now();\n\n if (field === '__id' && valuesToLoad.length === 1) {\n const idToFetch = valuesToLoad[0];\n logger.log(`[Store] Optimized Load Triggered for collection '${collectionName}', fetching single ID using getDoc.`);\n\n const entity = await db.getEntity<S>(collectionName, idToFetch);\n\n\n if (entity) {\n if (entity._deleted) {\n patchState(store, removeEntities([idToFetch]));\n } else {\n patchState(store, setEntities<S>([entity], { selectId }));\n }\n } else {\n patchState(store, removeEntities([idToFetch]));\n }\n\n cachedLoads.setEntityLoadTime(collectionName, field, idToFetch, newLoadTime);\n } else {\n // 2. Group values by their entityLoadTime (Time Bucketing Strategy)\n // To prevent the N+1 problem of issuing dozens of queries for items with slightly\n // different load times, we group loaded items into 5-minute buckets.\n // Unloaded items (-1) are strictly kept in their own bucket to prevent over-fetching.\n const BUCKET_MS = 5 * 60 * 1000;\n\n // Map bucket index to the exact minimum time in that bucket and its values\n const groupsByBucket: Map<number, { minTime: number, values: string[] }> = new Map();\n\n logger.log(`[Store] Optimized Load Triggered for collection '${collectionName}', tracking ${valuesToLoad.length} IDs.`);\n\n valuesToLoad.forEach((val) => {\n const time = cachedLoads.getEntityLoadTime(collectionName, field, val);\n const bucketIndex = time === -1 ? -1 : Math.floor(time / BUCKET_MS);\n\n if (!groupsByBucket.has(bucketIndex)) {\n groupsByBucket.set(bucketIndex, { minTime: time, values: [] });\n }\n\n const group = groupsByBucket.get(bucketIndex)!;\n // Track the earliest load time in this bucket\n if (time !== -1 && time < group.minTime) {\n group.minTime = time;\n }\n group.values.push(val);\n });\n\n // 3. For each group, execute DB fetches\n logger.log(`[Store] Grouped ${valuesToLoad.length} IDs into ${groupsByBucket.size} time bucket(s).`);\n await Promise.all(Array.from(groupsByBucket.entries()).map(async ([bucketIndex, group]) => {\n const lastTime = group.minTime;\n const groupValues = group.values;\n logger.log(`[Store] Bucket ${bucketIndex === -1 ? '(-1: Never Loaded)' : bucketIndex} (minTime: ${lastTime === -1 ? 'Never' : new Date(lastTime).toISOString()}) fetching ${groupValues.length} IDs.`);\n // Chunk into 30s\n for (let i = 0; i < groupValues.length; i += 30) {\n const chunk = groupValues.slice(i, i + 30);\n const batchedParams: QueryParams = [[field, 'in', chunk]];\n logger.log(`[Store] -> Fetching chunk of ${chunk.length} IDs...`);\n\n // Fetch changed entities\n let queryParamsWithTime: QueryParams;\n if (lastTime === -1) {\n queryParamsWithTime = [...batchedParams, ['_deleted', '==', false]];\n } else {\n queryParamsWithTime = [\n ...batchedParams,\n ['_updatedAt', '>', dataTimestampFromMillis(lastTime)],\n ['_deleted', '==', false],\n ];\n }\n const entitiesDelta: S[] = await db.getEntities(collectionName, queryParamsWithTime, {});\n\n if (entitiesDelta.length > 0) {\n logger.log(`[Store] -> Loaded ${entitiesDelta.length} updated/new entities from chunk.`);\n }\n patchState(store, setEntities<S>(entitiesDelta, { selectId }));\n\n // Fetch soft-deleted entities\n let deletedParamsWithTime: QueryParams;\n if (lastTime === -1) {\n deletedParamsWithTime = [...batchedParams, ['_deleted', '==', true]];\n } else {\n deletedParamsWithTime = [\n ...batchedParams,\n ['_updatedAt', '>', dataTimestampFromMillis(lastTime)],\n ['_deleted', '==', true],\n ];\n }\n const entitiesDeletedDelta: S[] = await db.getEntities(collectionName, deletedParamsWithTime, {});\n\n if (entitiesDeletedDelta.length > 0) {\n logger.log(`[Store] -> Removed ${entitiesDeletedDelta.length} soft-deleted entities from chunk.`);\n }\n patchState(store, removeEntities(entitiesDeletedDelta.map(selectId) as string[]));\n }\n }));\n\n // 4. Update entityLoadTime for all fetched values to the unified newLoadTime\n valuesToLoad.forEach((val) => cachedLoads.setEntityLoadTime(collectionName, field, val, newLoadTime));\n }\n }\n }\n\n if (loadQueries) {\n // retrieve entities from store for loading queries\n // note we cannot simply use entities from load since it may not be all entities (only those for which updatedAt > lastLoadTime)\n const allQueriedEntities = store.selectEntities(queryParams, queryOptions);\n await processLoadQueries<S>(allQueriedEntities, loadQueries);\n }\n } catch (e) {\n logger.error(e);\n throw e;\n } finally {\n // stop loading icon\n options?.loading?.set(false);\n }\n },\n /** Count active backend records; does not populate the local entity store. */\n async count(\n queryParams: QueryParams,\n queryOptions: QueryOptions,\n options?: {\n loading?: WritableSignal<boolean>,\n },\n ): Promise<number> {\n\n try {\n // start loading icon if available\n options?.loading?.set(true);\n\n const queryParamsNotDeleted: QueryParams = [...queryParams, ['_deleted', '==', false]];\n return await db.count(collectionName, queryParamsNotDeleted, queryOptions);\n } catch (e) {\n logger.error(e);\n throw e;\n } finally {\n // stop loading icon\n options?.loading?.set(false);\n }\n },\n /** Compute backend aggregates over active records without loading them locally. */\n async aggregate<T extends { [k: string]: number }>(\n queryParams: QueryParams,\n queryOptions: QueryOptions,\n aggregateParams: { [K in keyof T]: [string] | [string, string] },\n options?: {\n loading?: WritableSignal<boolean>,\n },\n ): Promise<{ [K in keyof T]: number | null }> {\n\n try {\n // start loading icon if available\n options?.loading?.set(true);\n\n const queryParamsNotDeleted: QueryParams = [...queryParams, ['_deleted', '==', false]];\n return await db.aggregate<T>(\n collectionName, queryParamsNotDeleted, queryOptions, aggregateParams,\n );\n } catch (e) {\n logger.error(e);\n throw e;\n } finally {\n // stop loading icon\n options?.loading?.set(false);\n }\n },\n async increment(id: string, field: string, delta: number, options?: {\n loading?: WritableSignal<boolean>,\n optimistic?: boolean\n }) {\n // get current value\n\n const currEntityValue = store.entityMap()[id];\n const changes = {};\n changes[field] = (typeof currEntityValue?.[field] === 'number' ? currEntityValue[field] : 0) + delta;\n changes['_updatedAt'] = dataTimestampNow();\n\n if (options?.optimistic) {\n try {\n // optimistically set then query backend\n patchState(store, updateEntity({\n id,\n changes: Object.assign({}, changes, {\n _updatedAt: dataTimestampNow(),\n }) as Partial<NoInfer<S>>,\n }, { selectId }));\n await db.incrementEntityField(collectionName, id, field, delta);\n } catch (e) {\n // undo ngrx store value\n if (currEntityValue) {\n patchState(store, setEntity<S>(currEntityValue, { selectId }));\n } else {\n patchState(store, removeEntity(id));\n }\n logger.error(e);\n throw e;\n }\n } else {\n try {\n // start loading icon\n options?.loading?.set(true);\n\n // update entity\n await db.incrementEntityField(collectionName, id, field, delta);\n patchState(store, updateEntity({\n id,\n changes: Object.assign({}, changes, {\n _updatedAt: dataTimestampNow(),\n }) as Partial<NoInfer<S>>,\n }, { selectId }));\n } catch (e) {\n logger.error(e);\n throw e;\n } finally {\n // stop loading icon\n options?.loading?.set(false);\n }\n }\n },\n /**\n * Create a record from domain fields, supplying ID/metadata when absent.\n * Local patches may run optimistically or after success; batchConfig queues\n * them under the batch coordinator instead of committing immediately.\n */\n async add(\n entityOpId: NewDataEntity<S>,\n options?: {\n optimistic?: boolean,\n loading?: WritableSignal<boolean>,\n snackBarConfig?: {\n successMessage: string,\n failureMessage: string,\n undoOnAction?: boolean,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config?: FeedbackConfig,\n },\n batchConfig?: {\n batch: WriteBatchI,\n revertBatch: WriteBatchI,\n patchFns: Array<() => void>,\n revertFns: Array<() => void>,\n dbRevertFns: Array<() => void>,\n optimistic?: boolean,\n }\n },\n ) {\n\n // Create an __id if one was not provided\n const entity = Object.assign({}, entityOpId, {\n __id: entityOpId['__id'] || db.createId(),\n });\n\n // Function for setting the entity locally\n const patchFn = () => {\n\n patchState(store, setEntity<S>(\n Object.assign({}, entity, {\n _updatedAt: dataTimestampNow(),\n _createdAt: entity._createdAt ?? dataTimestampNow(),\n _deleted: false,\n }) as S,\n { selectId },\n ));\n };\n\n // Function for reverting changes for optimistic adds\n const currEntityValue = store.entityMap()[entity.__id];\n const revertFn = () => {\n\n if (currEntityValue) {\n patchState(store, setEntity<S>(currEntityValue, { selectId }));\n } else {\n patchState(store, removeEntity(entity.__id));\n }\n };\n\n // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar\n const dbRevertFn = async () => {\n\n try {\n if (currEntityValue) {\n await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);\n } else {\n await db.removeEntity(collectionName, entity.__id, options?.batchConfig?.revertBatch);\n }\n } catch (e) {\n logger.error(e);\n throw e;\n }\n };\n\n // Add the patchFn, revertFn, dbRevertFn if this is a batch write\n options?.batchConfig?.patchFns?.push(patchFn);\n options?.batchConfig?.revertFns?.push(revertFn);\n options?.batchConfig?.dbRevertFns?.push(dbRevertFn);\n\n\n // optimistically set locally, then in backend and revert if needed\n if (options?.optimistic || options?.batchConfig?.optimistic) {\n patchFn();\n try {\n await db.addEntity(collectionName, entity, options?.batchConfig?.batch);\n // it will only go into here when not in a batch setting\n // since there is no snackBarConfig in the a batch seting\n if (options?.snackBarConfig) {\n openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);\n }\n } catch (e) {\n // will only get here when it's not a batch\n revertFn();\n logger.error(e);\n if (options?.snackBarConfig) {\n snackBar.open(\n options.snackBarConfig.failureMessage,\n '',\n options.snackBarConfig.config,\n );\n }\n throw e;\n }\n // set in backend and then locally if successful\n } else {\n // start loading icon\n options?.loading?.set(true);\n try {\n await db.addEntity(collectionName, entity, options?.batchConfig?.batch);\n // only patch if not using batch writes since if we're using\n // batch writes, we should be patching after the batch write\n // is successful\n if (!options?.batchConfig?.batch) {\n patchFn();\n if (options?.snackBarConfig) {\n openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);\n }\n }\n } catch (e) {\n logger.error(e);\n // will only get here when it's not a batch\n if (options?.snackBarConfig) {\n snackBar.open(\n options.snackBarConfig.failureMessage,\n '',\n options.snackBarConfig.config,\n );\n }\n throw e;\n } finally {\n // stop loading icon\n options?.loading?.set(false);\n }\n }\n },\n /** Update a record with rollback/undo support and an advanced _updatedAt value. */\n async update(\n id: string,\n changes: Partial<S>,\n options?: {\n optimistic?: boolean,\n loading?: WritableSignal<boolean>,\n snackBarConfig?: {\n successMessage: string,\n failureMessage: string,\n undoOnAction?: boolean,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config?: FeedbackConfig,\n },\n batchConfig?: {\n batch: WriteBatchI,\n revertBatch: WriteBatchI,\n patchFns?: Array<() => void>,\n revertFns: Array<() => void>,\n dbRevertFns: Array<() => void>,\n optimistic?: boolean,\n }\n },\n ) {\n\n // Function for updating the entity locally\n const patchFn = () => {\n\n patchState(store, updateEntity({\n id,\n changes: Object.assign({}, changes, {\n _updatedAt: dataTimestampNow(),\n }) as Partial<NoInfer<S>>,\n }, { selectId }));\n };\n\n // Function for reverting changes for optimistic updates\n const currEntityValue = store.entityMap()[id];\n const revertFn = () => {\n\n if (currEntityValue) {\n patchState(store, setEntity<S>(currEntityValue, { selectId }));\n } else {\n patchState(store, removeEntity(id));\n }\n };\n\n // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar\n const dbRevertFn = async () => {\n\n try {\n if (currEntityValue) {\n await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);\n } else {\n await db.removeEntity(collectionName, id, options?.batchConfig?.revertBatch);\n }\n } catch (e) {\n logger.error(e);\n throw e;\n }\n };\n\n // Add the patchFn, revertFn, dbRevertFn if this is a batch write\n options?.batchConfig?.patchFns?.push(patchFn);\n options?.batchConfig?.revertFns?.push(revertFn);\n options?.batchConfig?.dbRevertFns?.push(dbRevertFn);\n\n // optimistically update locally, then in backend and revert if needed\n if (options?.optimistic || options?.batchConfig?.optimistic) {\n patchFn();\n try {\n await db.updateEntity(collectionName, id, changes, options?.batchConfig?.batch);\n // it will only go into here when not in a batch setting\n // since there is no snackBarConfig in the a batch seting\n if (options?.snackBarConfig) {\n openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);\n }\n } catch (e) {\n // will only get here when it's not a batch\n revertFn();\n logger.error(e);\n if (options?.snackBarConfig) {\n snackBar.open(\n options.snackBarConfig.failureMessage,\n '',\n options.snackBarConfig.config,\n );\n }\n throw e;\n }\n // update in backend and then locally if successful\n } else {\n // start loading icon\n options?.loading?.set(true);\n try {\n await db.updateEntity(collectionName, id, changes, options?.batchConfig?.batch);\n // only patch if not using batch writes since if we're using\n // batch writes, we should be patching after the batch write\n // is successful\n if (!options?.batchConfig?.batch) {\n patchFn();\n if (options?.snackBarConfig) {\n openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);\n }\n }\n } catch (e) {\n logger.error(e);\n // will only get here when it's not a batch\n if (options?.snackBarConfig) {\n snackBar.open(\n options.snackBarConfig.failureMessage,\n '',\n options.snackBarConfig.config,\n );\n }\n throw e;\n } finally {\n // stop loading icon\n options?.loading?.set(false);\n }\n }\n },\n /** Remove locally and soft-delete remotely so other clients can observe the change. */\n async remove(\n id: string,\n options?: {\n optimistic?: boolean,\n loading?: WritableSignal<boolean>,\n snackBarConfig?: {\n successMessage: string,\n failureMessage: string,\n undoOnAction?: boolean,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config?: FeedbackConfig,\n },\n batchConfig?: {\n batch: WriteBatchI,\n revertBatch: WriteBatchI,\n patchFns?: Array<() => void>,\n revertFns: Array<() => void>,\n dbRevertFns: Array<() => void>,\n optimistic?: boolean,\n }\n },\n ) {\n\n // Function for updating the entity locally\n const patchFn = () => {\n\n patchState(store, removeEntity(id));\n };\n\n // Function for reverting changes for optimistic deletes\n const currEntityValue = store.entityMap()[id];\n const revertFn = () => {\n\n if (currEntityValue) {\n patchState(store, setEntity<S>(currEntityValue, { selectId }));\n }\n };\n\n // Function for reverting changes to the DB when 'Undo' is clicked in the snackbar\n const dbRevertFn = async () => {\n\n try {\n if (currEntityValue) {\n await db.addEntity(collectionName, currEntityValue, options?.batchConfig?.revertBatch);\n }\n } catch (e) {\n logger.error(e);\n throw e;\n }\n };\n\n // Add the patchFn, revertFn, dbRevertFn if this is a batch write\n options?.batchConfig?.patchFns?.push(patchFn);\n options?.batchConfig?.revertFns?.push(revertFn);\n options?.batchConfig?.dbRevertFns?.push(dbRevertFn);\n\n // optimistically remove locally, then in backend and revert if needed\n if (options?.optimistic || options?.batchConfig?.optimistic) {\n patchFn();\n try {\n await db.removeEntity(collectionName, id, options?.batchConfig?.batch);\n // it will only go into here when not in a batch setting\n // since there is no snackBarConfig in the a batch seting\n if (options?.snackBarConfig) {\n openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);\n }\n } catch (e) {\n // will only get here when it's not a batch\n revertFn();\n logger.error(e);\n if (options?.snackBarConfig) {\n snackBar.open(\n options.snackBarConfig.failureMessage,\n '',\n options.snackBarConfig.config,\n );\n }\n throw e;\n }\n // update in backend and then locally if successful\n } else {\n // start loading icon\n options?.loading?.set(true);\n try {\n await db.removeEntity(collectionName, id, options?.batchConfig?.batch);\n // only patch if not using batch writes since if we're using\n // batch writes, we should be patching after the batch write\n // is successful\n if (!options?.batchConfig?.batch) {\n patchFn();\n if (options?.snackBarConfig) {\n openSnackBarWithUndoOption(snackBar, options.snackBarConfig, [revertFn], [dbRevertFn]);\n }\n }\n } catch (e) {\n logger.error(e);\n // will only get here when it's not a batch\n if (options?.snackBarConfig) {\n snackBar.open(\n options.snackBarConfig.failureMessage,\n '',\n options.snackBarConfig.config,\n );\n }\n throw e;\n } finally {\n // stop loading icon\n options?.loading?.set(false);\n }\n }\n },\n })),\n );\n}\n","import { InjectionToken, WritableSignal } from '@angular/core';\nimport { DataFeedback, FeedbackConfig } from './feedback';\nimport { openSnackBarWithUndoOption } from './undo';\n\n/** Minimal common surface of Firestore and mock write batches. */\nexport interface WriteBatchI {\n update(docRef: any, changes: any): any;\n set(docRef: any, entity: any): any;\n delete(docRef: any): any;\n commit(): Promise<unknown>;\n}\n/** Mutable work queues shared by store writes participating in one batch. */\nexport interface BatchConfig {\n /** Forward backend writes, committed after the preparation callback finishes. */\n batch: WriteBatchI;\n /** Inverse backend writes prepared for a later user-requested undo. */\n revertBatch: WriteBatchI;\n /** Local patches applied after commit when optimistic mode is off. */\n patchFns: Array<() => void>;\n /** Local compensations, run in reverse order on rollback or successful undo. */\n revertFns: Array<() => void>;\n /** Restore backend state directly or queue inverse writes into revertBatch. */\n dbRevertFns: Array<() => void | Promise<unknown>>;\n optimistic?: boolean;\n}\n/** Controls local update timing, an optional busy signal and write notifications. */\nexport interface WriteOptions {\n /** Apply local changes while preparing writes; revert them if preparation/commit fails. */\n optimistic?: boolean;\n /** Set true across preparation and commit, then reset even when either fails. */\n loading?: WritableSignal<boolean>;\n snackBarConfig?: {\n successMessage: string;\n failureMessage: string;\n undoOnAction?: boolean;\n config?: FeedbackConfig;\n };\n}\n/** Coordinates store writes through one adapter-owned batch and rollback boundary. */\nexport interface BatchWriteService {\n batchWrite(batchFn: (config: BatchConfig) => void | Promise<unknown>, options?: WriteOptions): Promise<void>;\n}\nexport const BATCH_WRITE_SERVICE = new InjectionToken<BatchWriteService>('PlatformBatchWriteService');\n\n/**\n * Shared coordinator for real and mock batches. The callback queues backend\n * writes and records local patches/compensations; this function commits once.\n * Keep the original optimistic/non-optimistic branches visible: one patches\n * during preparation, the other patches after commit. Preparation is inside\n * the try block so a preparation failure also rolls back optimistic changes.\n */\nexport async function processBatchWrite(\n batchFn: (config: BatchConfig) => void | Promise<unknown>,\n options: WriteOptions | undefined,\n batch: WriteBatchI,\n revertBatch: WriteBatchI,\n feedback: DataFeedback,\n): Promise<void> {\n const config: BatchConfig = {\n batch, revertBatch, patchFns: [], revertFns: [], dbRevertFns: [], optimistic: options?.optimistic,\n };\n options?.loading?.set(true);\n if (options?.optimistic) {\n // This includes optimistically patching locally when batchFn uses add, update,\n // or remove from the NgRx entity stores with this batchConfig. Those methods\n // also record revertFns so a failed preparation or commit can restore state.\n let committed = false;\n try {\n await batchFn(config);\n await batch.commit();\n committed = true;\n if (options?.snackBarConfig) {\n openSnackBarWithUndoOption(feedback, options.snackBarConfig, config.revertFns, config.dbRevertFns, revertBatch);\n }\n } catch (error) {\n // A notification failure after commit must not undo an already-saved write.\n if (!committed) [...config.revertFns].reverse().forEach(revert => revert());\n if (options?.snackBarConfig) feedback.open(options.snackBarConfig.failureMessage, '', options.snackBarConfig.config);\n throw error;\n } finally {\n options?.loading?.set(false);\n }\n } else {\n // Store methods queue local patches; apply them only after the backend succeeds.\n try {\n await batchFn(config);\n await batch.commit();\n config.patchFns.forEach(patch => patch());\n if (options?.snackBarConfig) {\n openSnackBarWithUndoOption(feedback, options.snackBarConfig, config.revertFns, config.dbRevertFns, revertBatch);\n }\n } catch (error) {\n if (options?.snackBarConfig) feedback.open(options.snackBarConfig.failureMessage, '', options.snackBarConfig.config);\n throw error;\n } finally {\n options?.loading?.set(false);\n }\n }\n}\n","/**\n * Core entry point: shared values, entity stores and adapter contracts.\n * Keep Firebase, mock fixtures and Material dependencies in their secondary\n * entry points so importing core does not require those integrations.\n */\nexport * from './model';\nexport * from './entity-definition';\nexport * from './timestamp';\nexport * from './data-access';\nexport * from './config';\nexport * from './feedback';\nexport * from './selectors';\nexport * from './entity-store';\nexport * from './query-descriptors';\nexport * from './cached-listeners';\nexport * from './stream-multiplexer';\nexport * from './batch-write';\nexport * from './undo';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["selectId","DATABASE_SERVICE"],"mappings":";;;;;;;;AAmBA;;;;;;;AAOG;AACG,SAAU,YAAY,CAAuB,UAAkC,EAAA;AACnF,IAAA,MAAM,IAAI,GAAG,UAAU,CAAC,UAAU;AAClC,IAAA,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,IAAI,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;AACjH,QAAA,MAAM,IAAI,KAAK,CAAC,CAAA,gCAAA,EAAmC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAA,CAAE,CAAC;IAC5E;IACA,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC;AAC5C;;ACzBA;;;;AAIG;SACa,aAAa,CAAC,OAAe,EAAE,WAAW,GAAG,CAAC,EAAA;IAC5D,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,C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|
+
"name": "@tech4good/platform-data",
|
|
3
|
+
"version": "0.1.0-alpha.0",
|
|
4
|
+
"description": "Shared entity stores and Firestore data infrastructure for Tech4Good Angular applications.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"peerDependencies": {
|
|
8
|
+
"@angular/common": "^21.0.0",
|
|
9
|
+
"@angular/core": "^21.0.0",
|
|
10
|
+
"@angular/material": "^21.0.0",
|
|
11
|
+
"@ngrx/signals": "^21.0.0",
|
|
12
|
+
"firebase": "^12.0.0",
|
|
13
|
+
"rxjs": "^7.8.0",
|
|
14
|
+
"@tech4good/platform-logging": "0.1.0-alpha.0"
|
|
15
|
+
},
|
|
16
|
+
"peerDependenciesMeta": {
|
|
17
|
+
"@angular/material": {
|
|
18
|
+
"optional": true
|
|
19
|
+
},
|
|
20
|
+
"firebase": {
|
|
21
|
+
"optional": true
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"tslib": "^2.3.0"
|
|
26
|
+
},
|
|
27
|
+
"module": "fesm2022/tech4good-platform-data.mjs",
|
|
28
|
+
"typings": "types/tech4good-platform-data.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
"./package.json": {
|
|
31
|
+
"default": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./types/tech4good-platform-data.d.ts",
|
|
35
|
+
"default": "./fesm2022/tech4good-platform-data.mjs"
|
|
36
|
+
},
|
|
37
|
+
"./firestore": {
|
|
38
|
+
"types": "./types/tech4good-platform-data-firestore.d.ts",
|
|
39
|
+
"default": "./fesm2022/tech4good-platform-data-firestore.mjs"
|
|
40
|
+
},
|
|
41
|
+
"./material": {
|
|
42
|
+
"types": "./types/tech4good-platform-data-material.d.ts",
|
|
43
|
+
"default": "./fesm2022/tech4good-platform-data-material.mjs"
|
|
44
|
+
},
|
|
45
|
+
"./testing": {
|
|
46
|
+
"types": "./types/tech4good-platform-data-testing.d.ts",
|
|
47
|
+
"default": "./fesm2022/tech4good-platform-data-testing.mjs"
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"type": "module"
|
|
51
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken } from '@angular/core';
|
|
3
|
+
import { Observable } from 'rxjs';
|
|
4
|
+
import { Timestamp, Firestore, AggregateSpec, QueryConstraint } from 'firebase/firestore';
|
|
5
|
+
import { DataTimestamp, BatchWriteService, BatchConfig, WriteOptions, DataAccess, QueryParams, QueryOptions, NewDataEntity, WriteBatchI } from '@tech4good/platform-data';
|
|
6
|
+
|
|
7
|
+
/** Preserve the SDK value's precision. Firestore itself persists microsecond precision. */
|
|
8
|
+
declare function fromFirestoreTimestamp(value: Timestamp): DataTimestamp;
|
|
9
|
+
/** The SDK validates its narrower supported date range. */
|
|
10
|
+
declare function toFirestoreTimestamp(value: DataTimestamp): Timestamp;
|
|
11
|
+
/** DataTimestamp values become native SDK values, including query operands and cursor tuples. */
|
|
12
|
+
declare function encodeFirestoreData(value: unknown): any;
|
|
13
|
+
/** Snapshot timestamp values become shared values, including nested domain fields. */
|
|
14
|
+
declare function decodeFirestoreData(value: unknown): any;
|
|
15
|
+
|
|
16
|
+
/** The app chooses the Firestore instance, project, cache, and emulator. */
|
|
17
|
+
declare const PLATFORM_FIRESTORE: InjectionToken<Firestore>;
|
|
18
|
+
/**
|
|
19
|
+
* Translate shared query descriptors into SDK constraints, including nested
|
|
20
|
+
* timestamps in operands/cursors. Undefined filters are omitted consistently
|
|
21
|
+
* with local queries. Backend validation and index requirements remain Firestore's.
|
|
22
|
+
*/
|
|
23
|
+
declare function firestoreQueryConstraints(queryParams?: QueryParams, queryOptions?: QueryOptions): QueryConstraint[];
|
|
24
|
+
/**
|
|
25
|
+
* Translate named count/sum/average requests while preserving result aliases.
|
|
26
|
+
* For example, { countOfDocs: ['count'], totalPopulation: ['sum', 'population'],
|
|
27
|
+
* averagePopulation: ['average', 'population'] } describes three calculations;
|
|
28
|
+
* the keys name the output fields, while the tuples choose the operations.
|
|
29
|
+
*/
|
|
30
|
+
declare function firestoreAggregateSpec(params: Record<string, [string] | [string, string]>): AggregateSpec;
|
|
31
|
+
/**
|
|
32
|
+
* DataAccess implementation using the modular Firestore SDK. Reads attach the
|
|
33
|
+
* document ID and decode timestamps recursively. Pending server timestamps use
|
|
34
|
+
* SDK estimates so local snapshot records retain usable metadata; later snapshots
|
|
35
|
+
* supply committed values. Unsubscribing from a stream detaches its SDK listener.
|
|
36
|
+
* Authentication, profile provisioning and routing remain application concerns.
|
|
37
|
+
*/
|
|
38
|
+
declare class FirestoreDataService implements DataAccess {
|
|
39
|
+
protected readonly dataFirestore: Firestore;
|
|
40
|
+
createId(): string;
|
|
41
|
+
private dataQuery;
|
|
42
|
+
streamEntity<T>(collectionName: string, id: string): Observable<T | null>;
|
|
43
|
+
streamEntities<T>(collectionName: string, params?: QueryParams, options?: QueryOptions): Observable<T[]>;
|
|
44
|
+
streamEntitiesChanges<T>(collectionName: string, params?: QueryParams, options?: QueryOptions): Observable<{
|
|
45
|
+
type: string;
|
|
46
|
+
docData: T;
|
|
47
|
+
}[]>;
|
|
48
|
+
getEntity<T>(collectionName: string, id: string): Promise<T | null>;
|
|
49
|
+
getEntities<T>(collectionName: string, params?: QueryParams, options?: QueryOptions): Promise<T[]>;
|
|
50
|
+
count(collectionName: string, params?: QueryParams, options?: QueryOptions): Promise<number>;
|
|
51
|
+
aggregate<S extends Record<string, number>>(collectionName: string, params: QueryParams, options: QueryOptions, aggregates: {
|
|
52
|
+
[K in keyof S]: [string] | [string, string];
|
|
53
|
+
}): Promise<{
|
|
54
|
+
[K in keyof S]: number | null;
|
|
55
|
+
}>;
|
|
56
|
+
addEntity<T extends NewDataEntity & {
|
|
57
|
+
__id: string;
|
|
58
|
+
}>(collectionName: string, entity: T, batch?: WriteBatchI): Promise<any>;
|
|
59
|
+
updateEntity<T extends object>(collectionName: string, id: string, changes: Partial<T>, batch?: WriteBatchI): Promise<any>;
|
|
60
|
+
removeEntity(collectionName: string, id: string, batch?: WriteBatchI): Promise<any>;
|
|
61
|
+
incrementEntityField(collectionName: string, id: string, field: string, delta: number): Promise<void>;
|
|
62
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<FirestoreDataService, never>;
|
|
63
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<FirestoreDataService>;
|
|
64
|
+
}
|
|
65
|
+
/** Creates separate forward/undo SDK batches and uses the shared write coordinator. */
|
|
66
|
+
declare class FirestoreBatchWriteService implements BatchWriteService {
|
|
67
|
+
private readonly firestore;
|
|
68
|
+
private readonly feedback;
|
|
69
|
+
batchWrite(fn: (config: BatchConfig) => void | Promise<unknown>, options?: WriteOptions): Promise<void>;
|
|
70
|
+
static ɵfac: i0.ɵɵFactoryDeclaration<FirestoreBatchWriteService, never>;
|
|
71
|
+
static ɵprov: i0.ɵɵInjectableDeclaration<FirestoreBatchWriteService>;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Bind core data and batch tokens to Firestore. The factory runs in an Angular
|
|
76
|
+
* injection context and must return an already-configured instance; it may inject
|
|
77
|
+
* the app's existing Firestore service. This provider does not initialize Firebase
|
|
78
|
+
* or choose a project, emulator, authentication flow or cache policy.
|
|
79
|
+
*/
|
|
80
|
+
declare function provideFirestoreData(firestore: () => Firestore): i0.EnvironmentProviders;
|
|
81
|
+
|
|
82
|
+
export { FirestoreBatchWriteService as BatchWriteDBService, FirestoreBatchWriteService, FirestoreDataService, PLATFORM_FIRESTORE, decodeFirestoreData, encodeFirestoreData, firestoreAggregateSpec, firestoreQueryConstraints, fromFirestoreTimestamp, provideFirestoreData, toFirestoreTimestamp };
|
|
83
|
+
//# sourceMappingURL=tech4good-platform-data-firestore.d.ts.map
|