@tech4good/platform-tooling 0.1.0-alpha.1 → 0.1.0-alpha.3

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.
@@ -0,0 +1,313 @@
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.generateEntityRegistrySources = generateEntityRegistrySources;
40
+ exports.generateEntityRegistries = generateEntityRegistries;
41
+ exports.watchEntityRegistries = watchEntityRegistries;
42
+ const fs = __importStar(require("node:fs"));
43
+ const path = __importStar(require("node:path"));
44
+ const typescript_1 = __importDefault(require("typescript"));
45
+ const slash = (value) => value.replace(/\\/g, '/');
46
+ const header = '// Generated by t4g-entities. Do not edit; update *.model.ts / *.mock.ts instead.\n';
47
+ function quote(value) {
48
+ return "'" + value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")
49
+ .replace(/[\u0000-\u001f\u2028\u2029]/g, character => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`) + "'";
50
+ }
51
+ /** Normalize both slash styles so path validation is consistent across developer machines. */
52
+ function relativeDirectory(value) {
53
+ const portable = slash(value);
54
+ const normalized = path.posix.normalize(portable).replace(/\/+$/, '') || '.';
55
+ if (path.isAbsolute(value) || path.posix.isAbsolute(portable) || /^[a-z]:/i.test(portable) || normalized === '..' || normalized.startsWith('../')) {
56
+ throw new Error(`Entity registry paths must stay inside the project: ${value}`);
57
+ }
58
+ return normalized;
59
+ }
60
+ function unwrap(node) {
61
+ while (typescript_1.default.isParenthesizedExpression(node) || typescript_1.default.isAsExpression(node) || typescript_1.default.isSatisfiesExpression(node))
62
+ node = node.expression;
63
+ return node;
64
+ }
65
+ /** Resolve named aliases/namespace imports; type-only imports cannot identify runtime helpers. */
66
+ function imports(file) {
67
+ const values = new Map();
68
+ for (const statement of file.statements) {
69
+ if (!typescript_1.default.isImportDeclaration(statement) || !typescript_1.default.isStringLiteral(statement.moduleSpecifier) || statement.importClause?.isTypeOnly)
70
+ continue;
71
+ const bindings = statement.importClause?.namedBindings;
72
+ if (bindings && typescript_1.default.isNamedImports(bindings)) {
73
+ for (const binding of bindings.elements)
74
+ if (!binding.isTypeOnly) {
75
+ values.set(binding.name.text, { module: statement.moduleSpecifier.text, name: binding.propertyName?.text ?? binding.name.text });
76
+ }
77
+ }
78
+ else if (bindings && typescript_1.default.isNamespaceImport(bindings)) {
79
+ values.set(bindings.name.text, { module: statement.moduleSpecifier.text, name: '*' });
80
+ }
81
+ }
82
+ return values;
83
+ }
84
+ function reference(node, names) {
85
+ node = unwrap(node);
86
+ if (typescript_1.default.isIdentifier(node))
87
+ return names.get(node.text);
88
+ if (typescript_1.default.isPropertyAccessExpression(node) && typescript_1.default.isIdentifier(node.expression)) {
89
+ const parent = names.get(node.expression.text);
90
+ if (parent?.name === '*')
91
+ return { module: parent.module, name: node.name.text };
92
+ }
93
+ return undefined;
94
+ }
95
+ /**
96
+ * Accept only exported top-level constants calling the expected package helper.
97
+ * Reject recognizable but unsupported uses instead of silently omitting entities.
98
+ * Arbitrary factories, re-export chains and app execution are outside this scanner.
99
+ */
100
+ function declarations(file, helper, module) {
101
+ const names = imports(file);
102
+ const declarations = [];
103
+ function visit(node) {
104
+ if (typescript_1.default.isCallExpression(node)) {
105
+ const callee = reference(node.expression, names);
106
+ if (callee?.module === module && callee.name === helper) {
107
+ let parent = node;
108
+ while (parent.parent && (typescript_1.default.isParenthesizedExpression(parent.parent) || typescript_1.default.isAsExpression(parent.parent) || typescript_1.default.isSatisfiesExpression(parent.parent)))
109
+ parent = parent.parent;
110
+ const declaration = parent.parent;
111
+ const list = declaration?.parent;
112
+ const statement = list?.parent;
113
+ if (!declaration || !typescript_1.default.isVariableDeclaration(declaration) || !typescript_1.default.isIdentifier(declaration.name) ||
114
+ !list || !typescript_1.default.isVariableDeclarationList(list) || !(list.flags & typescript_1.default.NodeFlags.Const) ||
115
+ !statement || !typescript_1.default.isVariableStatement(statement) || statement.parent !== file ||
116
+ !statement.modifiers?.some(modifier => modifier.kind === typescript_1.default.SyntaxKind.ExportKeyword)) {
117
+ throw new Error(`${file.fileName}: ${helper} must initialize an exported top-level const.`);
118
+ }
119
+ declarations.push({ name: declaration.name.text, call: node });
120
+ }
121
+ }
122
+ typescript_1.default.forEachChild(node, visit);
123
+ }
124
+ visit(file);
125
+ return { names, declarations };
126
+ }
127
+ function modulePath(from, to) {
128
+ const relative = slash(path.posix.relative(path.posix.dirname(from), to)).replace(/\.ts$/, '');
129
+ return relative.startsWith('.') ? relative : `./${relative}`;
130
+ }
131
+ /**
132
+ * Produce both registry modules from project-relative source text, with no disk
133
+ * access or app execution. Also accepts the leading slash used by schematic Trees.
134
+ * Models are discovered first, then mocks are matched by direct relative import.
135
+ * Invalid declarations, duplicate collections and orphan mocks throw before any
136
+ * output is returned. Files without entity helper calls need no registration.
137
+ */
138
+ function generateEntityRegistrySources(sources, options = {}) {
139
+ const sourceRoot = relativeDirectory(options.sourceRoot ?? 'src/app');
140
+ const outputDir = relativeDirectory(options.outputDir ?? 'src/app/core/store');
141
+ const entities = [];
142
+ const models = new Map();
143
+ const files = Object.entries(sources).map(([name, text]) => [slash(name).replace(/^\//, ''), text])
144
+ .filter(([name]) => (sourceRoot === '.' || name.startsWith(`${sourceRoot}/`)) && /\.(model|mock)\.ts$/.test(name))
145
+ .sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)
146
+ .map(([name, text]) => typescript_1.default.createSourceFile(name, text, typescript_1.default.ScriptTarget.Latest, true));
147
+ for (const file of files) {
148
+ const errors = file.parseDiagnostics;
149
+ if (errors.length)
150
+ throw new Error(`${file.fileName}: ${typescript_1.default.flattenDiagnosticMessageText(errors[0].messageText, '\n')}`);
151
+ if (!file.fileName.endsWith('.model.ts'))
152
+ continue;
153
+ for (const { name, call } of declarations(file, 'defineEntity', '@tech4good/platform-data').declarations) {
154
+ const value = call.arguments[0] && unwrap(call.arguments[0]);
155
+ if (call.arguments.length !== 1 || !value || !typescript_1.default.isObjectLiteralExpression(value)) {
156
+ throw new Error(`${file.fileName}: defineEntity requires { collection: 'literal-name' }.`);
157
+ }
158
+ const allowedProps = new Set(['collection', 'accessPolicy']);
159
+ let collection;
160
+ for (const property of value.properties) {
161
+ if (!typescript_1.default.isPropertyAssignment(property)) {
162
+ throw new Error(`${file.fileName}: defineEntity requires { collection: 'literal-name' }.`);
163
+ }
164
+ const propName = property.name.getText(file).replace(/^['"]|['"]$/g, '');
165
+ if (!allowedProps.has(propName)) {
166
+ throw new Error(`${file.fileName}: defineEntity requires { collection: 'literal-name' }.`);
167
+ }
168
+ if (propName === 'collection') {
169
+ collection = unwrap(property.initializer);
170
+ }
171
+ }
172
+ if (!collection || !typescript_1.default.isStringLiteralLike(collection) || !collection.text || collection.text.trim() !== collection.text ||
173
+ collection.text.includes('/') || ['.', '..'].includes(collection.text) || /^__.*__$/.test(collection.text)) {
174
+ throw new Error(`${file.fileName}: collection must be a nonempty literal collection name, without slashes.`);
175
+ }
176
+ if (entities.some(entity => entity.collection === collection.text))
177
+ throw new Error(`${file.fileName}: Duplicate entity collection "${collection.text}".`);
178
+ const entity = { file: file.fileName, name, collection: collection.text };
179
+ entities.push(entity);
180
+ models.set(`${file.fileName}#${name}`, entity);
181
+ }
182
+ }
183
+ // A separate pass makes associations independent of filename/traversal order.
184
+ for (const file of files.filter(file => file.fileName.endsWith('.mock.ts'))) {
185
+ const { names, declarations: mocks } = declarations(file, 'defineEntityMock', '@tech4good/platform-data/testing');
186
+ for (const { name, call } of mocks) {
187
+ const target = call.arguments[0] && reference(call.arguments[0], names);
188
+ let model = target && target.module.startsWith('.') ? path.posix.normalize(path.posix.join(path.posix.dirname(file.fileName), target.module)) : '';
189
+ model = model.replace(/\.js$/, '.ts');
190
+ if (!model.endsWith('.ts'))
191
+ model += '.ts';
192
+ const entity = target && models.get(`${model}#${target.name}`);
193
+ if (!entity)
194
+ throw new Error(`${file.fileName}: ${name} must reference a defineEntity export imported directly from its relative *.model file.`);
195
+ if (call.arguments.length !== 2)
196
+ throw new Error(`${file.fileName}: ${name} requires an entity definition and mock options.`);
197
+ if (entity.mock)
198
+ throw new Error(`${file.fileName}: Duplicate mock definition for "${entity.collection}".`);
199
+ entity.mock = { file: file.fileName, name };
200
+ }
201
+ }
202
+ entities.sort((a, b) => a.collection < b.collection ? -1 : a.collection > b.collection ? 1 : 0);
203
+ // Production consumers can import entity identities/types without importing
204
+ // fixture modules. Development providers import the separate mock registry.
205
+ const entityFile = `${outputDir}/entities.generated.ts`;
206
+ const mockFile = `${outputDir}/entity-mocks.generated.ts`;
207
+ const entityImports = entities.map((entity, i) => `import { ${entity.name} as entity${i} } from ${quote(modulePath(entityFile, entity.file))};`).join('\n');
208
+ const entityEntries = entities.map((entity, i) => ` [${quote(entity.collection)}]: entity${i},`).join('\n');
209
+ const mockImports = entities.map((entity, i) => entity.mock
210
+ ? `import { ${entity.mock.name} as mock${i} } from ${quote(modulePath(mockFile, entity.mock.file))};`
211
+ : `import { ${entity.name} as entity${i} } from ${quote(modulePath(mockFile, entity.file))};`).join('\n');
212
+ const mockEntries = entities.map((entity, i) => ` [${quote(entity.collection)}]: ${entity.mock ? `mock${i}` : `defineEntityMock(entity${i}, { seeds: [] })`},`).join('\n');
213
+ return {
214
+ collections: entities.map(entity => entity.collection),
215
+ files: {
216
+ [entityFile]: `${header}import type { EntityType } from '@tech4good/platform-data';\n${entityImports}\n\nexport const APP_ENTITIES = {\n${entityEntries}\n} as const;\n\nexport type AppEntityMap = {\n [K in keyof typeof APP_ENTITIES]: EntityType<(typeof APP_ENTITIES)[K]>;\n};\n`,
217
+ [mockFile]: `${header}${entities.some(entity => !entity.mock) ? "import { defineEntityMock } from '@tech4good/platform-data/testing';\n" : ''}${mockImports}\n\nexport const APP_ENTITY_MOCKS = {\n${mockEntries}\n} as const;\n`,
218
+ },
219
+ };
220
+ }
221
+ function readSources(options) {
222
+ const root = path.resolve(options.projectRoot ?? process.cwd());
223
+ const directory = path.join(root, relativeDirectory(options.sourceRoot ?? 'src/app'));
224
+ if (!fs.existsSync(directory))
225
+ throw new Error(`Entity source directory does not exist: ${directory}`);
226
+ const sources = {};
227
+ function visit(directory) {
228
+ for (const entry of fs.readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : 1)) {
229
+ const file = path.join(directory, entry.name);
230
+ if (entry.isDirectory() && !entry.name.startsWith('.') && !['node_modules', 'dist'].includes(entry.name))
231
+ visit(file);
232
+ else if (entry.isFile() && /\.(model|mock)\.ts$/.test(entry.name))
233
+ sources[slash(path.relative(root, file))] = fs.readFileSync(file, 'utf8');
234
+ }
235
+ }
236
+ visit(directory);
237
+ return sources;
238
+ }
239
+ /**
240
+ * Compare before writing to avoid needless Angular rebuilds. Check mode reports
241
+ * missing/stale files without changing them. In write mode the generated header
242
+ * marks files we own; refuse handwritten destinations before updating either file.
243
+ */
244
+ function writeResult(result, options, check) {
245
+ const root = path.resolve(options.projectRoot ?? process.cwd());
246
+ const changed = [];
247
+ // Validate both destinations before changing either one.
248
+ if (!check)
249
+ for (const file of Object.keys(result.files)) {
250
+ const target = path.join(root, file);
251
+ if (fs.existsSync(target) && !fs.readFileSync(target, 'utf8').startsWith(header)) {
252
+ throw new Error(`Refusing to overwrite a non-generated file: ${file}`);
253
+ }
254
+ }
255
+ for (const [file, text] of Object.entries(result.files)) {
256
+ const target = path.join(root, file);
257
+ const previous = fs.existsSync(target) ? fs.readFileSync(target, 'utf8') : undefined;
258
+ if (previous === text)
259
+ continue;
260
+ changed.push(file);
261
+ if (!check) {
262
+ if (previous !== undefined && !previous.startsWith(header))
263
+ throw new Error(`Refusing to overwrite a non-generated file: ${file}`);
264
+ fs.mkdirSync(path.dirname(target), { recursive: true });
265
+ // Rename prevents the Angular watcher from reading a partially written module.
266
+ const temporary = `${target}.${process.pid}.tmp`;
267
+ try {
268
+ fs.writeFileSync(temporary, text);
269
+ fs.renameSync(temporary, target);
270
+ }
271
+ finally {
272
+ if (fs.existsSync(temporary))
273
+ fs.unlinkSync(temporary);
274
+ }
275
+ }
276
+ }
277
+ return { ...result, changed, success: !check || changed.length === 0 };
278
+ }
279
+ /**
280
+ * Discover from disk and write changed registries, or compare only with check:true.
281
+ * `changed` lists different/missing outputs in either mode; `success` is false
282
+ * only when check mode finds stale output. Discovery or filesystem errors throw.
283
+ */
284
+ function generateEntityRegistries(options = {}) {
285
+ return writeResult(generateEntityRegistrySources(readSources(options), options), options, options.check ?? false);
286
+ }
287
+ /**
288
+ * Generate synchronously before starting a polling watcher, so callers can start
289
+ * Angular only after valid modules exist. Polling finds new/deleted directories
290
+ * across Node platforms. Later invalid edits report onError and retain the last
291
+ * valid output; another source edit retries. The caller must close the watcher.
292
+ */
293
+ function watchEntityRegistries(options, callbacks = {}) {
294
+ const initial = readSources(options);
295
+ const result = writeResult(generateEntityRegistrySources(initial, options), options, false);
296
+ callbacks.onChange?.(result);
297
+ let signature = JSON.stringify(initial);
298
+ const timer = setInterval(() => {
299
+ try {
300
+ const sources = readSources(options);
301
+ const next = JSON.stringify(sources);
302
+ if (next === signature)
303
+ return;
304
+ // Remember invalid source too, so the same error is not repeated every tick.
305
+ signature = next;
306
+ callbacks.onChange?.(writeResult(generateEntityRegistrySources(sources, options), options, false));
307
+ }
308
+ catch (error) {
309
+ callbacks.onError?.(error instanceof Error ? error : new Error(String(error)));
310
+ }
311
+ }, callbacks.intervalMs ?? 300);
312
+ return { close: () => clearInterval(timer) };
313
+ }
@@ -39,16 +39,32 @@ interface MissingIndex {
39
39
  queries: Query[];
40
40
  requiredFields: FirestoreIndexField[];
41
41
  }
