@aws-blocks/core 0.2.0 → 0.4.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.
Files changed (178) hide show
  1. package/README.md +13 -0
  2. package/dist/api.d.ts.map +1 -1
  3. package/dist/api.js +32 -0
  4. package/dist/api.test.js +22 -0
  5. package/dist/bb-utils.d.ts +1 -0
  6. package/dist/bb-utils.d.ts.map +1 -1
  7. package/dist/bb-utils.js +3 -0
  8. package/dist/cdk/apigateway-account.d.ts +33 -0
  9. package/dist/cdk/apigateway-account.d.ts.map +1 -0
  10. package/dist/cdk/apigateway-account.js +60 -0
  11. package/dist/cdk/blocks-backend.d.ts +43 -9
  12. package/dist/cdk/blocks-backend.d.ts.map +1 -1
  13. package/dist/cdk/blocks-backend.js +69 -73
  14. package/dist/cdk/blocks-backend.test.js +78 -69
  15. package/dist/cdk/blocks-defaults.d.ts +92 -2
  16. package/dist/cdk/blocks-defaults.d.ts.map +1 -1
  17. package/dist/cdk/blocks-defaults.js +22 -2
  18. package/dist/cdk/blocks-defaults.test.js +21 -2
  19. package/dist/cdk/blocks-stack.test.js +94 -37
  20. package/dist/cdk/compute/compute-registry.d.ts +19 -0
  21. package/dist/cdk/compute/compute-registry.d.ts.map +1 -0
  22. package/dist/cdk/compute/compute-registry.js +38 -0
  23. package/dist/cdk/compute/compute.d.ts +2 -0
  24. package/dist/cdk/compute/compute.d.ts.map +1 -1
  25. package/dist/cdk/compute/compute.js +8 -0
  26. package/dist/cdk/compute/default-compute-factory.d.ts +34 -0
  27. package/dist/cdk/compute/default-compute-factory.d.ts.map +1 -0
  28. package/dist/cdk/compute/default-compute-factory.js +3 -0
  29. package/dist/cdk/config-registry.d.ts +34 -4
  30. package/dist/cdk/config-registry.d.ts.map +1 -1
  31. package/dist/cdk/config-registry.js +83 -25
  32. package/dist/cdk/config-registry.test.d.ts +2 -0
  33. package/dist/cdk/config-registry.test.d.ts.map +1 -0
  34. package/dist/cdk/config-registry.test.js +115 -0
  35. package/dist/cdk/index.d.ts +76 -7
  36. package/dist/cdk/index.d.ts.map +1 -1
  37. package/dist/cdk/index.js +99 -9
  38. package/dist/cdk/internal.d.ts +1 -0
  39. package/dist/cdk/internal.d.ts.map +1 -1
  40. package/dist/client/index.d.ts +1 -1
  41. package/dist/client/index.d.ts.map +1 -1
  42. package/dist/client/index.js +1 -1
  43. package/dist/common/config.d.ts +34 -0
  44. package/dist/common/config.d.ts.map +1 -1
  45. package/dist/common/config.js +45 -3
  46. package/dist/common/config.test.js +19 -0
  47. package/dist/common/index.d.ts +8 -0
  48. package/dist/common/index.d.ts.map +1 -1
  49. package/dist/errors.d.ts +16 -0
  50. package/dist/errors.d.ts.map +1 -1
  51. package/dist/errors.js +20 -0
  52. package/dist/hosting-secrets.d.ts +48 -0
  53. package/dist/hosting-secrets.d.ts.map +1 -0
  54. package/dist/hosting-secrets.js +57 -0
  55. package/dist/hosting-secrets.test.d.ts +2 -0
  56. package/dist/hosting-secrets.test.d.ts.map +1 -0
  57. package/dist/hosting-secrets.test.js +81 -0
  58. package/dist/hosting.d.ts +97 -6
  59. package/dist/hosting.d.ts.map +1 -1
  60. package/dist/hosting.js +91 -23
  61. package/dist/hosting.test.js +182 -10
  62. package/dist/index.cdk.d.ts +13 -12
  63. package/dist/index.cdk.d.ts.map +1 -1
  64. package/dist/index.cdk.js +13 -9
  65. package/dist/index.d.ts +8 -7
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js +9 -5
  68. package/dist/lambda-handler.d.ts +17 -0
  69. package/dist/lambda-handler.d.ts.map +1 -1
  70. package/dist/lambda-handler.js +52 -3
  71. package/dist/lambda-handler.test.js +196 -1
  72. package/dist/pipeline/index.d.ts +24 -2
  73. package/dist/pipeline/index.d.ts.map +1 -1
  74. package/dist/pipeline/index.js +41 -1
  75. package/dist/pipeline.test.d.ts +2 -0
  76. package/dist/pipeline.test.d.ts.map +1 -0
  77. package/dist/pipeline.test.js +47 -0
  78. package/dist/rpc.d.ts +21 -0
  79. package/dist/rpc.d.ts.map +1 -1
  80. package/dist/rpc.js +34 -0
  81. package/dist/rpc.test.js +38 -1
  82. package/dist/scripts/config.d.ts +15 -0
  83. package/dist/scripts/config.d.ts.map +1 -0
  84. package/dist/scripts/config.js +29 -0
  85. package/dist/scripts/deploy.d.ts.map +1 -1
  86. package/dist/scripts/deploy.js +4 -0
  87. package/dist/scripts/dev-server.d.ts +8 -0
  88. package/dist/scripts/dev-server.d.ts.map +1 -1
  89. package/dist/scripts/dev-server.js +31 -0
  90. package/dist/scripts/generate-client.d.ts.map +1 -1
  91. package/dist/scripts/generate-client.js +9 -4
  92. package/dist/scripts/generate-client.test.js +19 -4
  93. package/dist/scripts/index.d.ts +13 -10
  94. package/dist/scripts/index.d.ts.map +1 -1
  95. package/dist/scripts/index.js +11 -8
  96. package/dist/scripts/preflight-credentials.d.ts +30 -0
  97. package/dist/scripts/preflight-credentials.d.ts.map +1 -0
  98. package/dist/scripts/preflight-credentials.js +108 -0
  99. package/dist/scripts/preflight-credentials.test.d.ts +2 -0
  100. package/dist/scripts/preflight-credentials.test.d.ts.map +1 -0
  101. package/dist/scripts/preflight-credentials.test.js +77 -0
  102. package/dist/scripts/sandbox-args.test.d.ts +2 -0
  103. package/dist/scripts/sandbox-args.test.d.ts.map +1 -0
  104. package/dist/scripts/sandbox-args.test.js +77 -0
  105. package/dist/scripts/sandbox-empty-buckets.test.d.ts +2 -0
  106. package/dist/scripts/sandbox-empty-buckets.test.d.ts.map +1 -0
  107. package/dist/scripts/sandbox-empty-buckets.test.js +171 -0
  108. package/dist/scripts/sandbox.d.ts +106 -0
  109. package/dist/scripts/sandbox.d.ts.map +1 -1
  110. package/dist/scripts/sandbox.js +255 -40
  111. package/dist/scripts/secret.d.ts +15 -0
  112. package/dist/scripts/secret.d.ts.map +1 -0
  113. package/dist/scripts/secret.js +29 -0
  114. package/dist/scripts/secret.test.d.ts +2 -0
  115. package/dist/scripts/secret.test.d.ts.map +1 -0
  116. package/dist/scripts/secret.test.js +28 -0
  117. package/dist/scripts/typegen.d.ts +15 -0
  118. package/dist/scripts/typegen.d.ts.map +1 -0
  119. package/dist/scripts/typegen.js +16 -0
  120. package/dist/secret-naming.d.ts +58 -0
  121. package/dist/secret-naming.d.ts.map +1 -0
  122. package/dist/secret-naming.js +67 -0
  123. package/dist/secret-naming.test.d.ts +2 -0
  124. package/dist/secret-naming.test.d.ts.map +1 -0
  125. package/dist/secret-naming.test.js +40 -0
  126. package/dist/version.d.ts +1 -1
  127. package/dist/version.js +1 -1
  128. package/package.json +4 -1
  129. package/src/api.test.ts +25 -0
  130. package/src/api.ts +39 -0
  131. package/src/bb-utils.ts +3 -0
  132. package/src/cdk/apigateway-account.ts +66 -0
  133. package/src/cdk/blocks-backend.test.ts +291 -272
  134. package/src/cdk/blocks-backend.ts +88 -83
  135. package/src/cdk/blocks-defaults.test.ts +25 -2
  136. package/src/cdk/blocks-defaults.ts +94 -2
  137. package/src/cdk/blocks-stack.test.ts +186 -118
  138. package/src/cdk/compute/compute-registry.ts +45 -0
  139. package/src/cdk/compute/compute.ts +10 -0
  140. package/src/cdk/compute/default-compute-factory.ts +38 -0
  141. package/src/cdk/config-registry.test.ts +135 -0
  142. package/src/cdk/config-registry.ts +92 -34
  143. package/src/cdk/index.ts +129 -10
  144. package/src/cdk/internal.ts +1 -0
  145. package/src/client/index.ts +1 -1
  146. package/src/common/config.test.ts +21 -0
  147. package/src/common/config.ts +47 -3
  148. package/src/common/index.ts +8 -0
  149. package/src/errors.ts +21 -0
  150. package/src/hosting-secrets.test.ts +106 -0
  151. package/src/hosting-secrets.ts +106 -0
  152. package/src/hosting.test.ts +272 -63
  153. package/src/hosting.ts +200 -68
  154. package/src/index.cdk.ts +80 -38
  155. package/src/index.ts +35 -16
  156. package/src/lambda-handler.test.ts +215 -1
  157. package/src/lambda-handler.ts +54 -2
  158. package/src/pipeline/index.ts +64 -11
  159. package/src/pipeline.test.ts +55 -0
  160. package/src/rpc.test.ts +44 -1
  161. package/src/rpc.ts +41 -0
  162. package/src/scripts/config.ts +35 -0
  163. package/src/scripts/deploy.ts +5 -0
  164. package/src/scripts/dev-server.ts +40 -0
  165. package/src/scripts/generate-client.test.ts +43 -8
  166. package/src/scripts/generate-client.ts +70 -65
  167. package/src/scripts/index.ts +20 -17
  168. package/src/scripts/preflight-credentials.test.ts +110 -0
  169. package/src/scripts/preflight-credentials.ts +131 -0
  170. package/src/scripts/sandbox-args.test.ts +92 -0
  171. package/src/scripts/sandbox-empty-buckets.test.ts +191 -0
  172. package/src/scripts/sandbox.ts +287 -39
  173. package/src/scripts/secret.test.ts +35 -0
  174. package/src/scripts/secret.ts +35 -0
  175. package/src/scripts/typegen.ts +18 -0
  176. package/src/secret-naming.test.ts +59 -0
  177. package/src/secret-naming.ts +99 -0
  178. package/src/version.ts +1 -1
