@friggframework/devtools 2.0.0-next.127 → 2.0.0-next.128

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 (32) hide show
  1. package/infrastructure/README.md +32 -5
  2. package/infrastructure/__tests__/helpers/bundled-prisma-engine-excludes.js +39 -0
  3. package/infrastructure/__tests__/management-api-gateway-routes.test.js +3 -0
  4. package/infrastructure/__tests__/postgres-config.test.js +3 -0
  5. package/infrastructure/__tests__/scaffold-default-infrastructure.test.js +3 -0
  6. package/infrastructure/__tests__/scoped-environment.test.js +3 -0
  7. package/infrastructure/__tests__/ssm-preload-node-options.test.js +3 -0
  8. package/infrastructure/__tests__/template-generation.test.js +3 -0
  9. package/infrastructure/app-definition-schema-contract.test.js +5 -0
  10. package/infrastructure/domains/admin-scripts/admin-script-builder.js +2 -0
  11. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +22 -6
  12. package/infrastructure/domains/database/migration-builder.js +21 -2
  13. package/infrastructure/domains/database/migration-builder.test.js +61 -6
  14. package/infrastructure/domains/database/migration-engines.js +93 -0
  15. package/infrastructure/domains/database/migration-engines.test.js +142 -0
  16. package/infrastructure/domains/integration/integration-builder.js +2 -0
  17. package/infrastructure/domains/integration/integration-builder.test.js +22 -6
  18. package/infrastructure/domains/shared/environment-builder.js +31 -5
  19. package/infrastructure/domains/shared/environment-builder.test.js +93 -7
  20. package/infrastructure/domains/shared/lambda-architectures.js +113 -0
  21. package/infrastructure/domains/shared/lambda-architectures.test.js +164 -0
  22. package/infrastructure/domains/shared/utilities/base-definition-factory.js +13 -1
  23. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +51 -4
  24. package/infrastructure/domains/shared/utilities/nested-node-modules.js +6 -5
  25. package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +20 -26
  26. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +92 -12
  27. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +158 -6
  28. package/infrastructure/infrastructure-composer.js +12 -1
  29. package/infrastructure/infrastructure-composer.test.js +71 -0
  30. package/infrastructure/scripts/build-prisma-layer.js +136 -50
  31. package/infrastructure/scripts/build-prisma-layer.test.js +100 -0
  32. package/package.json +7 -7