42
+ /** Source-analysis report, not a check of indexes deployed to a Firebase project. */
42
43
  export interface CheckResult {
44
+ /** False for unresolved checks, or missing definitions unless fix mode added them. */
43
45
  success: boolean;
46
+ /** App call sites analyzed; one load call may expand into multiple query shapes. */
44
47
  checkedQueries: number;
48
+ /** Deduplicated missing definitions, retained in the report even after fix mode adds them. */
45
49
  missingIndexes: MissingIndex[];
50
+ /** Unsupported/dynamic queries and analysis failures that need manual review. */
46
51
  unresolvedQueries: Diagnostic[];
47
52
  }
53
+ /** Local analysis settings; no mode contacts Firebase or deploys indexes. */
48
54
  export interface CheckOptions {
55
+ /** App directory containing src/app and firestore.indexes.json; defaults to cwd. */
49
56
  projectRoot?: string;
57
+ /** Append confidently inferred missing definitions to the local index file. */
50
58
  fix?: boolean;
59
+ /** Suppress console diagnostics while retaining the structured result. */
51
60
  quiet?: boolean;
52
61
  }
62
+ /**
63
+ * Compare statically discoverable app queries with local Firestore definitions.
64
+ * Store calls expand into their runtime shapes, including _deleted filters and
65
+ * initial/incremental load variants. Dynamic or unsupported queries are reported
66
+ * as unresolved rather than treated as covered. Fix mode only edits the local
67
+ * index file; deployment and runtime validation remain separate steps.
68
+ */
53
69
  export declare function checkFirestoreIndexes(options?: CheckOptions): CheckResult;
