@friggframework/devtools 2.0.0--canary.691.01b391d.0 → 2.0.0--canary.686.ba9ded3.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,119 @@
1
+ /**
2
+ * Build for a non-AWS provider (friggframework/frigg#545, 302ab9ba /
3
+ * c8705715).
4
+ *
5
+ * Instead of the serverless/CloudFormation pipeline, the provider plugin
6
+ * (resolved from appDefinition.provider) does the build:
7
+ * 1. validate(appDefinition) - errors abort, warnings print
8
+ * 2. generateConfig(appDefinition) - e.g. netlify.toml
9
+ * 3. getFunctionEntryPoints(appDefinition) - written to <project>/netlify/functions
10
+ * 4. getLibEntryPoints(appDefinition) - written to <project>/netlify/lib
11
+ *
12
+ * <project> is the directory that holds backend/: the generated entry points
13
+ * require '../../backend/...', so they must sit beside it. #545 had two
14
+ * copies of this, and the CLI one wrote into the backend directory itself,
15
+ * where those relative requires do not resolve.
16
+ *
17
+ * Shared by createFriggInfrastructure() (`node infrastructure.js package`,
18
+ * what a backend's `npm run build` runs) and `frigg build`.
19
+ */
20
+ const path = require('path');
21
+ const fs = require('fs');
22
+
23
+ const CONFIG_FILE_NAMES = { netlify: 'netlify.toml' };
24
+
25
+ /**
26
+ * @param {Object} params
27
+ * @param {Object} params.appDefinition
28
+ * @param {string} params.backendDir - directory containing the backend's index.js
29
+ * @param {Object} [params.provider] - resolved plugin; defaults to resolveProvider(appDefinition)
30
+ * @param {boolean} [params.verbose]
31
+ * @param {Function} [params.exit] - called with 1 on validation errors (default process.exit)
32
+ * @returns {{ projectDir: string, written: string[] }}
33
+ */
34
+ function buildWithProvider({
35
+ appDefinition,
36
+ backendDir,
37
+ provider,
38
+ verbose = false,
39
+ exit = (code) => process.exit(code),
40
+ }) {
41
+ const providerName = appDefinition.provider;
42
+ const plugin =
43
+ provider ||
44
+ require('@friggframework/core/providers/resolve-provider').resolveProvider(
45
+ appDefinition
46
+ );
47
+ const projectDir = path.dirname(path.resolve(backendDir));
48
+ const written = [];
49
+
50
+ console.log(`Building for ${providerName} provider (skipping AWS infrastructure)...`);
51
+
52
+ if (typeof plugin.validate === 'function') {
53
+ const validation = plugin.validate(appDefinition);
54
+ if (validation.errors?.length > 0) {
55
+ console.error(`\nValidation errors for ${providerName}:`);
56
+ for (const error of validation.errors) {
57
+ console.error(` - ${error}`);
58
+ }
59
+ exit(1);
60
+ return { projectDir, written };
61
+ }
62
+ for (const warning of validation.warnings || []) {
63
+ console.warn(` Warning: ${warning}`);
64
+ }
65
+ }
66
+
67
+ const write = (filePath, content) => {
68
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
69
+ fs.writeFileSync(filePath, content, 'utf-8');
70
+ written.push(filePath);
71
+ if (verbose) console.log(` Written ${path.relative(projectDir, filePath)}`);
72
+ };
73
+
74
+ if (typeof plugin.generateConfig === 'function') {
75
+ const fileName = CONFIG_FILE_NAMES[providerName] || `${providerName}.config`;
76
+ write(path.join(projectDir, fileName), plugin.generateConfig(appDefinition));
77
+ console.log(` Written ${fileName}`);
78
+ }
79
+
80
+ if (typeof plugin.getFunctionEntryPoints === 'function') {
81
+ const entryPoints = plugin.getFunctionEntryPoints(appDefinition);
82
+ for (const [fileName, content] of Object.entries(entryPoints)) {
83
+ write(path.join(projectDir, 'netlify', 'functions', fileName), content);
84
+ }
85
+ console.log(` Generated ${Object.keys(entryPoints).length} function entry points`);
86
+ }
87
+
88
+ if (typeof plugin.getLibEntryPoints === 'function') {
89
+ const libEntryPoints = plugin.getLibEntryPoints(appDefinition);
90
+ for (const [fileName, content] of Object.entries(libEntryPoints)) {
91
+ write(path.join(projectDir, 'netlify', 'lib', fileName), content);
92
+ }
93
+ console.log(` Generated ${Object.keys(libEntryPoints).length} lib entry points`);
94
+ }
95
+
96
+ if (typeof plugin.generateEnvTemplate === 'function') {
97
+ const missing = Object.entries(plugin.generateEnvTemplate(appDefinition)).filter(
98
+ ([key]) => !process.env[key]
99
+ );
100
+ if (missing.length > 0) {
101
+ console.log('\n Environment variables not set locally (configure them on the platform):');
102
+ for (const [key] of missing) console.log(` - ${key}`);
103
+ }
104
+ }
105
+
106
+ console.log(`\nBuild complete for ${providerName}.`);
107
+ return { projectDir, written };
108
+ }
109
+
110
+ /**
111
+ * True when the app definition names a provider other than AWS.
112
+ * @param {Object} [appDefinition]
113
+ */
114
+ function isNonAwsProvider(appDefinition) {
115
+ const name = appDefinition?.provider;
116
+ return Boolean(name) && name !== 'aws';
117
+ }
118
+
119
+ module.exports = { buildWithProvider, isNonAwsProvider };
@@ -249,6 +249,36 @@ async function createLayerStructure() {
249
249
  logSuccess(`Created ${LAYER_NODE_MODULES}`);
250
250
  }
