@jhits/plugin-dep 0.0.9 → 0.0.10

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.
package/src/config.ts DELETED
@@ -1,137 +0,0 @@
1
- /**
2
- * Plugin Deprecated - Auto Setup
3
- * Automatically creates API routes in the client app
4
- */
5
-
6
- import { writeFileSync, mkdirSync, existsSync } from 'fs';
7
- import { join } from 'path';
8
-
9
- /**
10
- * Ensure the deprecated API route is set up in the client app
11
- */
12
- /**
13
- * @deprecated Routes are now handled by the unified /api/[pluginId]/[...path]/route.ts
14
- * This function is kept for backwards compatibility but does nothing
15
- */
16
- export function ensureDepRoutes() {
17
- // Routes are now handled by the unified /api/[pluginId]/[...path]/route.ts
18
- // No need to generate individual routes anymore
19
- return;
20
- try {
21
- // Find the host app directory (where next.config.ts is)
22
- let appDir = process.cwd();
23
- const possiblePaths = [
24
- appDir,
25
- join(appDir, '..'),
26
- join(appDir, '..', '..'),
27
- ];
28
-
29
- for (const basePath of possiblePaths) {
30
- const configPath = join(basePath, 'next.config.ts');
31
- if (existsSync(configPath)) {
32
- appDir = basePath;
33
- break;
34
- }
35
- }
36
-
37
- const apiDir = join(appDir, 'src', 'app', 'api');
38
- const pluginDepApiDir = join(apiDir, 'plugin-dep', '[...path]');
39
- const pluginDepApiPath = join(pluginDepApiDir, 'route.ts');
40
-
41
- // Check if route already exists
42
- if (existsSync(pluginDepApiPath)) {
43
- const fs = require('fs');
44
- const existingContent = fs.readFileSync(pluginDepApiPath, 'utf8');
45
- if (existingContent.includes('@jhits/plugin-dep') || existingContent.includes('plugin-dep')) {
46
- // Already set up, skip
47
- return;
48
- }
49
- }
50
-
51
- // Create plugin-dep API catch-all route
52
- mkdirSync(pluginDepApiDir, { recursive: true });
53
- writeFileSync(pluginDepApiPath, `// Auto-generated by @jhits/plugin-dep - Deprecated API Plugin
54
- // This route is automatically created for the deprecated API plugin
55
- import { NextRequest } from 'next/server';
56
- import { handleDepApi } from '@jhits/plugin-dep';
57
- import clientPromise from '@/lib/mongodb';
58
- import { authOptions } from '@jhits/dashboard/lib/auth';
59
- import { join } from 'path';
60
-
61
- export const dynamic = 'force-dynamic';
62
-
63
- async function getConfig() {
64
- return {
65
- mongoClient: clientPromise,
66
- jwtSecret: process.env.JWT_SECRET || 'secret',
67
- authOptions,
68
- emailConfig: process.env.EMAIL_SERVER_HOST ? {
69
- host: process.env.EMAIL_SERVER_HOST,
70
- port: Number(process.env.EMAIL_SERVER_PORT || 465),
71
- user: process.env.EMAIL_SERVER_USER || '',
72
- password: process.env.EMAIL_SERVER_PASSWORD || '',
73
- from: process.env.EMAIL_FROM || '',
74
- } : undefined,
75
- baseUrl: process.env.NEXT_PUBLIC_BASE_URL,
76
- githubWebhookSecret: process.env.GITHUB_WEBHOOK_SECRET,
77
- deploymentPaths: {
78
- flagPath: process.env.DEPLOYMENT_FLAG_PATH || '/home/pi/botanics/update-pending.json',
79
- scriptPath: process.env.DEPLOYMENT_SCRIPT_PATH || '/home/pi/botanics/scripts/update.sh',
80
- },
81
- localesDir: process.env.LOCALES_DIR || join(process.cwd(), 'data/locales'),
82
- uploadsDir: process.env.UPLOADS_DIR || join(process.cwd(), 'data/uploads'),
83
- };
84
- }
85
-
86
- export async function GET(
87
- req: NextRequest,
88
- { params }: { params: Promise<{ path: string[] }> }
89
- ) {
90
- const { path } = await params;
91
- const config = await getConfig();
92
- return handleDepApi(req, path, config);
93
- }
94
-
95
- export async function POST(
96
- req: NextRequest,
97
- { params }: { params: Promise<{ path: string[] }> }
98
- ) {
99
- const { path } = await params;
100
- const config = await getConfig();
101
- return handleDepApi(req, path, config);
102
- }
103
-
104
- export async function PUT(
105
- req: NextRequest,
106
- { params }: { params: Promise<{ path: string[] }> }
107
- ) {
108
- const { path } = await params;
109
- const config = await getConfig();
110
- return handleDepApi(req, path, config);
111
- }
112
-
113
- export async function PATCH(
114
- req: NextRequest,
115
- { params }: { params: Promise<{ path: string[] }> }
116
- ) {
117
- const { path } = await params;
118
- const config = await getConfig();
119
- return handleDepApi(req, path, config);
120
- }
121
-
122
- export async function DELETE(
123
- req: NextRequest,
124
- { params }: { params: Promise<{ path: string[] }> }
125
- ) {
126
- const { path } = await params;
127
- const config = await getConfig();
128
- return handleDepApi(req, path, config);
129
- }
130
- `);
131
-
132
- } catch (error) {
133
- // Ignore errors - route might already exist or app structure is different
134
- console.warn('[plugin-dep] Could not ensure deprecated routes:', error);
135
- }
136
- }
137
-
@@ -1,20 +0,0 @@
1
- import 'server-only';
2
-
3
- /**
4
- * Plugin Deprecated - Server-Only Entry Point
5
- * Re-exports server-side API handlers and business logic
6
- *
7
- * Note: This file is server-only (no 'use server' needed - that's only for Server Actions)
8
- */
9
-
10
- // Export router (main API handler)
11
- export { handleDepApi as handleApi } from './router';
12
-
13
- // Export actions (business logic)
14
- export * as actions from './actions';
15
-
16
- // Export types
17
- export * from './types';
18
-
19
- // Note: Config functions are server-only and not exported to avoid client-side import errors
20
- // They are deprecated anyway since routes are now handled by the unified route system
package/src/index.ts DELETED
@@ -1,14 +0,0 @@
1
- /**
2
- * Plugin Deprecated - Root Entry Point
3
- *
4
- * NOTE: This plugin is SERVER-ONLY and has no client UI.
5
- *
6
- * This file exists only to satisfy package.json "main" field requirements.
7
- * It should NEVER be imported by client code.
8
- *
9
- * For server-side usage, ALWAYS import from '@jhits/plugin-dep/server' instead.
10
- */
11
-
12
- // Empty export - this plugin has no client-side code
13
- // Importing this will result in an empty module
14
- // Use '@jhits/plugin-dep/server' for server-side imports
package/src/router.ts DELETED
@@ -1,391 +0,0 @@
1
- 'use server';
2
-
3
- /**
4
- * Plugin Deprecated - Router
5
- * Framework-agnostic router that routes API requests to business logic actions
6
- *
7
- * SERVER-ONLY: This module must never be imported by client code
8
- */
9
-
10
- import 'server-only';
11
-
12
- import { NextRequest, NextResponse } from 'next/server';
13
- import { DepApiConfig } from './types';
14
- import * as actions from './actions';
15
- import { verifyToken } from './utils/auth';
16
- import crypto from 'crypto';
17
-
18
- /**
19
- * Handle deprecated API requests
20
- * Routes requests to appropriate action handlers based on path and method
21
- */
22
- export async function handleDepApi(
23
- req: NextRequest,
24
- path: string[],
25
- config: DepApiConfig
26
- ): Promise<NextResponse> {
27
- const method = req.method;
28
- const route = path[0] || '';
29
-
30
- try {
31
- // ====================================================================
32
- // AUTH ROUTES
33
- // ====================================================================
34
- if (route === 'me') {
35
- if (method === 'GET') {
36
- let session: any = null;
37
- if (config.authOptions) {
38
- const { getServerSession } = await import('next-auth');
39
- session = await getServerSession(config.authOptions);
40
- }
41
- const result = await actions.getMe(config, session);
42
- return NextResponse.json(result);
43
- }
44
- }
45
-
46
- // ====================================================================
47
- // FEEDBACK ROUTES
48
- // ====================================================================
49
- else if (route === 'feedback') {
50
- if (path[1]) {
51
- // /api/plugin-dep/feedback/[id]
52
- const id = path[1];
53
- if (method === 'PATCH') {
54
- const body = await req.json();
55
- const result = await actions.updateFeedback(config, id, body);
56
- return NextResponse.json(result);
57
- } else if (method === 'DELETE') {
58
- const result = await actions.deleteFeedback(config, id);
59
- return NextResponse.json(result);
60
- }
61
- } else {
62
- // /api/plugin-dep/feedback
63
- if (method === 'GET') {
64
- const result = await actions.listFeedback(config);
65
- return NextResponse.json(result);
66
- } else if (method === 'POST') {
67
- const body = await req.json();
68
- const cookies = await req.cookies;
69
- const token = cookies.get('auth_token')?.value;
70
- let userId: string | undefined;
71
- if (token) {
72
- const payload = verifyToken(token, config.jwtSecret);
73
- if (payload && typeof payload !== 'string') {
74
- userId = payload.id;
75
- }
76
- }
77
- const result = await actions.createFeedback(config, body, userId);
78
- return NextResponse.json(result);
79
- }
80
- }
81
- }
82
-
83
- // ====================================================================
84
- // SETTINGS ROUTES
85
- // ====================================================================
86
- else if (route === 'settings') {
87
- if (path[1] === 'maintenance') {
88
- // /api/plugin-dep/settings/maintenance
89
- if (method === 'GET') {
90
- const result = await actions.getMaintenanceMode(config);
91
- return NextResponse.json(result);
92
- } else if (method === 'POST') {
93
- const body = await req.json();
94
- const result = await actions.setMaintenanceMode(config, body.active);
95
- return NextResponse.json(result);
96
- }
97
- } else {
98
- // /api/plugin-dep/settings
99
- if (method === 'GET') {
100
- const result = await actions.getSettings(config);
101
- return NextResponse.json(result);
102
- } else if (method === 'POST') {
103
- const body = await req.json();
104
- const result = await actions.updateSettings(config, body);
105
- return NextResponse.json(result);
106
- }
107
- }
108
- }
109
-
110
- // ====================================================================
111
- // USER ROUTES
112
- // ====================================================================
113
- else if (route === 'users') {
114
- if (path[1]) {
115
- // /api/plugin-dep/users/[id]
116
- const id = path[1];
117
- if (method === 'PATCH') {
118
- const body = await req.json();
119
- const result = await actions.updateUser(config, id, body);
120
- return NextResponse.json(result);
121
- } else if (method === 'DELETE') {
122
- const result = await actions.deleteUser(config, id);
123
- return NextResponse.json(result);
124
- }
125
- } else {
126
- // /api/plugin-dep/users
127
- if (method === 'GET') {
128
- const result = await actions.listUsers(config);
129
- return NextResponse.json(result);
130
- } else if (method === 'POST') {
131
- const body = await req.json();
132
- const result = await actions.createUser(config, body);
133
- return NextResponse.json(result);
134
- }
135
- }
136
- }
137
-
138
- // ====================================================================
139
- // NEWSLETTER ROUTES
140
- // ====================================================================
141
- else if (route === 'newsletter') {
142
- if (path[1] === 'subscribers') {
143
- if (path[2]) {
144
- // /api/plugin-dep/newsletter/subscribers/[user]
145
- const email = decodeURIComponent(path[2]).toLowerCase();
146
- if (method === 'GET') {
147
- const result = await actions.getSubscriber(config, email);
148
- return NextResponse.json(result);
149
- } else if (method === 'DELETE') {
150
- const result = await actions.deleteSubscriber(config, email);
151
- return NextResponse.json(result);
152
- }
153
- } else {
154
- // /api/plugin-dep/newsletter/subscribers
155
- if (method === 'GET') {
156
- const result = await actions.listSubscribers(config);
157
- return NextResponse.json(result);
158
- } else if (method === 'POST') {
159
- const body = await req.json();
160
- const headers = await req.headers;
161
- const host = headers.get('host') || undefined;
162
- const result = await actions.subscribeNewsletter(config, body, host);
163
- return NextResponse.json(result, { status: 201 });
164
- }
165
- }
166
- } else if (path[1] === 'settings') {
167
- // /api/plugin-dep/newsletter/settings
168
- if (method === 'GET') {
169
- const result = await actions.getNewsletterSettings(config);
170
- return NextResponse.json(result);
171
- } else if (method === 'POST') {
172
- const body = await req.json();
173
- const result = await actions.updateNewsletterSettings(config, body);
174
- return NextResponse.json(result);
175
- }
176
- }
177
- }
178
-
179
- // ====================================================================
180
- // NOTIFICATIONS ROUTES
181
- // ====================================================================
182
- else if (route === 'notifications') {
183
- if (path[1] === 'stream') {
184
- // /api/plugin-dep/notifications/stream
185
- if (method === 'GET') {
186
- return handleNotificationStream(req, config);
187
- }
188
- } else if (path[1] === 'action') {
189
- // /api/plugin-dep/notifications/action
190
- if (method === 'POST') {
191
- const body = await req.json();
192
- const cookies = await req.cookies;
193
- const token = cookies.get('auth_token')?.value;
194
- if (!token) {
195
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
196
- }
197
- const payload = verifyToken(token, config.jwtSecret);
198
- if (!payload || typeof payload === 'string') {
199
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
200
- }
201
- const result = await actions.updateNotification(config, body, payload.id);
202
- return NextResponse.json(result);
203
- }
204
- }
205
- }
206
-
207
- // ====================================================================
208
- // TRANSLATION ROUTES
209
- // ====================================================================
210
- else if (route === 'save-translation') {
211
- if (method === 'POST') {
212
- const body = await req.json();
213
- const result = await actions.saveTranslation(config, body);
214
- return NextResponse.json(result);
215
- }
216
- }
217
-
218
- // ====================================================================
219
- // STATS ROUTES
220
- // ====================================================================
221
- else if (route === 'stats') {
222
- if (path[1] === 'storage') {
223
- // /api/plugin-dep/stats/storage
224
- if (method === 'GET') {
225
- const result = await actions.getStorageStats(config);
226
- return NextResponse.json(result);
227
- }
228
- }
229
- } else if (route === 'media') {
230
- if (path[1] === 'stats') {
231
- // /api/plugin-dep/media/stats
232
- if (method === 'GET') {
233
- const result = await actions.getMediaStats(config);
234
- return NextResponse.json(result);
235
- }
236
- }
237
- }
238
-
239
- // ====================================================================
240
- // VERSION ROUTES
241
- // ====================================================================
242
- else if (route === 'version') {
243
- if (method === 'GET') {
244
- const result = await actions.getVersion();
245
- return NextResponse.json(result);
246
- }
247
- }
248
-
249
- // ====================================================================
250
- // GITHUB DEPLOYMENT ROUTES
251
- // ====================================================================
252
- else if (route === 'github') {
253
- if (path[1] === 'deploy') {
254
- // /api/plugin-dep/github/deploy
255
- if (method === 'GET') {
256
- const result = await actions.getDeploymentStatus(config);
257
- return NextResponse.json(result);
258
- } else if (method === 'POST') {
259
- const signature = req.headers.get('x-hub-signature-256') || '';
260
- let payload: any = null;
261
- if (signature !== 'manual') {
262
- const rawBody = await req.text();
263
- const secret = config.githubWebhookSecret;
264
- if (!secret) {
265
- return NextResponse.json({ error: 'Server configuration error' }, { status: 500 });
266
- }
267
- const hmac = crypto.createHmac('sha256', secret);
268
- const digest = 'sha256=' + hmac.update(rawBody).digest('hex');
269
- if (signature !== digest) {
270
- return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
271
- }
272
- payload = rawBody.startsWith('payload=')
273
- ? JSON.parse(decodeURIComponent(rawBody.substring(8)))
274
- : JSON.parse(rawBody);
275
- }
276
- const result = await actions.triggerDeployment(config, signature, payload);
277
- return NextResponse.json(result);
278
- }
279
- }
280
- }
281
-
282
- // Method not allowed
283
- return NextResponse.json(
284
- { error: `Method ${method} not allowed for route: ${route || '/'}` },
285
- { status: 405 }
286
- );
287
- } catch (error: any) {
288
- console.error('[DepApiRouter] Error:', error);
289
- const status = error.message?.includes('not found') ? 404
290
- : error.message?.includes('Unauthorized') ? 401
291
- : error.message?.includes('already') ? 409
292
- : error.message?.includes('too short') ? 400
293
- : 500;
294
- return NextResponse.json(
295
- { error: error.message || 'Internal server error' },
296
- { status }
297
- );
298
- }
299
- }
300
-
301
- /**
302
- * Handle Server-Sent Events stream for notifications
303
- */
304
- async function handleNotificationStream(
305
- req: NextRequest,
306
- config: DepApiConfig
307
- ): Promise<NextResponse> {
308
- const encoder = new TextEncoder();
309
- const cookies = await req.cookies;
310
- const token = cookies.get('auth_token')?.value;
311
-
312
- let userRole = 'guest';
313
- let currentUserId: string | null = null;
314
-
315
- if (token) {
316
- try {
317
- const payload = verifyToken(token, config.jwtSecret);
318
- if (payload && typeof payload !== 'string') {
319
- userRole = payload.role || 'guest';
320
- currentUserId = payload.id;
321
- }
322
- } catch (e) {
323
- console.error('Token verification failed in stream');
324
- }
325
- }
326
-
327
- let changeStream: any;
328
-
329
- const stream = new ReadableStream({
330
- async start(controller) {
331
- try {
332
- const client = await config.mongoClient;
333
- const db = client.db();
334
- const collection = db.collection('notifications');
335
-
336
- const streamData = await actions.getNotificationStream(config, userRole, currentUserId);
337
-
338
- // Send history
339
- streamData.history.forEach((notif) => {
340
- controller.enqueue(encoder.encode(`data: ${JSON.stringify(notif)}\n\n`));
341
- });
342
-
343
- // Send connection status
344
- controller.enqueue(encoder.encode(`data: ${JSON.stringify({ status: 'connected', role: userRole })}\n\n`));
345
-
346
- // Watch for changes
347
- changeStream = collection.watch(streamData.pipeline, { fullDocument: 'updateLookup' });
348
-
349
- changeStream.on('change', (change: any) => {
350
- if (change.operationType === 'insert') {
351
- const data = `data: ${JSON.stringify(change.fullDocument)}\n\n`;
352
- controller.enqueue(encoder.encode(data));
353
- }
354
- });
355
-
356
- const keepAlive = setInterval(() => {
357
- try {
358
- controller.enqueue(encoder.encode(': keep-alive\n\n'));
359
- } catch {
360
- clearInterval(keepAlive);
361
- }
362
- }, 20000);
363
-
364
- changeStream.on('error', (err: any) => {
365
- console.error('Mongo Stream Error:', err);
366
- clearInterval(keepAlive);
367
- if (changeStream) changeStream.close();
368
- });
369
- } catch (err) {
370
- console.error('Stream Start Error:', err);
371
- controller.error(err);
372
- }
373
- },
374
- cancel() {
375
- if (changeStream) {
376
- changeStream.close();
377
- console.log(`Stream connection closed for role: ${userRole}`);
378
- }
379
- },
380
- });
381
-
382
- return new NextResponse(stream, {
383
- headers: {
384
- 'Content-Type': 'text/event-stream',
385
- 'Cache-Control': 'no-cache, no-transform',
386
- Connection: 'keep-alive',
387
- 'X-Accel-Buffering': 'no',
388
- },
389
- });
390
- }
391
-
package/src/types.ts DELETED
@@ -1,58 +0,0 @@
1
- /**
2
- * Plugin Deprecated - Types
3
- * Type definitions for deprecated client API routes
4
- */
5
-
6
- import { MongoClient } from 'mongodb';
7
- import { NextRequest } from 'next/server';
8
-
9
- export interface DepApiConfig {
10
- /** MongoDB client promise */
11
- mongoClient: Promise<MongoClient>;
12
- /** JWT secret for token verification */
13
- jwtSecret: string;
14
- /** NextAuth auth options (for session-based auth) */
15
- authOptions?: any;
16
- /** Email configuration for newsletter */
17
- emailConfig?: {
18
- host: string;
19
- port: number;
20
- user: string;
21
- password: string;
22
- from: string;
23
- };
24
- /** Base URL for email links */
25
- baseUrl?: string;
26
- /** GitHub webhook secret */
27
- githubWebhookSecret?: string;
28
- /** Paths for deployment scripts */
29
- deploymentPaths?: {
30
- flagPath: string;
31
- scriptPath: string;
32
- };
33
- /** Locales directory path */
34
- localesDir?: string;
35
- /** Uploads directory path */
36
- uploadsDir?: string;
37
- }
38
-
39
- export interface ApiRequest {
40
- method: string;
41
- url: string;
42
- body?: any;
43
- headers: Headers;
44
- cookies?: Map<string, string>;
45
- }
46
-
47
- export interface ApiResponse {
48
- status: number;
49
- body: any;
50
- headers?: Record<string, string>;
51
- }
52
-
53
- export type ApiHandler = (
54
- req: ApiRequest,
55
- config: DepApiConfig,
56
- params?: Record<string, string>
57
- ) => Promise<ApiResponse>;
58
-
package/src/utils/auth.ts DELETED
@@ -1,20 +0,0 @@
1
- /**
2
- * Auth utilities for plugin-dep
3
- */
4
-
5
- import jwt from 'jsonwebtoken';
6
-
7
- export interface AuthPayload {
8
- id: string;
9
- email: string;
10
- role: string;
11
- }
12
-
13
- export function verifyToken(token: string, secret: string): AuthPayload | null {
14
- try {
15
- return jwt.verify(token, secret) as AuthPayload;
16
- } catch {
17
- return null;
18
- }
19
- }
20
-