54
70
  export {};
@@ -118,6 +118,15 @@ class Literals {
118
118
  const receiverSymbol = this.symbol(receiver);
119
119
  if (receiverSymbol && this.mutated.has(receiverSymbol))
120
120
  return undefined;
121
+ // Entity collection identity now lives beside the interface in *.model.ts.
122
+ // Resolve the declarative helper without executing application code.
123
+ if (node.name.text === 'collection') {
124
+ const definition = this.resolve(node.expression, new Set(seen));
125
+ if (definition && typescript_1.default.isCallExpression(definition) && this.name(definition.expression) === 'defineEntity') {
126
+ const options = this.object(definition.arguments[0]);
127
+ return this.resolve(options?.get('collection'), seen);
128
+ }
129
+ }
121
130
  }
122
131
  const symbol = this.symbol(node);
123
132
  if (!symbol || this.mutated.has(symbol))
@@ -608,6 +617,13 @@ function validateIndexes(value) {
608
617
  if ('fieldOverrides' in value && !Array.isArray(value.fieldOverrides))
609
618
  throw new Error('fieldOverrides must be an array.');
610
619
  }
620
+ /**
621
+ * Compare statically discoverable app queries with local Firestore definitions.
622
+ * Store calls expand into their runtime shapes, including _deleted filters and
623
+ * initial/incremental load variants. Dynamic or unsupported queries are reported
624
+ * as unresolved rather than treated as covered. Fix mode only edits the local
625
+ * index file; deployment and runtime validation remain separate steps.
626
+ */
611
627
  function checkFirestoreIndexes(options = {}) {
612
628
  const root = path.resolve(options.projectRoot || process.cwd());
613
629
  const indexesPath = path.join(root, 'firestore.indexes.json');
@@ -0,0 +1,35 @@
1
+ export declare const ENTITY_RULES_MARKER = "// @t4g-entity-rules";
2
+ export interface FirestoreRulesOptions {
3
+ /** Application root directory containing firestore.base.rules (default: process.cwd()). */
4
+ projectRoot?: string;
5
+ /** Project-relative directory scanned for *.firestore.rules fragments (default: src/app). */
6
+ sourceRoot?: string;
7
+ /** Project-relative base rules file containing shared helpers and the marker (default: firestore.base.rules). */
8
+ baseFile?: string;
9
+ /** Project-relative compiled output file (default: firestore.rules). */
10
+ outputFile?: string;
11
+ }
12
+ export interface FirestoreRulesResult {
13
+ success: boolean;
14
+ /** Project-relative output file path (e.g. firestore.rules). */
15
+ outputFile: string;
16
+ /** Generated compiled rules text. */
17
+ content: string;
18
+ /** Project-relative fragment paths included in deterministic order. */
19
+ fragments: string[];
20
+ /** Whether the output file differed from disk (or was missing). */
21
+ changed: boolean;
22
+ }
23
+ /**
24
+ * Pure in-memory assembler shared by both `t4g-rules` CLI and Angular schematics.
25
+ * Combines `firestore.base.rules` with all `*.firestore.rules` fragments under `sourceRoot`
26
+ * (sorted deterministically) at the `// @t4g-entity-rules` marker.
27
+ */
28
+ export declare function assembleFirestoreRulesSources(sources: Record<string, string>, options?: Pick<FirestoreRulesOptions, 'sourceRoot' | 'baseFile' | 'outputFile'>): Omit<FirestoreRulesResult, 'success' | 'changed'>;
29
+ /**
30
+ * Read `firestore.base.rules` and `*.firestore.rules` from disk, assemble `firestore.rules`,
31
+ * and write it (or verify it is up to date when `check: true`).
32
+ */
33
+ export declare function generateFirestoreRules(options?: FirestoreRulesOptions & {
34
+ check?: boolean;
35
+ }): FirestoreRulesResult;
@@ -0,0 +1,164 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ENTITY_RULES_MARKER = void 0;
37
+ exports.assembleFirestoreRulesSources = assembleFirestoreRulesSources;
38
+ exports.generateFirestoreRules = generateFirestoreRules;
39
+ const fs = __importStar(require("node:fs"));
40
+ const path = __importStar(require("node:path"));
41
+ exports.ENTITY_RULES_MARKER = '// @t4g-entity-rules';
42
+ const slash = (p) => p.replace(/\\/g, '/');
43
+ function normalizeRelPath(p) {
44
+ const clean = path.posix.normalize(slash(p)).replace(/^\/+|\/+$/g, '');
45
+ if (!clean || clean === '..' || clean.startsWith('../')) {
46
+ throw new Error(`Invalid project-relative path: ${JSON.stringify(p)}`);
47
+ }
48
+ return clean;
49
+ }
50
+ /** Indent every non-empty line of a fragment so it nests cleanly under `match /databases/{database}/documents`. */
51
+ function indentBlock(text, spaces) {
52
+ const prefix = ' '.repeat(spaces);
53
+ return text
54
+ .replace(/\r\n/g, '\n')
55
+ .trim()
56
+ .split('\n')
57
+ .map((line) => (line.trim().length > 0 ? `${prefix}${line}` : ''))
58
+ .join('\n');
59
+ }
60
+ /** Extract top-level `match /<collection>/...` paths in a fragment to catch duplicate collection rules. */
61
+ function extractMatchPaths(fragment) {
62
+ const matches = [];
63
+ const regex = /\bmatch\s+\/([A-Za-z0-9_-]+)\/\{[^}]+\}/g;
64
+ let m;
65
+ while ((m = regex.exec(fragment)) !== null) {
66
+ matches.push(m[1]);
67
+ }
68
+ return matches;
69
+ }
70
+ /**
71
+ * Pure in-memory assembler shared by both `t4g-rules` CLI and Angular schematics.
72
+ * Combines `firestore.base.rules` with all `*.firestore.rules` fragments under `sourceRoot`
73
+ * (sorted deterministically) at the `// @t4g-entity-rules` marker.
74
+ */
75
+ function assembleFirestoreRulesSources(sources, options = {}) {
76
+ const sourceRoot = normalizeRelPath(options.sourceRoot ?? 'src/app');
77
+ const baseFile = normalizeRelPath(options.baseFile ?? 'firestore.base.rules');
78
+ const outputFile = normalizeRelPath(options.outputFile ?? 'firestore.rules');
79
+ const normalized = new Map();
80
+ for (const [filePath, text] of Object.entries(sources)) {
81
+ normalized.set(slash(filePath).replace(/^\/+/, ''), text);
82
+ }
83
+ const baseContent = normalized.get(baseFile);
84
+ if (baseContent === undefined) {
85
+ throw new Error(`Base rules file "${baseFile}" was not found.`);
86
+ }
87
+ if (!baseContent.includes(exports.ENTITY_RULES_MARKER)) {
88
+ throw new Error(`Base rules file "${baseFile}" must contain the marker "${exports.ENTITY_RULES_MARKER}".`);
89
+ }
90
+ const fragmentPaths = [...normalized.keys()]
91
+ .filter((file) => (sourceRoot === '.' || file.startsWith(`${sourceRoot}/`)) && file.endsWith('.firestore.rules'))
92
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
93
+ const seenCollections = new Map();
94
+ const renderedBlocks = [];
95
+ for (const fragmentPath of fragmentPaths) {
96
+ const raw = (normalized.get(fragmentPath) ?? '').trim();
97
+ if (!raw) {
98
+ throw new Error(`${fragmentPath}: entity rules fragment cannot be empty.`);
99
+ }
100
+ if (/\brules_version\b/.test(raw) || /\bservice\s+cloud\.firestore\b/.test(raw)) {
101
+ throw new Error(`${fragmentPath}: entity rules fragments must contain only match blocks, not rules_version or service wrappers.`);
102
+ }
103
+ for (const collection of extractMatchPaths(raw)) {
104
+ const existing = seenCollections.get(collection);
105
+ if (existing) {
106
+ throw new Error(`${fragmentPath}: duplicate Firestore rules for collection "${collection}" (already defined in ${existing}).`);
107
+ }
108
+ seenCollections.set(collection, fragmentPath);
109
+ }
110
+ renderedBlocks.push(` // Source: ${fragmentPath}\n${indentBlock(raw, 4)}`);
111
+ }
112
+ // Replace the marker line (including its leading indentation) cleanly.
113
+ const markerLineRegex = new RegExp(`^[ \\t]*${exports.ENTITY_RULES_MARKER.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[ \\t]*$`, 'm');
114
+ const assembledBody = baseContent
115
+ .replace(/\r\n/g, '\n')
116
+ .replace(markerLineRegex, renderedBlocks.join('\n\n'));
117
+ const header = `// Generated by t4g-rules from ${baseFile} and ${sourceRoot}/**/*.firestore.rules.\n` +
118
+ `// Do not edit this file directly; edit ${baseFile} or per-entity *.firestore.rules files and run \`npm run generate:rules\`.\n`;
119
+ const content = `${header}${assembledBody.trimEnd()}\n`;
120
+ return { outputFile, content, fragments: fragmentPaths };
121
+ }
122
+ function walkRuleFiles(dir, projectRoot, out) {
123
+ if (!fs.existsSync(dir))
124
+ return;
125
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
126
+ if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name.startsWith('.'))
127
+ continue;
128
+ const full = path.join(dir, entry.name);
129
+ if (entry.isDirectory()) {
130
+ walkRuleFiles(full, projectRoot, out);
131
+ }
132
+ else if (entry.isFile() && entry.name.endsWith('.firestore.rules')) {
133
+ const rel = slash(path.relative(projectRoot, full));
134
+ out[rel] = fs.readFileSync(full, 'utf8');
135
+ }
136
+ }
137
+ }
138
+ /**
139
+ * Read `firestore.base.rules` and `*.firestore.rules` from disk, assemble `firestore.rules`,
140
+ * and write it (or verify it is up to date when `check: true`).
141
+ */
142
+ function generateFirestoreRules(options = {}) {
143
+ const projectRoot = path.resolve(options.projectRoot ?? process.cwd());
144
+ const sourceRoot = normalizeRelPath(options.sourceRoot ?? 'src/app');
145
+ const baseFile = normalizeRelPath(options.baseFile ?? 'firestore.base.rules');
146
+ const outputFile = normalizeRelPath(options.outputFile ?? 'firestore.rules');
147
+ const sources = {};
148
+ const absBase = path.join(projectRoot, baseFile);
149
+ if (fs.existsSync(absBase)) {
150
+ sources[baseFile] = fs.readFileSync(absBase, 'utf8');
151
+ }
152
+ walkRuleFiles(path.join(projectRoot, sourceRoot), projectRoot, sources);
153
+ const assembled = assembleFirestoreRulesSources(sources, { sourceRoot, baseFile, outputFile });
154
+ const absOutput = path.join(projectRoot, outputFile);
155
+ const existing = fs.existsSync(absOutput) ? fs.readFileSync(absOutput, 'utf8') : undefined;
156
+ const changed = existing !== assembled.content;
157
+ if (options.check) {
158
+ return { ...assembled, changed, success: !changed };
159
+ }
160
+ if (changed) {
161
+ fs.writeFileSync(absOutput, assembled.content, 'utf8');
162
+ }
163
+ return { ...assembled, changed, success: true };
164
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1,4 @@
1
1
  export { checkFirestoreIndexes, CheckOptions, CheckResult } from './firestore-indexes';
2
+ export { generateEntityRegistries, generateEntityRegistrySources, watchEntityRegistries, EntityRegistryOptions, EntityRegistryResult } from './entity-registry';
3
+ export { ENTITY_RULES_MARKER, assembleFirestoreRulesSources, generateFirestoreRules, FirestoreRulesOptions, FirestoreRulesResult, } from './firestore-rules';
4
+ export { SKILLS_MANIFEST_FILE, SKILLS_GITIGNORE_FILE, discoverPackageSkills, syncPlatformSkills, DiscoveredSkill, SkillsSyncOptions, SkillsSyncResult, } from './skills-sync';
package/dist/index.js CHANGED
@@ -1,5 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.checkFirestoreIndexes = void 0;
3
+ exports.syncPlatformSkills = exports.discoverPackageSkills = exports.SKILLS_GITIGNORE_FILE = exports.SKILLS_MANIFEST_FILE = exports.generateFirestoreRules = exports.assembleFirestoreRulesSources = exports.ENTITY_RULES_MARKER = exports.watchEntityRegistries = exports.generateEntityRegistrySources = exports.generateEntityRegistries = exports.checkFirestoreIndexes = void 0;
4
4
  var firestore_indexes_1 = require("./firestore-indexes");
5
5
  Object.defineProperty(exports, "checkFirestoreIndexes", { enumerable: true, get: function () { return firestore_indexes_1.checkFirestoreIndexes; } });
6
+ var entity_registry_1 = require("./entity-registry");
7
+ Object.defineProperty(exports, "generateEntityRegistries", { enumerable: true, get: function () { return entity_registry_1.generateEntityRegistries; } });
8
+ Object.defineProperty(exports, "generateEntityRegistrySources", { enumerable: true, get: function () { return entity_registry_1.generateEntityRegistrySources; } });
9
+ Object.defineProperty(exports, "watchEntityRegistries", { enumerable: true, get: function () { return entity_registry_1.watchEntityRegistries; } });
10
+ var firestore_rules_1 = require("./firestore-rules");
11
+ Object.defineProperty(exports, "ENTITY_RULES_MARKER", { enumerable: true, get: function () { return firestore_rules_1.ENTITY_RULES_MARKER; } });
12
+ Object.defineProperty(exports, "assembleFirestoreRulesSources", { enumerable: true, get: function () { return firestore_rules_1.assembleFirestoreRulesSources; } });
13
+ Object.defineProperty(exports, "generateFirestoreRules", { enumerable: true, get: function () { return firestore_rules_1.generateFirestoreRules; } });
14
+ var skills_sync_1 = require("./skills-sync");
15
+ Object.defineProperty(exports, "SKILLS_MANIFEST_FILE", { enumerable: true, get: function () { return skills_sync_1.SKILLS_MANIFEST_FILE; } });
16
+ Object.defineProperty(exports, "SKILLS_GITIGNORE_FILE", { enumerable: true, get: function () { return skills_sync_1.SKILLS_GITIGNORE_FILE; } });
17
+ Object.defineProperty(exports, "discoverPackageSkills", { enumerable: true, get: function () { return skills_sync_1.discoverPackageSkills; } });
18
+ Object.defineProperty(exports, "syncPlatformSkills", { enumerable: true, get: function () { return skills_sync_1.syncPlatformSkills; } });
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};