@codapult/cli 0.4.2 → 0.6.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.
@@ -1,16 +1,25 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { ENV_FILE_NAME } from '../../utils/project-env.js';
2
3
  vi.mock('node:fs');
3
4
  vi.mock('node:child_process');
4
5
  vi.mock('../../utils/project.js', () => ({
5
6
  findProjectRoot: vi.fn(),
6
7
  readProjectFile: vi.fn(),
7
8
  }));
9
+ vi.mock('../../utils/project-env.js', () => ({
10
+ ENV_FILE_NAME: '.env.local',
11
+ getProjectEnvOptions: vi.fn((envSource) => ({ envFile: envSource !== 'process' })),
12
+ getProjectEnvSource: vi.fn((options) => options?.envFile === false ? 'process' : 'file'),
13
+ loadProjectEnv: vi.fn(),
14
+ }));
8
15
  const { existsSync, readFileSync, readdirSync } = await import('node:fs');
9
16
  const { execSync } = await import('node:child_process');
10
17
  const { findProjectRoot, readProjectFile } = await import('../../utils/project.js');
18
+ const { loadProjectEnv } = await import('../../utils/project-env.js');
11
19
  const { registerProjectTools } = await import('./project.js');
12
20
  const mockedFindRoot = vi.mocked(findProjectRoot);
13
21
  const mockedReadProject = vi.mocked(readProjectFile);
22
+ const mockedLoadProjectEnv = vi.mocked(loadProjectEnv);
14
23
  const mockedExists = vi.mocked(existsSync);
15
24
  const mockedRead = vi.mocked(readFileSync);
16
25
  const mockedReaddir = vi.mocked(readdirSync);
@@ -18,6 +27,12 @@ const mockedExec = vi.mocked(execSync);
18
27
  beforeEach(() => {
19
28
  vi.resetAllMocks();
20
29
  mockedFindRoot.mockReturnValue('/project');
30
+ mockedLoadProjectEnv.mockReturnValue({
31
+ source: 'file',
32
+ filePath: `/project/${ENV_FILE_NAME}`,
33
+ fileExists: false,
34
+ content: '',
35
+ });
21
36
  });