@@ -285,23 +285,50 @@ const appDefinition = {
285
285
 
286
286
  > ℹ️ When `usePrismaLambdaLayer: false`, Prisma stays inside each bundle and the runtime automatically loads the correct binary. No extra configuration is required.
287
287
 
288
- **Keeping nested node_modules in Lambda packages:**
288
+ **Nested node_modules in Lambda packages:**
289
289
 
290
- By default every function package excludes `node_modules/**/node_modules/**`. npm only nests a package when the root copy cannot satisfy a dependant, so the exclusion makes a package resolve whatever version is hoisted, and it removes the package entirely when the root copy is a dev dependency. The first `require` of such a package then fails at Lambda init with `Runtime.ImportModuleError`.
290
+ npm nests a package under its dependant only when the root copy cannot satisfy the dependant's range. Function packages ship the dependency tree the way npm resolved it. Nested copies of `@friggframework/*`, `aws-sdk`, `@aws-sdk/*` and, when the Prisma layer is enabled, `@prisma/*` and `.prisma` are excluded: the app's single core, the Lambda runtime and the layer provide them.
291
291
 
292
- To ship the dependency tree the way npm resolved it, opt in per app:
292
+ An app can exclude every nested `node_modules` to make packages smaller:
293
293
 
294
294
  ```javascript
295
295
  const appDefinition = {
296
296
  name: 'my-app',
297
297
  lambda: {
298
- keepNestedNodeModules: true,
298
+ keepNestedNodeModules: false,
299
299
  },
300
300
  integrations: [{ Definition: { name: 'salesforce' } }],
301
301
  };
302
302
  ```
303
303
 
304
- Nested copies of `@friggframework/*`, `aws-sdk`, `@aws-sdk/*` and, when the Prisma layer is enabled, `@prisma/*` and `.prisma` stay excluded: the app's single core, the Lambda runtime and the layer provide them. Expect each function package to grow by the size of the nested directories that remain (a few MB compressed in a typical app). The default stays unchanged for apps that do not set the flag.
304
+ With the opt-out, each nested package resolves whatever version is hoisted to the root, and a package whose root copy is a dev dependency is not shipped at all. The first `require` of such a package fails at Lambda init with `Runtime.ImportModuleError`.
305
+
306
+ **Lambda architecture (arm64 / Graviton):**
307
+
308
+ Every function, the Prisma layer and the migration worker deploy as x86_64 unless the app definition sets `architecture`:
309
+
310
+ ```javascript
311
+ const appDefinition = {
312
+ name: 'my-app',
313
+ architecture: 'arm64', // or 'x86_64'; unset keeps today's template
314
+ integrations: [{ Definition: { name: 'hubspot' } }],
315
+ };
316
+ ```
317
+
318
+ An explicit value sets `provider.architecture` and the layer's `compatibleArchitectures`, builds the layer with that architecture's Prisma query engine, ships the migration worker with its schema engine and query engine library, and pins the migrate CLI to them through `PRISMA_SCHEMA_ENGINE_BINARY` and `PRISMA_QUERY_ENGINE_LIBRARY`. With `usePrismaLambdaLayer: false`, each function bundles only that engine. An unset key adds no field to the template.
319
+
320
+ Before you flip an app to `arm64`:
321
+
322
+ - It needs a `@friggframework/core` release whose generated Prisma clients include the `linux-arm64-openssl-3.0.x` engine (both schemas list it in `binaryTargets`). With an older core the layer build fails naming the core version.
323
+ - The deploy host must reach Prisma's engine CDN (`binaries.prisma.sh`) at package time: the migration worker's engines for the target are fetched there, and packaging fails if either is missing.
324
+ - This runs on every compose where the migration worker is enabled, and downloads only when the target's engines are missing from the app's `node_modules/@prisma/engines`.
325
+ - Air-gapped or offline deploy hosts set `PRISMA_ENGINES_MIRROR` to an internal mirror of the CDN. Prisma's download honours it (`@prisma/fetch-engine` 6.19.3, `dist/chunk-LONQL55G.js`, where the download URL is built from `PRISMA_BINARIES_MIRROR || PRISMA_ENGINES_MIRROR || "https://binaries.prisma.sh"`).
326
+ - The app must have `prisma` installed in its own `node_modules`, not only in a hoisted parent: the worker ships its engines from there, and packaging fails otherwise. The worker runs the app's own `prisma` CLI and pins `PRISMA_SCHEMA_ENGINE_BINARY` and `PRISMA_QUERY_ENGINE_LIBRARY` to that `@prisma/engines`, so the CLI and its engines always agree. That `prisma` must still be able to run the schema and migrations of `@friggframework/core`.
327
+ - Published core carries one more query engine per generated client (about 15 MB unpacked each).
328
+ - Native addons of the app itself (`sharp`, `bcrypt`, and the like) are built for the deploy host's architecture by `npm ci`, not for the target. Build them for arm64 or replace them.
329
+ - During the stack update, functions run mixed for a short time, so flip in a low-traffic window.
330
+ - The cached layer under `layers/prisma` rebuilds on the flip: its marker records the Prisma binary target, the client set and the core and `@prisma/client` versions, and a mismatch rebuilds.
331
+ - The first compose after upgrading to a Frigg release with this support rebuilds the Prisma layer once, because cache markers written by older releases never match.
305
332
 
306
333
  ## Usage Examples
307
334
 
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Shared cases for every builder whose functions bundle Prisma when the
3
+ * Prisma layer is off.
4
+ * @param {(usePrismaLayer: boolean, architecture?: string) => Promise<Object[]>|Object[]} functionsOf
5
+ * Builds the app and returns its function definitions
6
+ */
7
+ function itBundlesOnlyTheTargetPrismaEngine(functionsOf) {
8
+ it.each([
9
+ [undefined, 'rhel-openssl-3.0.x', 'linux-arm64-openssl-3.0.x'],
10
+ ['x86_64', 'rhel-openssl-3.0.x', 'linux-arm64-openssl-3.0.x'],
11
+ ['arm64', 'linux-arm64-openssl-3.0.x', 'rhel-openssl-3.0.x'],
12
+ ])(
13
+ 'with the layer off and architecture %s, the bundled Prisma keeps only the %s engine',
14
+ async (architecture, target, otherTarget) => {
15
+ for (const fn of await functionsOf(false, architecture)) {
16
+ expect(fn.package.exclude).toEqual(
17
+ expect.arrayContaining([
18
+ '**/libquery_engine-debian*',
19
+ `**/libquery_engine-${otherTarget}*`,
20
+ ])
21
+ );
22
+ expect(fn.package.exclude).not.toContain(`**/libquery_engine-${target}*`);
23
+ }
24
+ }
25
+ );
26
+
27
+ it('with the layer on, adds no engine patterns, since the layer carries the engines', async () => {
28
+ for (const fn of await functionsOf(true, 'arm64')) {
29
+ expect(fn.package.exclude).not.toEqual(
30
+ expect.arrayContaining(['**/libquery_engine-rhel-openssl-3.0.x*'])
31
+ );
32
+ expect(fn.package.exclude).not.toEqual(
33
+ expect.arrayContaining(['**/libquery_engine-debian*'])
34
+ );
35
+ }
36
+ });
37
+ }
38
+
39
+ module.exports = { itBundlesOnlyTheTargetPrismaEngine };
@@ -37,6 +37,9 @@ jest.mock('../domains/shared/resource-discovery', () => {
37
37
  }),
38
38
  };
