@egdesk/next-api-plugin 1.5.136 → 1.5.199

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.
@@ -33,5 +33,5 @@ export interface GenerateHelpersOptions {
33
33
  apiKeyNames?: string[];
34
34
  }
35
35
  /** Bump when generated helper/middleware behavior changes; EGDesk regenerates stale projects. */
36
- export declare const EGDESK_HELPERS_GENERATION_VERSION = "4";
36
+ export declare const EGDESK_HELPERS_GENERATION_VERSION = "6";
37
37
  export declare function generateHelpers(projectPath: string, options?: GenerateHelpersOptions): void;
@@ -134,7 +134,7 @@ function ensureSchemaFile(projectPath, tables) {
134
134
  };
135
135
  }
136
136
  /** Bump when generated helper/middleware behavior changes; EGDesk regenerates stale projects. */
137
- exports.EGDESK_HELPERS_GENERATION_VERSION = '4';
137
+ exports.EGDESK_HELPERS_GENERATION_VERSION = '6';
138
138
  function generateHelpers(projectPath, options = {}) {
139
139
  const helperPath = path.join(projectPath, 'egdesk-helpers.ts');
140
140
  const helperContent = `/**
@@ -154,11 +154,13 @@ function generateHelpers(projectPath, options = {}) {
154
154
  * - egdesk.config.ts — auto-generated runtime snapshot (gitignored; do not edit)
155
155
  *
156
156
  * AI / external agents:
157
- * - If egdesk-user-data MCP is connected (Claude Desktop / Antigravity / Cursor), prefer MCP tools
158
- * for exploring My DB: user_data_list_projects → user_data_select_project → user_data_list_tables / query.
159
- * - Check that EGDesk is running and MCP tools are actually available before relying on them.
160
- * - For app code in this repo, keep using these helpers (queryTable, etc.) — MCP is optional for agents.
161
- * - If MCP tools are missing/empty, fall back to helpers + EGDESK-README.md; ask the user to install MCP from EGDesk.
157
+ * - Install MCP from EGDesk (MCP Server → Claude Desktop / Antigravity / Cursor). One server key \`egdesk\`
158
+ * runs \`mcp-stdio-proxy.js combined\` against \`http://localhost:8080\` (full tool catalog when services are enabled).
159
+ * - Do not rely on \`egdesk-recorder\` alone (Recorder on :8081) for My DB — that catalog is Playwright / phone / scheduler only.
160
+ * - Prefer MCP tools when present: user_data_list_projects → user_data_select_project → user_data_list_tables / query.
161
+ * - If tools are only browser_recording_* / phone_* / scheduler_*, fix MCP config (main \`egdesk\` on :8080, EGDesk running), then restart the agent.
162
+ * - For app code in this repo, keep using these helpers — MCP is optional for external agents.
163
+ * - If MCP tools are missing/empty, fall back to helpers + EGDESK-README.md and ask the user to reinstall MCP from EGDesk.
162
164
  * - Tunnel: getEgdeskTunnel() (live prod/dev URLs + X-Api-Key). Embed into Apps Script with setupAppsScriptEgdeskTunnel().
163
165
  */
164
166
 
@@ -241,11 +243,38 @@ export async function apiFetch(path: string, options?: RequestInit): Promise<Res
241
243
  }
242
244
  }
243
245
 
244
- return fetch(url, {
246
+ const fetchOpts: RequestInit = {
245
247
  ...options,
246
248
  headers,
247
249
  credentials: options?.credentials ?? 'same-origin',
248
- });
250
+ };
251
+
252
+ try {
253
+ return await fetch(url, fetchOpts);
254
+ } catch (err: any) {
255
+ const method = (options?.method || 'GET').toUpperCase();
256
+ const isIdempotentRead = method === 'GET' || method === 'HEAD';
257
+ const isAborted = Boolean(options?.signal?.aborted) || err?.name === 'AbortError';
258
+ if (isIdempotentRead && !isAborted) {
259
+ await new Promise<void>((resolve) => {
260
+ const timer = setTimeout(resolve, 350);
261
+ if (options?.signal) {
262
+ options.signal.addEventListener(
263
+ 'abort',
264
+ () => {
265
+ clearTimeout(timer);
266
+ resolve();
267
+ },
268
+ { once: true },
269
+ );
270
+ }
271
+ });
272
+ if (!options?.signal?.aborted) {
273
+ return fetch(url, fetchOpts);
274
+ }
275
+ }
276
+ throw err;
277
+ }
249
278
  }
250
279
 
251
280
  /** Build EGDesk routing headers (project-id + env) for server-side direct calls. */
@@ -643,22 +672,56 @@ export async function callUserDataTool(
643
672
  return parseEgdeskMcpToolResponse(response);
644
673
  }
645
674
 
675
+ export type UserDataFilterValue = string | number | boolean;
676
+ export type UserDataFilterMap = Record<string, UserDataFilterValue | undefined | null>;
677
+
678
+ function normalizeUserDataFilters(options?: {
679
+ filters?: UserDataFilterMap;
680
+ where?: UserDataFilterMap;
681
+ }): Record<string, string> | undefined {
682
+ const rawFilters = options?.filters ?? options?.where;
683
+ if (!rawFilters || typeof rawFilters !== 'object') {
684
+ return undefined;
685
+ }
686
+ const entries = Object.entries(rawFilters);
687
+ if (entries.length === 0) {
688
+ return undefined;
689
+ }
690
+ const normalized: Record<string, string> = {};
691
+ for (const [key, value] of entries) {
692
+ if (value !== undefined && value !== null) {
693
+ normalized[key] = String(value);
694
+ }
695
+ }
696
+ if (Object.keys(normalized).length === 0) {
697
+ throw new Error(
698
+ \`EGDesk user-data filter (\${entries.map(([k]) => k).join(', ')}) resolved to undefined/null; refusing to run unfiltered operation.\`,
699
+ );
700
+ }
701
+ return normalized;
702
+ }
703
+
646
704
  /**
647
705
  * Query table data
648
706
  */
649
707
  export async function queryTable(
650
708
  tableName: string,
651
709
  options: {
652
- filters?: Record<string, string>;
710
+ filters?: UserDataFilterMap;
711
+ /** @deprecated Use \`filters\` instead. Supported as a fallback alias. */
712
+ where?: UserDataFilterMap;
653
713
  limit?: number;
654
714
  offset?: number;
655
715
  orderBy?: string;
656
716
  orderDirection?: 'ASC' | 'DESC';
657
717
  } = {}
658
718
  ) {
719
+ const { filters: _rawFilters, where: _rawWhere, ...restOptions } = options;
720
+ const filters = normalizeUserDataFilters(options);
659
721
  return callUserDataTool('user_data_query', {
660
722
  tableName,
661
- ...options
723
+ ...restOptions,
724
+ ...(filters ? { filters } : {})
662
725
  });
663
726
  }
664
727
 
@@ -685,15 +748,20 @@ export async function aggregateTable(
685
748
  column: string,
686
749
  aggregateFunction: 'SUM' | 'AVG' | 'MIN' | 'MAX' | 'COUNT',
687
750
  options: {
688
- filters?: Record<string, string>;
751
+ filters?: UserDataFilterMap;
752
+ /** @deprecated Use \`filters\` instead. Supported as a fallback alias. */
753
+ where?: UserDataFilterMap;
689
754
  groupBy?: string;
690
755
  } = {}
691
756
  ) {
757
+ const { filters: _rawFilters, where: _rawWhere, ...restOptions } = options;
758
+ const filters = normalizeUserDataFilters(options);
692
759
  return callUserDataTool('user_data_aggregate', {
693
760
  tableName,
694
761
  column,
695
762
  function: aggregateFunction,
696
- ...options
763
+ ...restOptions,
764
+ ...(filters ? { filters } : {})
697
765
  });
698
766
  }
699
767
 
@@ -727,17 +795,22 @@ export async function joinTables(
727
795
  }>,
728
796
  options: {
729
797
  select?: string[];
730
- filters?: Record<string, string>;
798
+ filters?: UserDataFilterMap;
799
+ /** @deprecated Use \`filters\` instead. Supported as a fallback alias. */
800
+ where?: UserDataFilterMap;
731
801
  limit?: number;
732
802
  offset?: number;
733
803
  orderBy?: string;
734
804
  orderDirection?: 'ASC' | 'DESC';
735
805
  } = {}
736
806
  ) {
807
+ const { filters: _rawFilters, where: _rawWhere, ...restOptions } = options;
808
+ const filters = normalizeUserDataFilters(options);
737
809
  return callUserDataTool('user_data_join', {
738
810
  fromTable,
739
811
  joins,
740
- ...options
812
+ ...restOptions,
813
+ ...(filters ? { filters } : {})
741
814
  });
742
815
  }
743
816
 
@@ -815,11 +888,13 @@ export async function updateRows(
815
888
  updatesOrPayload: Record<string, any>,
816
889
  options?: {
817
890
  ids?: number[];
818
- filters?: Record<string, string>;
891
+ filters?: UserDataFilterMap;
892
+ /** @deprecated Use \`filters\` instead. Supported as a fallback alias. */
893
+ where?: UserDataFilterMap;
819
894
  }
820
895
  ) {
821
896
  let updates: Record<string, any>;
822
- let rowOptions: typeof options;
897
+ let rowOptions: { ids?: number[]; filters?: Record<string, string> } | undefined;
823
898
 
824
899
  if (
825
900
  options === undefined &&
@@ -833,13 +908,24 @@ export async function updateRows(
833
908
  const payload = updatesOrPayload as {
834
909
  updates: Record<string, any>;
835
910
  ids?: number[];
836
- filters?: Record<string, string>;
911
+ filters?: UserDataFilterMap;
912
+ where?: UserDataFilterMap;
837
913
  };
838
914
  updates = payload.updates;
839
- rowOptions = { ids: payload.ids, filters: payload.filters };
915
+ const filters = normalizeUserDataFilters(payload);
916
+ rowOptions = {
917
+ ...(payload.ids ? { ids: payload.ids } : {}),
918
+ ...(filters ? { filters } : {})
919
+ };
840
920
  } else {
841
921
  updates = updatesOrPayload;
842
- rowOptions = options;
922
+ const filters = normalizeUserDataFilters(options);
923
+ rowOptions = options
924
+ ? {
925
+ ...(options.ids ? { ids: options.ids } : {}),
926
+ ...(filters ? { filters } : {})
927
+ }
928
+ : undefined;
843
929
  }
844
930
 
845
931
  return callUserDataTool('user_data_update_rows', {
@@ -856,12 +942,17 @@ export async function deleteRows(
856
942
  tableName: string,
857
943
  options: {
858
944
  ids?: number[];
859
- filters?: Record<string, string>;
945
+ filters?: UserDataFilterMap;
946
+ /** @deprecated Use \`filters\` instead. Supported as a fallback alias. */
947
+ where?: UserDataFilterMap;
860
948
  }
861
949
  ) {
950
+ const { filters: _rawFilters, where: _rawWhere, ...restOptions } = options;
951
+ const filters = normalizeUserDataFilters(options);
862
952
  return callUserDataTool('user_data_delete_rows', {
863
953
  tableName,
864
- ...options
954
+ ...restOptions,
955
+ ...(filters ? { filters } : {})
865
956
  });
866
957
  }
867
958
 
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,125 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const strict_1 = __importDefault(require("node:assert/strict"));
7
+ const node_fs_1 = __importDefault(require("node:fs"));
8
+ const node_os_1 = __importDefault(require("node:os"));
9
+ const node_path_1 = __importDefault(require("node:path"));
10
+ const node_test_1 = __importDefault(require("node:test"));
11
+ const typescript_1 = __importDefault(require("typescript"));
12
+ const node_vm_1 = __importDefault(require("node:vm"));
13
+ const generate_helpers_1 = require("./generate-helpers");
14
+ function loadGeneratedHelpersModule() {
15
+ const tmpDir = node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), 'egdesk-helpers-test-'));
16
+ try {
17
+ (0, generate_helpers_1.generateHelpers)(tmpDir, { apiKeyNames: ['default'] });
18
+ const helperSource = node_fs_1.default.readFileSync(node_path_1.default.join(tmpDir, 'egdesk-helpers.ts'), 'utf-8');
19
+ const transpiled = typescript_1.default.transpileModule(helperSource, {
20
+ compilerOptions: {
21
+ module: typescript_1.default.ModuleKind.CommonJS,
22
+ target: typescript_1.default.ScriptTarget.ES2020,
23
+ },
24
+ }).outputText;
25
+ const calls = [];
26
+ let fetchImpl = async (url, options) => {
27
+ calls.push({ url, options });
28
+ return {
29
+ ok: true,
30
+ status: 200,
31
+ statusText: 'OK',
32
+ json: async () => ({
33
+ success: true,
34
+ result: { content: [{ text: JSON.stringify({ rows: [], total: 0 }) }] },
35
+ }),
36
+ };
37
+ };
38
+ const moduleExports = {};
39
+ const sandbox = {
40
+ exports: moduleExports,
41
+ module: { exports: moduleExports },
42
+ require: (id) => {
43
+ if (id === './egdesk.config') {
44
+ return {
45
+ EGDESK_CONFIG: {
46
+ apiUrl: 'http://localhost:8080',
47
+ apiKey: 'test-key',
48
+ tables: {},
49
+ },
50
+ };
51
+ }
52
+ throw new Error(`Unexpected require: ${id}`);
53
+ },
54
+ process: { env: {} },
55
+ fetch: (url, options) => fetchImpl(url, options),
56
+ Headers,
57
+ URL,
58
+ setTimeout,
59
+ clearTimeout,
60
+ console,
61
+ };
62
+ node_vm_1.default.runInNewContext(transpiled, sandbox);
63
+ return {
64
+ helpers: sandbox.module.exports,
65
+ calls,
66
+ setFetchImpl: (fn) => {
67
+ fetchImpl = fn;
68
+ },
69
+ };
70
+ }
71
+ finally {
72
+ node_fs_1.default.rmSync(tmpDir, { recursive: true, force: true });
73
+ }
74
+ }
75
+ (0, node_test_1.default)('EGDESK_HELPERS_GENERATION_VERSION is 6', () => {
76
+ const { helpers } = loadGeneratedHelpersModule();
77
+ strict_1.default.equal(generate_helpers_1.EGDESK_HELPERS_GENERATION_VERSION, '6');
78
+ strict_1.default.equal(helpers.EGDESK_HELPERS_GENERATION_VERSION, '6');
79
+ });
80
+ (0, node_test_1.default)('queryTable normalizes where fallback and coerces primitive values to strings', async () => {
81
+ const { helpers, calls } = loadGeneratedHelpersModule();
82
+ await helpers.queryTable('tokens', {
83
+ where: { user_id: 42, active: true, ignored: undefined },
84
+ limit: 10,
85
+ });
86
+ strict_1.default.equal(calls.length, 1);
87
+ const body = JSON.parse(String(calls[0].options.body));
88
+ strict_1.default.equal(body.tool, 'user_data_query');
89
+ strict_1.default.deepEqual(body.arguments, {
90
+ tableName: 'tokens',
91
+ limit: 10,
92
+ filters: {
93
+ user_id: '42',
94
+ active: 'true',
95
+ },
96
+ });
97
+ });
98
+ (0, node_test_1.default)('queryTable throws when non-empty filter object resolves entirely to undefined/null', async () => {
99
+ const { helpers, calls } = loadGeneratedHelpersModule();
100
+ await strict_1.default.rejects(() => helpers.queryTable('tokens', {
101
+ filters: { user_id: undefined },
102
+ }), /resolved to undefined\/null; refusing to run unfiltered operation/);
103
+ strict_1.default.equal(calls.length, 0);
104
+ });
105
+ (0, node_test_1.default)('apiFetch retries transient GET network failure once and does not retry POST', async () => {
106
+ const { helpers, setFetchImpl } = loadGeneratedHelpersModule();
107
+ let getAttempts = 0;
108
+ setFetchImpl(async () => {
109
+ getAttempts += 1;
110
+ if (getAttempts === 1) {
111
+ throw new TypeError('Failed to fetch');
112
+ }
113
+ return { ok: true, status: 200 };
114
+ });
115
+ const getRes = await helpers.apiFetch('/api/workspaces');
116
+ strict_1.default.equal(getRes.status, 200);
117
+ strict_1.default.equal(getAttempts, 2);
118
+ let postAttempts = 0;
119
+ setFetchImpl(async () => {
120
+ postAttempts += 1;
121
+ throw new TypeError('Failed to fetch');
122
+ });
123
+ await strict_1.default.rejects(() => helpers.apiFetch('/api/workspaces', { method: 'POST' }), /Failed to fetch/);
124
+ strict_1.default.equal(postAttempts, 1);
125
+ });
@@ -779,6 +779,10 @@ export function VisitorGcpByoPanel() {
779
779
  <p style={{ fontSize: '0.9rem', color: '#444' }}>
780
780
  Upload a Web application OAuth client JSON. Secrets stay on the operator&apos;s EGDesk PC, not this site&apos;s server.
781
781
  </p>
782
+ <p style={{ fontSize: '0.85rem', color: '#555', marginTop: 8 }}>
783
+ In Google Cloud Console → APIs &amp; Services → Library, enable: Google Drive API, Google Sheets API,
784
+ Google Apps Script API, and Maps JavaScript API on the same project as your OAuth client.
785
+ </p>
782
786
  <label style={{ display: 'block', marginBottom: 8 }}>
783
787
  Handle (optional)
784
788
  <input
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.147";
11
+ export declare const COMPATIBLE_APP_VERSION = "1.4.220";
12
12
  export interface SetupOptions {
13
13
  egdeskUrl?: string;
14
14
  /** Production EGDesk server URL — written to .env.production.local. Falls back to egdeskUrl. */
package/dist/index.js CHANGED
@@ -46,7 +46,7 @@ exports.setupNextApiPlugin = setupNextApiPlugin;
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.147';
49
+ exports.COMPATIBLE_APP_VERSION = '1.4.220';
50
50
  const fs = __importStar(require("fs"));
51
51
  const path = __importStar(require("path"));
52
52
  const setup_userdata_1 = require("./setup-userdata");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@egdesk/next-api-plugin",
3
- "version": "1.5.136",
3
+ "version": "1.5.199",
4
4
  "description": "Next.js plugin for EGDesk database proxy integration",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -16,7 +16,7 @@
16
16
  },
17
17
  "scripts": {
18
18
  "build": "tsc",
19
- "test": "npm run build && node --test dist/canonical-visitor-redirect.test.js",
19
+ "test": "npm run build && node --test dist/canonical-visitor-redirect.test.js dist/generate-helpers.test.js",
20
20
  "dev": "tsc --watch",
21
21
  "prepublishOnly": "npm run build"
22
22
  },