@egdesk/next-api-plugin 1.5.50 → 1.5.54

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/README.md CHANGED
@@ -32,8 +32,9 @@ This will generate:
32
32
  - `middleware.ts` or `proxy.ts` - Database proxy (includes visitor auth/google)
33
33
  - `egdesk.config.ts` - Type-safe table definitions
34
34
  - `egdesk-helpers.ts` - Helper functions for database access
35
- - `egdesk-visitor-google.ts` - Visitor Google login (EGDesk Auth users, brokered by EGDesk)
36
- - `app/auth/callback/page.tsx` - Exchanges EGDesk’s one-time login code
35
+ - `egdesk-visitor-google.ts` - Visitor Google login helper (**generated — do not edit**)
36
+ - `egdesk.visitor-auth.ts` - Site-owned login defaults (created once, never overwritten)
37
+ - `app/auth/callback/page.tsx` - Exchanges EGDesk’s one-time login code (**generated — do not edit**)
37
38
  - `.env.local` - Environment variables (`NEXT_PUBLIC_EGDESK_*` only — no Supabase keys)
38
39
 
39
40
  Add `{EGDesk public URL}/visitor-auth/callback` to the EGDesk Supabase Auth redirect allowlist (once per EGDesk/tunnel origin, not each published site).
@@ -81,6 +82,42 @@ Do not add `?vid=` — extra query params make Supabase fall back to the Site UR
81
82
 
82
83
  Owner MCP (`startDriveAuthLogin`) is a separate credential on the EGDesk machine. Visitor login does not overwrite it.
83
84
 
85
+ ### Visitor login: generated vs site-owned
86
+
87
+ | File | Owner | Overwritten on codegen? |
88
+ |------|--------|-------------------------|
89
+ | `egdesk-visitor-google.ts` | EGDesk plugin | Yes |
90
+ | `app/auth/callback/page.tsx` | EGDesk plugin | Yes |
91
+ | `egdesk.visitor-auth.ts` | The site | **No** |
92
+ | `app/login/page.tsx` (or any custom UI) | The site | Never generated |
93
+
94
+ Do not copy helper constants into `src/` to survive regeneration. Import presets and pass them:
95
+
96
+ ```typescript
97
+ import {
98
+ startVisitorGoogleLogin,
99
+ VISITOR_BASIC_SCOPES,
100
+ VISITOR_WORKSPACE_SCOPES,
101
+ } from './egdesk-visitor-google';
102
+
103
+ // Sign-in only (smaller Google consent)
104
+ await startVisitorGoogleLogin({ next: '/dashboard', scopes: VISITOR_BASIC_SCOPES });
105
+
106
+ // Drive / Sheets / Docs / Slides
107
+ await startVisitorGoogleLogin({ next: '/drive', scopes: VISITOR_WORKSPACE_SCOPES });
108
+ ```
109
+
110
+ Project default (never overwritten):
111
+
112
+ ```typescript
113
+ // egdesk.visitor-auth.ts
114
+ export const VISITOR_AUTH = {
115
+ scopes: 'basic' as 'basic' | 'workspace',
116
+ };
117
+ ```
118
+
119
+ `NEXT_PUBLIC_EGDESK_VISITOR_SCOPES=basic|workspace` overrides that file. EGDesk allowlists scopes server-side; unknown Google APIs are dropped. Older helpers that send no scopes still get workspace (previous default).
120
+
84
121
  ### Custom Setup
85
122
 
86
123
  You can programmatically run the setup:
@@ -166,7 +203,8 @@ startDriveAuthLogin()
166
203
  getDriveAuthStatus()
167
204
 
168
205
  // Visitor Google — import from egdesk-visitor-google.ts, not egdesk-helpers.ts
169
- startVisitorGoogleLogin()
206
+ startVisitorGoogleLogin({ scopes: VISITOR_BASIC_SCOPES })
207
+ startVisitorGoogleLogin({ scopes: VISITOR_WORKSPACE_SCOPES })
170
208
  getVisitorGoogleStatus()
171
209
  listVisitorDriveFiles()
172
210
  getVisitorSheetRange(spreadsheetId, range)
@@ -139,7 +139,7 @@ function generateHelpers(projectPath, options = {}) {
139
139
  *
140
140
  * Type-safe helpers for EGDesk user data, Google Workspace (Sheets / Drive / Docs / Slides MCP + sync, Gmail, Apps Script),
141
141
  * FinanceHub (banks, cards, Hometax, promissory notes),
142
- * internal knowledge / business identity / company research (MCP), Korean law (MCP), and browser recorder replay / live browse.
142
+ * internal knowledge / business identity / company research (MCP), Korean law (MCP), Bizinfo grants (MCP), NPS workplace headcount (MCP), and browser recorder replay / live browse.
143
143
  * Works in both client and server components.
144
144
  *
145
145
  * Generated by @egdesk/next-api-plugin — do not edit by hand.
@@ -247,7 +247,13 @@ async function parseEgdeskMcpToolResponse(response: Response): Promise<any> {
247
247
  }
248
248
 
249
249
  const content = result.result?.content?.[0]?.text;
250
- return content ? JSON.parse(content) : null;
250
+ if (!content) return null;
251
+ try {
252
+ return JSON.parse(content);
253
+ } catch {
254
+ // Some tools still return a plain sentence (e.g. "Successfully wrote...").
255
+ return content;
256
+ }
251
257
  }