39
39
  });
40
+ jest.mock('../domains/database/migration-engines', () => ({
41
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
42
+ }));
40
43
 
41
44
  // createIntegrationRouter loads the app definition from the consuming
42
45
  // backend; give it an empty one so the router can be built in isolation.
@@ -36,6 +36,9 @@ const accountWithDefaultVpc = (overrides = {}) => ({
36
36
  defaultRouteTableId: 'rtb-12345',
37
37
  ...overrides,
38
38
  });
39
+ jest.mock('../domains/database/migration-engines', () => ({
40
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
41
+ }));
39
42
 
40
43
  const postgresApp = (postgres, extra = {}) => ({
41
44
  name: 'test-app',
@@ -146,3 +146,6 @@ describe('frigg init default infrastructure', () => {
146
146
  expect(definition.provider.logRetentionInDays).toBe(14);
147
147
  });
148
148
  });
149
+ jest.mock('../domains/database/migration-engines', () => ({
150
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
151
+ }));
@@ -24,6 +24,9 @@ jest.mock('../domains/shared/resource-discovery', () => {
24
24
  }),
25
25
  };
26
26
  });
27
+ jest.mock('../domains/database/migration-engines', () => ({
28
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
29
+ }));
27
30
 
28
31
  const buildApp = (overrides = {}) => ({
29
32
  name: 'scoped-test-app',
@@ -23,6 +23,9 @@ jest.mock('../domains/shared/resource-discovery', () => {
23
23
  }),
24
24
  };
25
25
  });
26
+ jest.mock('../domains/database/migration-engines', () => ({
27
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
28
+ }));
26
29
 
27
30
  const buildApp = (overrides = {}) => ({
28
31
  name: 'preload-test',
@@ -631,6 +631,9 @@ describe('CloudFormation Template Generation', () => {
631
631
  });
632
632
  });
633
633
  });
634
+ jest.mock('../domains/database/migration-engines', () => ({
635
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
636
+ }));
634
637
 
635
638
  // Helper functions
636
639
  function findAllRefs(obj, refs = []) {
@@ -40,6 +40,9 @@ jest.mock('./domains/shared/resource-discovery', () => {
40
40
  const actual = jest.requireActual('./domains/shared/resource-discovery');
41
41
  return { ...actual, gatherDiscoveredResources: jest.fn() };
42
42
  });
43
+ jest.mock('./domains/database/migration-engines', () => ({
44
+ ensureMigrationEngines: jest.fn().mockResolvedValue(undefined),
45
+ }));
43
46
  jest.mock('./domains/shared/utilities/prisma-layer-manager', () => ({
44
47
  ensurePrismaLayerExists: jest.fn().mockResolvedValue(undefined),
45
48
  }));
@@ -278,6 +281,7 @@ const MATRIX = {
278
281
  },
279
282
  lambda: { scopedEnvironment: true, keepNestedNodeModules: false },
280
283
  usePrismaLambdaLayer: true,
284
+ architecture: 'x86_64',
281
285
  }),
