@aws-blocks/core 0.1.4 → 0.1.10

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 (91) hide show
  1. package/dist/cdk/index.d.ts +1 -1
  2. package/dist/cdk/index.d.ts.map +1 -1
  3. package/dist/cdk/index.js +1 -1
  4. package/dist/client/index.d.ts +1 -1
  5. package/dist/client/index.d.ts.map +1 -1
  6. package/dist/client/index.js +1 -1
  7. package/dist/db-naming.d.ts +17 -5
  8. package/dist/db-naming.d.ts.map +1 -1
  9. package/dist/db-naming.js +18 -6
  10. package/dist/db-naming.test.js +44 -3
  11. package/dist/errors.d.ts +28 -0
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +27 -1
  14. package/dist/errors.test.d.ts +2 -0
  15. package/dist/errors.test.d.ts.map +1 -0
  16. package/dist/errors.test.js +47 -0
  17. package/dist/hosting.d.ts +71 -1
  18. package/dist/hosting.d.ts.map +1 -1
  19. package/dist/hosting.js +47 -8
  20. package/dist/hosting.test.js +60 -0
  21. package/dist/index.cdk.d.ts +1 -1
  22. package/dist/index.cdk.d.ts.map +1 -1
  23. package/dist/index.cdk.js +1 -1
  24. package/dist/index.d.ts +1 -1
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +1 -1
  27. package/dist/scripts/deploy.d.ts.map +1 -1
  28. package/dist/scripts/deploy.js +4 -2
  29. package/dist/scripts/dev-server-supervisor.test.d.ts +2 -0
  30. package/dist/scripts/dev-server-supervisor.test.d.ts.map +1 -0
  31. package/dist/scripts/dev-server-supervisor.test.js +551 -0
  32. package/dist/scripts/dev-server.d.ts +73 -0
  33. package/dist/scripts/dev-server.d.ts.map +1 -1
  34. package/dist/scripts/dev-server.js +279 -29
  35. package/dist/scripts/ensure-secrets.d.ts +5 -2
  36. package/dist/scripts/ensure-secrets.d.ts.map +1 -1
  37. package/dist/scripts/ensure-secrets.js +14 -6
  38. package/dist/scripts/external-migrations-step.d.ts.map +1 -1
  39. package/dist/scripts/external-migrations-step.js +5 -1
  40. package/dist/scripts/index.d.ts +1 -0
  41. package/dist/scripts/index.d.ts.map +1 -1
  42. package/dist/scripts/index.js +1 -0
  43. package/dist/scripts/process-tree.d.ts +126 -0
  44. package/dist/scripts/process-tree.d.ts.map +1 -0
  45. package/dist/scripts/process-tree.js +198 -0
  46. package/dist/scripts/sandbox.d.ts.map +1 -1
  47. package/dist/scripts/sandbox.js +51 -4
  48. package/dist/scripts/stack-id.d.ts +37 -0
  49. package/dist/scripts/stack-id.d.ts.map +1 -0
  50. package/dist/scripts/stack-id.js +79 -0
  51. package/dist/scripts/stack-id.test.d.ts +2 -0
  52. package/dist/scripts/stack-id.test.d.ts.map +1 -0
  53. package/dist/scripts/stack-id.test.js +104 -0
  54. package/dist/telemetry/client.d.ts +3 -1
  55. package/dist/telemetry/client.d.ts.map +1 -1
  56. package/dist/telemetry/client.js +20 -24
  57. package/dist/telemetry/telemetry-send-worker.d.ts +2 -0
  58. package/dist/telemetry/telemetry-send-worker.d.ts.map +1 -0
  59. package/dist/telemetry/telemetry-send-worker.js +58 -0
  60. package/dist/telemetry/telemetry.test.js +77 -1
  61. package/dist/telemetry/trackCommand.d.ts +1 -1
  62. package/dist/telemetry/trackCommand.js +3 -3
  63. package/dist/version.d.ts +1 -1
  64. package/dist/version.d.ts.map +1 -1
  65. package/dist/version.js +1 -1
  66. package/package.json +1 -1
  67. package/src/cdk/index.ts +1 -1
  68. package/src/client/index.ts +1 -1
  69. package/src/db-naming.test.ts +50 -5
  70. package/src/db-naming.ts +18 -6
  71. package/src/errors.test.ts +55 -0
  72. package/src/errors.ts +32 -1
  73. package/src/hosting.test.ts +79 -0
  74. package/src/hosting.ts +127 -13
  75. package/src/index.cdk.ts +1 -1
  76. package/src/index.ts +1 -1
  77. package/src/scripts/deploy.ts +4 -2
  78. package/src/scripts/dev-server-supervisor.test.ts +621 -0
  79. package/src/scripts/dev-server.ts +316 -27
  80. package/src/scripts/ensure-secrets.ts +17 -6
  81. package/src/scripts/external-migrations-step.ts +5 -1
  82. package/src/scripts/index.ts +1 -0
  83. package/src/scripts/process-tree.ts +245 -0
  84. package/src/scripts/sandbox.ts +50 -4
  85. package/src/scripts/stack-id.test.ts +123 -0
  86. package/src/scripts/stack-id.ts +87 -0
  87. package/src/telemetry/client.ts +22 -30
  88. package/src/telemetry/telemetry-send-worker.ts +60 -0
  89. package/src/telemetry/telemetry.test.ts +91 -1
  90. package/src/telemetry/trackCommand.ts +3 -3
  91. package/src/version.ts +1 -1