@@ -1,17 +1,67 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import { test, describe, before } from 'node:test';
5
4
  import assert from 'node:assert';
6
- import { fileURLToPath } from 'node:url';
7
5
  import { dirname, join } from 'node:path';
6
+ import { before, describe, test } from 'node:test';
7
+ import { fileURLToPath } from 'node:url';
8
8
  import * as cdk from 'aws-cdk-lib';
9
+ import * as apigateway from 'aws-cdk-lib/aws-apigateway';
10
+ import * as lambda from 'aws-cdk-lib/aws-lambda-nodejs';
11
+ import type { Construct } from 'constructs';
12
+ import type { ScopeParent } from '../common/index.js';
13
+ import { BLOCKS_RPC_PREFIX } from '../constants.js';
9
14
  import { BlocksBackend } from './blocks-backend.js';
15
+ import { Compute } from './compute/compute.js';
16
+ import { getComputes } from './compute/compute-registry.js';
17
+ import type { DefaultComputeFactory } from './compute/default-compute-factory.js';
10
18
  import { BlocksStack, BlocksPresets, Scope } from './index.js';
11
19
 
20
+ // A real app gets its default compute from @aws-blocks/bb-lambda-compute (via
21
+ // @aws-blocks/blocks), which core's own tests can't depend on. Use an
22
+ // equivalent inline stub: a Compute that owns a NodejsFunction + API Gateway,
23
+ // so create() can build the default and the handler/gateway/apiUrl accessors
24
+ // and synth-shape assertions have something real to resolve to. It is passed to
25
+ // each create() via the internal `defaultComputeFactory` option (see makeStack /
26
+ // makeBackend), exactly as @aws-blocks/blocks injects LambdaCompute.
27
+ class StubLambdaCompute extends Compute {
28
+ readonly fn: lambda.NodejsFunction;
29
+ readonly apiGateway: apigateway.RestApi;
30
+ readonly apiUrl: string;
31
+ readonly logGroup: cdk.aws_logs.LogGroup;
32
+
33
+ constructor(scope: ScopeParent, id: string) {
34
+ super(id, { parent: scope });
35
+ this.logGroup = new cdk.aws_logs.LogGroup(this, 'HandlerLogGroup', {
36
+ removalPolicy: cdk.RemovalPolicy.DESTROY,
37
+ });
38
+ this.fn = new lambda.NodejsFunction(this, 'Handler', {
39
+ entry: this.backendHandlerPath,
40
+ runtime: cdk.aws_lambda.Runtime.NODEJS_22_X,
41
+ handler: 'handler',
42
+ role: this.executionRole,
43
+ logGroup: this.logGroup,
44
+ environment: { BLOCKS_STACK_NAME: this.backendStackName },
45
+ bundling: { minify: true, esbuildArgs: { '--conditions': 'aws-runtime' } },
46
+ });
47
+ this.apiGateway = new apigateway.RestApi(this, 'API', { restApiName: 'Blocks API' });
48
+ this.apiGateway.root.addProxy({
49
+ defaultIntegration: new apigateway.LambdaIntegration(this.fn),
50
+ anyMethod: true,
51
+ });
52
+ this.apiUrl = `${this.apiGateway.url}${BLOCKS_RPC_PREFIX.slice(1)}`;
53
+ }
54
+
55
+ setEnv(key: string, value: string): void {
56
+ this.fn.addEnvironment(key, value);
57
+ }
58
+ }
59
+
60
+ const stubComputeFactory: DefaultComputeFactory = (root) => new StubLambdaCompute(root as never, 'DefaultCompute');
61
+
12
62
  // Simulate the CDK condition being active (tests import CDK files directly)
