@tech4good/platform-tooling 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/README.md ADDED
@@ -0,0 +1,324 @@
1
+ # @tech4good/platform-tooling
2
+
3
+ Development tools for Tech4Good Angular/Firebase applications. The first tool
4
+ checks local Firestore composite-index definitions against supported lab query
5
+ calls. It runs as compiled JavaScript on Node.js 22 or later and has no Angular
6
+ runtime or Firebase credential dependency.
7
+
8
+ This is an unpublished `0.1.0-alpha.0` packaging pilot. The query analyzer was
9
+ extracted from angular-schematics without changing its index-planning behavior.
10
+ Store-feature discovery also recognizes named and aliased imports from packages
11
+ whose implementations are outside the scanned app sources.
12
+ This also improves discovery of stores created through an imported Angular
13
+ `inject` function.
14
+
15
+ ## Use in an application
16
+
17
+ Once this version is published, install it as a development dependency:
18
+
19
+ ```bash
20
+ npm install --save-dev --save-exact @tech4good/platform-tooling@0.1.0-alpha.0
21
+ ```
22
+
23
+ Use these package scripts (also emitted by the updated `ng-add` schematic):
24
+
25
+ ```json
26
+ {
27
+ "scripts": {
28
+ "check:indexes": "t4g-check-firestore-indexes",
29
+ "fix:indexes": "t4g-check-firestore-indexes --fix"
30
+ }
31
+ }
32
+ ```
33
+
34
+ ```bash
35
+ npm run check:indexes
36
+ npm run fix:indexes
37
+ npm run check:indexes -- --project-root "/path/with spaces/my-app"
38
+ npm run check:indexes -- --help
39
+ npm run check:indexes -- --version
40
+ ```
41
+
42
+ The default project root is the working directory. The checker reads
43
+ `src/app/**/*.ts` and `firestore.indexes.json` under that root. It never contacts
44
+ Firebase or checks deployment readiness. Without `--fix`, it does not write
45
+ application files. Fixing appends missing indexes and preserves existing
46
+ definitions, field overrides, and other top-level JSON settings. Known fixes can
47
+ be applied even when other queries are unresolved; those unresolved queries
48
+ still cause failure. Review and deploy indexes separately.
49
+
50
+ Exit codes are 0 for successful checking/fixing, 1 for missing indexes or
51
+ unresolved checks (including invalid project/index input), and 2 for invalid CLI
52
+ arguments. Unknown options are rejected before any fixes are performed.
53
+
54
+ For an existing app, replace its script commands and add this dev dependency.
55
+ Remove its copied `scripts/check-firestore-indexes.ts` only after checking for
56
+ local customizations and updating direct imports/callers. Do not rerun the
57
+ overwrite-based `ng-add` schematic to adopt this package. Future checker fixes
58
+ arrive by updating this dependency and its lockfile.
59
+
60
+ ## Programmatic API
61
+
62
+ Both ESM imports and CommonJS `require` are supported. Importing the library
63
+ does not run the CLI or alter `process.exitCode`.
64
+
65
+ ```typescript
66
+ import { checkFirestoreIndexes } from '@tech4good/platform-tooling';
67
+
68
+ const result = checkFirestoreIndexes({
69
+ projectRoot: '/path/to/application',
70
+ quiet: true,
71
+ });
72
+ // result.success, result.checkedQueries, result.missingIndexes,
73
+ // result.unresolvedQueries
74
+ ```
75
+
76
+ `CheckOptions` and `CheckResult` are exported TypeScript types. `fix` defaults
77
+ to false. After a successful fix, `missingIndexes` describes the definitions
78
+ that were found and added during that run; rerun without `fix` to verify the
79
+ resulting file. The package owns its TypeScript parser dependency, independently
80
+ of the application's compiler version.
81
+
82
+ ## Supported scope
83
+
84
+ - Lab store `load`, `stream`, `count`, and `aggregate` calls.
85
+ - Store parameters and properties annotated as `InstanceType<typeof Store>`,
86
+ including aliases of locally imported store constructors.
87
+ - `Load<Entity>.create` and `Stream<Entity>.create` factories, with collection
88
+ names discovered from local store definitions and query-class constructors.
89
+ - Database `getEntities`, `streamEntities`, `streamEntitiesChanges`, `count`,
90
+ and `aggregate` calls with resolvable collection paths.
91
+ - Literal or resolvable constant filter/option structures, including local
92
+ imports, readonly properties, assertions, and spreads.
93
+
94
+ The analyzer models the current lab runtime's soft-delete and incremental-load
95
+ filters, batched factories, ordering, array modes, and automatic indexing. It
96
+ excludes tests, declaration files, and the known copied infrastructure files
97
+ whose behavior is modeled at call sites. Local entity stores can import the
98
+ standard store feature from a package; dependencies themselves are not scanned.
99
+
100
+ Existing vector indexes are accepted and preserved during `--fix`. Their
101
+ `vectorConfig` must specify an integer dimension from 1 to 2048 and `flat: {}`;
102
+ each field must use exactly one of `order`, `arrayConfig`, or `vectorConfig`.
103
+ Vector indexes do not count as coverage for ordinary queries. These rules follow
104
+ the [Firebase index format](https://firebase.google.com/docs/reference/firestore/indexes)
105
+ and [vector configuration limits](https://firebase.google.com/docs/firestore/vector-search#create_and_manage_vector_indexes).
106
+
107
+ Raw Firebase SDK calls, custom APIs, collection-group queries, vector-search
108
+ queries, and code outside `src/app` are not covered. Arbitrary package-defined
109
+ store implementations are not a general supported discovery contract. Dynamic
110
+ or mutable structures in supported calls are reported as unresolved. A passed
111
+ check is limited to the calls analyzed, not every possible runtime query. See
112
+ the generated `docs-infra/firestore-index-checker.md` for further query details.
113
+
114
+ ## Develop and trial locally
115
+
116
+ Read-only trials on 2026-09-08 passed against the current lab applications:
117
+ Mentor had 42 analyzed call sites and MathPets had 25, each with zero missing
118
+ indexes and zero unresolved checks. Neither application's indexes were changed.
119
+ The earlier trial blockers are resolved: the checker follows Mentor's
120
+ `InstanceType<typeof Store>` guard parameters and accepts MathPets' vector index
121
+ definitions. MathPets' Python vector-search scripts remain outside the supported
122
+ query scope; passing this check does not verify those searches or deployed indexes.
123
+
124
+ From the angular-schematics repository root:
125
+
126
+ ```bash
127
+ npm install
128
+ npm run build:tooling
129
+ npm run test --workspace @tech4good/platform-tooling
130
+ npm run test:indexes
131
+ npm run pack:tooling
132
+ ```
133
+
134
+ The last command creates `tech4good-platform-tooling-0.1.0-alpha.0.tgz` in the repository
135
+ root. In a disposable application checkout, install its absolute path as a dev
136
+ dependency and apply the scripts shown above. A tarball installation exercises
137
+ the same compiled files, exports, and executable that npm consumers receive.
138
+ Do not commit a machine-specific tarball path into an application's lockfile.
139
+
140
+ ### Run against MathPets while developing
141
+
142
+ For a quick development check, build tooling and point its CLI at MathPets.
143
+ These commands use the current local code and do not install or publish a package:
144
+
145
+ ```bash
146
+ cd /path/to/angular-schematics
147
+ npm run build:tooling
148
+ node packages/tooling/dist/cli.js --project-root /path/to/math-pets
149
+ ```
150
+
151
+ Replace the paths with your checkouts. This is a read-only index check: neither
152
+ MathPets' dependencies nor its index file are changed. `node` runs the compiled
153
+ checker, and `--project-root` tells that checker where to find the application's
154
+ source and index definitions. This option is specific to the checker; it does
155
+ not install tooling into MathPets or run MathPets' build, tests, or application.
156
+ After editing tooling,
157
+ rebuild and rerun the command; no version bump is needed. For continuous
158
+ compilation, run `npm run build --workspace @tech4good/platform-tooling -- --watch`
159
+ in another terminal, then rerun the CLI whenever you want to check the result.
160
+
161
+ ### Try the installed package before publishing
162
+
163
+ Pack the current code in angular-schematics, then install that local archive in
164
+ MathPets (or a disposable application checkout):
165
+
166
+ ```bash
167
+ cd /path/to/angular-schematics
168
+ npm run pack:tooling
169
+
170
+ cd /path/to/math-pets
171
+ npm install --no-save --package-lock=false /path/to/angular-schematics/tech4good-platform-tooling-0.1.0-alpha.0.tgz
172
+ ./node_modules/.bin/t4g-check-firestore-indexes
173
+ ```
174
+
175
+ Use the archive filename printed by `pack:tooling` if the version changes.
176
+ `--no-save --package-lock=false` installs into `node_modules` without recording
177
+ the local archive in the application's `package.json` or lockfile. Dependencies
178
+ may still be downloaded from npm; the tooling package itself comes from the
179
+ local archive. This command works before adding `check:indexes` to the app's
180
+ scripts. See [npm's local install support](https://docs.npmjs.com/cli/v10/commands/npm-install/).
181
+
182
+ A tarball is a snapshot: after changing tooling, pack again and reinstall the
183
+ archive before rerunning the installed CLI. Use the direct CLI workflow above
184
+ for quicker iteration. A later `npm ci` restores the app's dependencies from
185
+ its committed lockfile and removes this temporary installation.
186
+
187
+ For a runtime library such as the proposed data package, install or link the
188
+ local build into the consuming app and run that app's build, tests, and relevant
189
+ features. The root README's [general cross-repo development guide](../../README.md#testing-packages-in-another-repo-before-publishing)
190
+ compares tarball installs, local links, and published alphas. An alpha is useful
191
+ for shared testing on other machines; it is not required for local development.
192
+
193
+ The integration suite packs tooling and the installed TypeScript dependency,
194
+ installs them offline into temporary directories, and runs the generated npm
195
+ scripts. It covers ESM/CommonJS consumers, the public API, project roots with
196
+ spaces, package-based store imports, diagnostics, invalid input, preservation,
197
+ and repeated fixes. Fixtures are removed after testing.
198
+
199
+ The root `npm test` includes these tests and the remaining schematic suites.
200
+ The root schematic package excludes this workspace from its own npm tarball.
201
+ `prepack` builds tooling so that a normal pack includes current compiled output.
202
+
203
+ ## Releasing and publishing
204
+
205
+ Run all maintainer commands below from the angular-schematics repository root,
206
+ using Node.js 22 or later and an npm account with permission to publish under
207
+ `@tech4good`. A release records a version of this package; publishing uploads
208
+ that version to npm so applications can install it.
209
+
210
+ The existing `publish-npm` agent skill and root `release:patch`, `release:minor`,
211
+ and `release:major` scripts currently prepare angular-schematics releases. Use
212
+ the workspace workflow below for tooling. Its versions are independent of
213
+ the Angular/schematics version.
214
+
215
+ ### 1. Prepare the version
216
+
217
+ For the first pilot release, keep the existing `0.1.0-alpha.0` version. It is
218
+ already set in the package manifest, root lockfile, and generated dependency.
219
+
220
+ For a subsequent release, choose an unused version and bump only this workspace.
221
+ For example, after publishing `0.1.0-alpha.0`, prepare the next alpha with:
222
+
223
+ ```bash
224
+ npm version 0.1.0-alpha.1 --workspace @tech4good/platform-tooling --no-git-tag-version --ignore-scripts
225
+ ```
226
+
227
+ Replace the example version with the one being released. This updates
228
+ `packages/tooling/package.json` and the workspace entry in the root
229
+ `package-lock.json`. It does not create a Git commit or tag, and `--ignore-scripts`
230
+ skips lifecycle hooks during the version bump.
231
+
232
+ Then update these files together:
233
+
234
+ - Set `devDependencies["@tech4good/platform-tooling"]` in
235
+ `src/ng-add/files/package.json.template` to the same exact version.
236
+ - Record the release's changes under that version in `packages/tooling/CHANGELOG.md`.
237
+ - Update versioned installation examples and remove any obsolete "unpublished"
238
+ wording in this README and the root README as part of preparing the release.
239
+
240
+ The template determines which tooling version newly generated apps install.
241
+ Existing apps receive updates when their dependency and lockfile are updated.
242
+ The tooling changelog is maintained manually for this pilot; the root changelog
243
+ command generates angular-schematics release notes.
244
+
245
+ ### 2. Validate and commit the release
246
+
247
+ ```bash
248
+ npm test
249
+ npm pack --workspace @tech4good/platform-tooling --dry-run
250
+ ```
251
+
252
+ `npm test` builds both packages, checks the generated dependency version, and
253
+ tests an installed tooling tarball. The pack preview should contain this
254
+ package's `package.json`, README, and compiled `dist` files. It does not upload
255
+ anything. Normal packing and publishing run `prepack`, which rebuilds tooling.
256
+
257
+ Review and commit the intended release changes, including the tooling manifest,
258
+ root lockfile, generated dependency, and release notes. For the first release,
259
+ include the reviewed packaging implementation and new package files as well.
260
+ Publish from that reviewed release commit.
261
+
262
+ ### 3. Publish to npm
263
+
264
+ For the first alpha release:
265
+
266
+ ```bash
267
+ npm login
268
+ npm whoami
269
+ npm publish --workspace @tech4good/platform-tooling --access public --tag alpha
270
+ ```
271
+
272
+ Follow npm's authentication and two-factor prompts. `--workspace` selects only
273
+ tooling, and `--access public` makes it publicly installable. `--tag alpha` keeps
274
+ this pilot on the alpha release channel. An npm tag is a label pointing to a
275
+ version; it is separate from a Git tag. Use `--tag alpha` for later alpha releases
276
+ as well. See [npm's publish command](https://docs.npmjs.com/cli/v11/commands/npm-publish/).
277
+
278
+ When ready for a stable release, prepare a version without the prerelease suffix
279
+ (for example, `0.1.0`) using steps 1 and 2, then publish with:
280
+
281
+ ```bash
282
+ npm publish --workspace @tech4good/platform-tooling --access public --tag latest
283
+ ```
284
+
285
+ `latest` is the default version selected by an install without an explicit
286
+ version or tag. Publishing uploads the version already in the manifest; it
287
+ does not bump that version. A published name/version pair cannot be reused for
288
+ different contents, so later changes require a new version.
289
+
290
+ ### 4. Verify and record the published release
291
+
292
+ For the first alpha (substitute the actual version for later releases):
293
+
294
+ ```bash
295
+ npm view @tech4good/platform-tooling@0.1.0-alpha.0 version
296
+ npm view @tech4good/platform-tooling dist-tags
297
+ git tag -a platform-tooling-v0.1.0-alpha.0 -m "Release @tech4good/platform-tooling 0.1.0-alpha.0"
298
+ ```
299
+
300
+ Confirm the first command returns `0.1.0-alpha.0` and the `alpha` tag points to
301
+ that version. Create the Git tag on the release commit, and push that commit
302
+ through the repository's normal Git workflow. Then push this specific tag:
303
+
304
+ ```bash
305
+ git push origin platform-tooling-v0.1.0-alpha.0
306
+ ```
307
+
308
+ The `platform-tooling-v` prefix distinguishes tooling releases from the existing
309
+ schematics tags. Publish tooling and verify the exact version is available on
310
+ npm before releasing angular-schematics with a template that references it.
311
+
312
+ ### 5. Update an application
313
+
314
+ From the application's directory, install the chosen published version:
315
+
316
+ ```bash
317
+ npm install --save-dev --save-exact @tech4good/platform-tooling@0.1.0-alpha.0
318
+ npm run check:indexes
319
+ ```
320
+
321
+ For first-time adoption, also add or replace `check:indexes` and `fix:indexes`
322
+ with the commands in [Use in an application](#use-in-an-application) before running the check.
323
+ Commit the application's updated `package.json` and lockfile. A tooling upgrade
324
+ does not require upgrading angular-schematics in that application.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const firestore_indexes_1 = require("./firestore-indexes");
5
+ const help = `Usage: t4g-check-firestore-indexes [--fix] [--project-root <path>]
6
+
7
+ Check supported queries under src/app against firestore.indexes.json.
8
+ The project root defaults to the current working directory.
9
+
10
+ --fix Append missing indexes; unresolved queries still fail
11
+ --project-root <path> Check another project without changing directories
12
+ --help, -h Show this help
13
+ --version, -v Show the installed package version
14
+
15
+ Exit codes: 0 = verified/fixed, 1 = missing indexes or unresolved checks,
16
+ 2 = invalid command arguments. No Firebase connection or deployment is made.`;
17
+ function main(args) {
18
+ const options = {};
19
+ let showHelp = false;
20
+ let showVersion = false;
21
+ for (let i = 0; i < args.length; i++) {
22
+ const argument = args[i];
23
+ if (argument === '--fix')
24
+ options.fix = true;
25
+ else if (argument === '--help' || argument === '-h')
26
+ showHelp = true;
27
+ else if (argument === '--version' || argument === '-v')
28
+ showVersion = true;
29
+ else if (argument === '--project-root') {
30
+ const value = args[++i];
31
+ if (!value || value.startsWith('-'))
32
+ throw new Error('--project-root requires a path.');
33
+ options.projectRoot = value;
34
+ }
35
+ else {
36
+ throw new Error(`Unknown argument: ${argument}`);
37
+ }
38
+ }
39
+ if (showHelp) {
40
+ console.log(help);
41
+ return 0;
42
+ }
43
+ if (showVersion) {
44
+ console.log(require('../package.json').version);
45
+ return 0;
46
+ }
47
+ return (0, firestore_indexes_1.checkFirestoreIndexes)(options).success ? 0 : 1;
48
+ }
49
+ try {
50
+ process.exitCode = main(process.argv.slice(2));
51
+ }
52
+ catch (error) {
53
+ console.error(error instanceof Error ? error.message : String(error));
54
+ console.error('Run t4g-check-firestore-indexes --help for usage.');
55
+ process.exitCode = 2;
56
+ }
@@ -0,0 +1,50 @@
1
+ type Direction = 'ASCENDING' | 'DESCENDING';
2
+ interface FirestoreIndexField {
3
+ fieldPath: string;
4
+ order?: Direction;
5
+ arrayConfig?: 'CONTAINS';
6
+ vectorConfig?: {
7
+ dimension: number;
8
+ flat: Record<string, never>;
9
+ };
10
+ }
11
+ interface Filter {
12
+ field: string;
13
+ operator: string;
14
+ }
15
+ interface Sort {
16
+ field: string;
17
+ direction: Direction;
18
+ }
19
+ interface Query {
20
+ file: string;
21
+ line: number;
22
+ rawText: string;
23
+ collection: string;
24
+ filters: Filter[];
25
+ orderBy: Sort[];
26
+ aggregateFields: string[];
27
+ }
28
+ interface Diagnostic {
29
+ file: string;
30
+ line: number;
31
+ reason: string;
32
+ }
33
+ interface MissingIndex {
34
+ collection: string;
35
+ query: Query;
36
+ requiredFields: FirestoreIndexField[];
37
+ }
38
+ export interface CheckResult {
39
+ success: boolean;
40
+ checkedQueries: number;
41
+ missingIndexes: MissingIndex[];
42
+ unresolvedQueries: Diagnostic[];
43
+ }
44
+ export interface CheckOptions {
45
+ projectRoot?: string;
46
+ fix?: boolean;
47
+ quiet?: boolean;
48
+ }
49
+ export declare function checkFirestoreIndexes(options?: CheckOptions): CheckResult;
50
+ export {};
@@ -0,0 +1,657 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.checkFirestoreIndexes = checkFirestoreIndexes;
40
+ const fs = __importStar(require("node:fs"));
41
+ const path = __importStar(require("node:path"));
42
+ const typescript_1 = __importDefault(require("typescript"));
43
+ const equalityOps = new Set(['==', 'in']);
44
+ const rangeOps = new Set(['<', '<=', '>', '>=', '!=', 'not-in']);
45
+ const arrayOps = new Set(['array-contains', 'array-contains-any']);
46
+ // These are the shared implementations whose behavior is expanded at their call sites.
47
+ // Keep this list exact: feature code and custom store files must still be checked.
48
+ const runtimeFiles = new Set([
49
+ 'src/app/core/store/app.store.ts',
50
+ 'src/app/core/firebase/database.service.ts',
51
+ 'src/app/core/firebase/firebase.service.ts',
52
+ 'src/app/core/firebase/firebase.mock.service.ts',
53
+ 'src/app/core/firebase/cached-listeners.service.ts',
54
+ 'src/app/core/firebase/stream-multiplexer.ts',
55
+ ]);
56
+ function findTsFiles(dir) {
57
+ if (!fs.existsSync(dir))
58
+ return [];
59
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
60
+ const filename = path.join(dir, entry.name);
61
+ if (entry.isDirectory()) {
62
+ return ['node_modules', 'dist', '.git', '.cache'].includes(entry.name) ? [] : findTsFiles(filename);
63
+ }
64
+ return entry.isFile() && /\.ts$/.test(entry.name) && !/\.(spec|test|d)\.ts$/.test(entry.name) ? [filename] : [];
65
+ }).sort();
66
+ }
67
+ function unwrap(node) {
68
+ while (typescript_1.default.isParenthesizedExpression(node) || typescript_1.default.isAsExpression(node) ||
69
+ typescript_1.default.isTypeAssertionExpression(node) || typescript_1.default.isSatisfiesExpression(node) || typescript_1.default.isNonNullExpression(node)) {
70
+ node = node.expression;
71
+ }
72
+ return node;
73
+ }
74
+ /** Resolve constants through TypeScript symbols, preserving lexical scope and import aliases. */
75
+ class Literals {
76
+ checker;
77
+ mutated;
78
+ constructor(checker, mutated) {
79
+ this.checker = checker;
80
+ this.mutated = mutated;
81
+ }
82
+ symbol(node) {
83
+ const symbol = typescript_1.default.isShorthandPropertyAssignment(node.parent) && node.parent.name === node ?
84
+ this.checker.getShorthandAssignmentValueSymbol(node.parent) : this.checker.getSymbolAtLocation(node);
85
+ if (!symbol || !(symbol.flags & typescript_1.default.SymbolFlags.Alias))
86
+ return symbol;
87
+ const target = this.checker.getAliasedSymbol(symbol);
88
+ // Dependencies are intentionally not loaded into this source-only program.
89
+ // Preserve the import declaration when TypeScript resolves it to `unknown`.
90
+ return target.declarations?.length ? target : symbol;
91
+ }
92
+ name(node) {
93
+ const symbol = this.symbol(node);
94
+ const imported = symbol?.declarations?.find(typescript_1.default.isImportSpecifier);
95
+ return imported?.propertyName?.text || symbol?.name || node.getText();
96
+ }
97
+ resolve(node, seen = new Set()) {
98
+ if (!node)
99
+ return undefined;
100
+ node = unwrap(node);
101
+ if (seen.has(node))
102
+ return undefined;
103
+ seen.add(node);
104
+ if (typescript_1.default.isIdentifier(node) || typescript_1.default.isPropertyAccessExpression(node)) {
105
+ if (typescript_1.default.isPropertyAccessExpression(node)) {
106
+ let receiver = node.expression;
107
+ while (typescript_1.default.isPropertyAccessExpression(receiver))
108
+ receiver = receiver.expression;
109
+ const receiverSymbol = this.symbol(receiver);
110
+ if (receiverSymbol && this.mutated.has(receiverSymbol))
111
+ return undefined;
112
+ }
113
+ const symbol = this.symbol(node);
114
+ if (!symbol || this.mutated.has(symbol))
115
+ return undefined;
116
+ for (const declaration of symbol.declarations || []) {
117
+ if (typescript_1.default.isVariableDeclaration(declaration) && declaration.initializer &&
118
+ typescript_1.default.isVariableDeclarationList(declaration.parent) && declaration.parent.flags & typescript_1.default.NodeFlags.Const) {
119
+ return this.resolve(declaration.initializer, seen);
120
+ }
121
+ if (typescript_1.default.isPropertyDeclaration(declaration) && declaration.initializer &&
122
+ declaration.modifiers?.some((m) => m.kind === typescript_1.default.SyntaxKind.ReadonlyKeyword)) {
123
+ return this.resolve(declaration.initializer, seen);
124
+ }
125
+ if (typescript_1.default.isPropertyAssignment(declaration))
126
+ return this.resolve(declaration.initializer, seen);
127
+ if (typescript_1.default.isEnumMember(declaration) && declaration.initializer)
128
+ return this.resolve(declaration.initializer, seen);
129
+ }
130
+ return undefined;
131
+ }
132
+ return node;
133
+ }
134
+ string(node) {
135
+ const value = this.resolve(node);
136
+ return value && typescript_1.default.isStringLiteralLike(value) ? value.text : undefined;
137
+ }
138
+ array(node, seen = new Set()) {
139
+ const value = this.resolve(node);
140
+ if (!value || !typescript_1.default.isArrayLiteralExpression(value) || seen.has(value))
141
+ return undefined;
142
+ seen.add(value);
143
+ const result = [];
144
+ for (const element of value.elements) {
145
+ if (typescript_1.default.isSpreadElement(element)) {
146
+ const spread = this.array(element.expression, new Set(seen));
147
+ if (!spread)
148
+ return undefined;
149
+ result.push(...spread);
150
+ }
151
+ else {
152
+ result.push(element);
153
+ }
154
+ }
155
+ return result;
156
+ }
157
+ object(node, seen = new Set()) {
158
+ const value = this.resolve(node);
159
+ if (!value || !typescript_1.default.isObjectLiteralExpression(value) || seen.has(value))
160
+ return undefined;
161
+ seen.add(value);
162
+ const result = new Map();
163
+ for (const property of value.properties) {
164
+ if (typescript_1.default.isSpreadAssignment(property)) {
165
+ const spread = this.object(property.expression, new Set(seen));
166
+ if (!spread)
167
+ return undefined;
168
+ for (const [key, initializer] of spread)
169
+ result.set(key, initializer);
170
+ }
171
+ else if (typescript_1.default.isPropertyAssignment(property) || typescript_1.default.isShorthandPropertyAssignment(property)) {
172
+ const name = property.name;
173
+ const key = typescript_1.default.isComputedPropertyName(name) ? this.string(name.expression) :
174
+ typescript_1.default.isIdentifier(name) || typescript_1.default.isStringLiteralLike(name) || typescript_1.default.isNumericLiteral(name) ? name.text : undefined;
175
+ if (key === undefined)
176
+ return undefined;
177
+ result.set(key, typescript_1.default.isPropertyAssignment(property) ? property.initializer : property.name);
178
+ }
179
+ else {
180
+ return undefined;
181
+ }
182
+ }
183
+ return result;
184
+ }
185
+ }
186
+ function collectMutations(files, checker) {
187
+ const symbols = new Set();
188
+ const aliases = [];
189
+ const symbolAt = (node) => {
190
+ const symbol = checker.getSymbolAtLocation(node);
191
+ return symbol && symbol.flags & typescript_1.default.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
192
+ };
193
+ function mark(node) {
194
+ node = unwrap(node);
195
+ const symbol = symbolAt(node);
196
+ if (symbol)
197
+ symbols.add(symbol);
198
+ if (typescript_1.default.isPropertyAccessExpression(node) || typescript_1.default.isElementAccessExpression(node))
199
+ mark(node.expression);
200
+ }
201
+ function visit(node) {
202
+ if (typescript_1.default.isVariableDeclaration(node) && typescript_1.default.isIdentifier(node.name) && node.initializer) {
203
+ const initializer = unwrap(node.initializer);
204
+ if (typescript_1.default.isIdentifier(initializer) || typescript_1.default.isPropertyAccessExpression(initializer)) {
205
+ const alias = symbolAt(node.name);
206
+ const target = symbolAt(initializer);
207
+ if (alias && target)
208
+ aliases.push([alias, target]);
209
+ }
210
+ }
211
+ if (typescript_1.default.isBinaryExpression(node) && node.operatorToken.kind >= typescript_1.default.SyntaxKind.FirstAssignment &&
212
+ node.operatorToken.kind <= typescript_1.default.SyntaxKind.LastAssignment)
213
+ mark(node.left);
214
+ if (typescript_1.default.isDeleteExpression(node))
215
+ mark(node.expression);
216
+ if ((typescript_1.default.isPostfixUnaryExpression(node) || typescript_1.default.isPrefixUnaryExpression(node)) &&
217
+ [typescript_1.default.SyntaxKind.PlusPlusToken, typescript_1.default.SyntaxKind.MinusMinusToken].includes(node.operator))
218
+ mark(node.operand);
219
+ if (typescript_1.default.isCallExpression(node) && typescript_1.default.isPropertyAccessExpression(node.expression) &&
220
+ ['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin', 'set', 'delete', 'clear', 'add']
221
+ .includes(node.expression.name.text))
222
+ mark(node.expression.expression);
223
+ if (typescript_1.default.isCallExpression(node) && typescript_1.default.isPropertyAccessExpression(node.expression) &&
224
+ ['Object.assign', 'Object.defineProperty', 'Reflect.set'].includes(node.expression.getText()) && node.arguments[0])
225
+ mark(node.arguments[0]);
226
+ typescript_1.default.forEachChild(node, visit);
227
+ }
228
+ files.forEach((file) => visit(file));
229
+ let changed = true;
230
+ while (changed) {
231
+ changed = false;
232
+ for (const [alias, target] of aliases) {
233
+ if (symbols.has(alias) || symbols.has(target)) {
234
+ if (!symbols.has(alias) || !symbols.has(target))
235
+ changed = true;
236
+ symbols.add(alias);
237
+ symbols.add(target);
238
+ }
239
+ }
240
+ }
241
+ return symbols;
242
+ }
243
+ function discoverMappings(files, literals) {
244
+ const stores = new Map([
245
+ ['userStore', 'users'], ['UserStore', 'users'],
246
+ ['userContextStore', 'userContexts'], ['UserContextStore', 'userContexts'],
247
+ ['userPrivateStore', 'userPrivates'], ['UserPrivateStore', 'userPrivates'],
248
+ ]);
249
+ const classes = new Map();
250
+ for (const [suffix, collection] of [['User', 'users'], ['UserContext', 'userContexts'], ['UserPrivate', 'userPrivates']]) {
251
+ classes.set(`Load${suffix}`, { collection, operation: 'load' });
252
+ classes.set(`Stream${suffix}`, { collection, operation: 'stream' });
253
+ }
254
+ for (const file of files) {
255
+ function visit(node) {
256
+ if (typescript_1.default.isCallExpression(node)) {
257
+ const name = literals.name(node.expression);
258
+ if (name === 'withEntitiesAndDBMethods') {
259
+ const collection = literals.string(node.arguments[0]);
260
+ if (collection) {
261
+ const base = path.basename(file.fileName, '.store.ts').replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
262
+ stores.set(`${base}Store`, collection);
263
+ let parent = node.parent;
264
+ while (parent && !typescript_1.default.isVariableDeclaration(parent))
265
+ parent = parent.parent;
266
+ if (parent && typescript_1.default.isVariableDeclaration(parent) && typescript_1.default.isIdentifier(parent.name))
267
+ stores.set(parent.name.text, collection);
268
+ }
269
+ }
270
+ if (node.expression.kind === typescript_1.default.SyntaxKind.SuperKeyword) {
271
+ let parent = node.parent;
272
+ while (parent && !typescript_1.default.isClassDeclaration(parent))
273
+ parent = parent.parent;
274
+ const collection = literals.string(node.arguments[0]);
275
+ if (parent && typescript_1.default.isClassDeclaration(parent) && parent.name && collection) {
276
+ const bases = parent.heritageClauses?.flatMap((clause) => clause.types.map((type) => literals.name(type.expression))) || [];
277
+ const operation = bases.includes('EntityStreamQuery') ? 'stream' : bases.includes('EntityLoadQuery') ? 'load' : undefined;
278
+ if (operation)
279
+ classes.set(parent.name.text, { collection, operation });
280
+ }
281
+ }
282
+ }
283
+ typescript_1.default.forEachChild(node, visit);
284
+ }
285
+ visit(file);
286
+ }
287
+ return { stores, classes };
288
+ }
289
+ function storeCollection(node, mappings, literals, seen = new Set()) {
290
+ node = unwrap(node);
291
+ if (seen.has(node))
292
+ return undefined;
293
+ seen.add(node);
294
+ const symbol = literals.symbol(node);
295
+ // Resolve injected stores and aliases before falling back to conventional variable names.
296
+ for (const declaration of symbol?.declarations || []) {
297
+ if (typescript_1.default.isVariableDeclaration(declaration) || typescript_1.default.isPropertyDeclaration(declaration) || typescript_1.default.isParameter(declaration)) {
298
+ if (declaration.type && typescript_1.default.isTypeReferenceNode(declaration.type)) {
299
+ const type = declaration.type;
300
+ // Signal stores are constructors; helper parameters commonly describe
301
+ // their instances with InstanceType<typeof Store>, without an inject().
302
+ const argument = type.typeArguments?.[0];
303
+ const token = literals.name(type.typeName) === 'InstanceType' && type.typeArguments?.length === 1 &&
304
+ argument && typescript_1.default.isTypeQueryNode(argument) ? argument.exprName : type.typeName;
305
+ const name = literals.name(token);
306
+ if (mappings.stores.has(name))
307
+ return mappings.stores.get(name);
308
+ }
309
+ if (declaration.initializer) {
310
+ const value = unwrap(declaration.initializer);
311
+ const target = typescript_1.default.isCallExpression(value) && (literals.symbol(value.expression)?.name || value.expression.getText()) === 'inject' ? value.arguments[0] : value;
312
+ if (target) {
313
+ const collection = storeCollection(target, mappings, literals, new Set(seen));
314
+ if (collection)
315
+ return collection;
316
+ }
317
+ }
318
+ }
319
+ }
320
+ const name = symbol?.name || (typescript_1.default.isPropertyAccessExpression(node) ? node.name.text : node.getText());
321
+ return mappings.stores.get(name);
322
+ }
323
+ function parseFilters(node, literals) {
324
+ const params = literals.array(node);
325
+ if (!params)
326
+ throw new Error('Query filters are not a resolvable constant array.');
327
+ return params.map((param) => {
328
+ const tuple = literals.array(param);
329
+ const field = tuple && literals.string(tuple[0]);
330
+ const operator = tuple && literals.string(tuple[1]);
331
+ if (!tuple || tuple.length !== 3 || !field || !operator ||
332
+ !(equalityOps.has(operator) || rangeOps.has(operator) || arrayOps.has(operator))) {
333
+ throw new Error('A filter field/operator is dynamic or unsupported.');
334
+ }
335
+ return { field, operator };
336
+ });
337
+ }
338
+ function parseOptions(node, literals) {
339
+ if (!node || typescript_1.default.isIdentifier(node) && node.text === 'undefined')
340
+ return { orderBy: [], hasOptions: false };
341
+ const value = literals.resolve(node);
342
+ if (value?.kind === typescript_1.default.SyntaxKind.NullKeyword)
343
+ return { orderBy: [], hasOptions: false };
344
+ const options = literals.object(node);
345
+ if (!options)
346
+ throw new Error('Query options are not a resolvable constant object.');
347
+ const order = options.get('orderBy');
348
+ if (!order)
349
+ return { orderBy: [], hasOptions: options.size > 0 };
350
+ const singleField = literals.string(order);
351
+ if (singleField)
352
+ return { orderBy: [{ field: singleField, direction: 'ASCENDING' }], hasOptions: true };
353
+ const values = literals.array(order);
354
+ if (!values || values.length === 0)
355
+ throw new Error('orderBy is dynamic or unsupported.');
356
+ const tuples = literals.string(values[0]) !== undefined ? [values] : values.map((v) => literals.array(v));
357
+ const orderBy = tuples.map((tuple) => {
358
+ const field = tuple && literals.string(tuple[0]);
359
+ const direction = tuple && tuple.length === 1 ? 'asc' : tuple && literals.string(tuple[1]);
360
+ if (!tuple || tuple.length > 2 || !field || !['asc', 'desc'].includes(direction || ''))
361
+ throw new Error('An orderBy field/direction is dynamic or invalid.');
362
+ return { field, direction: direction === 'desc' ? 'DESCENDING' : 'ASCENDING' };
363
+ });
364
+ if (new Set(orderBy.map((sort) => sort.field)).size !== orderBy.length)
365
+ throw new Error('Duplicate orderBy fields.');
366
+ return { orderBy, hasOptions: true };
367
+ }
368
+ function parseAggregates(node, literals) {
369
+ const object = literals.object(node);
370
+ if (!object)
371
+ throw new Error('Aggregate fields are not a resolvable constant object.');
372
+ const fields = [];
373
+ for (const [key, value] of object) {
374
+ const tuple = literals.array(value);
375
+ const operator = tuple && literals.string(tuple[0]);
376
+ if (!operator || !['count', 'sum', 'average'].includes(operator))
377
+ throw new Error('An aggregate operator is dynamic or unsupported.');
378
+ // Match FirebaseService.aggregate, which currently dispatches on the object key.
379
+ if (key !== operator)
380
+ throw new Error('Aggregate keys must match count, sum, or average in FirebaseService.aggregate.');
381
+ if (operator !== 'count') {
382
+ const field = tuple && literals.string(tuple[1]);
383
+ if (!field)
384
+ throw new Error('An aggregate field is dynamic or unsupported.');
385
+ fields.push(field);
386
+ }
387
+ }
388
+ return [...new Set(fields)].sort();
389
+ }
390
+ function extractQueries(files, root, literals, mappings) {
391
+ const queries = [];
392
+ const diagnostics = [];
393
+ let checked = 0;
394
+ for (const file of files) {
395
+ const relative = path.relative(root, file.fileName).split(path.sep).join('/');
396
+ if (runtimeFiles.has(relative))
397
+ continue;
398
+ function visit(node) {
399
+ if (typescript_1.default.isCallExpression(node) && typescript_1.default.isPropertyAccessExpression(node.expression)) {
400
+ const expression = node.expression;
401
+ const method = expression.name.text;
402
+ const receiver = expression.expression;
403
+ let operation;
404
+ let collection;
405
+ let offset = 0;
406
+ let factory = false;
407
+ if (['load', 'stream', 'count', 'aggregate'].includes(method)) {
408
+ collection = storeCollection(receiver, mappings, literals);
409
+ if (collection || /store$/i.test(typescript_1.default.isPropertyAccessExpression(receiver) ? receiver.name.text : receiver.getText(file)))
410
+ operation = method;
411
+ }
412
+ if (!operation && method === 'create') {
413
+ const name = literals.symbol(receiver)?.name || receiver.getText(file);
414
+ const mapping = mappings.classes.get(name);
415
+ if (mapping || /^(Load|Stream)[A-Z]/.test(name)) {
416
+ operation = mapping?.operation || (name.startsWith('Stream') ? 'stream' : 'load');
417
+ collection = mapping?.collection;
418
+ offset = 1;
419
+ factory = true;
420
+ }
421
+ }
422
+ if (!operation && ['getEntities', 'streamEntities', 'streamEntitiesChanges', 'count', 'aggregate'].includes(method)) {
423
+ collection = literals.string(node.arguments[0]);
424
+ // Avoid treating unrelated collection.count() methods as database calls.
425
+ if (collection || /^(this\.)?(db|database)$/.test(receiver.getText(file)) || method.startsWith('getEntities') || method.startsWith('streamEntities')) {
426
+ operation = 'database';
427
+ offset = 1;
428
+ }
429
+ }
430
+ if (operation) {
431
+ const line = file.getLineAndCharacterOfPosition(node.getStart()).line + 1;
432
+ try {
433
+ if (!collection)
434
+ throw new Error('Cannot resolve the Firestore collection; no collection name is guessed.');
435
+ const segments = collection.split('/');
436
+ if (segments.some((segment) => !segment) || segments.length % 2 === 0)
437
+ throw new Error('Invalid collection path.');
438
+ const filters = parseFilters(node.arguments[offset], literals);
439
+ const { orderBy, hasOptions } = parseOptions(node.arguments[offset + 1], literals);
440
+ const aggregateFields = method === 'aggregate' ? parseAggregates(node.arguments[offset + 2], literals) : [];
441
+ const query = { file: relative, line, rawText: node.getText(file), collection: segments[segments.length - 1], filters, orderBy, aggregateFields };
442
+ if (new Set(filters.filter((filter) => arrayOps.has(filter.operator)).map((filter) => filter.field)).size > 1)
443
+ throw new Error('Queries with multiple array fields are unsupported by composite indexes.');
444
+ checked++;
445
+ // A direct single-ID load uses getEntity. Factory queries can be batched into IN queries.
446
+ if (operation === 'load' && !factory && !hasOptions && filters.length === 1 && filters[0].field === '__id' && filters[0].operator === '==') {
447
+ // No collection query is issued.
448
+ }
449
+ else if (operation === 'database' || operation === 'stream') {
450
+ queries.push(query);
451
+ }
452
+ else {
453
+ const active = { ...query, filters: [...filters, { field: '_deleted', operator: '==' }] };
454
+ queries.push(active);
455
+ if (operation === 'load' && !hasOptions) {
456
+ queries.push({ ...active, filters: [...active.filters, { field: '_updatedAt', operator: '>' }] });
457
+ }
458
+ }
459
+ }
460
+ catch (error) {
461
+ diagnostics.push({ file: relative, line, reason: error instanceof Error ? error.message : String(error) });
462
+ }
463
+ }
464
+ }
465
+ typescript_1.default.forEachChild(node, visit);
466
+ }
467
+ visit(file);
468
+ }
469
+ return { queries, diagnostics, checked };
470
+ }
471
+ function plan(query) {
472
+ const equality = [...new Set(query.filters.filter((filter) => equalityOps.has(filter.operator)).map((filter) => filter.field))].sort();
473
+ const arrays = [...new Set(query.filters.filter((filter) => arrayOps.has(filter.operator)).map((filter) => filter.field))].sort();
474
+ const ordered = query.orderBy.filter((sort) => sort.field !== '__name__' && !equality.includes(sort.field));
475
+ const lastDirection = query.orderBy[query.orderBy.length - 1]?.direction || 'ASCENDING';
476
+ // Firestore appends unmentioned inequality fields lexicographically, using the last explicit direction.
477
+ const ranges = [...new Set(query.filters.filter((filter) => rangeOps.has(filter.operator)).map((filter) => filter.field))].sort();
478
+ for (const field of ranges) {
479
+ if (field !== '__name__' && !ordered.some((sort) => sort.field === field) && !equality.includes(field))
480
+ ordered.push({ field, direction: lastDirection });
481
+ }
482
+ const aggregates = query.aggregateFields.filter((field) => !equality.includes(field) && !ordered.some((sort) => sort.field === field)).sort();
483
+ const nameDirection = query.orderBy.find((sort) => sort.field === '__name__')?.direction || lastDirection;
484
+ const fields = [
485
+ ...equality.filter((field) => field !== '__name__').map((fieldPath) => ({ fieldPath, order: 'ASCENDING' })),
486
+ ...arrays.map((fieldPath) => ({ fieldPath, arrayConfig: 'CONTAINS' })),
487
+ ...ordered.map((sort) => ({ fieldPath: sort.field, order: sort.direction })),
488
+ ...aggregates.map((fieldPath) => ({ fieldPath, order: 'ASCENDING' })),
489
+ { fieldPath: '__name__', order: nameDirection },
490
+ ];
491
+ return { equality: equality.filter((field) => field !== '__name__'), arrays, ordered, aggregates, nameDirection, fields };
492
+ }
493
+ function indexMatches(index, query, required) {
494
+ if (index.collectionGroup !== query.collection || index.queryScope !== 'COLLECTION')
495
+ return false;
496
+ // Vector indexes serve nearest-neighbor queries, which this analyzer does
497
+ // not model. Their directional prefixes cannot satisfy ordinary queries.
498
+ if (index.fields.some((field) => field.vectorConfig !== undefined))
499
+ return false;
500
+ const fields = index.fields;
501
+ if (new Set(fields.map((field) => field.fieldPath)).size !== fields.length)
502
+ return false;
503
+ const arrays = fields.filter((field) => field.arrayConfig === 'CONTAINS');
504
+ if (arrays.length !== required.arrays.length || arrays.some((field) => !required.arrays.includes(field.fieldPath)))
505
+ return false;
506
+ const directional = fields.filter((field) => !field.arrayConfig && field.fieldPath !== '__name__');
507
+ if (directional.some((field) => !field.order))
508
+ return false;
509
+ if (directional.length !== required.equality.length + required.ordered.length + required.aggregates.length)
510
+ return false;
511
+ const prefix = directional.slice(0, required.equality.length);
512
+ if (prefix.some((field) => !required.equality.includes(field.fieldPath)))
513
+ return false;
514
+ for (const [i, sort] of required.ordered.entries()) {
515
+ const field = directional[required.equality.length + i];
516
+ if (field?.fieldPath !== sort.field || field.order !== sort.direction)
517
+ return false;
518
+ }
519
+ const aggregates = directional.slice(required.equality.length + required.ordered.length);
520
+ if (aggregates.some((field) => !required.aggregates.includes(field.fieldPath)))
521
+ return false;
522
+ const explicitName = fields.find((field) => field.fieldPath === '__name__');
523
+ if (explicitName && fields[fields.length - 1] !== explicitName)
524
+ return false;
525
+ const nameDirection = explicitName?.order || directional[directional.length - 1]?.order || 'ASCENDING';
526
+ return nameDirection === required.nameDirection;
527
+ }
528
+ function automaticIndexes(query, indexes) {
529
+ const fields = new Set([...query.filters.map((filter) => filter.field), ...query.orderBy.map((sort) => sort.field), ...query.aggregateFields]);
530
+ return [...fields].filter((field) => field !== '__name__').flatMap((fieldPath) => {
531
+ const overrides = (indexes.fieldOverrides || []).filter((override) => override.collectionGroup === query.collection &&
532
+ (override.fieldPath === '*' || fieldPath === override.fieldPath || fieldPath.startsWith(`${override.fieldPath}.`)) && override.indexes !== undefined)
533
+ .sort((a, b) => (b.fieldPath === '*' ? 0 : b.fieldPath.length) - (a.fieldPath === '*' ? 0 : a.fieldPath.length));
534
+ const modes = overrides[0]?.indexes || (overrides.length ? [] : [
535
+ { order: 'ASCENDING', queryScope: 'COLLECTION' },
536
+ { order: 'DESCENDING', queryScope: 'COLLECTION' },
537
+ { arrayConfig: 'CONTAINS', queryScope: 'COLLECTION' },
538
+ ]);
539
+ return modes.filter((mode) => mode.queryScope === 'COLLECTION').map((mode) => ({
540
+ collectionGroup: query.collection, queryScope: 'COLLECTION',
541
+ fields: [{ fieldPath, ...(mode.arrayConfig ? { arrayConfig: mode.arrayConfig } : { order: mode.order }) }],
542
+ }));
543
+ });
544
+ }
545
+ function satisfied(query, required, indexes) {
546
+ if (required.fields.length === 1)
547
+ return true; // Document key / unfiltered collection reads.
548
+ const candidates = [...indexes.indexes, ...automaticIndexes(query, indexes)];
549
+ if (candidates.some((index) => indexMatches(index, query, required)))
550
+ return true;
551
+ // Merge equality/array indexes with the same ordering suffix. Never merge range queries.
552
+ if (query.filters.some((filter) => rangeOps.has(filter.operator)) || required.aggregates.length)
553
+ return false;
554
+ const covered = new Set();
555
+ for (const candidate of candidates) {
556
+ const equality = candidate.fields.filter((field) => !field.arrayConfig && required.equality.includes(field.fieldPath)).map((field) => field.fieldPath);
557
+ const arrays = candidate.fields.filter((field) => field.arrayConfig && required.arrays.includes(field.fieldPath)).map((field) => field.fieldPath);
558
+ const subset = { ...required, equality, arrays };
559
+ // Without an explicit non-equality sort, equality indexes can be scanned in either direction.
560
+ if (!required.ordered.length && !query.orderBy.some((sort) => sort.field === '__name__')) {
561
+ subset.nameDirection = candidate.fields.find((field) => field.fieldPath === '__name__')?.order ||
562
+ candidate.fields.filter((field) => field.order).slice(-1)[0]?.order || 'ASCENDING';
563
+ }
564
+ if (indexMatches(candidate, query, subset)) {
565
+ equality.concat(arrays).forEach((field) => covered.add(field));
566
+ }
567
+ }
568
+ return required.equality.concat(required.arrays).length > 0 && required.equality.concat(required.arrays).every((field) => covered.has(field));
569
+ }
570
+ function isRecord(value) {
571
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
572
+ }
573
+ function validateIndexes(value) {
574
+ if (!value || typeof value !== 'object' || !('indexes' in value) || !Array.isArray(value.indexes))
575
+ throw new Error('firestore.indexes.json must contain an indexes array.');
576
+ for (const index of value.indexes) {
577
+ if (!index || typeof index.collectionGroup !== 'string' || !['COLLECTION', 'COLLECTION_GROUP'].includes(index.queryScope) || !Array.isArray(index.fields))
578
+ throw new Error('Invalid composite index definition.');
579
+ for (const field of index.fields) {
580
+ if (!isRecord(field) || typeof field.fieldPath !== 'string' ||
581
+ ['order', 'arrayConfig', 'vectorConfig'].filter((mode) => field[mode] !== undefined).length !== 1) {
582
+ throw new Error('Invalid index field mode; use exactly one of order, arrayConfig, or vectorConfig.');
583
+ }
584
+ if (field.order !== undefined && field.order !== 'ASCENDING' && field.order !== 'DESCENDING' ||
585
+ field.arrayConfig !== undefined && field.arrayConfig !== 'CONTAINS')
586
+ throw new Error('Invalid index field mode.');
587
+ if (field.vectorConfig !== undefined) {
588
+ const vector = field.vectorConfig;
589
+ if (!isRecord(vector) || typeof vector.dimension !== 'number' || !Number.isInteger(vector.dimension) ||
590
+ vector.dimension < 1 || vector.dimension > 2048 || !isRecord(vector.flat) || Object.keys(vector.flat).length !== 0) {
591
+ throw new Error('Invalid vector index configuration; expected an integer dimension from 1 to 2048 and flat: {}.');
592
+ }
593
+ }
594
+ }
595
+ }
596
+ if ('fieldOverrides' in value && !Array.isArray(value.fieldOverrides))
597
+ throw new Error('fieldOverrides must be an array.');
598
+ }
599
+ function checkFirestoreIndexes(options = {}) {
600
+ const root = path.resolve(options.projectRoot || process.cwd());
601
+ const indexesPath = path.join(root, 'firestore.indexes.json');
602
+ const result = { success: false, checkedQueries: 0, missingIndexes: [], unresolvedQueries: [] };
603
+ const log = (message) => { if (!options.quiet)
604
+ console.log(message); };
605
+ try {
606
+ const indexes = JSON.parse(fs.readFileSync(indexesPath, 'utf8'));
607
+ validateIndexes(indexes);
608
+ const filenames = findTsFiles(path.join(root, 'src', 'app'));
609
+ if (!filenames.length)
610
+ throw new Error('No TypeScript source files found under src/app. Check the project root.');
611
+ const program = typescript_1.default.createProgram(filenames, {
612
+ target: typescript_1.default.ScriptTarget.ES2022, module: typescript_1.default.ModuleKind.ESNext, moduleResolution: typescript_1.default.ModuleResolutionKind.Node10,
613
+ baseUrl: root, noResolve: true, noLib: true, types: [], skipLibCheck: true,
614
+ });
615
+ const files = filenames.map((filename) => program.getSourceFile(filename)).filter((file) => !!file);
616
+ const checker = program.getTypeChecker();
617
+ const literals = new Literals(checker, collectMutations(files, checker));
618
+ const extracted = extractQueries(files, root, literals, discoverMappings(files, literals));
619
+ result.checkedQueries = extracted.checked;
620
+ result.unresolvedQueries.push(...extracted.diagnostics);
621
+ const signatures = new Set();
622
+ for (const query of extracted.queries) {
623
+ const required = plan(query);
624
+ if (satisfied(query, required, indexes))
625
+ continue;
626
+ // A disabled automatic index needs an exemption change, not an invalid one-field composite.
627
+ if (required.fields.length === 2 && (required.fields[0].order === required.nameDirection ||
628
+ required.fields[0].arrayConfig === 'CONTAINS' && required.nameDirection === 'ASCENDING')) {
629
+ result.unresolvedQueries.push({ file: query.file, line: query.line, reason: `Automatic indexing is disabled for ${query.collection}.${required.fields[0].fieldPath}; review fieldOverrides.` });
630
+ continue;
631
+ }
632
+ const signature = JSON.stringify([query.collection, required.fields]);
633
+ if (!signatures.has(signature)) {
634
+ signatures.add(signature);
635
+ result.missingIndexes.push({ collection: query.collection, query, requiredFields: required.fields });
636
+ }
637
+ }
638
+ for (const missing of result.missingIndexes) {
639
+ log(`Missing index: ${missing.collection} at ${missing.query.file}:${missing.query.line}\n ${JSON.stringify(missing.requiredFields)}`);
640
+ }
641
+ if (options.fix && result.missingIndexes.length) {
642
+ indexes.indexes.push(...result.missingIndexes.map((missing) => ({
643
+ collectionGroup: missing.collection, queryScope: 'COLLECTION', fields: missing.requiredFields,
644
+ })));
645
+ fs.writeFileSync(indexesPath, JSON.stringify(indexes, null, 2) + '\n');
646
+ log(`Added ${result.missingIndexes.length} indexes. Deploy with: firebase deploy --only firestore:indexes`);
647
+ }
648
+ result.success = result.unresolvedQueries.length === 0 && (options.fix === true || result.missingIndexes.length === 0);
649
+ }
650
+ catch (error) {
651
+ result.unresolvedQueries.push({ file: 'firestore.indexes.json', line: 1, reason: error instanceof Error ? error.message : String(error) });
652
+ }
653
+ for (const diagnostic of result.unresolvedQueries)
654
+ log(`Unable to verify ${diagnostic.file}:${diagnostic.line}: ${diagnostic.reason}`);
655
+ log(`Firestore index check: ${result.checkedQueries} query call sites analyzed; ${result.missingIndexes.length} missing definitions${options.fix ? ' added' : ''}; ${result.unresolvedQueries.length} unresolved checks. Scope: src/app, supported store/database calls; deployment state is not checked.`);
656
+ return result;
657
+ }
@@ -0,0 +1 @@
1
+ export { checkFirestoreIndexes, CheckOptions, CheckResult } from './firestore-indexes';
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkFirestoreIndexes = void 0;
4
+ var firestore_indexes_1 = require("./firestore-indexes");
5
+ Object.defineProperty(exports, "checkFirestoreIndexes", { enumerable: true, get: function () { return firestore_indexes_1.checkFirestoreIndexes; } });
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@tech4good/platform-tooling",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "Development tools for Tech4Good Angular and Firebase applications.",
5
+ "license": "MIT",
6
+ "type": "commonjs",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "bin": {
17
+ "t4g-check-firestore-indexes": "./dist/cli.js"
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "engines": {
23
+ "node": ">=22"
24
+ },
25
+ "scripts": {
26
+ "build": "tsc -p tsconfig.json",
27
+ "test": "tsc -p tsconfig.test.json && jasmine \"test-dist/test/*.spec.js\"",
28
+ "prepack": "npm run build"
29
+ },
30
+ "dependencies": {
31
+ "typescript": "~5.8.3"
32
+ },
33
+ "devDependencies": {
34
+ "@types/jasmine": "~5.1.0",
35
+ "@types/node": "^18.19.47",
36
+ "jasmine": "^5.1.0"
37
+ }
38
+ }