grada-run 0.40.16 → 0.41.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.
@@ -5,7 +5,7 @@ import { CloudFrontClient, ListDistributionsCommand } from '@aws-sdk/client-clou
5
5
  import color from 'picocolors';
6
6
  import { intro, outro, spinner } from '@clack/prompts';
7
7
  import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
8
- import { failCommand, failProjectNotInitialized, isProgrammaticCall } from '../utils/command.js';
8
+ import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
10
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
11
11
  import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
@@ -37,10 +37,12 @@ export async function runStatusWatch(input = {}) {
37
37
  export function parseStatusArgs(argv = []) {
38
38
  const args = normalizeArgv(argv);
39
39
  if (args[0] === 'status') args.shift();
40
- const { options } = parseFlags(args, {
40
+ const { options, unknown } = parseFlags(args, {
41
41
  string: ['region'],
42
+ boolean: ['headless'],
42
43
  bareBoolean: ['json', 'watch'],
43
44
  });
45
+ if (unknown.length > 0) options.unknownFlags = unknown;
44
46
  return options;
45
47
  }
46
48
 
@@ -424,6 +426,8 @@ export async function runStatus(input = {}) {
424
426
 
425
427
  async function runStatusMain(input = {}) {
426
428
  const options = normalizeOptions(input);
429
+ const unknownRefusal = await refuseUnknownFlags(options, { command: 'status', event: 'status_run' });
430
+ if (unknownRefusal) return unknownRefusal;
427
431
  const noExit = isProgrammaticCall(options);
428
432
  const asJson = Boolean(options.json);
429
433
  let cwd;
@@ -5,7 +5,7 @@ import { RDSClient, DescribeDBInstancesCommand, DescribeDBClustersCommand, Start
5
5
  import color from 'picocolors';
6
6
  import { intro, outro, spinner } from '@clack/prompts';
7
7
  import { trackSuccess, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
8
- import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized } from '../utils/command.js';
8
+ import { failCommand, failAwsError, trackAwsFailure, failProjectNotInitialized, refuseUnknownFlags } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
10
  import { isAuthError, handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
11
11
  import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget } from '../utils/resolvers.js';
@@ -36,13 +36,14 @@ export const DEFAULT_WAKE_POLL_INTERVAL_MS = 5000;
36
36
  export function parseWakeArgs(argv = []) {
37
37
  const args = normalizeArgv(argv);
38
38
  if (args[0] === 'wake') args.shift();
39
- const { options, rest } = parseFlags(args, {
39
+ const { options, rest, unknown } = parseFlags(args, {
40
40
  string: ['project-name', 'cluster', 'service', 'db-identifier', 'region', 'workspace'],
41
- boolean: ['skip-db', 'wait', 'no-wait', 'strict'],
41
+ boolean: ['skip-db', 'wait', 'no-wait', 'strict', 'headless'],
42
42
  });
43
43
  const positionals = rest.filter((arg) => typeof arg === 'string' && !arg.startsWith('-'));
44
44
  if (positionals.length > 0) options.env = positionals[0];
45
45
  if (positionals.length > 1) options.unexpectedPositionals = positionals.slice(1);
46
+ if (unknown.length > 0) options.unknownFlags = unknown;
46
47
  return options;
47
48
  }
48
49
 
@@ -59,6 +60,8 @@ export async function runWake(input = {}) {
59
60
 
60
61
  async function runWakeMain(input = {}) {
61
62
  const options = normalizeOptions(input);
63
+ const unknownRefusal = await refuseUnknownFlags(options, { command: 'wake', event: 'wake_run' });
64
+ if (unknownRefusal) return unknownRefusal;
62
65
  let cwd;
63
66
  let region;
64
67
  let projectName;
@@ -1,12 +1,19 @@
1
1
  import { normalizeArgv } from '../utils/args.js';
2
2
 
3
+ // The only meaningful --no-telemetry spellings (bare, =true, =false —
4
+ // the getBoolFlag convention). Anything else (=garbage, or a flag-like
5
+ // *value* such as --cmd "--no-telemetry=x") is not a global: it flows
6
+ // through to per-command parsing, where the unknown-flag gate rejects
7
+ // it loudly instead of this layer silently eating a command value.
8
+ const GLOBAL_ONLY_FLAGS = new Set(['--no-telemetry', '--no-telemetry=true', '--no-telemetry=false']);
9
+
3
10
  export function parseCliArgs(processArgs) {
4
11
  const argv = normalizeArgv(processArgs);
5
12
  // 1. Extract telemetry flag safely
6
- const hasNoTelemetry = argv.some(arg => arg === '--no-telemetry' || (typeof arg === 'string' && arg.startsWith('--no-telemetry=')));
13
+ const hasNoTelemetry = argv.some(arg => arg === '--no-telemetry' || arg === '--no-telemetry=true');
7
14
 
8
15
  // 2. Filter out telemetry flag
9
- const args = argv.filter(arg => arg !== '--no-telemetry' && !(typeof arg === 'string' && arg.startsWith('--no-telemetry=')));
16
+ const args = argv.filter(arg => !GLOBAL_ONLY_FLAGS.has(arg));
10
17
 
11
18
  // 3. Flag readers. Every value flag supports both `--flag=value` and
12
19
  // `--flag value` spellings; space-form values are recorded in
@@ -69,10 +76,11 @@ export function parseCliArgs(processArgs) {
69
76
  return false;
70
77
  };
71
78
 
72
- // 4. Parse execution flags
73
- const isHeadless = args.includes('--headless');
74
- const isDryRun = args.includes('--dry-run');
75
- const isPreconfigured = args.includes('--preconfigured');
79
+ // 4. Parse execution flags (getBoolFlag like their neighbors: bare and
80
+ // =true both set, =false and absent both clear)
81
+ const isHeadless = getBoolFlag('headless') === true;
82
+ const isDryRun = getBoolFlag('dry-run') === true;
83
+ const isPreconfigured = getBoolFlag('preconfigured') === true;
76
84
 
77
85
  // Headless values are always parsed (so consumption marking is
78
86
  // mode-independent) but only exposed in headless mode.
@@ -132,7 +140,7 @@ export function parseCliArgs(processArgs) {
132
140
  projectName: getValueFlag('project-name'),
133
141
  githubRepo: getValueFlag('github-repo'),
134
142
  setupCiMigrate: getBoolOrValueFlag('setup-ci-migrate'),
135
- setupCiDrift: args.includes('--setup-ci-drift'),
143
+ setupCiDrift: getBoolFlag('setup-ci-drift') === true,
136
144
  };
137
145
 
138
146
  // 5. Isolate positional commands (non-string elements are positionals;
@@ -153,4 +161,14 @@ export function parseCliArgs(processArgs) {
153
161
  headlessOptions,
154
162
  initOptions
155
163
  };
164
+ }
165
+
166
+ // Args for per-command parsers: --no-telemetry is honored globally via
167
+ // DO_NOT_TRACK (see parseCliArgs), so it must not reach parseFlags —
168
+ // otherwise the unknown-flag gate would reject a documented global
169
+ // option on every command. Only meaningful spellings are stripped; a
170
+ // flag-like value (e.g. --cmd "--no-telemetry=x") passes through to the
171
+ // command untouched.
172
+ export function stripGlobalOnlyFlags(processArgs) {
173
+ return normalizeArgv(processArgs).filter((arg) => !GLOBAL_ONLY_FLAGS.has(arg));
156
174
  }
package/src/utils/args.js CHANGED
@@ -42,11 +42,14 @@ export function normalizeArgv(argv) {
42
42
  // - `alias`: single-dash shorthands (`{ f: 'follow' }` makes `-f` act as
43
43
  // the bare long flag).
44
44
  //
45
- // Unknown `--flags` are dropped and everything else is returned in `rest`
46
- // so each command can apply its own positional rules.
45
+ // Space-form values never consume a `--like` token (a following flag stays
46
+ // a flag). Unknown `--flags` are collected in `unknown` (never silently
47
+ // dropped) so commands can reject them loud; everything else is returned
48
+ // in `rest` so each command can apply its own positional rules.
47
49
  export function parseFlags(args, { string = [], number = [], boolean = [], bareBoolean = [], alias = {} } = {}) {
48
50
  const options = {};
49
51
  const rest = [];
52
+ const unknown = [];
50
53
  const strings = normalizeEntries(string);
51
54
  const numbers = normalizeEntries(number);
52
55
  const booleans = normalizeEntries(boolean);
@@ -70,12 +73,12 @@ export function parseFlags(args, { string = [], number = [], boolean = [], bareB
70
73
  const value = eq === -1 ? undefined : arg.slice(eq + 1);
71
74
  if (strings.has(name)) {
72
75
  if (value !== undefined) options[strings.get(name)] = value;
73
- else if (i + 1 < list.length) options[strings.get(name)] = list[++i];
76
+ else if (i + 1 < list.length && !String(list[i + 1]).startsWith('--')) options[strings.get(name)] = list[++i];
74
77
  continue;
75
78
  }
76
79
  if (numbers.has(name)) {
77
80
  if (value !== undefined) options[numbers.get(name)] = Number(value);
78
- else if (i + 1 < list.length) options[numbers.get(name)] = Number(list[++i]);
81
+ else if (i + 1 < list.length && !String(list[i + 1]).startsWith('--')) options[numbers.get(name)] = Number(list[++i]);
79
82
  continue;
80
83
  }
81
84
  if (booleans.has(name)) {
@@ -86,6 +89,9 @@ export function parseFlags(args, { string = [], number = [], boolean = [], bareB
86
89
  if (value === undefined) options[bares.get(name)] = true;
87
90
  continue;
88
91
  }
92
+ // Unknown --flags are collected, never silently dropped: commands
93
+ // reject them loud via refuseUnknownFlags.
94
+ unknown.push(arg);
89
95
  }
90
- return { options, rest };
96
+ return { options, rest, unknown };
91
97
  }
package/src/utils/aws.js CHANGED
@@ -70,10 +70,10 @@ export function resolveClient(injected, ClientClass, clientOptions = {}) {
70
70
  return new ClientClass(clientOptions);
71
71
  }
72
72
 
73
- export function handleAwsAuthError(error, clackSpinner = null, options = {}) {
74
- if (clackSpinner) {
75
- clackSpinner.stop(color.red('❌ AWS session expired or invalid credentials.'));
76
- }
73
+ // Print-only half of the auth-failure branch: the credential-recovery
74
+ // guidance without the exit, for callers (init) that own their own
75
+ // telemetry and exit path through failCommand.
76
+ export function printAwsAuthGuidance(options = {}) {
77
77
  if (!hasAwsCli(options)) {
78
78
  console.log(color.red('\n✖ AWS CLI not found.'));
79
79
  console.log(` Install the AWS CLI: ${color.blue(color.underline(AWS_CLI_INSTALL_URL))}`);
@@ -83,6 +83,13 @@ export function handleAwsAuthError(error, clackSpinner = null, options = {}) {
83
83
  console.log(`Run ${color.cyan('aws sso login')} or ${color.cyan('aws configure')} to refresh your credentials.`);
84
84
  }
85
85
  console.log(color.blue(`\n📘 Troubleshooting Guide: ${color.underline(TROUBLESHOOTING_URL)}\n`));
86
+ }
87
+
88
+ export function handleAwsAuthError(error, clackSpinner = null, options = {}) {
89
+ if (clackSpinner) {
90
+ clackSpinner.stop(color.red('❌ AWS session expired or invalid credentials.'));
91
+ }
92
+ printAwsAuthGuidance(options);
86
93
  process.exit(1);
87
94
  return;
88
95
  }
@@ -125,9 +132,10 @@ export async function provisionStateBucket(region, projectName) {
125
132
  // 2. Format Bucket Name
126
133
  const stateBucketName = formatStateBucketName(projectName, awsAccountId);
127
134
 
128
- // 3. Create S3 Bucket & Enable Versioning
135
+ // 3. Create S3 Bucket & Enable Versioning (shared helper, so init,
136
+ // recovery, and apply reconcile create identical buckets).
129
137
  const s3Client = new S3Client({ region });
130
- await createVersionedBucket(s3Client, stateBucketName, region);
138
+ await ensureStateBucketExists({ region, bucket: stateBucketName, s3Client });
131
139
 
132
140
  return { awsAccountId, stateBucketName, s3Client };
133
141
  }
@@ -135,14 +143,16 @@ export async function provisionStateBucket(region, projectName) {
135
143
  // Creates (or re-creates) one explicitly named state bucket with the same
136
144
  // tagging + versioning provisionStateBucket applies. Recovery reads the
137
145
  // bucket from backend.tf and lands here instead of re-deriving the name,
138
- // which would miss on suffixed trees.
139
- export async function ensureStateBucketExists({ region, bucket }) {
146
+ // which would miss on suffixed trees. `created` reports whether this
147
+ // call made the bucket (vs finding it already owned) so callers can
148
+ // tell creation from adoption without an extra HeadBucket round trip.
149
+ export async function ensureStateBucketExists({ region, bucket, s3Client = null }) {
140
150
  if (process.env.CI_MOCK_AWS === 'true') {
141
- return { bucket, mocked: true };
151
+ return { bucket, mocked: true, created: false };
142
152
  }
143
- const s3Client = new S3Client({ region });
144
- await createVersionedBucket(s3Client, bucket, region);
145
- return { bucket };
153
+ const client = s3Client ?? new S3Client({ region });
154
+ const { created } = await createVersionedBucket(client, bucket, region);
155
+ return { bucket, created };
146
156
  }
147
157
 
148
158
  async function createVersionedBucket(s3Client, bucket, region) {
@@ -151,26 +161,28 @@ async function createVersionedBucket(s3Client, bucket, region) {
151
161
  Bucket: bucket,
152
162
  CreateBucketConfiguration: region === 'us-east-1' ? undefined : { LocationConstraint: region }
153
163
  }));
154
-
155
- await s3Client.send(new PutBucketTaggingCommand({
156
- Bucket: bucket,
157
- Tagging: {
158
- TagSet: [
159
- { Key: "ManagedBy", Value: "grada" }
160
- ]
161
- }
162
- }));
163
-
164
- await s3Client.send(new PutBucketVersioningCommand({
165
- Bucket: bucket,
166
- VersioningConfiguration: { Status: 'Enabled' }
167
- }));
168
164
  } catch (error) {
169
165
  // Ignore if the bucket already exists and is owned by the user
170
166
  if (error.name !== 'BucketAlreadyOwnedByYou') {
171
167
  throw error;
172
168
  }
169
+ return { created: false };
173
170
  }
171
+
172
+ await s3Client.send(new PutBucketTaggingCommand({
173
+ Bucket: bucket,
174
+ Tagging: {
175
+ TagSet: [
176
+ { Key: "ManagedBy", Value: "grada" }
177
+ ]
178
+ }
179
+ }));
180
+
181
+ await s3Client.send(new PutBucketVersioningCommand({
182
+ Bucket: bucket,
183
+ VersioningConfiguration: { Status: 'Enabled' }
184
+ }));
185
+ return { created: true };
174
186
  }
175
187
 
176
188
  export async function teardownStateBucket(region, bucketName, options = {}) {
@@ -52,6 +52,26 @@ export async function refuseIfNonInteractive(options = {}, spec = {}) {
52
52
  });
53
53
  }
54
54
 
55
+ // Unknown flags fail loud at the gate: a typo like --skp-db must never
56
+ // silently widen a command. Parse functions surface parseFlags' unknown
57
+ // list as options.unknownFlags; run functions call this first.
58
+ export async function refuseUnknownFlags(options = {}, spec = {}) {
59
+ const opts = normalizeOptions(options);
60
+ const unknown = Array.isArray(opts.unknownFlags) ? opts.unknownFlags.filter((f) => typeof f === 'string' && f !== '') : [];
61
+ if (unknown.length === 0) return null;
62
+ const { command, event, telemetry } = spec;
63
+ return failCommand({
64
+ noExit: isProgrammaticCall(opts),
65
+ message: `\n✖ Unknown flag "${unknown[0]}" for ${command}.\n`,
66
+ hint: ' Check the spelling or run "grada --help" for usage.\n',
67
+ event,
68
+ telemetry,
69
+ errorCode: 'UNKNOWN_FLAG',
70
+ reason: 'unknown-flag',
71
+ exitCode: 1,
72
+ });
73
+ }
74
+
55
75
  function paint(tone, fallback) {
56
76
  return typeof color[tone] === 'function' ? color[tone] : fallback;
57
77
  }
@@ -127,25 +127,3 @@ export async function withProjectLock(cwd, fn, options = {}) {
127
127
  releaseLock(lockDir);
128
128
  }
129
129
  }
130
-
131
- // Synchronous single-attempt variant for sync-only call sites (domain
132
- // provider injection). Never waits: takes over stale locks, otherwise
133
- // throws FILE_LOCK_TIMEOUT immediately.
134
- export function withProjectLockSync(cwd, fn, options = {}) {
135
- const { scope = 'project', staleMs = DEFAULT_LOCK_STALE_MS } = options || {};
136
- const lockDir = lockDirFor(cwd, scope);
137
- fs.mkdirSync(path.dirname(lockDir), { recursive: true });
138
- if (!tryAcquire(lockDir)) {
139
- if (lockAgeMs(lockDir) > staleMs) {
140
- releaseLock(lockDir);
141
- if (!tryAcquire(lockDir)) throw timeoutError(scope, 0);
142
- } else {
143
- throw timeoutError(scope, 0);
144
- }
145
- }
146
- try {
147
- return fn();
148
- } finally {
149
- releaseLock(lockDir);
150
- }
151
- }
package/src/utils/hcl.js CHANGED
@@ -92,11 +92,14 @@ function escapeRegExp(raw) {
92
92
 
93
93
  // Locates `resource "<type>" "<name>" { ... }`. Returns
94
94
  // `{ headerIdx, openIdx, closeIdx }` or null when the resource or its
95
- // braces cannot be found.
95
+ // braces cannot be found. The header anchors to a line start (resource
96
+ // blocks are top-level), so a `#` comment quoting the header never
97
+ // false-positives.
96
98
  export function findResourceBlock(content, resourceType, resourceName) {
97
99
  const text = String(content ?? '');
98
100
  const pattern = new RegExp(
99
- `resource\\s+"${escapeRegExp(resourceType)}"\\s+"${escapeRegExp(resourceName)}"`
101
+ `^\\s*resource\\s+"${escapeRegExp(resourceType)}"\\s+"${escapeRegExp(resourceName)}"`,
102
+ 'm'
100
103
  );
101
104
  const match = pattern.exec(text);
102
105
  if (!match) return null;
@@ -108,6 +111,28 @@ export function findResourceBlock(content, resourceType, resourceName) {
108
111
  return { headerIdx, openIdx, closeIdx: bounds.closeIdx };
109
112
  }
110
113
 
114
+ // Removes the `resource "type" "name" { ... }` block plus comment lines
115
+ // directly attached above it (walking up over blanks, stopping at the
116
+ // first line of code). Returns the content unchanged when absent. Callers
117
+ // should normalize blank lines afterwards.
118
+ export function removeResourceBlock(content, resourceType, resourceName) {
119
+ const text = String(content ?? '');
120
+ const found = findResourceBlock(text, resourceType, resourceName);
121
+ if (!found) return text;
122
+ const lines = text.slice(0, found.headerIdx).split('\n');
123
+ let firstKept = lines.length;
124
+ for (let i = lines.length - 1; i >= 0; i--) {
125
+ const line = lines[i];
126
+ if (line.trim() === '' || /^\s*#/.test(line)) {
127
+ firstKept = i;
128
+ continue;
129
+ }
130
+ break;
131
+ }
132
+ const start = firstKept === 0 ? 0 : lines.slice(0, firstKept).join('\n').length + 1;
133
+ return text.slice(0, start) + text.slice(found.closeIdx + 1);
134
+ }
135
+
111
136
  // Locates a nested `blockName { ... }` (with optional quoted labels)
112
137
  // at the top level of a block slice. Returns
113
138
  // `{ startIdx, openIdx, closeIdx }` (startIdx is the keyword) or null.
@@ -0,0 +1,40 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ // Token offline scaffolds (`init --offline`) leave where the AWS account
5
+ // ID belongs: the bucket name in terraform/backend.tf plus every
6
+ // role-to-assume ARN in .github/workflows/*.yml. Detection only —
7
+ // rewriting lives in apply's reconcile pre-step.
8
+ export const PLACEHOLDER_ACCOUNT_ID = 'YOUR_AWS_ACCOUNT_ID';
9
+
10
+ // Repo-relative paths still containing the placeholder (`[]` when the
11
+ // tree is reconciled). Missing files are skipped, never an error; the
12
+ // workflows directory is globbed (not filename-hardcoded) so future
13
+ // workflows are covered.
14
+ export function findUnreconciledFiles(targetDir) {
15
+ const found = [];
16
+ const check = (repoPath) => {
17
+ let content;
18
+ try {
19
+ content = fs.readFileSync(path.join(targetDir, repoPath), 'utf8');
20
+ } catch {
21
+ return;
22
+ }
23
+ if (content.includes(PLACEHOLDER_ACCOUNT_ID)) found.push(repoPath);
24
+ };
25
+ check(path.join('terraform', 'backend.tf'));
26
+ let entries = [];
27
+ try {
28
+ entries = fs.readdirSync(path.join(targetDir, '.github', 'workflows'));
29
+ } catch {
30
+ entries = [];
31
+ }
32
+ for (const entry of entries.filter((name) => /\.ya?ml$/.test(name)).sort()) {
33
+ check(path.join('.github', 'workflows', entry));
34
+ }
35
+ return found.sort();
36
+ }
37
+
38
+ export function isValidAccountId(value) {
39
+ return typeof value === 'string' && /^\d{12}$/.test(value);
40
+ }
@@ -60,9 +60,10 @@ jobs:
60
60
  terraform workspace select -or-create ${{ env.WORKSPACE }}
61
61
  terraform apply -auto-approve
62
62
 
63
- # Extract the ALB URL to post to GitHub
64
- ALB_URL=$(terraform output -raw alb_direct_url)
65
- echo "PREVIEW_URL=$ALB_URL" >> $GITHUB_ENV
63
+ # Extract the CloudFront URL to post to GitHub (the ALB origin
64
+ # accepts CloudFront edges only — its direct URL is not browsable)
65
+ PREVIEW_URL=$(terraform output -raw cloudfront_url)
66
+ echo "PREVIEW_URL=$PREVIEW_URL" >> $GITHUB_ENV
66
67
 
67
68
  - name: Comment PR
68
69
  uses: actions/github-script@v7
@@ -41,8 +41,11 @@ jobs:
41
41
  run: |
42
42
  terraform init -input=false
43
43
  # PRs that never got a preview (early failure, pre-previews PR)
44
- # have no workspace — exit green instead of failing the run.
45
- if ! terraform workspace list 2>/dev/null | sed 's/^[* ]*//' | grep -qx "${{ env.WORKSPACE }}"; then
44
+ # have no workspace — exit green instead of failing the run. But
45
+ # a failed listing (backend outage, dead creds) must stay red:
46
+ # matching against empty output would leak the stack silently.
47
+ WORKSPACES=$(terraform workspace list 2>&1) || { echo "$WORKSPACES"; exit 1; }
48
+ if ! printf '%s\n' "$WORKSPACES" | sed 's/^[* ]*//' | grep -qx "${{ env.WORKSPACE }}"; then
46
49
  echo "No preview workspace ${{ env.WORKSPACE }} — nothing to tear down."
47
50
  exit 0
48
51
  fi