13
63
  before(() => {
14
- process.env.NODE_OPTIONS = (process.env.NODE_OPTIONS ?? '') + ' --conditions=cdk';
64
+ process.env.NODE_OPTIONS = (process.env.NODE_OPTIONS ?? '') + ' --conditions=cdk';
15
65
  });
16
66
 
17
67
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -19,135 +69,153 @@ const handlerPath = join(__dirname, '__fixtures__', 'handler.js');
19
69
  const sideEffectBackendPath = join(__dirname, '__fixtures__', 'side-effect-backend.js');
20
70
  const factoryBackendPath = join(__dirname, '__fixtures__', 'factory-backend.js');
21
71
 
72
+ // Wrap create(), injecting the stub default-compute factory the way
73
+ // @aws-blocks/blocks injects LambdaCompute — so tests don't repeat it.
74
+ const makeStack = (scope: Construct, id: string, backendCDKPath: string) =>
75
+ BlocksStack.create(scope, id, { backendHandlerPath: handlerPath, backendCDKPath, defaults: BlocksPresets.production, defaultComputeFactory: stubComputeFactory });
76
+ const makeBackend = (scope: Construct, id: string, backendCDKPath: string) =>
77
+ BlocksBackend.create(scope, id, { backendHandlerPath: handlerPath, backendCDKPath, defaults: BlocksPresets.production, defaultComputeFactory: stubComputeFactory });
78
+
22
79
  describe('ESM cache-busting (multi-stage)', () => {
23
- test('BlocksStack.create() with same backendCDKPath but different IDs produces constructs in each', async () => {
24
- const app = new cdk.App();
25
-
26
- const stack1 = await BlocksStack.create(app, 'PipelineStage1', {
27
- backendHandlerPath: handlerPath,
28
- backendCDKPath: sideEffectBackendPath,
29
- defaults: BlocksPresets.production,
30
- });
31
-
32
- const stack2 = await BlocksStack.create(app, 'PipelineStage2', {
33
- backendHandlerPath: handlerPath,
34
- backendCDKPath: sideEffectBackendPath,
35
- defaults: BlocksPresets.production,
36
- });
37
-
38
- const findMarker = (scope: any) => scope.node.tryFindChild('SideEffectMarker');
39
-
40
- assert.ok(
41
- findMarker(stack1),
42
- 'First stack should have SideEffectMarker from module side effect',
43
- );
44
- assert.ok(
45
- findMarker(stack2),
46
- 'Second stack should have SideEffectMarker from re-executed module (cache busted)',
47
- );
48
- });
80
+ test('BlocksStack.create() with same backendCDKPath but different IDs produces constructs in each', async () => {
81
+ const app = new cdk.App();
82
+
83
+ const stack1 = await makeStack(app, 'PipelineStage1', sideEffectBackendPath);
84
+
85
+ const stack2 = await makeStack(app, 'PipelineStage2', sideEffectBackendPath);
86
+
87
+ const findMarker = (scope: any) => scope.node.tryFindChild('SideEffectMarker');
88
+
89
+ assert.ok(findMarker(stack1), 'First stack should have SideEffectMarker from module side effect');
90
+ assert.ok(
91
+ findMarker(stack2),
92
+ 'Second stack should have SideEffectMarker from re-executed module (cache busted)',
93
+ );
94
+ });
49
95
  });
