@egdesk/next-api-plugin 1.5.86 → 1.5.106

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,8 @@
1
+ /**
2
+ * Generate Next.js App Router handlers that proxy chunked uploads to EGDesk MCP.
3
+ * Browser → these routes (tunnel-safe small chunks) → localhost MCP upload endpoints.
4
+ */
5
+ /** My DB row attachments → MCP /user-data/uploads */
6
+ export declare function generateChunkedUploadRoutes(projectPath: string): void;
7
+ /** Voice Transcript audio → MCP /voice-transcript/uploads (allowlisted for transcribe) */
8
+ export declare function generateVoiceTranscriptChunkedUploadRoutes(projectPath: string): void;
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ /**
3
+ * Generate Next.js App Router handlers that proxy chunked uploads to EGDesk MCP.
4
+ * Browser → these routes (tunnel-safe small chunks) → localhost MCP upload endpoints.
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || (function () {
23
+ var ownKeys = function(o) {
24
+ ownKeys = Object.getOwnPropertyNames || function (o) {
25
+ var ar = [];
26
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
27
+ return ar;
28
+ };
29
+ return ownKeys(o);
30
+ };
31
+ return function (mod) {
32
+ if (mod && mod.__esModule) return mod;
33
+ var result = {};
34
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
35
+ __setModuleDefault(result, mod);
36
+ return result;
37
+ };
38
+ })();
39
+ Object.defineProperty(exports, "__esModule", { value: true });
40
+ exports.generateChunkedUploadRoutes = generateChunkedUploadRoutes;
41
+ exports.generateVoiceTranscriptChunkedUploadRoutes = generateVoiceTranscriptChunkedUploadRoutes;
42
+ const fs = __importStar(require("fs"));
43
+ const path = __importStar(require("path"));
44
+ const os = __importStar(require("os"));
45
+ function usesSrcDirectory(projectPath) {
46
+ const srcAppPath = path.join(projectPath, 'src', 'app');
47
+ return fs.existsSync(srcAppPath);
48
+ }
49
+ function writeFile(filePath, content) {
50
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
51
+ fs.writeFileSync(filePath, content.replace(/\r?\n/g, os.EOL), 'utf-8');
52
+ console.log(`✅ Generated ${filePath}`);
53
+ }
54
+ const SHARED_HELPER = `import { NextRequest, NextResponse } from 'next/server';
55
+
56
+ function resolveEgdeskMcpApiUrl(): string {
57
+ const internal = process.env.EGDESK_MCP_INTERNAL_URL;
58
+ if (internal && internal.trim()) return internal.replace(/\\/$/, '');
59
+ return (process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080').replace(/\\/$/, '');
60
+ }
61
+
62
+ function buildEgdeskHeaders(extra?: HeadersInit): HeadersInit {
63
+ const headers: Record<string, string> = {};
64
+ const apiKey = process.env.NEXT_PUBLIC_EGDESK_API_KEY;
65
+ const projectId = process.env.NEXT_PUBLIC_EGDESK_PROJECT_ID;
66
+ const egdeskEnv = process.env.NEXT_PUBLIC_EGDESK_ENV;
67
+ if (apiKey) headers['X-Api-Key'] = apiKey;
68
+ if (projectId) headers['X-EGDesk-Project-Id'] = projectId;
69
+ if (egdeskEnv) headers['X-EGDesk-Env'] = egdeskEnv;
70
+ if (extra) {
71
+ const e = new Headers(extra);
72
+ e.forEach((v, k) => {
73
+ headers[k] = v;
74
+ });
75
+ }
76
+ return headers;
77
+ }
78
+
79
+ export async function proxyJson(pathname: string, init?: RequestInit) {
80
+ const apiUrl = resolveEgdeskMcpApiUrl();
81
+ const response = await fetch(\`\${apiUrl}\${pathname}\`, {
82
+ ...init,
83
+ headers: buildEgdeskHeaders(init?.headers),
84
+ cache: 'no-store',
85
+ });
86
+ const text = await response.text();
87
+ let body: any = text;
88
+ try {
89
+ body = text ? JSON.parse(text) : {};
90
+ } catch {
91
+ body = { success: false, error: text || \`HTTP \${response.status}\` };
92
+ }
93
+ return NextResponse.json(body, { status: response.status });
94
+ }
95
+
96
+ export async function proxyRaw(
97
+ pathname: string,
98
+ method: string,
99
+ body: ArrayBuffer | null,
100
+ headers?: HeadersInit,
101
+ ) {
102
+ const apiUrl = resolveEgdeskMcpApiUrl();
103
+ const response = await fetch(\`\${apiUrl}\${pathname}\`, {
104
+ method,
105
+ headers: buildEgdeskHeaders(headers),
106
+ body: body && body.byteLength > 0 ? body : undefined,
107
+ // @ts-expect-error duplex required for streaming bodies in some runtimes
108
+ duplex: 'half',
109
+ cache: 'no-store',
110
+ });
111
+ const text = await response.text();
112
+ let parsed: any = text;
113
+ try {
114
+ parsed = text ? JSON.parse(text) : {};
115
+ } catch {
116
+ parsed = { success: false, error: text || \`HTTP \${response.status}\` };
117
+ }
118
+ return NextResponse.json(parsed, { status: response.status });
119
+ }
120
+ `;
121
+ function generateChunkedUploadRouteTree(projectPath, spec) {
122
+ const hasSrc = usesSrcDirectory(projectPath);
123
+ const appRoot = hasSrc ? path.join(projectPath, 'src', 'app') : path.join(projectPath, 'app');
124
+ const base = path.join(appRoot, ...spec.appApiSegments);
125
+ const mcp = spec.mcpUploadsPath.replace(/\/$/, '');
126
+ writeFile(path.join(base, '_proxy.ts'), SHARED_HELPER);
127
+ writeFile(path.join(base, 'route.ts'), `import { NextRequest } from 'next/server';
128
+ import { proxyJson } from './_proxy';
129
+
130
+ /** ${spec.initPostComment} */
131
+ export async function POST(request: NextRequest) {
132
+ const body = await request.text();
133
+ return proxyJson('${mcp}', {
134
+ method: 'POST',
135
+ headers: { 'Content-Type': 'application/json' },
136
+ body,
137
+ });
138
+ }
139
+ `);
140
+ writeFile(path.join(base, '[id]', 'route.ts'), `import { NextRequest } from 'next/server';
141
+ import { proxyJson } from '../_proxy';
142
+
143
+ /** GET — upload status */
144
+ export async function GET(
145
+ _request: NextRequest,
146
+ ctx: { params: Promise<{ id: string }> | { id: string } },
147
+ ) {
148
+ const params = await Promise.resolve(ctx.params);
149
+ return proxyJson(\`${mcp}/\${params.id}\`, { method: 'GET' });
150
+ }
151
+
152
+ /** DELETE — abort upload */
153
+ export async function DELETE(
154
+ _request: NextRequest,
155
+ ctx: { params: Promise<{ id: string }> | { id: string } },
156
+ ) {
157
+ const params = await Promise.resolve(ctx.params);
158
+ return proxyJson(\`${mcp}/\${params.id}\`, { method: 'DELETE' });
159
+ }
160
+ `);
161
+ writeFile(path.join(base, '[id]', 'chunks', '[index]', 'route.ts'), `import { NextRequest } from 'next/server';
162
+ import { proxyRaw } from '../../../_proxy';
163
+
164
+ /** PUT — raw octet-stream chunk */
165
+ export async function PUT(
166
+ request: NextRequest,
167
+ ctx: { params: Promise<{ id: string; index: string }> | { id: string; index: string } },
168
+ ) {
169
+ const params = await Promise.resolve(ctx.params);
170
+ const buf = await request.arrayBuffer();
171
+ const sha = request.headers.get('x-chunk-sha256');
172
+ return proxyRaw(
173
+ \`${mcp}/\${params.id}/chunks/\${params.index}\`,
174
+ 'PUT',
175
+ buf,
176
+ {
177
+ 'Content-Type': 'application/octet-stream',
178
+ ...(sha ? { 'x-chunk-sha256': sha } : {}),
179
+ },
180
+ );
181
+ }
182
+ `);
183
+ writeFile(path.join(base, '[id]', 'complete', 'route.ts'), `import { NextRequest } from 'next/server';
184
+ import { proxyJson } from '../../_proxy';
185
+
186
+ /** POST — finalize upload */
187
+ export async function POST(
188
+ _request: NextRequest,
189
+ ctx: { params: Promise<{ id: string }> | { id: string } },
190
+ ) {
191
+ const params = await Promise.resolve(ctx.params);
192
+ return proxyJson(\`${mcp}/\${params.id}/complete\`, {
193
+ method: 'POST',
194
+ headers: { 'Content-Type': 'application/json' },
195
+ body: '{}',
196
+ });
197
+ }
198
+ `);
199
+ }
200
+ /** My DB row attachments → MCP /user-data/uploads */
201
+ function generateChunkedUploadRoutes(projectPath) {
202
+ generateChunkedUploadRouteTree(projectPath, {
203
+ appApiSegments: ['api', 'user', 'files', 'uploads'],
204
+ mcpUploadsPath: '/user-data/uploads',
205
+ initPostComment: 'POST /api/user/files/uploads — init chunked upload',
206
+ });
207
+ }
208
+ /** Voice Transcript audio → MCP /voice-transcript/uploads (allowlisted for transcribe) */
209
+ function generateVoiceTranscriptChunkedUploadRoutes(projectPath) {
210
+ generateChunkedUploadRouteTree(projectPath, {
211
+ appApiSegments: ['api', 'voice-transcript', 'uploads'],
212
+ mcpUploadsPath: '/voice-transcript/uploads',
213
+ initPostComment: 'POST /api/voice-transcript/uploads — init chunked audio upload',
214
+ });
215
+ }