282
286
  'frigg init scaffold (external db, no vpc)': () => ({
283
287
  ...base(),
@@ -294,6 +298,7 @@ const MATRIX = {
294
298
  database: { postgres: { enable: true, management: 'external' } },
295
299
  logging: { retentionInDays: 14 },
296
300
  ssm: { enable: false },
301
+ architecture: 'arm64',
297
302
  }),
298
303
  'external db, encryption none': () => ({
299
304
  ...base(),
@@ -16,6 +16,7 @@
16
16
  const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
17
17
  const { isScopedEnvironmentActive } = require('../shared/function-environments');
18
18
  const { nestedNodeModulesExcludes } = require('../shared/utilities/nested-node-modules');
19
+ const { bundledPrismaEngineExcludes } = require('../shared/lambda-architectures');
19
20
 
20
21
  class AdminScriptBuilder extends InfrastructureBuilder {
21
22
  constructor() {
@@ -412,6 +413,7 @@ class AdminScriptBuilder extends InfrastructureBuilder {
412
413
  'node_modules/@friggframework/core/generated/**',
413
414
  ]
414
415
  : []),
416
+ ...bundledPrismaEngineExcludes(appDefinition, usePrismaLayer),
415
417
  ...nestedNodeModulesExcludes(appDefinition, usePrismaLayer),
416
418
  'node_modules/@friggframework/test/**',
417
419
  'node_modules/@friggframework/eslint-config/**',
@@ -10,6 +10,7 @@
10
10
 
11
11
  const { AdminScriptBuilder } = require('./admin-script-builder');
12
12
  const { ValidationResult } = require('../shared/base-builder');
13
+ const { itBundlesOnlyTheTargetPrismaEngine } = require('../../__tests__/helpers/bundled-prisma-engine-excludes');
13
14
 
14
15
  describe('AdminScriptBuilder', () => {
15
16
  let adminScriptBuilder;
@@ -963,6 +964,21 @@ describe('AdminScriptBuilder', () => {
963
964
  });
964
965
  });
965
966
 
967
+ describe('Lambda architecture with usePrismaLambdaLayer=false', () => {
968
+ const functionsOf = async (usePrismaLambdaLayer, architecture) => {
969
+ const result = await adminScriptBuilder.build(
970
+ {
971
+ adminScripts: [{ Definition: { name: 'cleanup' } }],
972
+ usePrismaLambdaLayer,
973
+ ...(architecture && { architecture }),
974
+ },
975
+ {}
976
+ );
977
+ return Object.values(result.functions);
978
+ };
979
+ itBundlesOnlyTheTargetPrismaEngine(functionsOf);
980
+ });
981
+
966
982
  describe('getName()', () => {
967
983
  it('should return AdminScriptBuilder', () => {
968
984
  expect(adminScriptBuilder.getName()).toBe('AdminScriptBuilder');
@@ -1025,23 +1041,23 @@ describe('AdminScriptBuilder nested node_modules (lambda.keepNestedNodeModules)'
1025
1041
  result.functions.adminScriptRouter,
1026
1042
  ];
1027
1043
 
1028
- it('excludes every nested node_modules by default', async () => {
1044
+ it('keeps nested node_modules by default, still excluding nested Frigg copies', async () => {
1029
1045
  const result = await new AdminScriptBuilder().build(appDefinition(), {});
1030
1046
 
1031
1047
  for (const fn of executorAndRouter(result)) {
1032
- expect(fn.package.exclude).toContain('node_modules/**/node_modules/**');
1048
+ expect(fn.package.exclude).not.toContain('node_modules/**/node_modules/**');
1049
+ expect(fn.package.exclude).toContain('node_modules/**/node_modules/@friggframework/**');
1033
1050
  }
1034
1051
  });
1035
1052
 
1036
- it('keeps nested node_modules when the app opts in, still excluding nested Frigg copies', async () => {
1053
+ it('excludes every nested node_modules when the app opts out', async () => {
1037
1054
  const result = await new AdminScriptBuilder().build(
1038
- appDefinition({ keepNestedNodeModules: true }),
1055
+ appDefinition({ keepNestedNodeModules: false }),
1039
1056
  {}
1040
1057
  );
1041
1058
 
1042
1059
  for (const fn of executorAndRouter(result)) {
1043
- expect(fn.package.exclude).not.toContain('node_modules/**/node_modules/**');
1044
- expect(fn.package.exclude).toContain('node_modules/**/node_modules/@friggframework/**');
1060
+ expect(fn.package.exclude).toContain('node_modules/**/node_modules/**');
1045
1061
  }
1046
1062
  });
1047
1063
  });
@@ -16,6 +16,12 @@
16
16
  const { InfrastructureBuilder, ValidationResult } = require('../shared/base-builder');
17
17
  const { isScopedEnvironmentActive } = require('../shared/function-environments');
18
18
  const { nestedNodeModulesExcludes } = require('../shared/utilities/nested-node-modules');
19
+ const {
20
+ resolveLambdaArchitecture,
21
+ PRISMA_ENGINES_PACKAGE_DIR,
22
+ prismaEngineFileNames,
23
+ foreignPrismaEngineExcludes,
24
+ } = require('../shared/lambda-architectures');
19
25
  const { MigrationResourceResolver } = require('./migration-resolver');
20
26
  const { createEmptyDiscoveryResult, ResourceOwnership } = require('../shared/types');
21
27
 
@@ -239,6 +245,9 @@ class MigrationBuilder extends InfrastructureBuilder {
239
245
  async createFunctionDefinitions(result, usePrismaLayer = true, appDefinition = {}) {
240
246
  console.log(' 🔍 DEBUG: createFunctionDefinitions called');
241
247
  console.log(' 🔍 DEBUG: result.functions is:', typeof result.functions, result.functions);
248
+ const architecture = resolveLambdaArchitecture(appDefinition);
249
+ const engineExcludes = foreignPrismaEngineExcludes(architecture.name);
250
+ const engines = prismaEngineFileNames(architecture.prismaBinaryTarget);
242
251
  // Migration WORKER package config (needs Prisma CLI WASM files)
243
252
  const migrationWorkerPackageConfig = {
244
253
  individually: true,
@@ -293,12 +302,14 @@ class MigrationBuilder extends InfrastructureBuilder {
293
302
  'node_modules/@friggframework/core/handlers/routers/integration-*.js',
294
303
  'node_modules/@friggframework/core/handlers/workers/integration-*.js',
295
304
 
296
- // Exclude wrong OS binaries
305
+ // Exclude the engines of every platform and architecture this
306
+ // stack does not run on
297
307
  '**/query-engine-darwin*',
298
308
  '**/schema-engine-darwin*',
299
309
  '**/libquery_engine-darwin*',
300
310
  '**/*-darwin-arm64*',
301
311
  '**/*-darwin*',
312
+ ...engineExcludes,
302
313
 
303
314
  // Migration worker DOES need Prisma CLI WASM files (for migrate deploy)
304
315
  // Only exclude runtime engine WASM (query engine internals)
@@ -385,12 +396,14 @@ class MigrationBuilder extends InfrastructureBuilder {
385
396
  'node_modules/@friggframework/core/handlers/routers/integration-*.js',
386
397
  'node_modules/@friggframework/core/handlers/workers/**',
387
398
 
388
- // Exclude wrong OS binaries
399
+ // Exclude the engines of every platform and architecture this
400
+ // stack does not run on
389
401
  '**/query-engine-darwin*',
390
402
  '**/schema-engine-darwin*',
391
403
  '**/libquery_engine-darwin*',
392
404
  '**/*-darwin-arm64*',
393
405
  '**/*-darwin*',
406
+ ...engineExcludes,
394
407
 
395
408
  // Router doesn't run migrations - exclude ALL WASM files
396
409
  '**/runtime/*.wasm',
@@ -438,6 +451,12 @@ class MigrationBuilder extends InfrastructureBuilder {
438
451
  environment: {
439
452
  // Ensure migration functions get DATABASE_URL from provider.environment
440
453
  // Note: Serverless will merge this with provider.environment
454
+
455
+ // Pin the migrate CLI to the shipped engines. With these set,
456
+ // Prisma neither downloads an engine at cold start (into the
457
+ // read-only /var/task) nor picks another file.
458
+ PRISMA_SCHEMA_ENGINE_BINARY: `/var/task/${PRISMA_ENGINES_PACKAGE_DIR}/${engines.schemaEngine}`,
459
+ PRISMA_QUERY_ENGINE_LIBRARY: `/var/task/${PRISMA_ENGINES_PACKAGE_DIR}/${engines.queryEngineLibrary}`,
441
460
  },
442
461
  events: [
443
462
  {
@@ -322,6 +322,61 @@ describe('MigrationBuilder', () => {
322
322
  });
323
323
  });
324
324
 
325
+ describe('Lambda architecture (architecture)', () => {
326
+ const baseAppDefinition = { database: { postgres: { enable: true } } };
327
+ const workerAndRouter = (result) => [
328
+ result.functions.dbMigrationWorker,
329
+ result.functions.dbMigrationRouter,
330
+ ];
331
+
332
+ it.each([
333
+ [undefined, 'rhel-openssl-3.0.x', 'linux-arm64-openssl-3.0.x'],
334
+ ['x86_64', 'rhel-openssl-3.0.x', 'linux-arm64-openssl-3.0.x'],
335
+ ['arm64', 'linux-arm64-openssl-3.0.x', 'rhel-openssl-3.0.x'],
336
+ ])(
337
+ 'with architecture %s the worker and router ship only the %s engines',
338
+ async (architecture, target, otherTarget) => {
339
+ const result = await builder.build(
340
+ { ...baseAppDefinition, ...(architecture && { architecture }) },
341
+ {}
342
+ );
343
+
344
+ for (const fn of workerAndRouter(result)) {
345
+ expect(fn.package.exclude).toEqual(
346
+ expect.arrayContaining([
347
+ '**/libquery_engine-debian*',
348
+ '**/libquery_engine-linux-musl*',
349
+ `**/libquery_engine-${otherTarget}*`,
350
+ ])
351
+ );
352
+ expect(fn.package.exclude).not.toContain(`**/libquery_engine-${target}*`);
353
+ }
354
+ }
355
+ );
356
+
357
+ it.each([
358
+ [undefined, 'rhel-openssl-3.0.x'],
359
+ ['x86_64', 'rhel-openssl-3.0.x'],
360
+ ['arm64', 'linux-arm64-openssl-3.0.x'],
361
+ ])(
362
+ 'with architecture %s the worker pins the migrate CLI to the shipped %s engines',
363
+ async (architecture, target) => {
364
+ const result = await builder.build(
365
+ { ...baseAppDefinition, ...(architecture && { architecture }) },
366
+ {}
367
+ );
368
+
369
+ expect(result.functions.dbMigrationWorker.environment).toEqual(
370
+ expect.objectContaining({
371
+ PRISMA_SCHEMA_ENGINE_BINARY: `/var/task/node_modules/@prisma/engines/schema-engine-${target}`,
372
+ PRISMA_QUERY_ENGINE_LIBRARY: `/var/task/node_modules/@prisma/engines/libquery_engine-${target}.so.node`,
373
+ })
374
+ );
375
+ expect(result.functions.dbMigrationRouter.environment.PRISMA_SCHEMA_ENGINE_BINARY).toBeUndefined();
376
+ }
377
+ );
378
+ });
379
+
325
380
  describe('scoped environment (lambda.scopedEnvironment)', () => {
326
381
  beforeEach(() => {
327
382
  delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
@@ -432,23 +487,23 @@ describe('MigrationBuilder nested node_modules (lambda.keepNestedNodeModules)',
432
487
  result.functions.dbMigrationRouter,
433
488
  ];
434
489
 
435
- it('excludes every nested node_modules by default', async () => {
490
+ it('keeps nested node_modules by default, still excluding nested Frigg copies', async () => {
436
491
  const result = await new MigrationBuilder().build(baseAppDefinition, {});
437
492
 
438
493
  for (const fn of workerAndRouter(result)) {
439
- expect(fn.package.exclude).toContain('node_modules/**/node_modules/**');
494
+ expect(fn.package.exclude).not.toContain('node_modules/**/node_modules/**');
495
+ expect(fn.package.exclude).toContain('node_modules/**/node_modules/@friggframework/**');
440
496
  }
441
497
  });
442
498
 
443
- it('keeps nested node_modules when the app opts in, still excluding nested Frigg copies', async () => {
499
+ it('excludes every nested node_modules when the app opts out', async () => {
444
500
  const result = await new MigrationBuilder().build(
445
- { ...baseAppDefinition, lambda: { keepNestedNodeModules: true } },
501
+ { ...baseAppDefinition, lambda: { keepNestedNodeModules: false } },
446
502
  {}
447
503
  );
448
504
 
449
505
  for (const fn of workerAndRouter(result)) {
450
- expect(fn.package.exclude).not.toContain('node_modules/**/node_modules/**');
451
- expect(fn.package.exclude).toContain('node_modules/**/node_modules/@friggframework/**');
506
+ expect(fn.package.exclude).toContain('node_modules/**/node_modules/**');
452
507
  }
453
508
  });
454
509
  });
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Migration worker engines
3
+ *
4
+ * Domain Layer - Hexagonal Architecture
5
+ *
6
+ * The migration worker runs the Prisma CLI, which needs the schema engine
7
+ * and the query engine library for the Lambda architecture it runs on. Both
8
+ * ship from node_modules/@prisma/engines/, where the @prisma/engines
9
+ * postinstall put the deploy host's own engines. This fetches the deployed
10
+ * architecture's pair before packaging, and fails packaging when either is
11
+ * still missing, so a worker can never try to download an engine into the
12
+ * read-only /var/task at cold start.
13
+ */
14
+
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const { execFileSync } = require('child_process');
18
+ const { prismaEngineFileNames, PRISMA_ENGINES_PACKAGE_DIR } = require('../shared/lambda-architectures');
19
+
20
+ function resolveEnginesDir(cwd) {
21
+ const enginesDir = path.join(cwd, PRISMA_ENGINES_PACKAGE_DIR);
22
+ if (!fs.existsSync(path.join(enginesDir, 'scripts', 'postinstall.js'))) {
23
+ throw new Error(
24
+ `@prisma/engines was not found at ${enginesDir}.\n` +
25
+ 'The app must have prisma installed in its own node_modules, not only in a hoisted parent: ' +
26
+ 'the migration worker ships its engines from the app\'s node_modules.'
27
+ );
28
+ }
29
+ return enginesDir;
30
+ }
31
+
32
+ /**
33
+ * Runs the @prisma/engines postinstall for one target. It downloads only
34
+ * the engines that are missing, so the host's own engines stay. The host's
35
+ * pinned engine paths are hidden from it: with them set, the postinstall
36
+ * skips those engines instead of downloading them.
37
+ */
38
+ function runEnginesPostinstall({ enginesDir, prismaBinaryTarget }) {
39
+ const hostEnv = { ...process.env };
40
+ delete hostEnv.PRISMA_SCHEMA_ENGINE_BINARY;
41
+ delete hostEnv.PRISMA_QUERY_ENGINE_LIBRARY;
42
+ execFileSync(
43
+ process.execPath,
44
+ [path.join(enginesDir, 'scripts', 'postinstall.js')],
45
+ {
46
+ cwd: enginesDir,
47
+ stdio: 'inherit',
48
+ env: { ...hostEnv, PRISMA_CLI_BINARY_TARGETS: prismaBinaryTarget },
49
+ }
50
+ );
51
+ }
52
+
53
+ /**
54
+ * @param {Object} options
55
+ * @param {string} options.prismaBinaryTarget - The engine the deployed architecture loads
56
+ * @param {string} [options.cwd] - The app root
57
+ * @param {string} [options.enginesDir] - node_modules/@prisma/engines of the app
58
+ * @param {Function} [options.fetchEngines] - Fetches the target's engines into enginesDir
59
+ * @throws {Error} When either engine is missing after the fetch
60
+ */
61
+ async function ensureMigrationEngines({
62
+ prismaBinaryTarget,
63
+ cwd = process.cwd(),
64
+ enginesDir = resolveEnginesDir(cwd),
65
+ fetchEngines = runEnginesPostinstall,
66
+ }) {
67
+ const engineNames = Object.values(prismaEngineFileNames(prismaBinaryTarget));
68
+ const missing = () =>
69
+ engineNames.filter((name) => !fs.existsSync(path.join(enginesDir, name)));
70
+
71
+ if (missing().length === 0) {
72
+ console.log(`✓ Prisma ${prismaBinaryTarget} migration engines present in ${enginesDir}`);
73
+ return;
74
+ }
75
+
76
+ console.log(
77
+ `📦 Fetching ${missing().join(', ')} (Prisma ${prismaBinaryTarget}) into ${enginesDir}...`
78
+ );
79
+ fetchEngines({ enginesDir, prismaBinaryTarget });
80
+
81
+ const stillMissing = missing();
82
+ if (stillMissing.length > 0) {
83
+ throw new Error(
84
+ `Prisma migration engines for ${prismaBinaryTarget} are missing after the fetch: ` +
85
+ `${stillMissing.join(', ')} (in ${enginesDir}).\n` +
86
+ "The deploy host must reach Prisma's engine CDN (binaries.prisma.sh) at package time."
87
+ );
88
+ }
89
+ }
90
+
91
+ module.exports = {
92
+ ensureMigrationEngines,
93
+ };