@egdesk/next-api-plugin 1.5.4 → 1.5.6

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.
@@ -43,7 +43,7 @@ import type { NextRequest } from 'next/server';
43
43
  /**
44
44
  * EGDesk Database Proxy Middleware
45
45
  *
46
- * Intercepts __user_data_proxy, __browser_recording_proxy, and __internal_knowledge_proxy requests
46
+ * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, and __company_research_proxy requests
47
47
  * and forwards them to the EGDesk MCP HTTP server.
48
48
  * This allows CORS-free database access in both local and tunneled environments.
49
49
  *
@@ -151,6 +151,38 @@ export async function middleware(request: NextRequest) {
151
151
  }
152
152
  }
153
153
 
154
+ if (pathname.includes('__company_research_proxy')) {
155
+ try {
156
+ const body = await request.text();
157
+
158
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
159
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
160
+
161
+ const headers: HeadersInit = {
162
+ 'Content-Type': 'application/json',
163
+ };
164
+
165
+ if (apiKey) {
166
+ headers['X-Api-Key'] = apiKey;
167
+ }
168
+
169
+ const response = await fetch(\`\${apiUrl}/company-research/tools/call\`, {
170
+ method: 'POST',
171
+ headers,
172
+ body,
173
+ });
174
+
175
+ const result = await response.json();
176
+
177
+ return NextResponse.json(result, { status: response.status });
178
+ } catch (error: any) {
179
+ return NextResponse.json(
180
+ { error: 'Proxy error', message: error.message },
181
+ { status: 500 }
182
+ );
183
+ }
184
+ }
185
+
154
186
  // Continue to next middleware or route
155
187
  return NextResponse.next();
156
188
  }
@@ -45,11 +45,24 @@ import type { NextRequest } from 'next/server';
45
45
  /**
46
46
  * EGDesk Database Proxy (Next.js 16+)
47
47
  *
48
- * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __ai_center_proxy, and __korean_law_proxy requests
48
+ * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __company_research_proxy, __ai_center_proxy, __korean_law_proxy, __seo_proxy, __ssl_proxy, __local_agent_proxy, and __pageindex_proxy requests
49
49
  * and forwards them to the EGDesk MCP HTTP server. This avoids CORS in local and tunneled environments.
50
50
  *
51
51
  * Generated by @egdesk/next-api-plugin
52
52
  */