50
96
 
51
97
  describe('factory function support', () => {
52
- test('BlocksStack.create() calls default export function with the stack instance', async () => {
53
- const app = new cdk.App();
54
-
55
- const stack = await BlocksStack.create(app, 'FactoryBlocksStack', {
56
- backendHandlerPath: handlerPath,
57
- backendCDKPath: factoryBackendPath,
58
- defaults: BlocksPresets.production,
59
- });
60
-
61
- const marker = stack.node.tryFindChild('FactoryMarker');
62
- assert.ok(marker, 'Factory function should have created FactoryMarker on the stack');
63
- });
98
+ test('BlocksStack.create() calls default export function with the stack instance', async () => {
99
+ const app = new cdk.App();
100
+
101
+ const stack = await makeStack(app, 'FactoryBlocksStack', factoryBackendPath);
102
+
103
+ const marker = stack.node.tryFindChild('FactoryMarker');
104
+ assert.ok(marker, 'Factory function should have created FactoryMarker on the stack');
105
+ });
64
106
  });
65
107
 
66
108
  describe('legacy side-effect mode (no default export)', () => {
67
- test('module with only side effects still registers constructs via globalThis', async () => {
68
- const app = new cdk.App();
69
- const stack = new cdk.Stack(app, 'LegacyTestStack');
70
-
71
- const backend = await BlocksBackend.create(stack, 'LegacyStage', {
72
- backendHandlerPath: handlerPath,
73
- backendCDKPath: sideEffectBackendPath,
74
- defaults: BlocksPresets.production,
75
- });
76
-
77
- const marker = backend.node.tryFindChild('SideEffectMarker');
78
- assert.ok(
79
- marker,
80
- 'Side-effect-only module should register construct via globalThis.CURRENT_BLOCKS_STACK',
81
- );
82
- });
109
+ test('module with only side effects still registers constructs via globalThis', async () => {
110
+ const app = new cdk.App();
111
+ const stack = new cdk.Stack(app, 'LegacyTestStack');
112
+
113
+ const backend = await makeBackend(stack, 'LegacyStage', sideEffectBackendPath);
114
+
115
+ const marker = backend.node.tryFindChild('SideEffectMarker');
116
+ assert.ok(marker, 'Side-effect-only module should register construct via globalThis.CURRENT_BLOCKS_STACK');
117
+ });
83
118
  });
84
119
 