251
251
 
252
+ /**
253
+ * Run `npm install --omit=dev` confined to the layer directory.
254
+ *
255
+ * npm resolves its project root by walking up from cwd to the nearest
256
+ * package.json. If the layer's package.json is missing when npm starts (a
257
+ * concurrent build cleaned the directory, as two jest workers composing at
258
+ * once did), npm walked up into the enclosing workspace and ran
259
+ * `install --omit=dev` there, pruning the devDependencies (jest, jest-util)
260
+ * out of the repository's root node_modules. So: the package.json must exist,
261
+ * and `--prefix` pins npm's root to the layer directory while
262
+ * `--workspaces=false` stops it acting on an enclosing workspace.
263
+ *
264
+ * @param {string} layerNodejsDir - absolute path of <layer>/nodejs
265
+ * @param {Object} [options]
266
+ * @param {Object} [options.env]
267
+ * @param {Function} [options.exec] - execSync stand-in (tests)
268
+ */
269
+ function runLayerInstall(layerNodejsDir, { env = process.env, exec = execSync } = {}) {
270
+ const manifest = path.join(layerNodejsDir, 'package.json');
271
+ if (!fs.existsSync(manifest)) {
272
+ throw new Error(
273
+ `Refusing to run npm install: ${manifest} does not exist (npm would install into an enclosing project)`
274
+ );
275
+ }
276
+ exec(
277
+ `npm install --omit=dev --no-package-lock --workspaces=false --prefix ${JSON.stringify(layerNodejsDir)}`,
278
+ { cwd: layerNodejsDir, stdio: 'inherit', env }
279
+ );
280
+ }
281
+
252
282
  /**
253
283
  * Install Prisma client directly into layer (RUNTIME ONLY - NO CLI)
254
284
  *
@@ -285,11 +315,7 @@ async function installPrismaPackages() {
285
315
  PRISMA_CLI_BINARY_TARGETS: 'rhel-openssl-3.0.x',
286
316
  };
287
317
 
288
- execSync('npm install --omit=dev --no-package-lock', {
289
- cwd: path.join(LAYER_OUTPUT_PATH, 'nodejs'),
290
- stdio: 'inherit',
291
- env,
292
- });
318
+ runLayerInstall(path.join(LAYER_OUTPUT_PATH, 'nodejs'), { env });
293
319
  logSuccess('Prisma packages installed with Lambda binary target');
294
320
  } catch (error) {
295
321
  throw new Error(`Failed to install Prisma packages: ${error.message}`);
@@ -693,6 +719,7 @@ if (require.main === module) {
693
719
 
694
720
  module.exports = {
695
721
  buildPrismaLayer,
722
+ runLayerInstall,
696
723
  getGeneratedClientPackages,
697
724
  getMigrationsPackages,
698
725
  getMigrationSourcePath,
@@ -168,3 +168,38 @@ describe('getMigrationDestinationPath()', () => {
168
168
  );
169
169
  });
170
170
  });
171
+
172
+
173
+ describe('runLayerInstall', () => {
174
+ const fs = require('fs');
175
+ const os = require('os');
176
+ const path = require('path');
177
+ const { runLayerInstall } = require('./build-prisma-layer');
178
+
179
+ it('refuses when the layer package.json is missing (npm would walk up into the workspace)', () => {
180
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'layer-'));
181
+ const exec = jest.fn();
182
+ try {
183
+ expect(() => runLayerInstall(dir, { exec })).toThrow(/Refusing to run npm install/);
184
+ expect(exec).not.toHaveBeenCalled();
185
+ } finally {
186
+ fs.rmSync(dir, { recursive: true, force: true });
187
+ }
188
+ });
189
+
190
+ it('pins npm to the layer directory and off any enclosing workspace', () => {
191
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'layer-'));
192
+ fs.writeFileSync(path.join(dir, 'package.json'), '{}');
193
+ const exec = jest.fn();
194
+ try {
195
+ runLayerInstall(dir, { exec, env: { X: '1' } });
196
+ const [command, options] = exec.mock.calls[0];
197
+ expect(command).toContain('npm install --omit=dev');
198
+ expect(command).toContain('--workspaces=false');
199
+ expect(command).toContain(`--prefix ${JSON.stringify(dir)}`);
200
+ expect(options).toMatchObject({ cwd: dir, env: { X: '1' } });
201
+ } finally {
202
+ fs.rmSync(dir, { recursive: true, force: true });
203
+ }
204
+ });
205
+ });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@friggframework/devtools",
3
3
  "prettier": "@friggframework/prettier-config",
4
- "version": "2.0.0--canary.691.01b391d.0",
4
+ "version": "2.0.0--canary.686.ba9ded3.0",
5
5
  "bin": {
6
6
  "frigg": "./frigg-cli/index.js"
7
7
  },
@@ -26,9 +26,9 @@
26
26
  "@babel/eslint-parser": "^7.18.9",
27
27
  "@babel/parser": "^7.25.3",
28
28
  "@babel/traverse": "^7.25.3",
29
- "@friggframework/core": "2.0.0--canary.691.01b391d.0",
30
- "@friggframework/schemas": "2.0.0--canary.691.01b391d.0",
31
- "@friggframework/test": "2.0.0--canary.691.01b391d.0",
29
+ "@friggframework/core": "2.0.0--canary.686.ba9ded3.0",
30
+ "@friggframework/schemas": "2.0.0--canary.686.ba9ded3.0",
31
+ "@friggframework/test": "2.0.0--canary.686.ba9ded3.0",
32
32
  "@hapi/boom": "^10.0.1",
33
33
  "@inquirer/prompts": "^5.3.8",
34
34
  "axios": "^1.18.0",
@@ -56,8 +56,8 @@
56
56
  "validate-npm-package-name": "^5.0.0"
57
57
  },
58
58
  "devDependencies": {
59
- "@friggframework/eslint-config": "2.0.0--canary.691.01b391d.0",
60
- "@friggframework/prettier-config": "2.0.0--canary.691.01b391d.0",
59
+ "@friggframework/eslint-config": "2.0.0--canary.686.ba9ded3.0",
60
+ "@friggframework/prettier-config": "2.0.0--canary.686.ba9ded3.0",
61
61
  "aws-sdk-client-mock": "^4.1.0",
62
62
  "aws-sdk-client-mock-jest": "^4.1.0",
63
63
  "jest": "^30.1.3",
@@ -89,5 +89,5 @@
89
89
  "publishConfig": {
90
90
  "access": "public"
91
91
  },
92
- "gitHead": "01b391d641213f90ddc692629a531c014985ff43"
92
+ "gitHead": "ba9ded3f6b459c74127bac73ac5c0696a1144421"
93
93
  }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Jest setup: no test may run a package-manager command that rewrites a
3
+ * node_modules tree outside the OS temp directory.
4
+ *
5
+ * Why: two infrastructure tests composed a serverless definition in parallel,
6
+ * each building the real Prisma layer under packages/devtools/layers/prisma.
7
+ * One cleaned the layer while the other's `npm install --omit=dev` was
8
+ * starting, npm found no package.json in its cwd, walked up into the
9
+ * monorepo workspace and pruned the devDependencies (jest, jest-util) out of
10
+ * the repository's root node_modules. Every later workspace then failed with
11
+ * `jest: not found`.
12
+ *
13
+ * The guard wraps the real child_process functions. A test that mocks
14
+ * child_process (jest.mock) gets its mock and is unaffected; anything that
15
+ * reaches the real module with, for example, `npm install` in a repository
16
+ * directory throws instead of running.
17
+ */
18
+ const childProcess = require('child_process');
19
+ const fs = require('fs');
20
+ const os = require('os');
21
+ const path = require('path');
22
+
23
+ const PACKAGE_MANAGERS = new Set(['npm', 'npx', 'yarn', 'pnpm']);
24
+ const MUTATING = new Set([
25
+ 'install', 'i', 'in', 'ci', 'add', 'prune', 'uninstall', 'remove', 'rm', 'r', 'un',
26
+ 'update', 'up', 'upgrade', 'dedupe', 'link', 'rebuild',
27
+ ]);
28
+
29
+ function realpathOrSelf(p) {
30
+ try {
31
+ return fs.realpathSync(p);
32
+ } catch {
33
+ return path.resolve(p);
34
+ }
35
+ }
36
+
37
+ const TMP = realpathOrSelf(os.tmpdir());
38
+ // The monorepo root (packages/devtools/test -> ../../..). A checkout can
39
+ // itself live under the temp directory, so "under tmp" alone is not enough.
40
+ const REPO_ROOT = realpathOrSelf(path.resolve(__dirname, '..', '..', '..'));
41
+
42
+ const within = (dir, root) => dir === root || dir.startsWith(root + path.sep);
43
+
44
+ /** True only for a scratch directory: under tmp and outside this repository. */
45
+ function insideTmp(dir) {
46
+ const real = realpathOrSelf(dir);
47
+ return within(real, TMP) && !within(real, REPO_ROOT);
48
+ }
49
+
50
+ /** @returns {string|null} the offending command, or null when allowed */
51
+ function offending(tokens, cwd) {
52
+ const [bin, ...args] = tokens;
53
+ if (!bin || !PACKAGE_MANAGERS.has(path.basename(String(bin)))) return null;
54
+ const sub = args.find((a) => !String(a).startsWith('-'));
55
+ // npx <pkg> runs a package; only installs/prunes rewrite node_modules.
56
+ if (path.basename(String(bin)) === 'npx' || !MUTATING.has(sub)) return null;
57
+ const prefixAt = args.indexOf('--prefix');
58
+ const target = prefixAt >= 0 ? args[prefixAt + 1] : cwd;
59
+ if (insideTmp(target || process.cwd())) return null;
60
+ return tokens.join(' ');
61
+ }
62
+
63
+ const GUARDED = Symbol.for('frigg.devtools.npmInstallGuard');
64
+
65
+ function guard(name, fn, toTokens) {
66
+ // setupFiles runs once per test file in a shared worker: wrap once.
67
+ if (fn[GUARDED]) return fn;
68
+ const guarded = function guarded(...callArgs) {
69
+ const { tokens, cwd } = toTokens(callArgs);
70
+ const bad = offending(tokens, cwd);
71
+ if (bad) {
72
+ throw new Error(
73
+ `Test tried to run "${bad}" outside the temp directory (cwd ${cwd || process.cwd()}); ` +
74
+ 'it would rewrite a real node_modules. Mock it or run it in a temp dir.'
75
+ );
76
+ }
77
+ return fn.apply(this, callArgs);
78
+ };
79
+ guarded[GUARDED] = true;
80
+ return guarded;
81
+ }
82
+
83
+ const fromString = ([command, options]) => ({
84
+ tokens: String(command).trim().split(/\s+/),
85
+ cwd: options?.cwd,
86
+ });
87
+ const fromFile = ([file, args, options]) =>
88
+ Array.isArray(args)
89
+ ? { tokens: [file, ...args], cwd: options?.cwd }
90
+ : { tokens: [file], cwd: args?.cwd };
91
+
92
+ for (const name of ['execSync', 'exec']) {
93
+ childProcess[name] = guard(name, childProcess[name], fromString);
94
+ }
95
+ for (const name of ['execFileSync', 'execFile', 'spawn', 'spawnSync']) {
96
+ const original = childProcess[name];
97
+ childProcess[name] = guard(name, original, (callArgs) => {
98
+ const opts = Array.isArray(callArgs[1]) ? callArgs[2] : callArgs[1];
99
+ if (opts?.shell && !Array.isArray(callArgs[1])) return fromString([callArgs[0], opts]);
100
+ return fromFile(callArgs);
101
+ });
102
+ }
103
+
104
+ module.exports = { offending, insideTmp };
@@ -0,0 +1,53 @@
1
+ const os = require('os');
2
+ const path = require('path');
3
+ const childProcess = require('child_process');
4
+ // Read before this file loads the guard itself: jest's setupFiles must have
5
+ // installed it already, for every test file.
6
+ const guardedBySetup = Boolean(childProcess.execSync[Symbol.for('frigg.devtools.npmInstallGuard')]);
7
+ const { offending } = require('./npm-install-guard');
8
+
9
+ const repoDir = path.resolve(__dirname, '..');
10
+
11
+ describe('npm install guard (jest setupFiles)', () => {
12
+ // Every command here is a --dry-run, so even a broken guard that let it
13
+ // through could not rewrite this repository's node_modules.
14
+ it('is installed by jest setupFiles, before any test code runs', () => {
15
+ expect(guardedBySetup).toBe(true);
16
+ });
17
+
18
+ it('blocks installs and prunes on the real child_process', () => {
19
+ expect(() =>
20
+ childProcess.execSync('npm install --dry-run --omit=dev', { cwd: repoDir, stdio: 'ignore' })
21
+ ).toThrow(/outside the temp directory/);
22
+ expect(() =>
23
+ childProcess.spawnSync('npm', ['prune', '--dry-run'], { cwd: repoDir, stdio: 'ignore' })
24
+ ).toThrow(/outside the temp directory/);
25
+ expect(() =>
26
+ childProcess.execFileSync('/usr/bin/npm', ['ci', '--dry-run'], { cwd: repoDir, stdio: 'ignore' })
27
+ ).toThrow(/outside the temp directory/);
28
+ });
29
+
30
+ it('treats a temp dir inside this repository as part of the repository', () => {
31
+ // A checkout may itself live under os.tmpdir() (as in some sandboxes).
32
+ expect(offending(['npm', 'install'], path.join(repoDir, 'layers/prisma/nodejs'))).not.toBeNull();
33
+ });
34
+
35
+ it.each([
36
+ [['npm', 'install', '--omit=dev'], repoDir, true],
37
+ [['npm', 'ci'], repoDir, true],
38
+ [['yarn', 'add', 'x'], repoDir, true],
39
+ [['npm', 'install', '--prefix', repoDir], os.tmpdir(), true],
40
+ [['npm', 'install'], os.tmpdir(), false],
41
+ [['npm', 'install', '--prefix', path.join(os.tmpdir(), 'layer')], repoDir, false],
42
+ [['npm', 'root'], repoDir, false],
43
+ [['npm', 'run', 'build'], repoDir, false],
44
+ [['npx', 'netlify-cli', 'deploy'], repoDir, false],
45
+ [['git', 'install'], repoDir, false],
46
+ ])('%j in %s -> blocked %s', (tokens, cwd, blocked) => {
47
+ expect(offending(tokens, cwd) !== null).toBe(blocked);
48
+ });
49
+
50
+ it('lets harmless commands through', () => {
51
+ expect(childProcess.execSync('node -e "process.stdout.write(\'ok\')"', { encoding: 'utf8' })).toBe('ok');
52
+ });
53
+ });