22
37
  function createMockServer() {
23
38
  const tools = [];
@@ -42,17 +57,18 @@ describe('registerProjectTools', () => {
42
57
  const server = createMockServer();
43
58
  registerProjectTools(server);
44
59
  mockedRead.mockReturnValue(JSON.stringify({ name: 'codapult', version: '1.0.0' }));
45
- mockedReadProject.mockImplementation((_root, path) => {
46
- if (path === '.env.local')
47
- return [
48
- 'AUTH_PROVIDER=kinde',
49
- 'PAYMENT_PROVIDER=lemonsqueezy',
50
- 'STORAGE_PROVIDER=s3',
51
- 'ENABLE_TEAMS=false',
52
- 'GOOGLE_CLIENT_ID=abc',
53
- 'GOOGLE_CLIENT_SECRET=def',
54
- ].join('\n');
55
- return null;
60
+ mockedLoadProjectEnv.mockReturnValue({
61
+ source: 'file',
62
+ filePath: `/project/${ENV_FILE_NAME}`,
63
+ fileExists: true,
64
+ content: [
65
+ 'AUTH_PROVIDER=kinde',
66
+ 'PAYMENT_PROVIDER=lemonsqueezy',
67
+ 'STORAGE_PROVIDER=s3',
68
+ 'ENABLE_TEAMS=false',
69
+ 'GOOGLE_CLIENT_ID=abc',
70
+ 'GOOGLE_CLIENT_SECRET=def',
71
+ ].join('\n'),
56
72
  });
57
73
  mockedExists.mockReturnValue(true);
58
74
  mockedReaddir.mockReturnValue(['ai-kit.ts', 'crm.ts', 'index.ts']);
@@ -81,6 +97,24 @@ describe('registerProjectTools', () => {
81
97
  expect(parsed.git.branch).toBe('main');
82
98
  expect(parsed.git.dirty).toBe(false);
83
99
  });
100
+ it('uses process env when requested', () => {
101
+ const server = createMockServer();
102
+ registerProjectTools(server);
103
+ mockedRead.mockReturnValue(JSON.stringify({ name: 'codapult', version: '1.0.0' }));
104
+ mockedLoadProjectEnv.mockReturnValue({
105
+ source: 'process',
106
+ filePath: `/project/${ENV_FILE_NAME}`,
107
+ fileExists: false,
108
+ content: 'AUTH_PROVIDER=none\nENABLE_BLOG=false',
109
+ });
110
+ mockedExists.mockReturnValue(true);
111
+ mockedReaddir.mockReturnValue([]);
112
+ const handler = server.tools.find((t) => t.name === 'codapult_project_status').handler;
113
+ const result = handler({ env_source: 'process' });
114
+ const parsed = JSON.parse(result.content[0].text);
115
+ expect(parsed.adapters.auth).toBe('none');
116
+ expect(mockedLoadProjectEnv).toHaveBeenCalledWith('/project', { envFile: false });
117
+ });
84
118
  });
85
119
  describe('codapult_project_config', () => {
86
120
  it('returns app.ts content', () => {
@@ -127,5 +161,16 @@ describe('registerProjectTools', () => {
127
161
  const failedChecks = parsed.filter((c) => c.status === 'fail');
128
162
  expect(failedChecks.length).toBeGreaterThan(0);
129
163
  });
164
+ it('reports process env source when requested', () => {
165
+ const server = createMockServer();
166
+ registerProjectTools(server);
167
+ mockedExists.mockReturnValue(true);
168
+ mockedExec.mockReturnValue(Buffer.from(''));
169
+ const handler = server.tools.find((t) => t.name === 'codapult_doctor').handler;
170
+ const result = handler({ env_source: 'process' });
171
+ const parsed = JSON.parse(result.content[0].text);
172
+ const envCheck = parsed.find((c) => c.name === 'Environment source');
173
+ expect(envCheck?.detail).toBe('process.env');
174
+ });
130
175
  });
131
176
  });
@@ -0,0 +1,5 @@
1
+ import { z } from 'zod';
2
+ export declare const envSourceSchema: z.ZodDefault<z.ZodEnum<{
3
+ file: "file";
4
+ process: "process";
5
+ }>>;
@@ -0,0 +1,5 @@
1
+ import { z } from 'zod';
2
+ export const envSourceSchema = z
3
+ .enum(['file', 'process'])
4
+ .default('file')
5
+ .describe('Where to read environment variables from');
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * Keep this file in sync with the host's `env.features`, `env.auth`,
5
5
  * provider enums, and the `superRefine` validation in
6
- * `codapult/src/lib/config.ts`. The CLI parses `.env.local` directly (it
7
- * cannot import from the host project), so this module centralises the
8
- * provider/feature shape that several commands share (config-show, doctor,
9
- * MCP project status).
6
+ * `codapult/src/lib/config.ts`. The CLI cannot import from the host project,
7
+ * so this module centralises the provider/feature shape that several
8
+ * commands share regardless of whether env values come from `.env.local` or
9
+ * `process.env`.
10
10
  */
11
11
  export type DbProvider = 'turso' | 'postgres';
12
12
  export type AuthProvider = 'better-auth' | 'kinde' | 'none';
@@ -3,10 +3,10 @@
3
3
  *
4
4
  * Keep this file in sync with the host's `env.features`, `env.auth`,
5
5
  * provider enums, and the `superRefine` validation in
6
- * `codapult/src/lib/config.ts`. The CLI parses `.env.local` directly (it
7
- * cannot import from the host project), so this module centralises the
8
- * provider/feature shape that several commands share (config-show, doctor,
9
- * MCP project status).
6
+ * `codapult/src/lib/config.ts`. The CLI cannot import from the host project,
7
+ * so this module centralises the provider/feature shape that several
8
+ * commands share regardless of whether env values come from `.env.local` or
9
+ * `process.env`.
10
10
  */
11
11
  /** Feature toggle key → ENABLE_* env var. Order = display order. */
12
12
  export const FEATURE_ENV = {
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, } from 'node:fs';
2
2
  import { resolve, dirname, relative, basename, extname, join } from 'node:path';
3
+ import { ENV_FILE_NAME } from './project-env.js';
3
4
  const MARKER_START = (name) => `// --- plugin:${name}:start ---`;
4
5
  const MARKER_END = (name) => `// --- plugin:${name}:end ---`;
5
6
  function hasMarker(content, name) {
@@ -533,10 +534,10 @@ export function findPageBackups(projectRoot) {
533
534
  return found;
534
535
  }
535
536
  // ---------------------------------------------------------------------------
536
- // .env.local — append env vars
537
+ // env file — append env vars
537
538
  // ---------------------------------------------------------------------------
538
539
  export function patchEnvFile(projectRoot, pluginName, envVars, action) {
539
- const envPath = resolve(projectRoot, '.env.local');
540
+ const envPath = resolve(projectRoot, ENV_FILE_NAME);
540
541
  if (!existsSync(envPath))
541
542
  return;
542
543
  let content = readFileSync(envPath, 'utf-8');
@@ -1,5 +1,6 @@
1
1
  import { describe, it, expect, vi, beforeEach } from 'vitest';
2
2
  import { patchSchemaImports, patchSchemaTables, patchDbReExports, patchNextConfig, regenerateBarrel, createPluginRegistration, patchPages, findPageConflicts, findPageBackups, readPageExtensions, PageConflictError, patchEnvFile, patchPackageJson, } from './patchers.js';
3
+ import { ENV_FILE_NAME } from './project-env.js';
3
4
  vi.mock('node:fs');
4
5
  const { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, } = await import('node:fs');
5
6
  const mockedExists = vi.mocked(existsSync);
@@ -571,7 +572,7 @@ describe('patchEnvFile', () => {
571
572
  patchEnvFile(ROOT, 'test-plugin', { KEY: { required: true } }, 'add');
572
573
  expect(mockedWrite).not.toHaveBeenCalled();
573
574
  });
574
- it('does nothing when .env.local does not exist', () => {
575
+ it(`does nothing when ${ENV_FILE_NAME} does not exist`, () => {
575
576
  mockedExists.mockReturnValue(false);
576
577
  patchEnvFile(ROOT, 'test-plugin', { KEY: { required: true } }, 'add');
577
578
  expect(mockedWrite).not.toHaveBeenCalled();
@@ -0,0 +1,16 @@
1
+ export type ProjectEnvSource = 'file' | 'process';
2
+ export interface ProjectEnvOptions {
3
+ envFile?: boolean;
4
+ }
5
+ export interface LoadedProjectEnv {
6
+ source: ProjectEnvSource;
7
+ content: string;
8
+ filePath: string;
9
+ fileExists: boolean;
10
+ }
11
+ export declare const ENV_EXAMPLE_FILE_NAME = ".env.example";
12
+ export declare const ENV_FILE_NAME = ".env.local";
13
+ export declare function getProjectEnvFilePath(projectRoot: string): string;
14
+ export declare function getProjectEnvSource(options?: ProjectEnvOptions): ProjectEnvSource;
15
+ export declare function getProjectEnvOptions(envSource?: ProjectEnvSource): ProjectEnvOptions;
16
+ export declare function loadProjectEnv(projectRoot: string, options?: ProjectEnvOptions): LoadedProjectEnv;
@@ -0,0 +1,38 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ export const ENV_EXAMPLE_FILE_NAME = '.env.example';
4
+ export const ENV_FILE_NAME = '.env.local';
5
+ export function getProjectEnvFilePath(projectRoot) {
6
+ return resolve(projectRoot, ENV_FILE_NAME);
7
+ }
8
+ export function getProjectEnvSource(options) {
9
+ return options?.envFile === false ? 'process' : 'file';
10
+ }
11
+ export function getProjectEnvOptions(envSource) {
12
+ return envSource === 'process' ? { envFile: false } : { envFile: true };
13
+ }
14
+ function serializeProcessEnv(env) {
15
+ return Object.entries(env)
16
+ .filter(([, value]) => value !== undefined)
17
+ .map(([key, value]) => `${key}=${value}`)
18
+ .join('\n');
19
+ }
20
+ export function loadProjectEnv(projectRoot, options) {
21
+ const source = getProjectEnvSource(options);
22
+ const filePath = getProjectEnvFilePath(projectRoot);
23
+ const fileExists = existsSync(filePath);
24
+ if (source === 'process') {
25
+ return {
26
+ source,
27
+ content: serializeProcessEnv(process.env),
28
+ filePath,
29
+ fileExists,
30
+ };
31
+ }
32
+ return {
33
+ source,
34
+ content: fileExists ? readFileSync(filePath, 'utf-8') : '',
35
+ filePath,
36
+ fileExists,
37
+ };
38
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,47 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { ENV_FILE_NAME, getProjectEnvFilePath, getProjectEnvOptions, getProjectEnvSource, loadProjectEnv, } from './project-env.js';
3
+ vi.mock('node:fs');
4
+ const { existsSync, readFileSync } = await import('node:fs');
5
+ const mockedExists = vi.mocked(existsSync);
6
+ const mockedRead = vi.mocked(readFileSync);
7
+ beforeEach(() => {
8
+ vi.resetAllMocks();
9
+ vi.unstubAllEnvs();
10
+ });
11
+ describe('project-env', () => {
12
+ it('defaults to file env source', () => {
13
+ expect(getProjectEnvSource()).toBe('file');
14
+ });
15
+ it('uses process env source when envFile is disabled', () => {
16
+ expect(getProjectEnvSource({ envFile: false })).toBe('process');
17
+ });
18
+ it('maps env source to options', () => {
19
+ expect(getProjectEnvOptions('process')).toEqual({ envFile: false });
20
+ expect(getProjectEnvOptions('file')).toEqual({ envFile: true });
21
+ expect(getProjectEnvOptions()).toEqual({ envFile: true });
22
+ });
23
+ it(`loads env content from ${ENV_FILE_NAME} in file mode`, () => {
24
+ mockedExists.mockImplementation((path) => path === `/project/${ENV_FILE_NAME}`);
25
+ mockedRead.mockReturnValue('AUTH_PROVIDER=better-auth\nDB_PROVIDER=postgres');
26
+ expect(loadProjectEnv('/project')).toEqual({
27
+ source: 'file',
28
+ content: 'AUTH_PROVIDER=better-auth\nDB_PROVIDER=postgres',
29
+ filePath: `/project/${ENV_FILE_NAME}`,
30
+ fileExists: true,
31
+ });
32
+ });
33
+ it('loads env content from process.env in process mode', () => {
34
+ mockedExists.mockReturnValue(false);
35
+ vi.stubEnv('AUTH_PROVIDER', 'better-auth');
36
+ vi.stubEnv('DB_PROVIDER', 'postgres');
37
+ const env = loadProjectEnv('/project', { envFile: false });
38
+ expect(env.source).toBe('process');
39
+ expect(env.filePath).toBe(`/project/${ENV_FILE_NAME}`);
40
+ expect(env.fileExists).toBe(false);
41
+ expect(env.content).toContain('AUTH_PROVIDER=better-auth');
42
+ expect(env.content).toContain('DB_PROVIDER=postgres');
43
+ });
44
+ it(`returns ${ENV_FILE_NAME} path helper`, () => {
45
+ expect(getProjectEnvFilePath('/project')).toBe(`/project/${ENV_FILE_NAME}`);
46
+ });
47
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codapult/cli",
3
- "version": "0.4.2",
3
+ "version": "0.6.0",
4
4
  "description": "Codapult CLI — manage, update, and diagnose your Codapult SaaS project",
5
5
  "license": "MIT",
6
6
  "type": "module",