85
120
  describe('shared execution role (BlocksStack)', () => {
86
- // The role synth shape and the Scope.executionRole tree-walk are shared code
87
- // (setupBlocksInfra + the getter), covered in blocks-backend.test.ts. The only
88
- // BlocksStack-specific behavior is that its own constructor wires
89
- // executionRole — a separate code path from BlocksBackend's constructor.
90
- test('BlocksStack wires executionRole via its constructor', async () => {
91
- const app = new cdk.App();
92
- const stack = await BlocksStack.create(app, 'StackRoleStack', {
93
- backendHandlerPath: handlerPath,
94
- backendCDKPath: sideEffectBackendPath,
95
- defaults: BlocksPresets.production,
96
- });
97
-
98
- assert.ok(stack.executionRole, 'BlocksStack should expose a populated .executionRole');
99
- });
121
+ // The role synth shape and the Scope.executionRole tree-walk are shared code
122
+ // (setupBlocksInfra + the getter), covered in blocks-backend.test.ts. The only
123
+ // BlocksStack-specific behavior is that its own constructor wires
124
+ // executionRole — a separate code path from BlocksBackend's constructor.
125
+ test('BlocksStack wires executionRole via its constructor', async () => {
126
+ const app = new cdk.App();
127
+ const stack = await makeStack(app, 'StackRoleStack', sideEffectBackendPath);
128
+
129
+ assert.ok(stack.executionRole, 'BlocksStack should expose a populated .executionRole');
130
+ });
100
131
  });
101
132
 
102
133
  describe('executionRole globalThis fallback', () => {
103
- test('resolves via globalThis.CURRENT_BLOCKS_STACK when no owner is in the tree', async () => {
104
- const app = new cdk.App();
105
- const stack = await BlocksStack.create(app, 'FallbackStack', {
106
- backendHandlerPath: handlerPath,
107
- backendCDKPath: sideEffectBackendPath,
108
- defaults: BlocksPresets.production,
109
- });
110
-
111
- // A Scope whose construct-tree ancestry has no BlocksStack/BlocksBackend
112
- // (parented under a plain cdk.Stack) exhausts the tree-walk and falls back
113
- // to globalThis.CURRENT_BLOCKS_STACK. The `as any` is test plumbing a
114
- // plain Stack isn't a ScopeParent, but it IS a valid Construct parent.
115
- const plainStack = new cdk.Stack(app, 'PlainStack');
116
- (globalThis as any).CURRENT_BLOCKS_STACK = stack;
117
- const orphan = new Scope('orphan', { parent: plainStack as any });
118
-
119
- assert.strictEqual(
120
- orphan.executionRole,
121
- stack.executionRole,
122
- 'fallback resolves to the ambient stack role',
123
- );
124
- });
134
+ test('resolves via globalThis.CURRENT_BLOCKS_STACK when no owner is in the tree', async () => {
135
+ const app = new cdk.App();
136
+ const stack = await makeStack(app, 'FallbackStack', sideEffectBackendPath);
137
+
138
+ // A Scope whose construct-tree ancestry has no BlocksStack/BlocksBackend
139
+ // (parented under a plain cdk.Stack) exhausts the tree-walk and falls back
140
+ // to globalThis.CURRENT_BLOCKS_STACK. The `as any` is test plumbing — a
141
+ // plain Stack isn't a ScopeParent, but it IS a valid Construct parent.
142
+ const plainStack = new cdk.Stack(app, 'PlainStack');
143
+ (globalThis as any).CURRENT_BLOCKS_STACK = stack;
144
+ const orphan = new Scope('orphan', { parent: plainStack as any });
145
+
146
+ assert.strictEqual(orphan.executionRole, stack.executionRole, 'fallback resolves to the ambient stack role');
147
+ });
148
+ });
149
+
150
+ describe('root is bound to the owning stack (multi-stack synth)', () => {
151
+ test('a block under each of two stacks resolves its OWN stack, not the last globalThis', async () => {
152
+ // `root` is resolved once at Scope construction (not re-walked per getter),
153
+ // and `create()` mutates globalThis.CURRENT_BLOCKS_STACK for each stack it
154
+ // builds. With two stacks in one synth, a block constructed under the first
155
+ // must stay bound to the first even after the second stack is created and
156
+ // overwrites globalThis — otherwise its root-derived accessors (handler,
157
+ // executionRole, backendStackName) would silently point at the wrong stack.
158
+ const app = new cdk.App();
159
+
160
+ const stackA = await makeStack(app, 'RootBindingA', sideEffectBackendPath);
161
+ // A block explicitly parented under stackA (construct-tree walk resolves
162
+ // stackA regardless of the ambient globalThis).
163
+ const blockA = new Scope('blockA', { parent: stackA });
164
+
165
+ // Building the second stack overwrites globalThis.CURRENT_BLOCKS_STACK.
166
+ const stackB = await makeStack(app, 'RootBindingB', sideEffectBackendPath);
167
+ const blockB = new Scope('blockB', { parent: stackB });
168
+
169
+ assert.strictEqual(blockA.executionRole, stackA.executionRole, 'blockA stays bound to stackA');
170
+ assert.strictEqual(blockB.executionRole, stackB.executionRole, 'blockB binds to stackB');
171
+ assert.notStrictEqual(stackA.executionRole, stackB.executionRole, 'the two stacks have distinct roles');
172
+ assert.strictEqual(blockA.backendStackName, 'RootBindingA', 'blockA derives its own stack name');
173
+ assert.strictEqual(blockB.backendStackName, 'RootBindingB', 'blockB derives its own stack name');
174
+ });
175
+
176
+ test('each stack owns an isolated compute registry (no cross-stack bleed)', async () => {
177
+ // Computes self-register on their owning stack (keyed per stack, not a
178
+ // process-global list), so a multi-stack synth keeps each stack's computes
179
+ // separate — finalize steps for one stack never see another's compute.
180
+ const app = new cdk.App();
181
+
182
+ const stackA = await makeStack(app, 'ComputeRegistryA', sideEffectBackendPath);
183
+ const stackB = await makeStack(app, 'ComputeRegistryB', sideEffectBackendPath);
184
+
185
+ const computesA = getComputes(stackA);
186
+ const computesB = getComputes(stackB);
187
+
188
+ assert.strictEqual(computesA.length, 1, 'stackA registered exactly its default compute');
189
+ assert.strictEqual(computesB.length, 1, 'stackB registered exactly its default compute');
190
+ assert.strictEqual(computesA[0], stackA._defaultCompute, 'stackA lists its own default');
191
+ assert.strictEqual(computesB[0], stackB._defaultCompute, 'stackB lists its own default');
192
+ assert.notStrictEqual(computesA[0], computesB[0], 'the two stacks hold distinct computes');
193
+ });
125
194
  });
