@go-to-k/cdkd 0.235.0 → 0.236.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.
@@ -0,0 +1,828 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createHash } from "node:crypto";
3
+
4
+ //#region src/provisioning/resource-name.ts
5
+ /**
6
+ * Per-async-context stack name. Resource-name generation reads this so that
7
+ * concurrent deploys (`cdkd deploy --all` runs stacks in parallel up to
8
+ * `--stack-concurrency`) don't fight over a single shared variable.
9
+ *
10
+ * History: this was `let currentStackName: string | undefined` until
11
+ * 2026-05-01. Two parallel `deploy()` calls would each call
12
+ * `setCurrentStackName(...)` and the second would overwrite the first;
13
+ * any IAM Role / SQS Queue / etc. created by the first stack while the
14
+ * second was active would get the second stack's prefix in its physical
15
+ * name, then the second stack's own create attempt for the same logical
16
+ * id would collide ("Role with name X already exists"). Switching to
17
+ * `AsyncLocalStorage` scopes the value to each deploy's async chain.
18
+ */
19
+ const stackNameStore = new AsyncLocalStorage();
20
+ function withStackName(stackName, fn) {
21
+ return stackNameStore.run(stackName, fn);
22
+ }
23
+ /**
24
+ * Read the current async context's stack name, if any.
25
+ *
26
+ * Returns `undefined` outside any `withStackName` / `setCurrentStackName`
27
+ * scope. Used by the live renderer to scope per-stack in-flight task
28
+ * entries so concurrent deploys don't clobber each other's tasks (same
29
+ * `logicalId` in two stacks would collide on the singleton renderer's
30
+ * task Map without this).
31
+ */
32
+ function getCurrentStackName() {
33
+ return stackNameStore.getStore();
34
+ }
35
+ /**
36
+ * Per-async-context "skip the stack-name prefix on user-supplied physical
37
+ * names" flag. Read by `generateResourceName` when its caller passes
38
+ * `userSupplied: true`; auto-generated-name paths
39
+ * (`generateResourceName(logicalId, ...)`) ignore this flag.
40
+ *
41
+ * Scoped via AsyncLocalStorage so that `--stack-concurrency > 1` runs
42
+ * cannot cross-contaminate — each deploy's body is wrapped in its own
43
+ * `withSkipPrefix(...)` scope (the deploy CLI plumbs the resolved
44
+ * `--no-prefix-user-supplied-names` value through here). Default
45
+ * `false` preserves pre-PR behavior when the flag is not set.
46
+ */
47
+ const skipPrefixStore = new AsyncLocalStorage();
48
+ function withSkipPrefix(skip, fn) {
49
+ return skipPrefixStore.run(skip, fn);
50
+ }
51
+ /**
52
+ * Read the current async context's skip-prefix flag. Defaults to
53
+ * `false` when no `withSkipPrefix` scope is active.
54
+ *
55
+ * Public for unit tests; `generateResourceName` consumes this
56
+ * internally.
57
+ */
58
+ function getCurrentSkipPrefix() {
59
+ return skipPrefixStore.getStore() ?? false;
60
+ }
61
+ /**
62
+ * Resource types whose pre-PR #297 code path ran user-supplied
63
+ * physical names through `generateResourceName` (= got the stack-name
64
+ * prefix). These are the only types affected by
65
+ * `--no-prefix-user-supplied-names`; flipping the flag against an
66
+ * existing stack proposes REPLACEMENT on every state resource of
67
+ * one of these types whose `physicalId` is still prefixed.
68
+ *
69
+ * Pattern A providers (Lambda, S3, SNS, SQS, DynamoDB, Logs LogGroup,
70
+ * Events Rule, etc.) historically short-circuited user-supplied names
71
+ * **out** of `generateResourceName` entirely — those types never got
72
+ * the prefix regardless of the flag, so they are NOT included here.
73
+ *
74
+ * Used by the deploy-time pre-flight migration check in
75
+ * `src/cli/commands/prefix-migration-check.ts`. Keep in sync with the
76
+ * Pattern B provider call sites that consume
77
+ * `generateResourceNameWithFallback(...)`.
78
+ */
79
+ const PATTERN_B_RESOURCE_TYPES = [
80
+ "AWS::IAM::Role",
81
+ "AWS::IAM::User",
82
+ "AWS::IAM::Group",
83
+ "AWS::IAM::InstanceProfile",
84
+ "AWS::IAM::ManagedPolicy",
85
+ "AWS::ElasticLoadBalancingV2::LoadBalancer",
86
+ "AWS::ElasticLoadBalancingV2::TargetGroup"
87
+ ];
88
+ /**
89
+ * For each Pattern B resource type, the CFn template `Properties` field
90
+ * the user sets to supply a physical name (`new iam.Role(this, 'X',
91
+ * { roleName: 'my-role' })` → `Properties.RoleName: 'my-role'`).
92
+ *
93
+ * Used by the prefix-migration check to distinguish user-supplied
94
+ * physical names (which the v0.94.0 default flip would actually
95
+ * REPLACE on next deploy) from auto-generated logical-id-fallback
96
+ * names (which keep the prefix in BOTH old and new default — no
97
+ * REPLACE pending). Without this discriminator, the migration
98
+ * check naively flags every prefix-style physicalId regardless of
99
+ * its origin, surfacing a false-positive WARNING on auto-generated
100
+ * names that won't actually be touched.
101
+ *
102
+ * Keep in sync with `PATTERN_B_RESOURCE_TYPES` and with each
103
+ * provider's `Properties[<NameField>]` lookup in
104
+ * `src/provisioning/providers/`.
105
+ */
106
+ const PATTERN_B_NAME_PROPERTIES = {
107
+ "AWS::IAM::Role": "RoleName",
108
+ "AWS::IAM::User": "UserName",
109
+ "AWS::IAM::Group": "GroupName",
110
+ "AWS::IAM::InstanceProfile": "InstanceProfileName",
111
+ "AWS::IAM::ManagedPolicy": "ManagedPolicyName",
112
+ "AWS::ElasticLoadBalancingV2::LoadBalancer": "Name",
113
+ "AWS::ElasticLoadBalancingV2::TargetGroup": "Name"
114
+ };
115
+ /**
116
+ * For each Pattern B resource type, the `generateResourceName` options each
117
+ * provider passes at its name call site (maxLength + any lowercase /
118
+ * allowedPattern). Keep in sync with the provider call sites
119
+ * (`generateResourceNameWithFallback(...)` in
120
+ * `src/provisioning/providers/`).
121
+ *
122
+ * Used by the prefix-migration check to recompute BOTH the legacy
123
+ * (prefixed) and the post-v0.94 (unprefixed) physical name for a recorded
124
+ * user-supplied name through the SAME sanitize / truncate pipeline the
125
+ * provider used — so a name that needed sanitization (`my_role` ->
126
+ * `my-role`) or hash-suffix truncation (> maxLength) is compared exactly,
127
+ * not via a naive prefix concat / strip.
128
+ */
129
+ const PATTERN_B_NAME_OPTIONS = {
130
+ "AWS::IAM::Role": { maxLength: 64 },
131
+ "AWS::IAM::User": { maxLength: 64 },
132
+ "AWS::IAM::Group": { maxLength: 128 },
133
+ "AWS::IAM::InstanceProfile": { maxLength: 128 },
134
+ "AWS::IAM::ManagedPolicy": { maxLength: 128 },
135
+ "AWS::ElasticLoadBalancingV2::LoadBalancer": { maxLength: 32 },
136
+ "AWS::ElasticLoadBalancingV2::TargetGroup": { maxLength: 32 }
137
+ };
138
+ /**
139
+ * Generate a unique resource name from the logical ID.
140
+ *
141
+ * Generates names in CloudFormation-compatible format:
142
+ * `{StackName}-{LogicalId}-{Hash}` (truncated to maxLength).
143
+ *
144
+ * @param name The raw name (from properties or logicalId fallback)
145
+ * @param options Length and character constraints
146
+ * @returns A sanitized, truncated name that fits the constraints
147
+ */
148
+ function generateResourceName(name, options) {
149
+ const { maxLength, lowercase = false, allowedPattern = /[^a-zA-Z0-9-]/g, userSupplied = false } = options;
150
+ const currentStackName = stackNameStore.getStore();
151
+ const fullName = currentStackName && !(userSupplied && getCurrentSkipPrefix()) ? `${currentStackName}-${name}` : name;
152
+ let sanitized = lowercase ? fullName.toLowerCase() : fullName;
153
+ sanitized = sanitized.replace(allowedPattern, "-");
154
+ sanitized = sanitized.replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "");
155
+ if (sanitized.length <= maxLength) return sanitized;
156
+ const hash = createHash("sha256").update(fullName).digest("hex").substring(0, 8);
157
+ const maxPrefixLength = maxLength - hash.length - 1;
158
+ return `${sanitized.substring(0, maxPrefixLength).replace(/-+$/, "")}-${hash}`;
159
+ }
160
+ /**
161
+ * Generate a resource name from a user-declared physical name OR
162
+ * fall back to the logical id.
163
+ *
164
+ * Wraps {@link generateResourceName} to express the Pattern B call-site
165
+ * shape (`generateResourceName((properties['Name'] as string | undefined)
166
+ * || logicalId, opts)`) as a single typed helper. The user-supplied
167
+ * branch passes `userSupplied: true`, which makes the per-deploy
168
+ * `withSkipPrefix(true)` flag drop the stack-name prefix on that name.
169
+ * The fallback (logical-id) branch is `userSupplied: false` and keeps
170
+ * the prefix regardless of the flag — auto-generated names rely on
171
+ * the prefix for cross-stack uniqueness.
172
+ *
173
+ * Use at every Pattern B provider call site (currently IAM Role, IAM
174
+ * User, IAM Group, IAM InstanceProfile, ELBv2 LoadBalancer, ELBv2
175
+ * TargetGroup) so the `--no-prefix-user-supplied-names` flag controls
176
+ * those types consistently. Pattern A providers (Lambda, S3, SNS,
177
+ * SQS, DynamoDB, etc.) do NOT need this helper — they already
178
+ * short-circuit the user-supplied name out of the
179
+ * `generateResourceName` call entirely, so the prefix is never
180
+ * applied to user-supplied names regardless of the flag.
181
+ */
182
+ function generateResourceNameWithFallback(userSuppliedName, logicalId, options) {
183
+ if (userSuppliedName !== void 0 && userSuppliedName !== "") return generateResourceName(userSuppliedName, {
184
+ ...options,
185
+ userSupplied: true
186
+ });
187
+ return generateResourceName(logicalId, {
188
+ ...options,
189
+ userSupplied: false
190
+ });
191
+ }
192
+ /**
193
+ * Default name generation rules for CC API fallback.
194
+ *
195
+ * When an SDK provider falls back to CC API, the resource may need a
196
+ * default name that the SDK provider would have generated. This map
197
+ * defines the name property and generation options for each resource type.
198
+ *
199
+ * Format: resourceType → { nameProperty, options, postProcess? }
200
+ */
201
+ const FALLBACK_NAME_RULES = {
202
+ "AWS::S3::Bucket": {
203
+ nameProperty: "BucketName",
204
+ options: {
205
+ maxLength: 63,
206
+ lowercase: true
207
+ }
208
+ },
209
+ "AWS::SQS::Queue": {
210
+ nameProperty: "QueueName",
211
+ options: { maxLength: 80 }
212
+ },
213
+ "AWS::SNS::Topic": {
214
+ nameProperty: "TopicName",
215
+ options: { maxLength: 256 }
216
+ },
217
+ "AWS::Lambda::Function": {
218
+ nameProperty: "FunctionName",
219
+ options: { maxLength: 64 }
220
+ },
221
+ "AWS::Lambda::LayerVersion": {
222
+ nameProperty: "LayerName",
223
+ options: { maxLength: 64 }
224
+ },
225
+ "AWS::IAM::Role": {
226
+ nameProperty: "RoleName",
227
+ options: { maxLength: 64 }
228
+ },
229
+ "AWS::IAM::Policy": {
230
+ nameProperty: "PolicyName",
231
+ options: { maxLength: 64 }
232
+ },
233
+ "AWS::IAM::ManagedPolicy": {
234
+ nameProperty: "ManagedPolicyName",
235
+ options: { maxLength: 128 }
236
+ },
237
+ "AWS::IAM::User": {
238
+ nameProperty: "UserName",
239
+ options: { maxLength: 64 }
240
+ },
241
+ "AWS::IAM::Group": {
242
+ nameProperty: "GroupName",
243
+ options: { maxLength: 128 }
244
+ },
245
+ "AWS::IAM::InstanceProfile": {
246
+ nameProperty: "InstanceProfileName",
247
+ options: { maxLength: 128 }
248
+ },
249
+ "AWS::DynamoDB::Table": {
250
+ nameProperty: "TableName",
251
+ options: { maxLength: 255 }
252
+ },
253
+ "AWS::ECR::Repository": {
254
+ nameProperty: "RepositoryName",
255
+ options: {
256
+ maxLength: 256,
257
+ lowercase: true
258
+ }
259
+ },
260
+ "AWS::ECS::Cluster": {
261
+ nameProperty: "ClusterName",
262
+ options: { maxLength: 255 }
263
+ },
264
+ "AWS::ECS::Service": {
265
+ nameProperty: "ServiceName",
266
+ options: { maxLength: 255 }
267
+ },
268
+ "AWS::Logs::LogGroup": {
269
+ nameProperty: "LogGroupName",
270
+ options: { maxLength: 512 }
271
+ },
272
+ "AWS::CloudWatch::Alarm": {
273
+ nameProperty: "AlarmName",
274
+ options: { maxLength: 256 }
275
+ },
276
+ "AWS::Events::Rule": {
277
+ nameProperty: "Name",
278
+ options: { maxLength: 64 }
279
+ },
280
+ "AWS::Events::EventBus": {
281
+ nameProperty: "Name",
282
+ options: { maxLength: 256 }
283
+ },
284
+ "AWS::Kinesis::Stream": {
285
+ nameProperty: "Name",
286
+ options: { maxLength: 128 }
287
+ },
288
+ "AWS::StepFunctions::StateMachine": {
289
+ nameProperty: "StateMachineName",
290
+ options: { maxLength: 80 }
291
+ },
292
+ "AWS::SecretsManager::Secret": {
293
+ nameProperty: "Name",
294
+ options: {
295
+ maxLength: 512,
296
+ allowedPattern: /[^a-zA-Z0-9-/_]/g
297
+ }
298
+ },
299
+ "AWS::SSM::Parameter": {
300
+ nameProperty: "Name",
301
+ options: { maxLength: 2048 }
302
+ },
303
+ "AWS::Cognito::UserPool": {
304
+ nameProperty: "UserPoolName",
305
+ options: { maxLength: 128 }
306
+ },
307
+ "AWS::ElastiCache::SubnetGroup": {
308
+ nameProperty: "CacheSubnetGroupName",
309
+ options: {
310
+ maxLength: 255,
311
+ lowercase: true
312
+ }
313
+ },
314
+ "AWS::ElastiCache::CacheCluster": {
315
+ nameProperty: "ClusterName",
316
+ options: {
317
+ maxLength: 40,
318
+ lowercase: true
319
+ }
320
+ },
321
+ "AWS::RDS::DBSubnetGroup": {
322
+ nameProperty: "DBSubnetGroupName",
323
+ options: {
324
+ maxLength: 255,
325
+ lowercase: true
326
+ }
327
+ },
328
+ "AWS::RDS::DBCluster": {
329
+ nameProperty: "DBClusterIdentifier",
330
+ options: {
331
+ maxLength: 63,
332
+ lowercase: true
333
+ }
334
+ },
335
+ "AWS::RDS::DBInstance": {
336
+ nameProperty: "DBInstanceIdentifier",
337
+ options: {
338
+ maxLength: 63,
339
+ lowercase: true
340
+ }
341
+ },
342
+ "AWS::DocDB::DBSubnetGroup": {
343
+ nameProperty: "DBSubnetGroupName",
344
+ options: {
345
+ maxLength: 255,
346
+ lowercase: true
347
+ }
348
+ },
349
+ "AWS::DocDB::DBCluster": {
350
+ nameProperty: "DBClusterIdentifier",
351
+ options: {
352
+ maxLength: 63,
353
+ lowercase: true
354
+ }
355
+ },
356
+ "AWS::DocDB::DBInstance": {
357
+ nameProperty: "DBInstanceIdentifier",
358
+ options: {
359
+ maxLength: 63,
360
+ lowercase: true
361
+ }
362
+ },
363
+ "AWS::Neptune::DBSubnetGroup": {
364
+ nameProperty: "DBSubnetGroupName",
365
+ options: {
366
+ maxLength: 255,
367
+ lowercase: true
368
+ }
369
+ },
370
+ "AWS::Neptune::DBCluster": {
371
+ nameProperty: "DBClusterIdentifier",
372
+ options: {
373
+ maxLength: 63,
374
+ lowercase: true
375
+ }
376
+ },
377
+ "AWS::Neptune::DBInstance": {
378
+ nameProperty: "DBInstanceIdentifier",
379
+ options: {
380
+ maxLength: 63,
381
+ lowercase: true
382
+ }
383
+ },
384
+ "AWS::ElasticLoadBalancingV2::LoadBalancer": {
385
+ nameProperty: "Name",
386
+ options: { maxLength: 32 }
387
+ },
388
+ "AWS::ElasticLoadBalancingV2::TargetGroup": {
389
+ nameProperty: "Name",
390
+ options: { maxLength: 32 }
391
+ },
392
+ "AWS::WAFv2::WebACL": {
393
+ nameProperty: "Name",
394
+ options: { maxLength: 128 }
395
+ },
396
+ "AWS::CodeBuild::Project": {
397
+ nameProperty: "Name",
398
+ options: { maxLength: 255 }
399
+ },
400
+ "AWS::S3Express::DirectoryBucket": {
401
+ nameProperty: "BucketName",
402
+ options: {
403
+ maxLength: 63,
404
+ lowercase: true
405
+ }
406
+ }
407
+ };
408
+ /**
409
+ * Apply default name generation for CC API fallback.
410
+ *
411
+ * When a resource doesn't have an explicit name property set,
412
+ * generates the same default name that the SDK provider would have created.
413
+ * This ensures consistent naming regardless of whether SDK or CC API handles the resource.
414
+ *
415
+ * @param logicalId Logical ID from the template
416
+ * @param resourceType CloudFormation resource type
417
+ * @param properties Resource properties (will not be mutated)
418
+ * @returns Properties with default name applied if needed, or original properties if no rule exists
419
+ */
420
+ function applyDefaultNameForFallback(logicalId, resourceType, properties) {
421
+ const rule = FALLBACK_NAME_RULES[resourceType];
422
+ if (!rule) return properties;
423
+ if (properties[rule.nameProperty]) return properties;
424
+ const generatedName = generateResourceName(logicalId, rule.options);
425
+ return {
426
+ ...properties,
427
+ [rule.nameProperty]: generatedName
428
+ };
429
+ }
430
+
431
+ //#endregion
432
+ //#region src/utils/live-renderer.ts
433
+ /**
434
+ * Live multi-line progress renderer for the bottom of the terminal.
435
+ *
436
+ * Maintains a "live area" listing in-flight tasks (Creating MyBucket...),
437
+ * redrawn on a spinner timer. Other log output is routed through
438
+ * {@link LiveRenderer.printAbove} so it appears above the live area without
439
+ * disturbing the currently-displayed in-flight tasks.
440
+ *
441
+ * Design notes:
442
+ * - Multiple resources can be in flight concurrently (cdkd uses parallel DAG
443
+ * dispatch), so a single in-place line overwrite is not enough — each
444
+ * in-flight resource is its own line in the live area.
445
+ * - On non-TTY (CI/log-collection), the renderer stays inactive and
446
+ * {@link LiveRenderer.printAbove} falls through to a direct write, so output
447
+ * matches the previous append-only behavior.
448
+ * - In verbose mode (debug level) the caller should not start the renderer:
449
+ * debug logs would interleave too aggressively with the live area.
450
+ */
451
+ const SPINNER_FRAMES = [
452
+ "⠋",
453
+ "⠙",
454
+ "⠹",
455
+ "⠸",
456
+ "⠼",
457
+ "⠴",
458
+ "⠦",
459
+ "⠧",
460
+ "⠇",
461
+ "⠏"
462
+ ];
463
+ const FRAME_INTERVAL_MS = 80;
464
+ const ESC = "\x1B[";
465
+ /**
466
+ * Scope a task `id` to its calling stack so two stacks running in
467
+ * parallel — `cdkd deploy --all` with `--stack-concurrency > 1` — don't
468
+ * collide on the same `logicalId` in the renderer's task Map. Without
469
+ * this, stack B's `addTask('MyQueue', ...)` would overwrite stack A's
470
+ * entry, and stack A's later `removeTask('MyQueue')` would erase
471
+ * stack B's.
472
+ */
473
+ function scopedKey(id, stackName) {
474
+ return stackName ? `${stackName}:${id}` : id;
475
+ }
476
+ var LiveRenderer = class {
477
+ tasks = /* @__PURE__ */ new Map();
478
+ active = false;
479
+ spinnerIndex = 0;
480
+ interval = null;
481
+ linesDrawn = 0;
482
+ cursorHidden = false;
483
+ exitListener = null;
484
+ stream;
485
+ constructor(stream = process.stdout) {
486
+ this.stream = stream;
487
+ }
488
+ isActive() {
489
+ return this.active;
490
+ }
491
+ /**
492
+ * Enable the live renderer. No-op if stdout is not a TTY or if
493
+ * `CDKD_NO_LIVE=1`. Returns true if successfully enabled.
494
+ */
495
+ start() {
496
+ if (this.active) return true;
497
+ if (!this.stream.isTTY) return false;
498
+ if (process.env["CDKD_NO_LIVE"] === "1") return false;
499
+ this.active = true;
500
+ this.hideCursor();
501
+ if (!this.exitListener) {
502
+ this.exitListener = () => this.showCursor();
503
+ process.on("exit", this.exitListener);
504
+ }
505
+ this.interval = setInterval(() => this.draw(), FRAME_INTERVAL_MS);
506
+ if (typeof this.interval.unref === "function") this.interval.unref();
507
+ return true;
508
+ }
509
+ stop() {
510
+ if (!this.active) return;
511
+ if (this.interval) {
512
+ clearInterval(this.interval);
513
+ this.interval = null;
514
+ }
515
+ this.clear();
516
+ this.showCursor();
517
+ if (this.exitListener) {
518
+ process.removeListener("exit", this.exitListener);
519
+ this.exitListener = null;
520
+ }
521
+ this.tasks.clear();
522
+ this.active = false;
523
+ }
524
+ addTask(id, label) {
525
+ const stackName = getCurrentStackName();
526
+ this.tasks.set(scopedKey(id, stackName), {
527
+ label,
528
+ startedAt: Date.now(),
529
+ stackName
530
+ });
531
+ if (this.active) this.draw();
532
+ }
533
+ removeTask(id) {
534
+ const stackName = getCurrentStackName();
535
+ if (!this.tasks.delete(scopedKey(id, stackName))) return;
536
+ if (this.active) this.draw();
537
+ }
538
+ /**
539
+ * Replace the label of a previously-added task in place. No-op if the
540
+ * task is not currently tracked (e.g. it already finished). Used by the
541
+ * per-resource deadline wrapper to surface a "[taking longer than
542
+ * expected, Nm+]" suffix without disturbing the elapsed-time counter
543
+ * the renderer tracks via `startedAt`.
544
+ */
545
+ updateTaskLabel(id, label) {
546
+ const stackName = getCurrentStackName();
547
+ const task = this.tasks.get(scopedKey(id, stackName));
548
+ if (!task) return;
549
+ task.label = label;
550
+ if (this.active) this.draw();
551
+ }
552
+ /**
553
+ * Print content above the live area. Clears the live area, runs the writer,
554
+ * then redraws the live area. When the renderer is inactive, the writer
555
+ * runs directly so callers can use this unconditionally.
556
+ */
557
+ printAbove(write) {
558
+ if (!this.active) {
559
+ write();
560
+ return;
561
+ }
562
+ this.clear();
563
+ write();
564
+ this.draw();
565
+ }
566
+ clear() {
567
+ if (this.linesDrawn === 0) return;
568
+ this.stream.write("\r");
569
+ for (let i = 0; i < this.linesDrawn; i++) this.stream.write(`${ESC}1A${ESC}2K`);
570
+ this.linesDrawn = 0;
571
+ }
572
+ draw() {
573
+ if (!this.active) return;
574
+ this.clear();
575
+ if (this.tasks.size === 0) return;
576
+ const frame = SPINNER_FRAMES[this.spinnerIndex % SPINNER_FRAMES.length];
577
+ this.spinnerIndex++;
578
+ const distinctStacks = /* @__PURE__ */ new Set();
579
+ for (const task of this.tasks.values()) distinctStacks.add(task.stackName);
580
+ const showStackPrefix = distinctStacks.size > 1;
581
+ const cols = this.stream.columns ?? 80;
582
+ const lines = [];
583
+ for (const task of this.tasks.values()) {
584
+ const elapsed = ((Date.now() - task.startedAt) / 1e3).toFixed(1);
585
+ const raw = ` ${frame} ${showStackPrefix && task.stackName ? `[${task.stackName}] ` : ""}${task.label} (${elapsed}s)`;
586
+ lines.push(this.truncate(raw, cols));
587
+ }
588
+ this.stream.write(lines.join("\n") + "\n");
589
+ this.linesDrawn = lines.length;
590
+ }
591
+ truncate(s, maxLen) {
592
+ if (s.length <= maxLen) return s;
593
+ if (maxLen <= 1) return "…";
594
+ return s.substring(0, maxLen - 1) + "…";
595
+ }
596
+ hideCursor() {
597
+ if (this.cursorHidden) return;
598
+ this.stream.write(`${ESC}?25l`);
599
+ this.cursorHidden = true;
600
+ }
601
+ showCursor() {
602
+ if (!this.cursorHidden) return;
603
+ this.stream.write(`${ESC}?25h`);
604
+ this.cursorHidden = false;
605
+ }
606
+ };
607
+ let globalRenderer = null;
608
+ function getLiveRenderer() {
609
+ if (!globalRenderer) globalRenderer = new LiveRenderer();
610
+ return globalRenderer;
611
+ }
612
+
613
+ //#endregion
614
+ //#region src/utils/stack-context.ts
615
+ const outputBufferStore = new AsyncLocalStorage();
616
+ /**
617
+ * Run `fn` with a fresh log buffer scoped to its async chain. Any
618
+ * `logger.info / debug / warn / error` calls inside `fn` (and any
619
+ * `await`s) push into the buffer instead of writing to stdout/stderr.
620
+ * Returns the buffered lines (and either `result` or `error`) so the
621
+ * caller can flush them in one block.
622
+ */
623
+ async function runStackBuffered(fn) {
624
+ const buffer = { lines: [] };
625
+ return outputBufferStore.run(buffer, async () => {
626
+ try {
627
+ return {
628
+ ok: true,
629
+ result: await fn(),
630
+ lines: buffer.lines
631
+ };
632
+ } catch (error) {
633
+ return {
634
+ ok: false,
635
+ error,
636
+ lines: buffer.lines
637
+ };
638
+ }
639
+ });
640
+ }
641
+ /**
642
+ * Get the current async context's stack output buffer, or `undefined`
643
+ * if no `runStackBuffered` is active. The logger consults this on every
644
+ * call: present → push to buffer; absent → fall through to live
645
+ * renderer / console.
646
+ */
647
+ function getCurrentStackOutputBuffer() {
648
+ return outputBufferStore.getStore();
649
+ }
650
+
651
+ //#endregion
652
+ //#region src/utils/logger.ts
653
+ /**
654
+ * ANSI color codes
655
+ *
656
+ * Kept internal — `ConsoleLogger.formatMessage` references these for the
657
+ * verbose/compact mode level prefixes. For inline color wrapping in
658
+ * production code, import from `./colors.js` instead (which lives in a
659
+ * separate module so unit tests that mock `logger.ts` don't strip color
660
+ * helpers as a side effect).
661
+ */
662
+ const colors = {
663
+ reset: "\x1B[0m",
664
+ bright: "\x1B[1m",
665
+ dim: "\x1B[2m",
666
+ red: "\x1B[31m",
667
+ green: "\x1B[32m",
668
+ yellow: "\x1B[33m",
669
+ blue: "\x1B[34m",
670
+ cyan: "\x1B[36m",
671
+ gray: "\x1B[90m"
672
+ };
673
+ /**
674
+ * Format timestamp
675
+ */
676
+ function formatTimestamp() {
677
+ return (/* @__PURE__ */ new Date()).toISOString();
678
+ }
679
+ /**
680
+ * Console logger implementation
681
+ *
682
+ * Supports two output modes:
683
+ * - verbose (debug level): timestamps, module prefixes, all details
684
+ * - compact (info level): clean output without timestamps or prefixes
685
+ */
686
+ var ConsoleLogger = class {
687
+ level;
688
+ useColors;
689
+ constructor(level = "info", useColors = true) {
690
+ this.level = level;
691
+ this.useColors = useColors;
692
+ }
693
+ shouldLog(level) {
694
+ const levels = [
695
+ "debug",
696
+ "info",
697
+ "warn",
698
+ "error"
699
+ ];
700
+ const currentLevelIndex = levels.indexOf(this.level);
701
+ return levels.indexOf(level) >= currentLevelIndex;
702
+ }
703
+ formatMessage(level, message, ...args) {
704
+ const formattedArgs = args.length > 0 ? " " + args.map((a) => JSON.stringify(a)).join(" ") : "";
705
+ if (this.level === "debug") {
706
+ const timestamp = formatTimestamp();
707
+ const levelStr = level.toUpperCase().padEnd(5);
708
+ if (this.useColors) {
709
+ const levelColor = {
710
+ debug: colors.gray,
711
+ info: colors.blue,
712
+ warn: colors.yellow,
713
+ error: colors.red
714
+ }[level];
715
+ return `${colors.dim}${timestamp}${colors.reset} ${levelColor}${levelStr}${colors.reset} ${message}${formattedArgs}`;
716
+ }
717
+ return `${timestamp} ${levelStr} ${message}${formattedArgs}`;
718
+ }
719
+ if (this.useColors) {
720
+ if (level === "error") return `${colors.red}${message}${formattedArgs}${colors.reset}`;
721
+ if (level === "warn") return `${colors.yellow}${message}${formattedArgs}${colors.reset}`;
722
+ return `${message}${formattedArgs}`;
723
+ }
724
+ return `${message}${formattedArgs}`;
725
+ }
726
+ /**
727
+ * Route a formatted log line. When a per-stack output buffer is active in
728
+ * the current async context (parallel multi-stack deploy), capture the
729
+ * line into the buffer so it can be flushed as one atomic block when the
730
+ * stack finishes. Otherwise fall through to the live renderer / console
731
+ * as before.
732
+ */
733
+ emit(level, formatted) {
734
+ const buffer = getCurrentStackOutputBuffer();
735
+ if (buffer) {
736
+ buffer.lines.push(formatted);
737
+ return;
738
+ }
739
+ getLiveRenderer().printAbove(() => {
740
+ if (level === "error") console.error(formatted);
741
+ else if (level === "warn") console.warn(formatted);
742
+ else if (level === "info") console.info(formatted);
743
+ else console.debug(formatted);
744
+ });
745
+ }
746
+ debug(message, ...args) {
747
+ if (this.shouldLog("debug")) this.emit("debug", this.formatMessage("debug", message, ...args));
748
+ }
749
+ info(message, ...args) {
750
+ if (this.shouldLog("info")) this.emit("info", this.formatMessage("info", message, ...args));
751
+ }
752
+ warn(message, ...args) {
753
+ if (this.shouldLog("warn")) this.emit("warn", this.formatMessage("warn", message, ...args));
754
+ }
755
+ error(message, ...args) {
756
+ if (this.shouldLog("error")) this.emit("error", this.formatMessage("error", message, ...args));
757
+ }
758
+ /**
759
+ * Set log level
760
+ */
761
+ setLevel(level) {
762
+ this.level = level;
763
+ }
764
+ getLevel() {
765
+ return this.level;
766
+ }
767
+ /**
768
+ * Create a child logger with a prefix
769
+ *
770
+ * In verbose mode, prefix is shown as [Prefix]. In compact mode, prefix is hidden.
771
+ */
772
+ child(prefix) {
773
+ return new ChildLogger(prefix, this.useColors);
774
+ }
775
+ };
776
+ /**
777
+ * Child logger that always syncs level from global logger
778
+ */
779
+ var ChildLogger = class extends ConsoleLogger {
780
+ prefix;
781
+ constructor(prefix, useColors) {
782
+ super("info", useColors);
783
+ this.prefix = prefix;
784
+ }
785
+ syncLevel() {
786
+ if (globalLogger) this.setLevel(globalLogger.getLevel());
787
+ }
788
+ debug(message, ...args) {
789
+ this.syncLevel();
790
+ super.debug(`[${this.prefix}] ${message}`, ...args);
791
+ }
792
+ info(message, ...args) {
793
+ this.syncLevel();
794
+ const msg = this.getLevel() === "debug" ? `[${this.prefix}] ${message}` : message;
795
+ super.info(msg, ...args);
796
+ }
797
+ warn(message, ...args) {
798
+ this.syncLevel();
799
+ const msg = this.getLevel() === "debug" ? `[${this.prefix}] ${message}` : message;
800
+ super.warn(msg, ...args);
801
+ }
802
+ error(message, ...args) {
803
+ this.syncLevel();
804
+ const msg = this.getLevel() === "debug" ? `[${this.prefix}] ${message}` : message;
805
+ super.error(msg, ...args);
806
+ }
807
+ };
808
+ /**
809
+ * Global logger instance
810
+ */
811
+ let globalLogger = null;
812
+ /**
813
+ * Get or create global logger
814
+ */
815
+ function getLogger() {
816
+ if (!globalLogger) globalLogger = new ConsoleLogger();
817
+ return globalLogger;
818
+ }
819
+ /**
820
+ * Set global logger instance
821
+ */
822
+ function setLogger(logger) {
823
+ globalLogger = logger;
824
+ }
825
+
826
+ //#endregion
827
+ export { getLiveRenderer as a, PATTERN_B_RESOURCE_TYPES as c, generateResourceNameWithFallback as d, withSkipPrefix as f, runStackBuffered as i, applyDefaultNameForFallback as l, getLogger as n, PATTERN_B_NAME_OPTIONS as o, withStackName as p, setLogger as r, PATTERN_B_NAME_PROPERTIES as s, ConsoleLogger as t, generateResourceName as u };
828
+ //# sourceMappingURL=logger-BzO-joNR.js.map