53
+
54
+ /** Build EGDesk routing headers from env vars (injected into every upstream call). */
55
+ function buildEgdeskHeaders(): Record<string, string> {
56
+ const headers: Record<string, string> = { 'Content-Type': 'application/json' };
57
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
58
+ const projectId = process.env.NEXT_PUBLIC_EGDESK_PROJECT_ID;
59
+ const egdeskEnv = process.env.NEXT_PUBLIC_EGDESK_ENV;
60
+ if (apiKey) headers['X-Api-Key'] = apiKey;
61
+ if (projectId) headers['X-EGDesk-Project-Id'] = projectId;
62
+ if (egdeskEnv) headers['X-EGDesk-Env'] = egdeskEnv;
63
+ return headers;
64
+ }
65
+
53
66
  export async function proxy(request: NextRequest) {
54
67
  const { pathname } = request.nextUrl;
55
68
 
@@ -57,23 +70,12 @@ export async function proxy(request: NextRequest) {
57
70
  if (pathname.includes('__user_data_proxy')) {
58
71
  try {
59
72
  const body = await request.text();
60
-
61
- // Read API key and URL from environment
62
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
63
73
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
64
74
 
65
- const headers: HeadersInit = {
66
- 'Content-Type': 'application/json',
67
- };
68
-
69
- if (apiKey) {
70
- headers['X-Api-Key'] = apiKey;
71
- }
72
-
73
75
  // Forward to EGDesk MCP server
74
76
  const response = await fetch(\`\${apiUrl}/user-data/tools/call\`, {
75
77
  method: 'POST',
76
- headers,
78
+ headers: buildEgdeskHeaders(),
77
79
  body,
78
80
  });
79
81
 
@@ -91,21 +93,11 @@ export async function proxy(request: NextRequest) {
91
93
  if (pathname.includes('__browser_recording_proxy')) {
92
94
  try {
93
95
  const body = await request.text();
94
-
95
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
96
96
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
97
97
 
98
- const headers: HeadersInit = {
99
- 'Content-Type': 'application/json',
100
- };
101
-
102
- if (apiKey) {
103
- headers['X-Api-Key'] = apiKey;
104
- }
105
-
106
98
  const response = await fetch(\`\${apiUrl}/browser-recording/tools/call\`, {
107
99
  method: 'POST',
108
- headers,
100
+ headers: buildEgdeskHeaders(),
109
101
  body,
110
102
  });
111
103
 
@@ -123,21 +115,11 @@ export async function proxy(request: NextRequest) {
123
115
  if (pathname.includes('__internal_knowledge_proxy')) {
124
116
  try {
125
117
  const body = await request.text();
126
-
127
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
128
118
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
129
119
 
130
- const headers: HeadersInit = {
131
- 'Content-Type': 'application/json',
132
- };
133
-
134
- if (apiKey) {
135
- headers['X-Api-Key'] = apiKey;
136
- }
137
-
138
120
  const response = await fetch(\`\${apiUrl}/internal-knowledge/tools/call\`, {
139
121
  method: 'POST',
140
- headers,
122
+ headers: buildEgdeskHeaders(),
141
123
  body,
142
124
  });
143
125
 
@@ -155,21 +137,55 @@ export async function proxy(request: NextRequest) {
155
137
  if (pathname.includes('__ai_center_proxy')) {
156
138
  try {
157
139
  const body = await request.text();
140
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
141
+
142
+ const response = await fetch(\`\${apiUrl}/ai-center/tools/call\`, {
143
+ method: 'POST',
144
+ headers: buildEgdeskHeaders(),
145
+ body,
146
+ });
147
+
148
+ const result = await response.json();
149
+
150
+ return NextResponse.json(result, { status: response.status });
151
+ } catch (error: any) {
152
+ return NextResponse.json(
153
+ { error: 'Proxy error', message: error.message },
154
+ { status: 500 }
155
+ );
156
+ }
157
+ }
158
158
 
159
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
159
+ if (pathname.includes('__korean_law_proxy')) {
160
+ try {
161
+ const body = await request.text();
160
162
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
161
163
 
162
- const headers: HeadersInit = {
163
- 'Content-Type': 'application/json',
164
- };
164
+ const response = await fetch(\`\${apiUrl}/korean-law/tools/call\`, {
165
+ method: 'POST',
166
+ headers: buildEgdeskHeaders(),
167
+ body,
168
+ });
165
169
 
166
- if (apiKey) {
167
- headers['X-Api-Key'] = apiKey;
168
- }
170
+ const result = await response.json();
169
171
 
170
- const response = await fetch(\`\${apiUrl}/ai-center/tools/call\`, {
172
+ return NextResponse.json(result, { status: response.status });
173
+ } catch (error: any) {
174
+ return NextResponse.json(
175
+ { error: 'Proxy error', message: error.message },
176
+ { status: 500 }
177
+ );
178
+ }
179
+ }
180
+
181
+ if (pathname.includes('__seo_proxy')) {
182
+ try {
183
+ const body = await request.text();
184
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
185
+
186
+ const response = await fetch(\`\${apiUrl}/seo/tools/call\`, {
171
187
  method: 'POST',
172
- headers,
188
+ headers: buildEgdeskHeaders(),
173
189
  body,
174
190
  });
175
191
 
@@ -184,24 +200,80 @@ export async function proxy(request: NextRequest) {
184
200
  }
185
201
  }
186
202
 
187
- if (pathname.includes('__korean_law_proxy')) {
203
+ if (pathname.includes('__ssl_proxy')) {
188
204
  try {
189
205
  const body = await request.text();
206
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
190
207
 
191
- const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
208
+ const response = await fetch(\`\${apiUrl}/ssl/tools/call\`, {
209
+ method: 'POST',
210
+ headers: buildEgdeskHeaders(),
211
+ body,
212
+ });
213
+
214
+ const result = await response.json();
215
+
216
+ return NextResponse.json(result, { status: response.status });
217
+ } catch (error: any) {
218
+ return NextResponse.json(
219
+ { error: 'Proxy error', message: error.message },
220
+ { status: 500 }
221
+ );
222
+ }
223
+ }
224
+
225
+ if (pathname.includes('__company_research_proxy')) {
226
+ try {
227
+ const body = await request.text();
192
228
  const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
193
229
 
194
- const headers: HeadersInit = {
195
- 'Content-Type': 'application/json',
196
- };
230
+ const response = await fetch(\`\${apiUrl}/company-research/tools/call\`, {
231
+ method: 'POST',
232
+ headers: buildEgdeskHeaders(),
233
+ body,
234
+ });
197
235
 
198
- if (apiKey) {
199
- headers['X-Api-Key'] = apiKey;
200
- }
236
+ const result = await response.json();
201
237
 
202
- const response = await fetch(\`\${apiUrl}/korean-law/tools/call\`, {
238
+ return NextResponse.json(result, { status: response.status });
239
+ } catch (error: any) {
240
+ return NextResponse.json(
241
+ { error: 'Proxy error', message: error.message },
242
+ { status: 500 }
243
+ );
244
+ }
245
+ }
246
+
247
+ if (pathname.includes('__local_agent_proxy')) {
248
+ try {
249
+ const body = await request.text();
250
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
251
+
252
+ const response = await fetch(\`\${apiUrl}/local-agent/tools/call\`, {
253
+ method: 'POST',
254
+ headers: buildEgdeskHeaders(),
255
+ body,
256
+ });
257
+
258
+ const result = await response.json();
259
+
260
+ return NextResponse.json(result, { status: response.status });
261
+ } catch (error: any) {
262
+ return NextResponse.json(
263
+ { error: 'Proxy error', message: error.message },
264
+ { status: 500 }
265
+ );
266
+ }
267
+ }
268
+
269
+ if (pathname.includes('__pageindex_proxy')) {
270
+ try {
271
+ const body = await request.text();
272
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
273
+
274
+ const response = await fetch(\`\${apiUrl}/pageindex/tools/call\`, {
203
275
  method: 'POST',
204
- headers,
276
+ headers: buildEgdeskHeaders(),
205
277
  body,
206
278
  });
207
279
 
@@ -224,7 +296,7 @@ export const config = {
224
296
  matcher: [
225
297
  /*
226
298
  * Match all paths except static assets
227
- * The proxy function filters for __user_data_proxy / __browser_recording_proxy / __internal_knowledge_proxy / __ai_center_proxy / __korean_law_proxy
299
+ * The proxy function filters for __user_data_proxy / __browser_recording_proxy / __internal_knowledge_proxy / __company_research_proxy / __ai_center_proxy / __korean_law_proxy / __seo_proxy / __ssl_proxy / __local_agent_proxy / __pageindex_proxy
228
300
  */
229
301
  '/:path*',
230
302
  ],
package/src/index.ts CHANGED
@@ -7,18 +7,28 @@
7
7
 
8
8
  import {
9
9
  discoverTables,
10
- updateEnvLocal,
10
+ updateEnvFiles,
11
11
  generateConfigFile,
12
12
  type UserDataConfig,
13
13
  type UserDataTable
14
14
  } from './setup-userdata';
15
15
  import { generateMiddleware } from './generate-middleware';
16
16
  import { generateProxy } from './generate-proxy';
17
- import { generateHelpers } from './generate-helpers';
17
+ import { generateHelpers, ensureSchemaFile } from './generate-helpers';
18
18
  import { generateApiWrapper } from './generate-api-wrapper';
19
19
 
20
20
  export interface SetupOptions {
21
21
  egdeskUrl?: string;
22
+ /** Production EGDesk server URL — written to .env.production.local. Falls back to egdeskUrl. */
23
+ prodEgdeskUrl?: string;
24
+ /**
25
+ * URL used only for table discovery (discoverTables). Defaults to egdeskUrl.
26
+ * Set this to the EGDesk internal server URL (e.g. http://localhost:8080) when egdeskUrl
27
+ * is a per-project proxy port that doesn't serve the EGDesk MCP HTTP API.
28
+ */
29
+ discoveryUrl?: string;
30
+ /** Stable EGDesk project UUID — written as NEXT_PUBLIC_EGDESK_PROJECT_ID in env files */
31
+ egdeskProjectId?: string;
22
32
  apiKey?: string;
23
33
  useProxy?: boolean; // Use proxy.ts (Next.js 16+) instead of middleware.ts
24
34
  }
@@ -36,20 +46,23 @@ export async function setupNextApiPlugin(
36
46
  projectPath: string,
37
47
  options: SetupOptions = {}
38
48
  ): Promise<void> {
39
- const { egdeskUrl = 'http://localhost:8080', apiKey, useProxy = true } = options;
49
+ const { egdeskUrl = 'http://localhost:8080', prodEgdeskUrl, discoveryUrl, egdeskProjectId, apiKey, useProxy = true } = options;
40
50
 
41
51
  console.log('🔍 Discovering EGDesk user-data tables...');
42
52
 
43
53
  try {
44
- const tables = await discoverTables(egdeskUrl, apiKey);
54
+ const [devTables, prodTables] = await Promise.all([
55
+ discoverTables(discoveryUrl ?? egdeskUrl, apiKey, egdeskProjectId, 'development'),
56
+ discoverTables(discoveryUrl ?? egdeskUrl, apiKey, egdeskProjectId, 'production'),
57
+ ]);
45
58
 
46
- if (tables.length === 0) {
59
+ if (devTables.length === 0) {
47
60
  console.warn('⚠️ No tables found. Import data in EGDesk first.');
48
61
  console.log('');
49
62
  console.log('Generating files anyway with empty table list...');
50
63
  } else {
51
- console.log(`✅ Found ${tables.length} table(s):`);
52
- tables.forEach((table, index) => {
64
+ console.log(`✅ Found ${devTables.length} dev table(s), ${prodTables.length} prod table(s):`);
65
+ devTables.forEach((table, index) => {
53
66
  console.log(` ${index + 1}. ${table.displayName} (${table.rowCount} rows)`);
54
67
  });
55
68
  }
@@ -57,7 +70,9 @@ export async function setupNextApiPlugin(
57
70
  const config: UserDataConfig = {
58
71
  apiKey: apiKey || null,
59
72
  baseUrl: egdeskUrl,
60
- tables,
73
+ prodBaseUrl: prodEgdeskUrl,
74
+ egdeskProjectId,
75
+ tables: devTables,
61
76
  generatedAt: new Date().toISOString()
62
77
  };
63
78
 
@@ -75,9 +90,17 @@ export async function setupNextApiPlugin(
75
90
  }
76
91
 
77
92
  generateConfigFile(projectPath, config);
93
+ ensureSchemaFile(
94
+ projectPath,
95
+ devTables.map((table) => ({
96
+ tableName: table.tableName,
97
+ displayName: table.displayName,
98
+ columns: table.columns,
99
+ })),
100
+ );
78
101
  generateHelpers(projectPath);
79
102
  generateApiWrapper(projectPath);
80
- updateEnvLocal(projectPath, config);
103
+ updateEnvFiles(projectPath, config, prodTables);
81
104
 
82
105
  const proxyFile = useProxy ? 'proxy.ts' : 'middleware.ts';
83
106
 
@@ -85,12 +108,14 @@ export async function setupNextApiPlugin(
85
108
  console.log('✅ Setup complete! Files generated:');
86
109
  console.log(` - ${proxyFile} (database proxy)`);
87
110
  console.log(' - egdesk.config.ts (type-safe config)');
111
+ console.log(' - egdesk.schema.ts (committed seed schema — add to git if newly created)');
88
112
  console.log(' - egdesk-helpers.ts (helper functions)');
89
113
  console.log(' - src/lib/api.ts (basePath-aware fetch wrapper)');
90
- console.log(' - .env.local (environment variables)');
114
+ console.log(' - .env.development.local (dev environment variables)');
115
+ console.log(' - .env.production.local (prod environment variables)');
91
116
  console.log('');
92
117
  console.log('📝 Next steps:');
93
- console.log(' 1. Add .env.local to your .gitignore');
118
+ console.log(' 1. Add .env.*.local to your .gitignore');
94
119
  console.log(' 2. Restart your Next.js dev server');
95
120
  console.log(' 3. Import and use helpers in your components:');
96
121
  console.log(' import { queryTable } from "./egdesk-helpers"');
@@ -114,5 +139,6 @@ export type { UserDataTable, UserDataConfig } from './setup-userdata';
114
139
  export { discoverTables } from './setup-userdata';
115
140
  export { generateMiddleware } from './generate-middleware';
116
141
  export { generateProxy } from './generate-proxy';
117
- export { generateHelpers } from './generate-helpers';
142
+ export { generateHelpers, generateSchemaFile, ensureSchemaFile, formatEgdeskSchemaFileContent } from './generate-helpers';
143
+ export type { SchemaTableDefinition, EnsureSchemaFileResult } from './generate-helpers';
118
144
  export { generateApiWrapper } from './generate-api-wrapper';
@@ -22,7 +22,12 @@ export interface UserDataTable {
22
22
 
23
23
  export interface UserDataConfig {
24
24
  apiKey: string | null;
25
+ /** Dev server URL — used for .env.development.local and egdesk.config.ts */
25
26
  baseUrl: string;
27
+ /** Prod server URL — used for .env.production.local (falls back to baseUrl when absent) */
28
+ prodBaseUrl?: string;
29
+ /** Stable EGDesk project UUID — written as NEXT_PUBLIC_EGDESK_PROJECT_ID in env files */
30
+ egdeskProjectId?: string;
26
31
  tables: UserDataTable[];
27
32
  generatedAt: string;
28
33
  }
@@ -32,7 +37,9 @@ export interface UserDataConfig {
32
37
  */
33
38
  export async function discoverTables(
34
39
  egdeskUrl: string = 'http://localhost:8080',
35
- apiKey?: string
40
+ apiKey?: string,
41
+ egdeskProjectId?: string,
42
+ env: 'development' | 'production' = 'development'
36
43
  ): Promise<UserDataTable[]> {
37
44
  try {
38
45
  const headers: Record<string, string> = {
@@ -42,6 +49,10 @@ export async function discoverTables(
42
49
  if (apiKey) {
43
50
  headers['X-Api-Key'] = apiKey;
44
51
  }
52
+ if (egdeskProjectId) {
53
+ headers['X-EGDesk-Project-Id'] = egdeskProjectId;
54
+ headers['X-EGDesk-Env'] = env;
55
+ }
45
56
 
46
57
  // List all tables
47
58
  const listResponse = await fetch(`${egdeskUrl}/user-data/tools/call`, {
@@ -123,18 +134,21 @@ export async function discoverTables(
123
134
  }
124
135
 
125
136
  return tablesWithColumns;
126
- } catch (error) {
137
+ } catch (error: any) {
138
+ // Connection refused / server not yet up — treat as no tables rather than a hard failure
139
+ if (error?.cause?.code === 'ECONNREFUSED' || error?.code === 'ECONNREFUSED') {
140
+ console.warn(`⚠️ EGDesk server not reachable at ${egdeskUrl} — proceeding with empty table list`);
141
+ return [];
142
+ }
127
143
  console.error('Failed to discover tables:', error);
128
144
  throw error;
129
145
  }
130
146
  }
131
147
 
132
148
  /**
133
- * Read existing .env.local file or return empty object
149
+ * Parse an env file into a key→value map
134
150
  */
135
- export function readEnvLocal(projectPath: string): Record<string, string> {
136
- const envPath = path.join(projectPath, '.env.local');
137
-
151
+ function parseEnvFile(envPath: string): Record<string, string> {
138
152
  if (!fs.existsSync(envPath)) {
139
153
  return {};
140
154
  }
@@ -155,8 +169,16 @@ export function readEnvLocal(projectPath: string): Record<string, string> {
155
169
  return envVars;
156
170
  }
157
171
 
172
+ /**
173
+ * Read existing .env.local file or return empty object
174
+ */
175
+ export function readEnvLocal(projectPath: string): Record<string, string> {
176
+ return parseEnvFile(path.join(projectPath, '.env.local'));
177
+ }
178
+
158
179
  /**
159
180
  * Update .env.local file with Next.js environment variables
181
+ * @deprecated Use updateEnvFiles() instead for per-environment URL support
160
182
  */
161
183
  export function updateEnvLocal(
162
184
  projectPath: string,
@@ -190,6 +212,98 @@ export function updateEnvLocal(
190
212
  console.log(`✅ Updated ${envPath}`);
191
213
  }
192
214
 
215
+ /**
216
+ * Write .env.development.local (dev URL) and .env.production.local (prod URL).
217
+ *
218
+ * Next.js loads .env.development.local for `next dev` and .env.production.local
219
+ * for `next build` / `next start`, so the correct EGDesk server address is picked
220
+ * up automatically without any runtime switching.
221
+ */
222
+ export function updateEnvFiles(
223
+ projectPath: string,
224
+ config: UserDataConfig,
225
+ /** Tables discovered for the production environment. Falls back to config.tables when omitted. */
226
+ prodTables?: UserDataTable[]
227
+ ): void {
228
+ function buildTableComments(tables: UserDataTable[]): string[] {
229
+ return [
230
+ '',
231
+ '# Available Tables',
232
+ `# Total tables: ${tables.length}`,
233
+ ...tables.map((table, index) =>
234
+ `# ${index + 1}. ${table.displayName} (${table.tableName}) - ${table.rowCount != null ? table.rowCount : '?'} rows, ${table.columnCount} columns`
235
+ ),
236
+ ''
237
+ ];
238
+ }
239
+
240
+ // EGDesk-managed keys — always overwritten with fresh values
241
+ const egdeskKeys = new Set([
242
+ 'NEXT_PUBLIC_EGDESK_API_URL',
243
+ 'NEXT_PUBLIC_EGDESK_API_KEY',
244
+ 'NEXT_PUBLIC_EGDESK_PROJECT_ID',
245
+ 'NEXT_PUBLIC_EGDESK_ENV',
246
+ ]);
247
+
248
+ function writeEnvFile(
249
+ envPath: string,
250
+ apiUrl: string,
251
+ label: string,
252
+ egdeskEnv: 'development' | 'production',
253
+ tables: UserDataTable[]
254
+ ): void {
255
+ // Preserve existing non-EGDesk vars
256
+ const existing = parseEnvFile(envPath);
257
+ const preserved = Object.fromEntries(
258
+ Object.entries(existing).filter(([k]) => !egdeskKeys.has(k))
259
+ );
260
+
261
+ const aiWarning = egdeskEnv === 'production' ? [
262
+ '# ============================================================',
263
+ '# ⚠️ AI ASSISTANT — DO NOT READ, EDIT, OR USE THIS FILE ⚠️',
264
+ '# This is the PRODUCTION environment configuration.',
265
+ '# AI must only work with the development environment.',
266
+ '# Never query, reference, or modify production data.',
267
+ '# Changes to production are made by the developer, not AI.',
268
+ '# ============================================================',
269
+ '',
270
+ ] : [];
271
+
272
+ const vercelNote =
273
+ egdeskEnv === 'production' && apiUrl.includes('tunneling-service')
274
+ ? [
275
+ '# Vercel: copy these vars to your Vercel project Environment Variables.',
276
+ '# API URL is the MCP tunnel root (/t/{tunnelId}) — NOT the /p/{project} Next.js URL.',
277
+ '',
278
+ ]
279
+ : [];
280
+
281
+ const lines = [
282
+ ...aiWarning,
283
+ ...vercelNote,
284
+ `# EGDesk User Data Configuration (${label})`,
285
+ `# Generated at: ${config.generatedAt}`,
286
+ '',
287
+ `NEXT_PUBLIC_EGDESK_API_URL=${apiUrl}`,
288
+ ...(config.egdeskProjectId ? [`NEXT_PUBLIC_EGDESK_PROJECT_ID=${config.egdeskProjectId}`] : []),
289
+ `NEXT_PUBLIC_EGDESK_ENV=${egdeskEnv}`,
290
+ ...(config.apiKey ? [`NEXT_PUBLIC_EGDESK_API_KEY=${config.apiKey}`] : []),
291
+ ...Object.entries(preserved).map(([k, v]) => `${k}=${v}`),
292
+ ...buildTableComments(tables)
293
+ ];
294
+ fs.writeFileSync(envPath, lines.join('\n').replace(/\r?\n/g, os.EOL), 'utf-8');
295
+ console.log(`✅ Updated ${envPath}`);
296
+ }
297
+
298
+ // .env.development.local — loaded by `next dev`
299
+ const devPath = path.join(projectPath, '.env.development.local');
300
+ writeEnvFile(devPath, config.baseUrl, 'development', 'development', config.tables);
301
+
302
+ // .env.production.local — loaded by `next build` / `next start`
303
+ const prodPath = path.join(projectPath, '.env.production.local');
304
+ writeEnvFile(prodPath, config.prodBaseUrl ?? config.baseUrl, 'production', 'production', prodTables ?? config.tables);
305
+ }
306
+
193
307
  /**
194
308
  * Generate TypeScript config file with table definitions
195
309
  */