126
195
 
127
196
  describe('assertCdkConditionActive', () => {
128
- test('BlocksStack.create() throws when --conditions=cdk is missing', async () => {
129
- const origNodeOptions = process.env.NODE_OPTIONS;
130
- const origExecArgv = process.execArgv;
131
- process.env.NODE_OPTIONS = '';
132
- process.execArgv = [];
133
-
134
- try {
135
- const app = new cdk.App();
136
-
137
- await assert.rejects(
138
- BlocksStack.create(app, 'MissingConditionStack', {
139
- backendHandlerPath: handlerPath,
140
- backendCDKPath: sideEffectBackendPath,
141
- defaults: BlocksPresets.production,
142
- }),
143
- (err: Error) => {
144
- assert.ok(err.message.includes('Missing --conditions=cdk'), `Expected condition error, got: ${err.message}`);
145
- return true;
146
- },
147
- );
148
- } finally {
149
- process.env.NODE_OPTIONS = origNodeOptions;
150
- process.execArgv = origExecArgv;
151
- }
152
- });
197
+ test('BlocksStack.create() throws when --conditions=cdk is missing', async () => {
198
+ const origNodeOptions = process.env.NODE_OPTIONS;
199
+ const origExecArgv = process.execArgv;
200
+ process.env.NODE_OPTIONS = '';
201
+ process.execArgv = [];
202
+
203
+ try {
204
+ const app = new cdk.App();
205
+
206
+ await assert.rejects(
207
+ makeStack(app, 'MissingConditionStack', sideEffectBackendPath),
208
+ (err: Error) => {
209
+ assert.ok(
210
+ err.message.includes('Missing --conditions=cdk'),
211
+ `Expected condition error, got: ${err.message}`,
212
+ );
213
+ return true;
214
+ },
215
+ );
216
+ } finally {
217
+ process.env.NODE_OPTIONS = origNodeOptions;
218
+ process.execArgv = origExecArgv;
219
+ }
220
+ });
153
221
  });
@@ -0,0 +1,45 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import * as cdk from 'aws-cdk-lib';
5
+ import type { Construct } from 'constructs';
6
+ import type { Compute } from './compute.js';
7
+
8
+ const REGISTRY_KEY = Symbol.for('BLOCKS_COMPUTE_REGISTRY');
9
+
10
+ /**
11
+ * Get or create the compute list for a given stack. The list is stored on the
12
+ * stack object (keyed by a Symbol), so each stack in a multi-stack synth gets
13
+ * its own — a compute never leaks into another stack's list. Mirrors the config
14
+ * registry (`config-registry.ts`), which scopes its state the same way.
15
+ */
16
+ function getRegistry(stack: cdk.Stack): Compute[] {
17
+ let list = (stack as any)[REGISTRY_KEY] as Compute[] | undefined;
18
+ if (!list) {
19
+ list = [];
20
+ (stack as any)[REGISTRY_KEY] = list;
21
+ }
22
+ return list;
23
+ }
24
+
25
+ /**
26
+ * Register a compute on its owning stack. Called from the {@link Compute} base
27
+ * constructor, so every compute self-registers the moment it is constructed —
28
+ * the finalize steps then enumerate them without a separate discovery pass
29
+ * (mirrors how `registerConfig` accumulates config during the backend import).
30
+ *
31
+ * @param compute - The compute to register (used to locate its stack).
32
+ */
33
+ export function registerCompute(compute: Compute): void {
34
+ getRegistry(cdk.Stack.of(compute)).push(compute);
35
+ }
36
+
37
+ /**
38
+ * The computes registered on the stack that owns `scope`, in construction
39
+ * order. Returns an empty array before any compute is constructed.
40
+ *
41
+ * @param scope - Any construct in the stack (used to locate the stack).
42
+ */
43
+ export function getComputes(scope: Construct): readonly Compute[] {
44
+ return getRegistry(cdk.Stack.of(scope));
45
+ }
@@ -1,7 +1,9 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
+ import type { ScopeOptions } from '../../common/index.js';
4
5
  import { Scope } from '../index.js';
6
+ import { registerCompute } from './compute-registry.js';
5
7
 
6
8
  /**
7
9
  * Base class for a Blocks *compute* — a runtime that executes handler code
@@ -28,6 +30,14 @@ export abstract class Compute extends Scope {
28
30
  */
