backend-manager 5.0.106 → 5.0.108

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/CHANGELOG.md CHANGED
@@ -14,6 +14,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
14
14
  - `Fixed` for any bug fixes.
15
15
  - `Security` in case of vulnerabilities.
16
16
 
17
+ # [5.0.106] - 2026-03-04
18
+ ### Added
19
+ - `GET /payments/trial-eligibility`: returns whether the authenticated user is eligible for a free trial (checks for any previous subscription orders in `payments-orders`).
20
+
21
+ ### Fixed
22
+ - Payment frequency mapping now supports `daily` and `weekly` in addition to `monthly` and `annually` across Stripe (`resolvePriceId`), PayPal (`resolvePlanId`), and test processor (`createSubscriptionIntent`). Previously, these frequencies silently fell back to `monthly`.
23
+ - Updated docs (CLAUDE.md, README.md) to list all four supported frequency values.
24
+
17
25
  # [5.0.104] - 2026-03-02
18
26
  ### Added
19
27
  - `POST /payments/cancel`: cancels subscription at period end via processor abstraction (Stripe sets `cancel_at_period_end=true`; test processor writes webhook directly into the Firestore pipeline).
package/CLAUDE.md CHANGED
@@ -447,6 +447,8 @@ When `npx bm test` starts its own emulator, logs go to `emulator.log` (since it
447
447
 
448
448
  These files are overwritten on each run and are gitignored (`*.log`). Use them to search for errors, debug webhook pipelines, or review full function output after a test run.
449
449
 
450
+ - **`logs.log`** — Cloud Function logs from `npx bm logs:read` or `npx bm logs:tail` (raw JSON for `read`, streaming text for `tail`)
451
+
450
452
  ### Filtering Tests
451
453
  ```bash
452
454
  npx bm test rules/ # Run rules tests (both BEM and project)
@@ -587,6 +589,29 @@ npx bm auth:delete <uid-or-email> # Delete user (prompts for
587
589
  npx bm auth:set-claims <uid-or-email> '<json>' # Set custom claims
588
590
  ```
589
591
 
592
+ ### Logs Commands
593
+
594
+ Fetch or stream Cloud Function logs from Google Cloud Logging. Requires `gcloud` CLI installed and authenticated. Auto-resolves the project ID from `service-account.json`, `.firebaserc`, or `GCLOUD_PROJECT`.
595
+
596
+ ```bash
597
+ npx bm logs:read # Read last 1h of logs (default: 50 entries)
598
+ npx bm logs:read --fn bm_api # Filter by function name
599
+ npx bm logs:read --fn bm_api --severity ERROR # Filter by severity (DEBUG, INFO, WARNING, ERROR, CRITICAL)
600
+ npx bm logs:read --since 2d --limit 100 # Custom time range and limit
601
+ npx bm logs:tail # Stream live logs
602
+ npx bm logs:tail --fn bm_paymentsWebhookOnWrite # Stream filtered live logs
603
+ ```
604
+
605
+ Both commands save output to `logs.log` in the project directory (overwritten on each run). `logs:read` saves raw JSON; `logs:tail` streams text.
606
+
607
+ | Flag | Description | Default | Commands |
608
+ |------|-------------|---------|----------|
609
+ | `--fn <name>` | Filter by Cloud Function name | all | both |
610
+ | `--severity <level>` | Minimum severity level | all | both |
611
+ | `--since <duration>` | Time range (`30m`, `1h`, `2d`, `1w`) | `1h` | read only |
612
+ | `--limit <n>` | Max entries | `50` | read only |
613
+ | `--raw` | Output raw JSON | false | both |
614
+
590
615
  ### Shared Flags
591
616
 
592
617
  | Flag | Description |
@@ -705,7 +730,7 @@ subscription: {
705
730
  processor: null, // 'stripe' | 'paypal' | etc.
706
731
  orderId: null, // BEM order ID (e.g., '1234-5678-9012')
707
732
  resourceId: null, // provider subscription ID (e.g., 'sub_xxx')
708
- frequency: null, // 'monthly' | 'annually'
733
+ frequency: null, // 'monthly' | 'annually' | 'weekly' | 'daily'
709
734
  price: 0, // resolved from config (number, e.g., 4.99)
710
735
  startDate: { timestamp, timestampUNIX },
711
736
  updatedBy: {
@@ -911,7 +936,7 @@ payment: {
911
936
  type: 'subscription',
912
937
  limits: { requests: 1000 },
913
938
  trial: { days: 14 },
914
- prices: { monthly: 4.99, annually: 49.99 }, // Flat numbers only
939
+ prices: { monthly: 4.99, annually: 49.99 }, // Flat numbers; also supports 'weekly' and 'daily'
915
940
  stripe: { productId: 'prod_xxx', legacyProductIds: ['prod_OLD'] },
916
941
  paypal: { productId: 'PROD-abc123' },
917
942
  },
@@ -985,6 +1010,7 @@ The `test` processor generates Stripe-shaped data and auto-fires webhooks to the
985
1010
  | Firebase init helper (CLI) | `src/cli/commands/firebase-init.js` |
986
1011
  | Firestore CLI commands | `src/cli/commands/firestore.js` |
987
1012
  | Auth CLI commands | `src/cli/commands/auth.js` |
1013
+ | Logs CLI commands | `src/cli/commands/logs.js` |
988
1014
  | Intent creation | `src/manager/routes/payments/intent/post.js` |
989
1015
  | Webhook ingestion | `src/manager/routes/payments/webhook/post.js` |
990
1016
  | Webhook processing (on-write) | `src/manager/events/firestore/payments-webhooks/on-write.js` |
package/README.md CHANGED
@@ -749,9 +749,13 @@ npx backend-manager <command>
749
749
  | `bem auth:list` | List Auth users |
750
750
  | `bem auth:delete <uid-or-email>` | Delete an Auth user |
751
751
  | `bem auth:set-claims <uid-or-email> '<json>'` | Set custom claims on an Auth user |
752
+ | `bem logs:read` | Fetch Cloud Function logs from Google Cloud Logging |
753
+ | `bem logs:tail` | Stream live Cloud Function logs |
752
754
 
753
755
  All Firestore and Auth commands support `--emulator` to target the local emulator, `--force` to skip confirmation, and `--raw` for compact JSON output.
754
756
 
757
+ Logs commands support `--fn <name>` (function name filter), `--severity <level>`, `--since <duration>` (read only), `--limit <n>` (read only), and `--raw`. Requires `gcloud` CLI installed and authenticated.
758
+
755
759
  ## Environment Variables
756
760
 
757
761
  Set these in your `functions/.env` file:
@@ -795,9 +799,10 @@ npx bm test user/ admin/ # Multiple paths
795
799
 
796
800
  ### Log Files
797
801
 
798
- Both `npx bm emulator` and `npx bm test` automatically save all output to log files in the project directory:
799
- - **`emulator.log`** — Full emulator + Cloud Functions output
800
- - **`test.log`** — Test runner output (when running against an existing emulator)
802
+ BEM CLI commands automatically save output to log files in the project directory:
803
+ - **`emulator.log`** — Full emulator + Cloud Functions output (`npx bm emulator`)
804
+ - **`test.log`** — Test runner output (`npx bm test`, when running against an existing emulator)
805
+ - **`logs.log`** — Cloud Function logs (`npx bm logs:read` or `npx bm logs:tail`)
801
806
 
802
807
  Logs are overwritten on each run. Use them to debug failing tests or review function output.
803
808
 
@@ -922,7 +927,7 @@ payment: {
922
927
  {
923
928
  id: 'plus', name: 'Plus', type: 'subscription',
924
929
  limits: { requests: 100 }, trial: { days: 14 },
925
- prices: { monthly: 28, annually: 276 },
930
+ prices: { monthly: 28, annually: 276 }, // also supports 'weekly' and 'daily'
926
931
  stripe: { productId: 'prod_xxx' },
927
932
  paypal: { productId: 'PROD-abc123' },
928
933
  },
@@ -958,7 +963,7 @@ subscription: {
958
963
  payment: {
959
964
  processor: null, // 'stripe' | 'paypal' | etc.
960
965
  resourceId: null, // provider subscription ID (e.g., 'sub_xxx')
961
- frequency: null, // 'monthly' | 'annually'
966
+ frequency: null, // 'monthly' | 'annually' | 'weekly' | 'daily'
962
967
  startDate: { timestamp, timestampUNIX },
963
968
  updatedBy: {
964
969
  event: { name: null, id: null },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backend-manager",
3
- "version": "5.0.106",
3
+ "version": "5.0.108",
4
4
  "description": "Quick tools for developing Firebase functions",
5
5
  "main": "src/manager/index.js",
6
6
  "bin": {
@@ -118,4 +118,4 @@ function resolveProjectId(projectDir, functionsDir) {
118
118
  return process.env.GCLOUD_PROJECT || 'demo-project';
119
119
  }
120
120
 
121
- module.exports = { initFirebase };
121
+ module.exports = { initFirebase, resolveProjectId };
@@ -0,0 +1,344 @@
1
+ const BaseCommand = require('./base-command');
2
+ const chalk = require('chalk');
3
+ const fs = require('fs');
4
+ const { execSync, spawn } = require('child_process');
5
+ const path = require('path');
6
+ const jetpack = require('fs-jetpack');
7
+ const { resolveProjectId } = require('./firebase-init');
8
+
9
+ const SEVERITY_COLORS = {
10
+ DEFAULT: 'gray',
11
+ DEBUG: 'gray',
12
+ INFO: 'cyan',
13
+ NOTICE: 'blue',
14
+ WARNING: 'yellow',
15
+ ERROR: 'red',
16
+ CRITICAL: 'redBright',
17
+ ALERT: 'redBright',
18
+ EMERGENCY: 'redBright',
19
+ };
20
+
21
+ class LogsCommand extends BaseCommand {
22
+ async execute() {
23
+ const argv = this.main.argv;
24
+ const args = argv._ || [];
25
+ const subcommand = args[0]; // e.g., 'logs:read'
26
+ const action = subcommand.split(':')[1];
27
+
28
+ // Check gcloud is installed
29
+ if (!this.isGcloudInstalled()) {
30
+ this.logError('gcloud CLI is not installed or not in PATH.');
31
+ this.log(chalk.gray(' Install it: https://cloud.google.com/sdk/docs/install'));
32
+ return;
33
+ }
34
+
35
+ // Resolve project ID
36
+ const projectId = this.resolveProject();
37
+ if (!projectId) {
38
+ this.logError('Could not resolve project ID.');
39
+ this.log(chalk.gray(' Ensure functions/service-account.json, .firebaserc, or GCLOUD_PROJECT exists.'));
40
+ return;
41
+ }
42
+
43
+ this.log(chalk.gray(` Project: ${projectId}\n`));
44
+
45
+ switch (action) {
46
+ case 'read':
47
+ return await this.read(projectId, argv);
48
+ case 'tail':
49
+ case 'stream':
50
+ return await this.tail(projectId, argv);
51
+ default:
52
+ this.logError(`Unknown logs subcommand: ${action}`);
53
+ this.log(chalk.gray(' Available: logs:read, logs:tail, logs:stream'));
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Fetch historical logs.
59
+ * Usage: npx bm logs:read [--fn bm_api] [--severity ERROR] [--since 1h] [--limit 50]
60
+ */
61
+ async read(projectId, argv) {
62
+ const filter = this.buildFilter(argv);
63
+ const limit = parseInt(argv.limit, 10) || 50;
64
+
65
+ const cmd = [
66
+ 'gcloud', 'logging', 'read',
67
+ filter ? `'${filter}'` : '',
68
+ `--project=${projectId}`,
69
+ `--limit=${limit}`,
70
+ '--format=json',
71
+ '--order=asc',
72
+ ].filter(Boolean).join(' ');
73
+
74
+ // Set up log file in the project directory
75
+ const projectDir = this.main.firebaseProjectPath;
76
+ const logPath = path.join(projectDir, 'logs.log');
77
+
78
+ this.log(chalk.gray(` Filter: ${filter || '(none)'}`));
79
+ this.log(chalk.gray(` Limit: ${limit}`));
80
+ this.log(chalk.gray(` Logs saving to: ${logPath}\n`));
81
+
82
+ try {
83
+ const output = execSync(cmd, {
84
+ encoding: 'utf8',
85
+ maxBuffer: 10 * 1024 * 1024, // 10MB
86
+ timeout: 30000,
87
+ });
88
+
89
+ const entries = JSON.parse(output || '[]');
90
+
91
+ // Save raw JSON to log file for Claude/tooling to read
92
+ jetpack.write(logPath, JSON.stringify(entries, null, 2));
93
+
94
+ if (entries.length === 0) {
95
+ this.logWarning('No log entries found.');
96
+ return;
97
+ }
98
+
99
+ if (argv.raw) {
100
+ this.log(JSON.stringify(entries, null, 2));
101
+ return;
102
+ }
103
+
104
+ this.log(chalk.gray(` Found ${entries.length} entries\n`));
105
+ for (const entry of entries) {
106
+ this.formatEntry(entry);
107
+ }
108
+ } catch (error) {
109
+ if (error.status) {
110
+ this.logError(`gcloud command failed (exit code ${error.status}):`);
111
+ this.log(chalk.gray(error.stderr || error.message));
112
+ } else {
113
+ this.logError(`Failed to read logs: ${error.message}`);
114
+ }
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Poll for live logs by repeatedly running gcloud logging read.
120
+ * Usage: npx bm logs:tail [--fn bm_api] [--severity ERROR] [--interval 5]
121
+ */
122
+ async tail(projectId, argv) {
123
+ const interval = (parseInt(argv.interval, 10) || 5) * 1000;
124
+ let lastTimestamp = new Date(Date.now() - 60000).toISOString(); // Start 1 min ago
125
+ const seenIds = new Set();
126
+ let stopped = false;
127
+
128
+ // Set up log file in the project directory
129
+ const projectDir = this.main.firebaseProjectPath;
130
+ const logPath = path.join(projectDir, 'logs.log');
131
+ const logStream = fs.createWriteStream(logPath, { flags: 'w' });
132
+
133
+ const filter = this.buildFilter(argv, { excludeTimestamp: true });
134
+ this.log(chalk.gray(` Filter: ${filter || '(none)'}`));
135
+ this.log(chalk.gray(` Polling every ${interval / 1000}s`));
136
+ this.log(chalk.gray(` Logs saving to: ${logPath}`));
137
+ this.log(chalk.gray(' Tailing logs (Ctrl+C to stop)...\n'));
138
+
139
+ // Handle Ctrl+C gracefully
140
+ process.on('SIGINT', () => {
141
+ stopped = true;
142
+ });
143
+
144
+ while (!stopped) {
145
+ try {
146
+ const timestampFilter = `timestamp>="${lastTimestamp}"`;
147
+ const fullFilter = filter
148
+ ? `${filter} AND ${timestampFilter}`
149
+ : `${timestampFilter}`;
150
+
151
+ const cmd = [
152
+ 'gcloud', 'logging', 'read',
153
+ `'${fullFilter}'`,
154
+ `--project=${projectId}`,
155
+ '--limit=100',
156
+ '--format=json',
157
+ '--order=asc',
158
+ ].join(' ');
159
+
160
+ const output = execSync(cmd, {
161
+ encoding: 'utf8',
162
+ maxBuffer: 10 * 1024 * 1024,
163
+ timeout: 15000,
164
+ stdio: ['pipe', 'pipe', 'pipe'],
165
+ });
166
+
167
+ const entries = JSON.parse(output || '[]');
168
+
169
+ for (const entry of entries) {
170
+ // Deduplicate using insertId
171
+ const entryId = entry.insertId || `${entry.timestamp}-${entry.textPayload || ''}`;
172
+ if (seenIds.has(entryId)) {
173
+ continue;
174
+ }
175
+ seenIds.add(entryId);
176
+
177
+ // Write to log file
178
+ logStream.write(JSON.stringify(entry) + '\n');
179
+
180
+ // Display
181
+ if (argv.raw) {
182
+ this.log(JSON.stringify(entry));
183
+ } else {
184
+ this.formatEntry(entry);
185
+ }
186
+
187
+ // Advance timestamp watermark
188
+ if (entry.timestamp && entry.timestamp > lastTimestamp) {
189
+ lastTimestamp = entry.timestamp;
190
+ }
191
+ }
192
+
193
+ // Cap seenIds to prevent memory leak
194
+ if (seenIds.size > 5000) {
195
+ const arr = [...seenIds];
196
+ arr.splice(0, arr.length - 2500);
197
+ seenIds.clear();
198
+ arr.forEach(id => seenIds.add(id));
199
+ }
200
+ } catch (error) {
201
+ // Silently skip transient errors during polling
202
+ if (error.status) {
203
+ this.log(chalk.gray(` (poll error: ${(error.stderr || error.message).trim().split('\n')[0]})`));
204
+ }
205
+ }
206
+
207
+ // Wait before next poll
208
+ if (!stopped) {
209
+ await new Promise(resolve => setTimeout(resolve, interval));
210
+ }
211
+ }
212
+
213
+ logStream.end();
214
+ this.log(chalk.gray('\n Tail stopped.'));
215
+ }
216
+
217
+ /**
218
+ * Build a gcloud logging filter string from CLI flags.
219
+ */
220
+ buildFilter(argv, options = {}) {
221
+ const parts = [];
222
+
223
+ // Always scope to Cloud Functions
224
+ parts.push('resource.type="cloud_function"');
225
+
226
+ // Function name filter
227
+ if (argv.fn) {
228
+ parts.push(`resource.labels.function_name="${argv.fn}"`);
229
+ }
230
+
231
+ // Severity filter
232
+ if (argv.severity) {
233
+ parts.push(`severity>=${argv.severity.toUpperCase()}`);
234
+ }
235
+
236
+ // Timestamp filter (read only, not tail)
237
+ if (!options.excludeTimestamp) {
238
+ const since = argv.since || '1h';
239
+ const timestamp = this.parseSince(since);
240
+ if (timestamp) {
241
+ parts.push(`timestamp>="${timestamp}"`);
242
+ }
243
+ }
244
+
245
+ return parts.join(' AND ');
246
+ }
247
+
248
+ /**
249
+ * Parse a human-friendly duration (e.g., '1h', '2d', '30m') into an ISO timestamp.
250
+ */
251
+ parseSince(since) {
252
+ const match = since.match(/^(\d+)([mhdw])$/);
253
+ if (!match) {
254
+ this.logWarning(`Invalid --since format: "${since}". Use e.g., 30m, 1h, 2d, 1w`);
255
+ return null;
256
+ }
257
+
258
+ const value = parseInt(match[1], 10);
259
+ const unit = match[2];
260
+ const now = new Date();
261
+
262
+ switch (unit) {
263
+ case 'm': now.setMinutes(now.getMinutes() - value); break;
264
+ case 'h': now.setHours(now.getHours() - value); break;
265
+ case 'd': now.setDate(now.getDate() - value); break;
266
+ case 'w': now.setDate(now.getDate() - (value * 7)); break;
267
+ }
268
+
269
+ return now.toISOString();
270
+ }
271
+
272
+ /**
273
+ * Pretty-print a single log entry.
274
+ */
275
+ formatEntry(entry) {
276
+ const severity = entry.severity || 'DEFAULT';
277
+ const colorFn = chalk[SEVERITY_COLORS[severity] || 'white'];
278
+ const timestamp = entry.timestamp || entry.receiveTimestamp || '';
279
+ const fnName = entry.resource?.labels?.function_name || '';
280
+
281
+ // Extract the actual message
282
+ let message = '';
283
+ if (entry.textPayload) {
284
+ message = entry.textPayload;
285
+ } else if (entry.jsonPayload) {
286
+ message = typeof entry.jsonPayload.message === 'string'
287
+ ? entry.jsonPayload.message
288
+ : JSON.stringify(entry.jsonPayload, null, 2);
289
+ } else if (entry.protoPayload) {
290
+ message = JSON.stringify(entry.protoPayload, null, 2);
291
+ }
292
+
293
+ // Format timestamp to local time
294
+ let timeStr = '';
295
+ if (timestamp) {
296
+ const date = new Date(timestamp);
297
+ timeStr = date.toLocaleTimeString();
298
+ }
299
+
300
+ const severityTag = colorFn(`[${severity.padEnd(8)}]`);
301
+ const fnTag = fnName ? chalk.blue(`[${fnName}]`) : '';
302
+ const timeTag = chalk.gray(timeStr);
303
+
304
+ this.log(`${timeTag} ${severityTag} ${fnTag} ${message}`);
305
+ }
306
+
307
+ /**
308
+ * Resolve the project ID without initializing firebase-admin.
309
+ */
310
+ resolveProject() {
311
+ const projectDir = this.firebaseProjectPath;
312
+ const functionsDir = path.join(projectDir, 'functions');
313
+
314
+ // Try service-account.json first (most reliable for production)
315
+ const serviceAccountPath = path.join(functionsDir, 'service-account.json');
316
+ if (jetpack.exists(serviceAccountPath)) {
317
+ try {
318
+ const sa = JSON.parse(jetpack.read(serviceAccountPath));
319
+ if (sa.project_id) {
320
+ return sa.project_id;
321
+ }
322
+ } catch (e) {
323
+ // Fall through
324
+ }
325
+ }
326
+
327
+ // Fall back to shared resolver
328
+ return resolveProjectId(projectDir, functionsDir);
329
+ }
330
+
331
+ /**
332
+ * Check if gcloud CLI is available.
333
+ */
334
+ isGcloudInstalled() {
335
+ try {
336
+ execSync('gcloud --version', { encoding: 'utf8', stdio: 'pipe' });
337
+ return true;
338
+ } catch (e) {
339
+ return false;
340
+ }
341
+ }
342
+ }
343
+
344
+ module.exports = LogsCommand;
package/src/cli/index.js CHANGED
@@ -28,6 +28,7 @@ const WatchCommand = require('./commands/watch');
28
28
  const StripeCommand = require('./commands/stripe');
29
29
  const FirestoreCommand = require('./commands/firestore');
30
30
  const AuthCommand = require('./commands/auth');
31
+ const LogsCommand = require('./commands/logs');
31
32
 
32
33
  function Main() {}
33
34
 
@@ -145,6 +146,12 @@ Main.prototype.process = async function (args) {
145
146
  const cmd = new AuthCommand(self);
146
147
  return await cmd.execute();
147
148
  }
149
+
150
+ // Logs utility commands
151
+ if (self.options['logs:read'] || self.options['logs:tail'] || self.options['logs:stream']) {
152
+ const cmd = new LogsCommand(self);
153
+ return await cmd.execute();
154
+ }
148
155
  };
149
156
 
150
157
  // Test method for setup command