252
258
 
253
259
  async function parseEgdeskHttpResponse(response: Response): Promise<any> {
@@ -523,19 +529,47 @@ export async function insertRows(
523
529
 
524
530
  /**
525
531
  * Update rows in a table
532
+ *
533
+ * Supports both call styles:
534
+ * - updateRows('table', { col: 'val' }, { filters: { id: '1' } })
535
+ * - updateRows('table', { updates: { col: 'val' }, filters: { id: '1' } })
526
536
  */
527
537
  export async function updateRows(
528
538
  tableName: string,
529
- updates: Record<string, any>,
530
- options: {
539
+ updatesOrPayload: Record<string, any>,
540
+ options?: {
531
541
  ids?: number[];
532
542
  filters?: Record<string, string>;
533
543
  }
534
544
  ) {
545
+ let updates: Record<string, any>;
546
+ let rowOptions: typeof options;
547
+
548
+ if (
549
+ options === undefined &&
550
+ updatesOrPayload !== null &&
551
+ typeof updatesOrPayload === 'object' &&
552
+ 'updates' in updatesOrPayload &&
553
+ updatesOrPayload.updates !== null &&
554
+ typeof updatesOrPayload.updates === 'object' &&
555
+ !Array.isArray(updatesOrPayload.updates)
556
+ ) {
557
+ const payload = updatesOrPayload as {
558
+ updates: Record<string, any>;
559
+ ids?: number[];
560
+ filters?: Record<string, string>;
561
+ };
562
+ updates = payload.updates;
563
+ rowOptions = { ids: payload.ids, filters: payload.filters };
564
+ } else {
565
+ updates = updatesOrPayload;
566
+ rowOptions = options;
567
+ }
568
+
535
569
  return callUserDataTool('user_data_update_rows', {
536
570
  tableName,
537
571
  updates,
538
- ...options
572
+ ...(rowOptions || {})
539
573
  });
540
574
  }
541
575
 
@@ -1616,7 +1650,12 @@ export async function callCompanyResearchTool(
1616
1650
  /** Run full company research workflow for a domain (several minutes) */
1617
1651
  export async function runCompanyResearch(
1618
1652
  domain: string,
1619
- options: { bypassCache?: boolean; inquiryData?: Record<string, any> } = {}
1653
+ options: {
1654
+ bypassCache?: boolean;
1655
+ inquiryData?: Record<string, any>;
1656
+ companyName?: string;
1657
+ clientBusinessNumber?: string;
1658
+ } = {}
1620
1659
  ) {
1621
1660
  return callCompanyResearchTool('companyresearch_run', { domain, ...options });
1622
1661
  }
@@ -2308,6 +2347,254 @@ export async function getKoreanLawDecision(id: string) {
2308
2347
  return callKoreanLawTool('korean_law_get_decision', { id });
2309
2348
  }
2310
2349
 
2350
+ // ==========================================
2351
+ // BIZINFO / 기업마당 지원사업 (MCP)
2352
+ // ==========================================
2353
+
2354
+ /**
2355
+ * Call EGDesk Bizinfo MCP tool (기업마당 지원사업 공고 — grants, not company verify).
2356
+ *
2357
+ * - Server: \`POST {apiUrl}/bizinfo/tools/call\`
2358
+ * - Client: \`POST /__bizinfo_proxy\` (see proxy.ts / middleware)
2359
+ * - Tunnel: \`POST https://tunneling-service.onrender.com/t/{id}/bizinfo/tools/call\`
2360
+ */
2361
+ export async function callBizinfoTool(
2362
+ toolName: string,
2363
+ args: Record<string, any> = {}
2364
+ ): Promise<any> {
2365
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2366
+
2367
+ const isServer = typeof window === 'undefined';
2368
+
2369
+ let response: Response;
2370
+ if (isServer) {
2371
+ const apiUrl =
2372
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2373
+ EGDESK_CONFIG.apiUrl;
2374
+ response = await fetch(\`\${apiUrl}/bizinfo/tools/call\`, {
2375
+ method: 'POST',
2376
+ headers: buildServerEgdeskHeaders(),
2377
+ body
2378
+ });
2379
+ } else {
2380
+ response = await apiFetch('/__bizinfo_proxy', {
2381
+ method: 'POST',
2382
+ headers: { 'Content-Type': 'application/json' },
2383
+ body
2384
+ });
2385
+ }
2386
+
2387
+ return parseEgdeskMcpToolResponse(response);
2388
+ }
2389
+
2390
+ /** Search government grants / 지원사업 (category, region, optional client-side query). Not a company registry. */
2391
+ export async function searchBizinfo(
2392
+ options: {
2393
+ category?: 'finance' | 'tech' | 'talent' | 'export' | 'domestic' | 'startup' | 'management' | 'other';
2394
+ region?: string;
2395
+ hashtags?: string;
2396
+ query?: string;
2397
+ display?: number;
2398
+ page?: number;
2399
+ } = {}
2400
+ ) {
2401
+ return callBizinfoTool('bizinfo_search', options);
2402
+ }
2403
+
2404
+ /** Currently open 지원사업, sorted by deadline */
2405
+ export async function listOpenBizinfo(
2406
+ options: {
2407
+ category?: 'finance' | 'tech' | 'talent' | 'export' | 'domestic' | 'startup' | 'management' | 'other';
2408
+ region?: string;
2409
+ hashtags?: string;
2410
+ query?: string;
2411
+ display?: number;
2412
+ page?: number;
2413
+ } = {}
2414
+ ) {
2415
+ return callBizinfoTool('bizinfo_open', options);
2416
+ }
2417
+
2418
+ /** Get one announcement by pblancId */
2419
+ export async function getBizinfoAnnouncement(id: string) {
2420
+ return callBizinfoTool('bizinfo_get', { id });
2421
+ }
2422
+
2423
+ // ==========================================
2424
+ // NPS / 국민연금 가입 사업장 (MCP)
2425
+ // ==========================================
2426
+
2427
+ /**
2428
+ * Call EGDesk NPS MCP tool (국민연금 가입 사업장 내역 / 가입자 추이).
2429
+ *
2430
+ * - Server: \`POST {apiUrl}/nps/tools/call\`
2431
+ * - Client: \`POST /__nps_proxy\` (see proxy.ts / middleware)
2432
+ * - Tunnel: \`POST https://tunneling-service.onrender.com/t/{id}/nps/tools/call\`
2433
+ */
2434
+ export async function callNpsTool(
2435
+ toolName: string,
2436
+ args: Record<string, any> = {}
2437
+ ): Promise<any> {
2438
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2439
+
2440
+ const isServer = typeof window === 'undefined';
2441
+
2442
+ let response: Response;
2443
+ if (isServer) {
2444
+ const apiUrl =
2445
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2446
+ EGDESK_CONFIG.apiUrl;
2447
+ response = await fetch(\`\${apiUrl}/nps/tools/call\`, {
2448
+ method: 'POST',
2449
+ headers: buildServerEgdeskHeaders(),
2450
+ body
2451
+ });
2452
+ } else {
2453
+ response = await apiFetch('/__nps_proxy', {
2454
+ method: 'POST',
2455
+ headers: { 'Content-Type': 'application/json' },
2456
+ body
2457
+ });
2458
+ }
2459
+
2460
+ return parseEgdeskMcpToolResponse(response);
2461
+ }
2462
+
2463
+ /** Search NPS workplaces by name and/or 사업자번호 앞 6자리 */
2464
+ export async function searchNpsWorkplaces(
2465
+ options: {
2466
+ workplaceName?: string;
2467
+ businessNumber?: string;
2468
+ sidoCode?: string;
2469
+ sigunguCode?: string;
2470
+ emdCode?: string;
2471
+ page?: number;
2472
+ display?: number;
2473
+ } = {}
2474
+ ) {
2475
+ return callNpsTool('nps_search', options);
2476
+ }
2477
+
2478
+ /** NPS workplace detail (가입자수, 당월고지금액) by seq */
2479
+ export async function getNpsWorkplaceDetail(seq: string) {
2480
+ return callNpsTool('nps_detail', { seq });
2481
+ }
2482
+
2483
+ /** Monthly subscriber trend by seq */
2484
+ export async function getNpsWorkplaceTrend(seq: string) {
2485
+ return callNpsTool('nps_trend', { seq });
2486
+ }
2487
+
2488
+ /** Name (+ optional 사업자번호) → latest month + detail + 가입자 추이 */
2489
+ export async function lookupNpsWorkplace(options: {
2490
+ workplaceName: string;
2491
+ businessNumber?: string;
2492
+ sidoCode?: string;
2493
+ display?: number;
2494
+ }) {
2495
+ return callNpsTool('nps_lookup', options);
2496
+ }
2497
+
2498
+ // ==========================================
2499
+ // KONEPS / 나라장터 계약정보 (MCP)
2500
+ // ==========================================
2501
+
2502
+ export async function callKonepsTool(
2503
+ toolName: string,
2504
+ args: Record<string, any> = {}
2505
+ ): Promise<any> {
2506
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2507
+ const isServer = typeof window === 'undefined';
2508
+ let response: Response;
2509
+ if (isServer) {
2510
+ const apiUrl =
2511
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2512
+ EGDESK_CONFIG.apiUrl;
2513
+ response = await fetch(\`\${apiUrl}/koneps/tools/call\`, {
2514
+ method: 'POST',
2515
+ headers: buildServerEgdeskHeaders(),
2516
+ body
2517
+ });
2518
+ } else {
2519
+ response = await apiFetch('/__koneps_proxy', {
2520
+ method: 'POST',
2521
+ headers: { 'Content-Type': 'application/json' },
2522
+ body
2523
+ });
2524
+ }
2525
+ return parseEgdeskMcpToolResponse(response);
2526
+ }
2527
+
2528
+ export async function searchKonepsContracts(options: Record<string, any> = {}) {
2529
+ return callKonepsTool('koneps_search', options);
2530
+ }
2531
+
2532
+ export async function getKonepsContract(untyCntrctNo: string, category?: string) {
2533
+ return callKonepsTool('koneps_get', { untyCntrctNo, category });
2534
+ }
2535
+
2536
+ export async function lookupKonepsVendor(options: {
2537
+ companyName?: string;
2538
+ businessNumber?: string;
2539
+ startDate?: string;
2540
+ endDate?: string;
2541
+ category?: string;
2542
+ display?: number;
2543
+ }) {
2544
+ return callKonepsTool('koneps_lookup', options);
2545
+ }
2546
+
2547
+ // ==========================================
2548
+ // BidNotice / 나라장터 입찰공고 (MCP)
2549
+ // ==========================================
2550
+
2551
+ export async function callBidnoticeTool(
2552
+ toolName: string,
2553
+ args: Record<string, any> = {}
2554
+ ): Promise<any> {
2555
+ const body = JSON.stringify({ tool: toolName, arguments: args });
2556
+ const isServer = typeof window === 'undefined';
2557
+ let response: Response;
2558
+ if (isServer) {
2559
+ const apiUrl =
2560
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_API_URL) ||
2561
+ EGDESK_CONFIG.apiUrl;
2562
+ response = await fetch(\`\${apiUrl}/bidnotice/tools/call\`, {
2563
+ method: 'POST',
2564
+ headers: buildServerEgdeskHeaders(),
2565
+ body
2566
+ });
2567
+ } else {
2568
+ response = await apiFetch('/__bidnotice_proxy', {
2569
+ method: 'POST',
2570
+ headers: { 'Content-Type': 'application/json' },
2571
+ body
2572
+ });
2573
+ }
2574
+ return parseEgdeskMcpToolResponse(response);
2575
+ }
2576
+
2577
+ export async function searchBidNotices(options: Record<string, any> = {}) {
2578
+ return callBidnoticeTool('bidnotice_search', options);
2579
+ }
2580
+
2581
+ export async function getBidNotice(noticeNo: string, category?: string) {
2582
+ return callBidnoticeTool('bidnotice_get', { noticeNo, category });
2583
+ }
2584
+
2585
+ export async function lookupBidNotices(options: {
2586
+ title?: string;
2587
+ institutionName?: string;
2588
+ institutionDiv?: string;
2589
+ startDate?: string;
2590
+ endDate?: string;
2591
+ category?: string;
2592
+ openOnly?: boolean;
2593
+ display?: number;
2594
+ }) {
2595
+ return callBidnoticeTool('bidnotice_lookup', options);
2596
+ }
2597
+
2311
2598
  // ==========================================
2312
2599
  // SEO (MCP)
2313
2600
  // ==========================================
@@ -2862,7 +3149,7 @@ export async function deletePageIndexDocument(docId: string) {
2862
3149
  *
2863
3150
  * Owner MCP auth on EGDesk: GOOGLE_SERVICE_ACCOUNT_JSON or Google Workspace sign-in
2864
3151
  * via startDriveAuthLogin() — configures THIS EGDesk instance, not website visitors.
2865
- * Website visitors should use startVisitorGoogleLogin() from egdesk-visitor-google.ts
3152
+ * Website visitors should use startVisitorGoogleLogin({ scopes }) from egdesk-visitor-google.ts
2866
3153
  * (EGDesk brokers Auth; the site never receives Supabase keys).
2867
3154
  * Share target folders with the service account when using SA credentials.
2868
3155
  *
@@ -75,7 +75,7 @@ import type { NextRequest } from 'next/server';
75
75
  /**
76
76
  * EGDesk Database Proxy (Next.js 16+)
77
77
  *
78
- * 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, __pageindex_proxy, __drive_proxy, __sheets_proxy, __docs_proxy, __slides_proxy, __egdesk_http_proxy, __gmail_proxy, __apps_script_proxy, __knowledge_wiki_proxy, __egdesk_config_proxy, __ai_caller_proxy, __kakao_proxy, __phone_proxy, __instagram_proxy, __financehub_proxy, __blog_proxy, __youtube_proxy, __visitor_auth_proxy, and __visitor_google_proxy requests
78
+ * Intercepts __user_data_proxy, __browser_recording_proxy, __internal_knowledge_proxy, __company_research_proxy, __ai_center_proxy, __korean_law_proxy, __bizinfo_proxy, __nps_proxy, __seo_proxy, __ssl_proxy, __local_agent_proxy, __pageindex_proxy, __drive_proxy, __sheets_proxy, __docs_proxy, __slides_proxy, __egdesk_http_proxy, __gmail_proxy, __apps_script_proxy, __knowledge_wiki_proxy, __egdesk_config_proxy, __ai_caller_proxy, __kakao_proxy, __phone_proxy, __instagram_proxy, __financehub_proxy, __blog_proxy, __youtube_proxy, __visitor_auth_proxy, and __visitor_google_proxy requests
79
79
  * and forwards them to the EGDesk MCP HTTP server. This avoids CORS in local and tunneled environments.
80
80
  *
81
81
  * Generated by @egdesk/next-api-plugin
@@ -217,6 +217,94 @@ export async function proxy(request: NextRequest) {
217
217
  }
218
218
  }
219
219
 
220
+ if (pathname.includes('__bizinfo_proxy')) {
221
+ try {
222
+ const body = await request.text();
223
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
224
+
225
+ const response = await fetch(\`\${apiUrl}/bizinfo/tools/call\`, {
226
+ method: 'POST',
227
+ headers: buildEgdeskHeaders(),
228
+ body,
229
+ });
230
+
231
+ const result = await response.json();
232
+
233
+ return NextResponse.json(result, { status: response.status });
234
+ } catch (error: any) {
235
+ return NextResponse.json(
236
+ { error: 'Proxy error', message: error.message },
237
+ { status: 500 }
238
+ );
239
+ }
240
+ }
241
+
242
+ if (pathname.includes('__bidnotice_proxy')) {
243
+ try {
244
+ const body = await request.text();
245
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
246
+
247
+ const response = await fetch(\`\${apiUrl}/bidnotice/tools/call\`, {
248
+ method: 'POST',
249
+ headers: buildEgdeskHeaders(),
250
+ body,
251
+ });
252
+
253
+ const result = await response.json();
254
+
255
+ return NextResponse.json(result, { status: response.status });
256
+ } catch (error: any) {
257
+ return NextResponse.json(
258
+ { error: 'Proxy error', message: error.message },
259
+ { status: 500 }
260
+ );
261
+ }
262
+ }
263
+
264
+ if (pathname.includes('__koneps_proxy')) {
265
+ try {
266
+ const body = await request.text();
267
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
268
+
269
+ const response = await fetch(\`\${apiUrl}/koneps/tools/call\`, {
270
+ method: 'POST',
271
+ headers: buildEgdeskHeaders(),
272
+ body,
273
+ });
274
+
275
+ const result = await response.json();
276
+
277
+ return NextResponse.json(result, { status: response.status });
278
+ } catch (error: any) {
279
+ return NextResponse.json(
280
+ { error: 'Proxy error', message: error.message },
281
+ { status: 500 }
282
+ );
283
+ }
284
+ }
285
+
286
+ if (pathname.includes('__nps_proxy')) {
287
+ try {
288
+ const body = await request.text();
289
+ const apiUrl = process.env.NEXT_PUBLIC_EGDESK_API_URL || 'http://localhost:8080';
290
+
291
+ const response = await fetch(\`\${apiUrl}/nps/tools/call\`, {
292
+ method: 'POST',
293
+ headers: buildEgdeskHeaders(),
294
+ body,
295
+ });
296
+
297
+ const result = await response.json();
298
+
299
+ return NextResponse.json(result, { status: response.status });
300
+ } catch (error: any) {
301
+ return NextResponse.json(
302
+ { error: 'Proxy error', message: error.message },
303
+ { status: 500 }
304
+ );
305
+ }
306
+ }
307
+
220
308
  if (pathname.includes('__seo_proxy')) {
221
309
  try {
222
310
  const body = await request.text();
@@ -737,7 +825,7 @@ export const config = {
737
825
  matcher: [
738
826
  /*
739
827
  * Match all paths except static assets
740
- * 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 / __drive_proxy / __sheets_proxy / __docs_proxy / __slides_proxy / __egdesk_http_proxy / __gmail_proxy / __apps_script_proxy / __knowledge_wiki_proxy / __egdesk_config_proxy / __ai_caller_proxy / __kakao_proxy / __phone_proxy / __instagram_proxy / __financehub_proxy / __blog_proxy / __youtube_proxy / __visitor_auth_proxy / __visitor_google_proxy
828
+ * The proxy function filters for __user_data_proxy / __browser_recording_proxy / __internal_knowledge_proxy / __company_research_proxy / __ai_center_proxy / __korean_law_proxy / __bizinfo_proxy / __nps_proxy / __seo_proxy / __ssl_proxy / __local_agent_proxy / __pageindex_proxy / __drive_proxy / __sheets_proxy / __docs_proxy / __slides_proxy / __egdesk_http_proxy / __gmail_proxy / __apps_script_proxy / __knowledge_wiki_proxy / __egdesk_config_proxy / __ai_caller_proxy / __kakao_proxy / __phone_proxy / __instagram_proxy / __financehub_proxy / __blog_proxy / __youtube_proxy / __visitor_auth_proxy / __visitor_google_proxy
741
829
  */
742
830
  '/:path*',
743
831
  ],
@@ -5,4 +5,5 @@
5
5
  * EGDesk (same Auth project) and receive an opaque session id.
6
6
  * Published sites never receive SUPABASE_URL or the anon key.
7
7
  */
8
+ export declare function ensureVisitorAuthConfig(projectPath: string): boolean;
8
9
  export declare function generateVisitorAuth(projectPath: string): void;
@@ -40,6 +40,7 @@ var __importStar = (this && this.__importStar) || (function () {
40
40
  };
41
41
  })();
42
42
  Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.ensureVisitorAuthConfig = ensureVisitorAuthConfig;
43
44
  exports.generateVisitorAuth = generateVisitorAuth;
44
45
  const fs = __importStar(require("fs"));
45
46
  const path = __importStar(require("path"));
@@ -87,7 +88,11 @@ const CALLBACK_PAGE = `'use client';
87
88
 
88
89
  /**
89
90
  * Visitor Google OAuth callback.
90
- * Generated by @egdesk/next-api-plugin.
91
+ * Generated by @egdesk/next-api-plugin — do not edit.
92
+ *
93
+ * Customize login UI in your own pages (e.g. app/login/page.tsx).
94
+ * Set default scopes in egdesk.visitor-auth.ts, or pass them to
95
+ * startVisitorGoogleLogin({ scopes: VISITOR_BASIC_SCOPES }).
91
96
  *
92
97
  * EGDesk completes Google/Supabase OAuth, then redirects here with ?code=
93
98
  * (a one-time EGDesk code, not a Supabase token). This page exchanges it
@@ -126,6 +131,23 @@ export default function VisitorAuthCallbackPage() {
126
131
  );
127
132
  }
128
133
  `;
134
+ const VISITOR_AUTH_CONFIG = `/**
135
+ * Visitor Google login defaults for this site.
136
+ *
137
+ * OWNED BY THIS PROJECT — EGDesk will not overwrite this file.
138
+ * Generated helpers (egdesk-visitor-google.ts) read these defaults.
139
+ *
140
+ * Customize login UI in your own pages. Do not edit generated helpers.
141
+ */
142
+ export const VISITOR_AUTH = {
143
+ /**
144
+ * 'basic' — email/profile only (smaller Google consent).
145
+ * 'workspace' — Drive (per-file), Sheets, Docs, Slides.
146
+ * A page can still pass startVisitorGoogleLogin({ scopes: VISITOR_WORKSPACE_SCOPES }).
147
+ */
148
+ scopes: 'basic' as 'basic' | 'workspace',
149
+ };
150
+ `;
129
151
  const VISITOR_HELPERS = `/**
130
152
  * EGDesk visitor Google helpers (published-site visitors).
131
153
  *
@@ -134,25 +156,51 @@ const VISITOR_HELPERS = `/**
134
156
  * The opaque session is bound to this site origin and will not work on
135
157
  * another published site that shares the same EGDesk.
136
158
  *
137
- * Import this file only from pages that need visitor Google.
159
+ * Generated by @egdesk/next-api-plugin — do not edit.
160
+ * Customize login UI in your pages. Set default scopes in egdesk.visitor-auth.ts
161
+ * or pass startVisitorGoogleLogin({ scopes: VISITOR_BASIC_SCOPES }).
138
162
  *
139
- * Generated by @egdesk/next-api-plugin.
163
+ * Import this file only from pages that need visitor Google.
140
164
  */
141
165
 
142
166
  import { apiFetch } from './egdesk-helpers';
167
+ import { VISITOR_AUTH } from './egdesk.visitor-auth';
143
168
 
144
169
  const VISITOR_SESSION_KEY = 'egdesk_visitor_session';
145
170
 
146
- export const VISITOR_GOOGLE_OAUTH_SCOPES = [
171
+ export type VisitorScopePreset = 'basic' | 'workspace';
172
+
173
+ export const VISITOR_BASIC_SCOPES = [
147
174
  'https://www.googleapis.com/auth/userinfo.email',
148
175
  'https://www.googleapis.com/auth/userinfo.profile',
176
+ 'openid',
177
+ ] as const;
178
+
179
+ export const VISITOR_WORKSPACE_SCOPES = [
180
+ ...VISITOR_BASIC_SCOPES,
149
181
  'https://www.googleapis.com/auth/drive.file',
150
182
  'https://www.googleapis.com/auth/spreadsheets',
151
183
  'https://www.googleapis.com/auth/documents',
152
184
  'https://www.googleapis.com/auth/presentations',
153
- 'openid',
154
185
  ] as const;
155
186
 
187
+ /** @deprecated use VISITOR_WORKSPACE_SCOPES */
188
+ export const VISITOR_GOOGLE_OAUTH_SCOPES = VISITOR_WORKSPACE_SCOPES;
189
+
190
+ function resolveVisitorLoginScopes(
191
+ override?: readonly string[] | VisitorScopePreset,
192
+ ): string[] {
193
+ if (override === 'basic') return [...VISITOR_BASIC_SCOPES];
194
+ if (override === 'workspace') return [...VISITOR_WORKSPACE_SCOPES];
195
+ if (Array.isArray(override) && override.length > 0) return [...override];
196
+ const fromEnv =
197
+ (typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_EGDESK_VISITOR_SCOPES) || '';
198
+ if (fromEnv === 'workspace') return [...VISITOR_WORKSPACE_SCOPES];
199
+ if (fromEnv === 'basic') return [...VISITOR_BASIC_SCOPES];
200
+ if (VISITOR_AUTH.scopes === 'workspace') return [...VISITOR_WORKSPACE_SCOPES];
201
+ return [...VISITOR_BASIC_SCOPES];
202
+ }
203
+
156
204
  function getVisitorSessionId(): string | null {
157
205
  if (typeof window === 'undefined') return null;
158
206
  return window.localStorage.getItem(VISITOR_SESSION_KEY);
@@ -247,10 +295,14 @@ async function callVisitorGoogle(tool: string, args: Record<string, unknown> = {
247
295
  /**
248
296
  * Sign a website visitor in with Google via EGDesk.
249
297
  * Creates/uses an EGDesk user; Google tokens stay under that user_id on EGDesk.
298
+ *
299
+ * Default scopes come from egdesk.visitor-auth.ts (never overwritten).
300
+ * Pass scopes to override per button, e.g. VISITOR_BASIC_SCOPES or 'workspace'.
250
301
  */
251
302
  export async function startVisitorGoogleLogin(options: {
252
303
  next?: string;
253
304
  forceConsent?: boolean;
305
+ scopes?: readonly string[] | VisitorScopePreset;
254
306
  } = {}) {
255
307
  if (typeof window === 'undefined') {
256
308
  throw new Error('startVisitorGoogleLogin() must run in the browser');
@@ -262,11 +314,13 @@ export async function startVisitorGoogleLogin(options: {
262
314
  returnTo.searchParams.set('next', next);
263
315
  // Localhost → EGDesk :54321. Tunnel site → {gateway}/t/{id}/visitor-auth/callback.
264
316
  const egdeskPublicUrl = resolveEgdeskPublicUrl();
317
+ const scopes = resolveVisitorLoginScopes(options.scopes);
265
318
 
266
319
  const result = await callVisitorAuth('start', {
267
320
  returnTo: returnTo.toString(),
268
321
  egdeskPublicUrl,
269
322
  forceConsent: options.forceConsent === true,
323
+ scopes,
270
324
  });
271
325
  if (!result?.authUrl) {
272
326
  throw new Error(result?.error || 'Failed to start visitor Google login');
@@ -314,8 +368,17 @@ export async function getVisitorSheetRange(spreadsheetId: string, range: string)
314
368
  return callVisitorGoogle('getSheetRange', { spreadsheetId, range });
315
369
  }
316
370
  `;
371
+ function ensureVisitorAuthConfig(projectPath) {
372
+ const configPath = path.join(projectPath, 'egdesk.visitor-auth.ts');
373
+ if (fs.existsSync(configPath))
374
+ return false;
375
+ fs.writeFileSync(configPath, VISITOR_AUTH_CONFIG.replace(/\r?\n/g, os.EOL), 'utf-8');
376
+ console.log(`✅ Created ${configPath} (site-owned; will not be overwritten)`);
377
+ return true;
378
+ }
317
379
  function generateVisitorAuth(projectPath) {
318
380
  const appDir = resolveAppDir(projectPath);
381
+ ensureVisitorAuthConfig(projectPath);
319
382
  writeGenerated(path.join(appDir, 'auth', 'callback', 'page.tsx'), CALLBACK_PAGE);
320
383
  writeGenerated(path.join(projectPath, 'egdesk-visitor-google.ts'), VISITOR_HELPERS);
321
384
  removeIfExists(path.join(appDir, 'api', 'visitor-google', 'route.ts'));
package/dist/index.d.ts CHANGED
@@ -8,7 +8,7 @@
8
8
  * The minimum EGDesk app version this plugin version is compatible with.
9
9
  * The app checks this at setup time and warns on mismatch.
10
10
  */
11
- export declare const COMPATIBLE_APP_VERSION = "1.4.59";
11
+ export declare const COMPATIBLE_APP_VERSION = "1.4.62";
12
12
  export interface SetupOptions {
13
13
  egdeskUrl?: string;
14
14
  /** Production EGDesk server URL — written to .env.production.local. Falls back to egdeskUrl. */
@@ -43,4 +43,4 @@ export { generateProxy } from './generate-proxy';
43
43
  export { generateHelpers, generateSchemaFile, ensureSchemaFile, formatEgdeskSchemaFileContent } from './generate-helpers';
44
44
  export type { SchemaTableDefinition, EnsureSchemaFileResult, GenerateHelpersOptions } from './generate-helpers';
45
45
  export { generateApiWrapper } from './generate-api-wrapper';
46
- export { generateVisitorAuth } from './generate-visitor-auth';
46
+ export { generateVisitorAuth, ensureVisitorAuthConfig } from './generate-visitor-auth';
package/dist/index.js CHANGED
@@ -39,14 +39,14 @@ var __importStar = (this && this.__importStar) || (function () {
39
39
  };
40
40
  })();
41
41
  Object.defineProperty(exports, "__esModule", { value: true });
42
- exports.generateVisitorAuth = exports.generateApiWrapper = exports.formatEgdeskSchemaFileContent = exports.ensureSchemaFile = exports.generateSchemaFile = exports.generateHelpers = exports.generateProxy = exports.generateMiddleware = exports.updateEnvFiles = exports.loadTablesFromSchemaFile = exports.generateConfigFile = exports.discoverTables = exports.COMPATIBLE_APP_VERSION = void 0;
42
+ exports.ensureVisitorAuthConfig = exports.generateVisitorAuth = exports.generateApiWrapper = exports.formatEgdeskSchemaFileContent = exports.ensureSchemaFile = exports.generateSchemaFile = exports.generateHelpers = exports.generateProxy = exports.generateMiddleware = exports.updateEnvFiles = exports.loadTablesFromSchemaFile = exports.generateConfigFile = exports.discoverTables = exports.COMPATIBLE_APP_VERSION = void 0;
43
43
  exports.detectNextUseProxy = detectNextUseProxy;
44
44
  exports.setupNextApiPlugin = setupNextApiPlugin;
45
45
  /**
46
46
  * The minimum EGDesk app version this plugin version is compatible with.
47
47
  * The app checks this at setup time and warns on mismatch.
48
48
  */
49
- exports.COMPATIBLE_APP_VERSION = '1.4.59';
49
+ exports.COMPATIBLE_APP_VERSION = '1.4.62';
50
50
  const fs = __importStar(require("fs"));
51
51
  const path = __importStar(require("path"));
52
52
  const setup_userdata_1 = require("./setup-userdata");
@@ -196,7 +196,8 @@ async function setupNextApiPlugin(projectPath, options = {}) {
196
196
  console.log(' - egdesk.config.ts (type-safe config)');
197
197
  console.log(' - egdesk.schema.ts (committed seed schema — add to git if newly created)');
198
198
  console.log(' - egdesk-helpers.ts (helper functions)');
199
- console.log(' - egdesk-visitor-google.ts (visitor Google via EGDesk Auth broker)');
199
+ console.log(' - egdesk-visitor-google.ts (generated visitor Google helper — do not edit)');
200
+ console.log(' - egdesk.visitor-auth.ts (site-owned login defaults; never overwritten)');
200
201
  console.log(' - src/lib/api.ts (basePath-aware fetch wrapper)');
201
202
  console.log(' - app/auth/callback/page.tsx (exchanges EGDesk one-time login code)');
202
203
  console.log(' - .env.development.local (dev environment variables)');
@@ -243,3 +244,4 @@ var generate_api_wrapper_2 = require("./generate-api-wrapper");
243
244
  Object.defineProperty(exports, "generateApiWrapper", { enumerable: true, get: function () { return generate_api_wrapper_2.generateApiWrapper; } });
244
245
  var generate_visitor_auth_2 = require("./generate-visitor-auth");
245
246
  Object.defineProperty(exports, "generateVisitorAuth", { enumerable: true, get: function () { return generate_visitor_auth_2.generateVisitorAuth; } });
247
+ Object.defineProperty(exports, "ensureVisitorAuthConfig", { enumerable: true, get: function () { return generate_visitor_auth_2.ensureVisitorAuthConfig; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egdesk/next-api-plugin",
3
- "version": "1.5.50",
3
+ "version": "1.5.54",
4
4
  "description": "Next.js plugin for EGDesk database proxy integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",