29
31
  readonly namespaces: string[] = [];
30
32
 
33
+ constructor(id: string, options?: ScopeOptions) {
34
+ super(id, options);
35
+ // Self-register on the owning stack so finalize steps (config, routing,
36
+ // dashboards) can enumerate every compute without a separate discovery
37
+ // pass. Scoped per stack, so a multi-stack synth keeps lists isolated.
38
+ registerCompute(this);
39
+ }
40
+
31
41
  /**
32
42
  * Inject a runtime configuration value (an environment variable) into this
33
43
  * compute. The framework calls this instead of `handler.addEnvironment()`
@@ -0,0 +1,38 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import type * as cdk from 'aws-cdk-lib';
5
+ import type { Compute } from './compute.js';
6
+ import type { BlocksStack } from '../index.js';
7
+ import type { BlocksBackend } from '../blocks-backend.js';
8
+
9
+ /**
10
+ * Lambda-shaped surface of the default compute that the legacy
11
+ * `handler` / `gateway` / `apiUrl` accessors on BlocksStack/BlocksBackend read.
12
+ * The default compute (`LambdaCompute` from `@aws-blocks/bb-lambda-compute`)
13
+ * satisfies this structurally, so core exposes those accessors without
14
+ * importing the concrete class. To be removed with those accessors once
15
+ * consumers move to the multi-compute model.
16
+ *
17
+ * @internal
18
+ */
19
+ export interface LambdaShapedCompute extends Compute {
20
+ readonly fn: cdk.aws_lambda_nodejs.NodejsFunction;
21
+ readonly apiGateway: cdk.aws_apigateway.RestApi;
22
+ readonly apiUrl: string;
23
+ readonly logGroup: cdk.aws_logs.ILogGroup;
24
+ }
25
+
26
+ /**
27
+ * Builds the default {@link Compute} for a stack/backend. `create()` reads it
28
+ * from its props (`CoreBlocksStackProps.defaultComputeFactory`) and calls it to
29
+ * build the default without importing a concrete compute class — the factory is
30
+ * supplied by whoever owns both core and a concrete compute package (the
31
+ * umbrella `@aws-blocks/blocks`, which injects `LambdaCompute`). It lives on
32
+ * `CoreBlocksStackProps`/`CoreBlocksBackendProps`, which the umbrella derives
33
+ * from the customer-facing props, so it is absent from `BlocksStackProps` and
34
+ * customers cannot set it.
35
+ *
36
+ * @internal
37
+ */
38
+ export type DefaultComputeFactory = (root: BlocksStack | BlocksBackend) => Compute;
@@ -0,0 +1,135 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * CDK tests for the config registry — specifically the getConfigLocation ↔ finalizeConfigRegistry
6
+ * interaction. `getConfigLocation()` creates the config bucket eagerly (so co-located compute can
7
+ * inject BLOCKS_CONFIG_BUCKET/KEY at construction); finalize must therefore still upload the config
8
+ * object + wire the computes whenever a bucket exists, even if zero entries were registered —
9
+ * otherwise that compute's loadConfigToProcessEnv() would 404 forever against a created-but-empty
10
+ * bucket.
11
+ */
12
+ import assert from 'node:assert';
13
+ import { afterEach, test } from 'node:test';
14
+ import * as cdk from 'aws-cdk-lib';
15
+ import { Match, Template } from 'aws-cdk-lib/assertions';
16
+ import { Construct } from 'constructs';
17
+ import { Compute } from './compute/compute.js';
18
+ import { finalizeConfigRegistry, getConfigLocation, registerConfig } from './config-registry.js';
19
+ import { DEFAULT_NODE_RUNTIME } from './node-version.js';
20
+
21
+ // getConfigLocation reads globalThis.CURRENT_BLOCKS_STACK to place the bucket under the owning
22
+ // stack/backend; clear it between tests so one test's owner never leaks into another.
23
+ afterEach(() => {
24
+ delete (globalThis as any).CURRENT_BLOCKS_STACK;
25
+ });
26
+
27
+ // A real app's compute comes from @aws-blocks/bb-lambda-compute, which core's own tests can't
28
+ // depend on. This is the same shape: a Compute that owns a real Lambda function and injects config
29
+ // via addEnvironment — enough for finalizeConfigRegistry to stamp BLOCKS_CONFIG_BUCKET/KEY on it.
30
+ class TestCompute extends Compute {
31
+ readonly fn: cdk.aws_lambda.Function;
32
+
33
+ constructor(scope: Construct, id: string) {
34
+ super(id, { parent: scope as never });
35
+ this.fn = new cdk.aws_lambda.Function(this, 'Handler', {
36
+ runtime: DEFAULT_NODE_RUNTIME,
37
+ handler: 'index.handler',
38
+ code: cdk.aws_lambda.Code.fromInline('exports.handler = async () => {};'),
39
+ });
40
+ }
41
+
42
+ setEnv(key: string, value: string): void {
43
+ this.fn.addEnvironment(key, value);
44
+ }
45
+ }
46
+
47
+ function stackWithCompute(id: string): {
48
+ stack: cdk.Stack;
49
+ role: cdk.aws_iam.Role;
50
+ computes: readonly Compute[];
51
+ } {
52
+ const app = new cdk.App();
53
+ const stack = new cdk.Stack(app, id);
54
+ const role = new cdk.aws_iam.Role(stack, 'BlocksRole', {
55
+ assumedBy: new cdk.aws_iam.ServicePrincipal('lambda.amazonaws.com'),
56
+ });
57
+ const compute = new TestCompute(stack, 'Compute');
58
+ return { stack, role, computes: [compute] };
59
+ }
60
+
61
+ test('finalize uploads + wires the computes even with zero entries when a bucket was created', () => {
62
+ const { stack, role, computes } = stackWithCompute('EmptyWithBucket');
63
+ // Simulate a co-located BB that creates the bucket but registers no config of its own.
64
+ getConfigLocation(stack);
65
+ finalizeConfigRegistry(stack, role, computes);
66
+
67
+ const t = Template.fromStack(stack);
68
+ assert.strictEqual(Object.keys(t.findResources('AWS::S3::Bucket')).length, 1, 'one config bucket');
69
+ t.resourceCountIs('Custom::CDKBucketDeployment', 1); // the (empty) blocks-config.json is uploaded
70
+ t.hasResourceProperties('AWS::Lambda::Function', {
71
+ Environment: { Variables: Match.objectLike({ BLOCKS_CONFIG_KEY: 'blocks-config.json' }) },
72
+ });
73
+ // Read is granted once to the shared role (not per-function), so every compute that assumes it
74
+ // — including co-located compute that never went through finalize — can read the object.
75
+ t.hasResourceProperties('AWS::IAM::Policy', {
76
+ PolicyDocument: {
77
+ Statement: Match.arrayWith([
78
+ Match.objectLike({ Action: Match.arrayWith([Match.stringLikeRegexp('^s3:GetObject')]) }),
79
+ ]),
80
+ },
81
+ Roles: Match.arrayWith([Match.objectLike({ Ref: Match.stringLikeRegexp('BlocksRole') })]),
82
+ });
83
+ });
84
+
85
+ test('finalize is a no-op with zero entries and no bucket', () => {
86
+ const { stack, role, computes } = stackWithCompute('EmptyNoBucket');
87
+ finalizeConfigRegistry(stack, role, computes);
88
+
89
+ const t = Template.fromStack(stack);
90
+ assert.strictEqual(Object.keys(t.findResources('AWS::S3::Bucket')).length, 0, 'no config bucket created');
91
+ t.resourceCountIs('Custom::CDKBucketDeployment', 0);
92
+ });
93
+
94
+ test('finalize uploads + wires the computes when config was registered (bucket auto-created)', () => {
95
+ const { stack, role, computes } = stackWithCompute('WithEntries');
96
+ registerConfig(stack, 'BLOCKS_SOMETHING', 'value');
97
+ finalizeConfigRegistry(stack, role, computes);
98
+
99
+ const t = Template.fromStack(stack);
100
+ assert.strictEqual(Object.keys(t.findResources('AWS::S3::Bucket')).length, 1, 'one config bucket');
101
+ t.resourceCountIs('Custom::CDKBucketDeployment', 1);
102
+ t.hasResourceProperties('AWS::Lambda::Function', {
103
+ Environment: { Variables: Match.objectLike({ BLOCKS_CONFIG_KEY: 'blocks-config.json' }) },
104
+ });
105
+ });
106
+
107
+ test('the config bucket is created under the owning stack/backend, not the (deep) caller scope', () => {
108
+ // Mimic a BlocksBackend embedded in a customer stack: the owner is a nested construct, and the
109
+ // first caller of getConfigLocation is a *deep* construct (like the AgentCore Runtime).
110
+ const app = new cdk.App();
111
+ const stack = new cdk.Stack(app, 'CustomerStack');
112
+ const owner = new Construct(stack, 'Embedded'); // stands in for the BlocksBackend construct
113
+ (globalThis as any).CURRENT_BLOCKS_STACK = owner;
114
+ const deepScope = new Construct(new Construct(owner, 'agent'), 'runtime');
115
+
116
+ getConfigLocation(deepScope);
117
+
118
+ const t = Template.fromStack(stack);
119
+ const bucketIds = Object.keys(t.findResources('AWS::S3::Bucket'));
120
+ assert.strictEqual(bucketIds.length, 1, 'exactly one config bucket');
121
+ // Logical IDs encode the construct path — under the owner it's `EmbeddedBlocksConfigBucket…`,
122
+ // at the stack root it would be `BlocksConfigBucket…`. Pin that it follows the owner.
123
+ assert.ok(bucketIds[0].startsWith('Embedded'), `bucket should be nested under the owner, got ${bucketIds[0]}`);
124
+ });
125
+
126
+ test('getConfigLocation creates exactly one bucket across repeated calls (idempotent)', () => {
127
+ const app = new cdk.App();
128
+ const stack = new cdk.Stack(app, 'Idempotent');
129
+ const a = getConfigLocation(stack);
130
+ const b = getConfigLocation(stack);
131
+ assert.strictEqual(a.key, b.key, 'same config key');
132
+ assert.strictEqual(a.bucketName, b.bucketName, 'same bucket');
133
+ const t = Template.fromStack(stack);
134
+ assert.strictEqual(Object.keys(t.findResources('AWS::S3::Bucket')).length, 1, 'exactly one bucket');
135
+ });