@@ -1428,4 +1428,83 @@ describe('Hosting', () => {
1428
1428
  template.resourceCountIs('AWS::CloudFront::Distribution', 1);
1429
1429
  });
1430
1430
  });
1431
+
1432
+ // ── basePath prop (caller-declared source of truth) ─────────
1433
+ // Under KVS edge routing, basePath is no longer expressed as a per-behavior
1434
+ // PathPattern prefix — it lives in the KVS route table's `meta.bp`, which the
1435
+ // edge router uses for the canonical 308 + static strip. So these tests read
1436
+ // the basePath out of the RouteStoreKeys custom resource's Entries.
1437
+ describe('basePath prop', () => {
1438
+ const metaBasePath = (root: string, basePath?: string): string => {
1439
+ const app = new App();
1440
+ const stack = new Stack(app, 'BasePathStack', {
1441
+ env: { account: '123456789012', region: 'us-east-1' },
1442
+ });
1443
+ new Hosting(stack, 'Web', {
1444
+ root,
1445
+ framework: 'spa',
1446
+ buildOutputDir: 'dist',
1447
+ ...(basePath !== undefined ? { basePath } : {}),
1448
+ });
1449
+ const tpl = Template.fromStack(stack).toJSON() as {
1450
+ Resources: Record<string, { Type: string; Properties?: any }>;
1451
+ };
1452
+ const kvKeys = Object.entries(tpl.Resources).find(
1453
+ ([id, r]) =>
1454
+ r.Type === 'AWS::CloudFormation::CustomResource' &&
1455
+ /RouteStoreKeys/.test(id),
1456
+ );
1457
+ assert.ok(kvKeys, 'expected a RouteStoreKeys custom resource');
1458
+ const entries = JSON.parse(kvKeys![1].Properties.Entries);
1459
+ const meta = JSON.parse(entries.meta);
1460
+ return meta.bp as string;
1461
+ };
1462
+
1463
+ it('records basePath in the KVS route table when set (SPA, no framework base)', () => {
1464
+ createSpaBuildOutput(tmpDir);
1465
+ assert.strictEqual(metaBasePath(tmpDir, '/app'), '/app');
1466
+ });
1467
+
1468
+ it('normalizes a trailing slash (/app/ → /app)', () => {
1469
+ createSpaBuildOutput(tmpDir);
1470
+ assert.strictEqual(metaBasePath(tmpDir, '/app/'), '/app');
1471
+ });
1472
+
1473
+ it('treats "/" as no base path', () => {
1474
+ createSpaBuildOutput(tmpDir);
1475
+ assert.strictEqual(metaBasePath(tmpDir, '/'), '');
1476
+ });
1477
+ });
1478
+
1479
+ // ── P0.4: config.json ordering dependency ────────────────────
1480
+ describe('config.json deploy ordering (P0.4)', () => {
1481
+ it('BlocksConfigDeployment depends on the asset deployments', () => {
1482
+ // The asset deployments upload the whole static dir — including the
1483
+ // placeholder `.blocks-sandbox/config.json` — to the same key the
1484
+ // resolved config writes to. Without an ordering dependency the
1485
+ // placeholder can clobber the real config. The previous
1486
+ // `tryFindChild('AssetDeployment')` never matched the real child ids
1487
+ // (AssetDeploymentImmutable/Html/Mutable), so the dep was never wired.
1488
+ createSpaBuildOutput(tmpDir);
1489
+ const app = new App();
1490
+ const stack = new Stack(app, 'ConfigOrderStack');
1491
+ new Hosting(stack, 'Hosting', { root: tmpDir, api: MOCK_API });
1492
+
1493
+ const tpl = Template.fromStack(stack).toJSON() as {
1494
+ Resources: Record<string, { Type: string; DependsOn?: string[] }>;
1495
+ };
1496
+ const configId = Object.keys(tpl.Resources).find(
1497
+ (id) => /BlocksConfigDeployment/.test(id) && /CustomResource/.test(id),
1498
+ );
1499
+ assert.ok(configId, 'expected a BlocksConfigDeployment custom resource');
1500
+
1501
+ const dependsOn = tpl.Resources[configId].DependsOn ?? [];
1502
+ const assetDeps = dependsOn.filter((d) => /AssetDeployment/.test(d));
1503
+ assert.ok(
1504
+ assetDeps.length >= 1,
1505
+ `BlocksConfigDeployment must DependsOn the asset deployment(s); ` +
1506
+ `found DependsOn=${JSON.stringify(dependsOn)}`,
1507
+ );
1508
+ });
1509
+ });
1431
1510
  });
package/src/hosting.ts CHANGED
@@ -26,6 +26,7 @@ import {
26
26
  import {
27
27
  detectFramework,
28
28
  getAdapter,
29
+ normalizeBasePath,
29
30
  type FrameworkAdapterFn,
30
31
  } from '@aws-blocks/hosting/adapters';
31
32
  import type {
@@ -71,8 +72,29 @@ export type ComputeConfig = {
71
72
  * ```
72
73
  */
73
74
  timeout?: cdk.Duration | number;
74
- /** Reserved concurrent executions. Default: undefined (no reservation). */
75
+ /** Reserved concurrent executions for the SSR Lambda. Default: undefined (no reservation). */
75
76
  reservedConcurrency?: number;
77
+ /**
78
+ * Overrides for the image-optimization Lambda.
79
+ *
80
+ * `reservedConcurrency` defaults to undefined (no reservation). It is left
81
+ * unreserved so deploys succeed on fresh AWS accounts, whose default
82
+ * account-level unreserved-concurrency limit is 10 — reserving any
83
+ * concurrency there can drop the account below its required minimum and
84
+ * cause Lambda to reject the stack with a 400. Set this only if you have
85
+ * headroom and want to cap image-opt throughput.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * compute: {
90
+ * imageOptimization: { reservedConcurrency: 5 },
91
+ * }
92
+ * ```
93
+ */
94
+ imageOptimization?: {
95
+ /** Reserved concurrent executions. Default: undefined (no reservation). */
96
+ reservedConcurrency?: number;
97
+ };
76
98
  /** CloudWatch log retention for the SSR Lambda. Default: TWO_WEEKS. */
77
99
  logRetention?: cdk.aws_logs.RetentionDays;
78
100
  };
@@ -129,6 +151,27 @@ export interface HostingProps {
129
151
  /** Supply a custom adapter when using an unsupported framework. */
130
152
  customAdapter?: FrameworkAdapterFn;
131
153
 
154
+ /**
155
+ * URL prefix the whole site is served under (Next.js `basePath`, Astro
156
+ * `base`, Nuxt `app.baseURL`). When set, CloudFront behaviors are prefixed
157
+ * with it and the bare root issues a 308 redirect to `/<basePath>/`.
158
+ *
159
+ * Declaring it here is the recommended source of truth: the value is
160
+ * caller-provided rather than reverse-engineered from build output, so it
161
+ * can't drift with framework/bundler internals. When omitted, the adapter
162
+ * falls back to detecting the framework's own base-path config from the
163
+ * build output.
164
+ *
165
+ * Format: leading slash, no trailing slash (e.g. `'/app'`). A trailing
166
+ * slash or bare `'/'` is normalized/ignored.
167
+ *
168
+ * @example
169
+ * ```ts
170
+ * new Hosting(stack, 'Web', { root, framework: 'nuxt', basePath: '/app' });
171
+ * ```
172
+ */
173
+ basePath?: string;
174
+
132
175
  // ── Blocks backend integration ────────────────────────────────────
133
176
  /**
134
177
  * The Blocks backend stack (or any object with `apiUrl`).
@@ -183,6 +226,36 @@ export interface HostingProps {
183
226
  countries: string[];
184
227
  };
185
228
 
229
+ /**
230
+ * Overrides for the adjustable AWS Service Quotas the CloudFront
231
+ * distribution draws on. Each field maps to a named AWS quota you can
232
+ * request an increase on:
233
+ *
234
+ * - `cacheBehaviors` — "Cache behaviors per distribution" (default 25).
235
+ * Consumed by routed paths, prerendered pages, per-pattern header
236
+ * rules, assetPrefix, and the error-page behavior.
237
+ * - `edgeFunctions` — Lambda@Edge associations per distribution
238
+ * (default 25). Consumed by `runtime: 'edge'` routes.
239
+ * - `headerPolicies` — "Response headers policies per AWS account"
240
+ * (default 20, account-wide).
241
+ *
242
+ * Omitted fields use the AWS default. Set a field ONLY to match a quota
243
+ * increase AWS has actually granted — synth cannot verify your real quota,
244
+ * so an over-set value does not raise the AWS ceiling; it just moves the
245
+ * failure from a clear synth error to an opaque CloudFormation rollback.
246
+ *
247
+ * @example
248
+ * ```ts
249
+ * // After AWS grants "Cache behaviors per distribution" = 50:
250
+ * new Hosting(stack, 'Web', { root, quotas: { cacheBehaviors: 50 } });
251
+ * ```
252
+ */
253
+ quotas?: {
254
+ cacheBehaviors?: number;
255
+ edgeFunctions?: number;
256
+ headerPolicies?: number;
257
+ };
258
+
186
259
  /**
187
260
  * Build cache configuration. When enabled, provisions an S3 bucket for
188
261
  * framework build caches (e.g. Next.js .next/cache) and exports the bucket
@@ -380,6 +453,23 @@ export class Hosting extends Construct {
380
453
  manifest.buildId = generateBuildId();
381
454
  }
382
455
 
456
+ // ── 4b'. basePath: prop is the source of truth ───────────────
457
+ // A caller-declared `basePath` overrides whatever the adapter
458
+ // detected from build output. This is the robust path: the value
459
+ // is provided rather than reverse-engineered from framework/bundler
460
+ // internals (which drift across versions). When the prop is omitted,
461
+ // the adapter's detected `manifest.basePath` (if any) stands.
462
+ if (props.basePath !== undefined) {
463
+ const normalized = normalizeBasePath(props.basePath);
464
+ if (normalized) {
465
+ manifest.basePath = normalized;
466
+ } else {
467
+ // Explicit '/' (or empty) means "no base path" — clear any value
468
+ // the adapter may have detected so the prop genuinely wins.
469
+ delete manifest.basePath;
470
+ }
471
+ }
472
+
383
473
  // ── 4c. Prevent duplicate error pages ────────────────────────
384
474
  // The adapter may auto-detect error pages (e.g. SPA adapter finds
385
475
  // 404.html in build output and sets manifest.errorPages). When the
@@ -449,11 +539,12 @@ export class Hosting extends Construct {
449
539
  storage: props.retainOnDelete != null
450
540
  ? { retainOnDelete: props.retainOnDelete }
451
541
  : undefined,
452
- cdn: (props.contentSecurityPolicy || props.priceClass || props.geoRestriction)
542
+ cdn: (props.contentSecurityPolicy || props.priceClass || props.geoRestriction || props.quotas)
453
543
  ? {
454
544
  contentSecurityPolicy: props.contentSecurityPolicy,
455
545
  priceClass: props.priceClass,
456
546
  geoRestriction: props.geoRestriction,
547
+ quotas: props.quotas,
457
548
  }
458
549
  : undefined,
459
550
  logging: props.logging,
@@ -471,17 +562,26 @@ export class Hosting extends Construct {
471
562
  }
472
563
 
473
564
  // ── 7a. Inject Blocks env vars into compute functions ───────────
474
- const primaryFunction = hosting.computeFunctions.values().next().value as cdk.aws_lambda.Function | undefined;
565
+ // Lambda@Edge functions (edge-runtime routes) do NOT support environment
566
+ // variables — they surface in computeFunctions as EdgeFunction/IVersion
567
+ // without an `addEnvironment` method. Skip any function that can't take
568
+ // env vars instead of crashing (`fn.addEnvironment is not a function`).
569
+ const canAddEnv = (
570
+ fn: unknown,
571
+ ): fn is cdk.aws_lambda.Function =>
572
+ typeof (fn as { addEnvironment?: unknown })?.addEnvironment === 'function';
573
+
574
+ const primaryFunction = [...hosting.computeFunctions.values()].find(
575
+ canAddEnv,
576
+ );
475
577
 
476
578
  for (const [, fn] of hosting.computeFunctions) {
579
+ if (!canAddEnv(fn)) continue; // Lambda@Edge: no env var support
477
580
  if (props.api) {
478
- (fn as cdk.aws_lambda.Function).addEnvironment('BLOCKS_API_URL', props.api.apiUrl);
581
+ fn.addEnvironment('BLOCKS_API_URL', props.api.apiUrl);
479
582
  }
480
583
  if (props.backendConfig) {
481
- (fn as cdk.aws_lambda.Function).addEnvironment(
482
- 'BLOCKS_CONFIG',
483
- JSON.stringify(props.backendConfig),
484
- );
584
+ fn.addEnvironment('BLOCKS_CONFIG', JSON.stringify(props.backendConfig));
485
585
  }
486
586
  }
487
587
 
@@ -500,11 +600,25 @@ export class Hosting extends Construct {
500
600
  cacheControl: [s3deploy.CacheControl.fromString('public, max-age=60, must-revalidate')],
501
601
  });
502
602
 
503
- // Ensure config deployment runs after the hosting construct's
504
- // asset deployment so the resolved config.json is not overwritten.
505
- const assetDeployment = hosting.node.tryFindChild('AssetDeployment') as Construct | undefined;
506
- if (assetDeployment) {
507
- configDeployment.node.addDependency(assetDeployment);
603
+ // Ensure the config deployment runs AFTER the hosting construct's
604
+ // asset deployments. Those deployments upload the whole static dir
605
+ // which includes the *placeholder* `.blocks-sandbox/config.json`
606
+ // (`{_placeholder:true}`) written during synth — to the same
607
+ // `builds/<id>/.blocks-sandbox/config.json` key this deployment writes
608
+ // the resolved config to. Without an ordering dependency the
609
+ // placeholder can land last and clobber the real config.
610
+ //
611
+ // We depend on EVERY BucketDeployment under the hosting construct
612
+ // rather than a single hard-coded child id: the real children are
613
+ // `AssetDeploymentImmutable` / `AssetDeploymentHtml` / `...Mutable`
614
+ // (and vary by deploy shape), so the previous
615
+ // `tryFindChild('AssetDeployment')` never matched and the dependency
616
+ // was silently never wired.
617
+ const assetDeployments = hosting.node
618
+ .findAll()
619
+ .filter((c): c is s3deploy.BucketDeployment => c instanceof s3deploy.BucketDeployment);
620
+ for (const dep of assetDeployments) {
621
+ configDeployment.node.addDependency(dep);
508
622
  }
509
623
  }
510
624
 
package/src/index.cdk.ts CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  export { ApiNamespace, type BlocksContext, type ApiHandler } from './api.js';
5
5
  export { BLOCKS_RPC_PREFIX, BLOCKS_AUTH_PREFIX } from './constants.js';
6
- export { ApiError, isBlocksError } from './errors.js';
6
+ export { ApiError, isBlocksError, hasAuthError, DEFAULT_API_ERROR_NAME } from './errors.js';
7
7
  export { EventSourceMapping } from './lambda-handler.js';
8
8
  export { BlocksStackProps } from './common/index.js';
9
9
  export { registerSdkIdentifiers, getSdkIdentifiers, getAllSdkIdentifiers, _resetSdkRegistry } from './common/sdk-registry.js';
package/src/index.ts CHANGED
@@ -3,7 +3,7 @@
3
3
 
4
4
  export { ApiNamespace, type BlocksContext, type ApiHandler } from './api.js';
5
5
  export { BLOCKS_RPC_PREFIX, BLOCKS_AUTH_PREFIX } from './constants.js';
6
- export { ApiError, isBlocksError } from './errors.js';
6
+ export { ApiError, isBlocksError, hasAuthError, DEFAULT_API_ERROR_NAME } from './errors.js';
7
7
  export { Scope, type ScopeOptions, type ScopeParent, type BuildingBlockMeta } from './common/index.js';
8
8
  export { registerSdkIdentifiers, getSdkIdentifiers, getAllSdkIdentifiers, _resetSdkRegistry } from './common/sdk-registry.js';
9
9
  export { getConfig, getConfigSync, preloadConfig, loadConfigToProcessEnv, _resetConfigCache } from './common/config.js';
@@ -25,8 +25,10 @@ export async function deploy(options: DeployOptions) {
25
25
 
26
26
  process.env.BLOCKS_STAGE = 'production';
27
27
 
28
- // Provision secrets for production
29
- const secrets = await ensureSecrets('production');
28
+ // Provision secrets for production. projectRoot must match the root cdk
29
+ // synth uses (passed as --context below) so the written parameter name
30
+ // equals the one the app resolves at synth.
31
+ const secrets = await ensureSecrets('production', options.projectRoot);
30
32
  if (secrets.created.length > 0 || secrets.updated.length > 0) {
31
33
  console.log(`🔐 Secrets provisioned: ${[...secrets.created, ...secrets.updated].join(', ')}`);
32
34
  }