@egdesk/next-api-plugin 1.5.136 → 1.5.163

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 = "5";
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 = '5';
138
138
  function generateHelpers(projectPath, options = {}) {
139
139
  const helperPath = path.join(projectPath, 'egdesk-helpers.ts');
140
140
  const helperContent = `/**
@@ -241,11 +241,38 @@ export async function apiFetch(path: string, options?: RequestInit): Promise<Res
241
241
  }
242
242
  }
243
243
 
244
- return fetch(url, {
244
+ const fetchOpts: RequestInit = {
245
245
  ...options,
246
246
  headers,
247
247
  credentials: options?.credentials ?? 'same-origin',
248
- });
248
+ };
249
+
250
+ try {
251
+ return await fetch(url, fetchOpts);
252
+ } catch (err: any) {
253
+ const method = (options?.method || 'GET').toUpperCase();
254
+ const isIdempotentRead = method === 'GET' || method === 'HEAD';
255
+ const isAborted = Boolean(options?.signal?.aborted) || err?.name === 'AbortError';
256
+ if (isIdempotentRead && !isAborted) {
257
+ await new Promise<void>((resolve) => {
258
+ const timer = setTimeout(resolve, 350);
259
+ if (options?.signal) {
260
+ options.signal.addEventListener(
261
+ 'abort',
262
+ () => {
263
+ clearTimeout(timer);
264
+ resolve();
265
+ },
266
+ { once: true },
267
+ );
268
+ }
269
+ });
270
+ if (!options?.signal?.aborted) {
271
+ return fetch(url, fetchOpts);
272
+ }
273
+ }
274
+ throw err;
275
+ }
249
276
  }
250
277
 
251
278
  /** Build EGDesk routing headers (project-id + env) for server-side direct calls. */
@@ -643,22 +670,56 @@ export async function callUserDataTool(
643
670
  return parseEgdeskMcpToolResponse(response);
644
671
  }
645
672
 
673
+ export type UserDataFilterValue = string | number | boolean;
674
+ export type UserDataFilterMap = Record<string, UserDataFilterValue | undefined | null>;
675
+
676
+ function normalizeUserDataFilters(options?: {
677
+ filters?: UserDataFilterMap;
678
+ where?: UserDataFilterMap;
679
+ }): Record<string, string> | undefined {
680
+ const rawFilters = options?.filters ?? options?.where;
681
+ if (!rawFilters || typeof rawFilters !== 'object') {
682
+ return undefined;
683
+ }
684
+ const entries = Object.entries(rawFilters);
685
+ if (entries.length === 0) {
686
+ return undefined;
687
+ }
688
+ const normalized: Record<string, string> = {};
689
+ for (const [key, value] of entries) {
690
+ if (value !== undefined && value !== null) {
691
+ normalized[key] = String(value);
692
+ }
693
+ }
694
+ if (Object.keys(normalized).length === 0) {
695
+ throw new Error(
696
+ \`EGDesk user-data filter (\${entries.map(([k]) => k).join(', ')}) resolved to undefined/null; refusing to run unfiltered operation.\`,
697
+ );
698
+ }
699
+ return normalized;
700
+ }
701
+
646
702
  /**
647
703
  * Query table data
648
704
  */
649
705
  export async function queryTable(
650
706
  tableName: string,
651
707
  options: {
652
- filters?: Record<string, string>;
708
+ filters?: UserDataFilterMap;
709
+ /** @deprecated Use \`filters\` instead. Supported as a fallback alias. */
710
+ where?: UserDataFilterMap;
653
711
  limit?: number;
654
712
  offset?: number;
655
713
  orderBy?: string;
656
714
  orderDirection?: 'ASC' | 'DESC';
657
715
  } = {}
658
716
  ) {
717
+ const { filters: _rawFilters, where: _rawWhere, ...restOptions } = options;
718
+ const filters = normalizeUserDataFilters(options);
659
719
  return callUserDataTool('user_data_query', {
660
720
  tableName,
661
- ...options
721
+ ...restOptions,
722
+ ...(filters ? { filters } : {})
662
723
  });
663
724
  }
664
725
 
@@ -685,15 +746,20 @@ export async function aggregateTable(
685
746
  column: string,
686
747
  aggregateFunction: 'SUM' | 'AVG' | 'MIN' | 'MAX' | 'COUNT',
687
748
  options: {
688
- filters?: Record<string, string>;
749
+ filters?: UserDataFilterMap;
750
+ /** @deprecated Use \`filters\` instead. Supported as a fallback alias. */
751
+ where?: UserDataFilterMap;
689
752
  groupBy?: string;
690
753
  } = {}
691
754
  ) {
755
+ const { filters: _rawFilters, where: _rawWhere, ...restOptions } = options;
756
+ const filters = normalizeUserDataFilters(options);
692
757
  return callUserDataTool('user_data_aggregate', {
693
758
  tableName,
694
759
  column,
695
760
  function: aggregateFunction,
696
- ...options
761
+ ...restOptions,
762
+ ...(filters ? { filters } : {})
697
763
  });
698
764
  }
699
765
 
@@ -727,17 +793,22 @@ export async function joinTables(
727
793
  }>,
728
794
  options: {
729
795
  select?: string[];
730
- filters?: Record<string, string>;
796
+ filters?: UserDataFilterMap;
797
+ /** @deprecated Use \`filters\` instead. Supported as a fallback alias. */
798
+ where?: UserDataFilterMap;
731
799
  limit?: number;
732
800
  offset?: number;
733
801
  orderBy?: string;
734
802
  orderDirection?: 'ASC' | 'DESC';
735
803
  } = {}
736
804
  ) {
805
+ const { filters: _rawFilters, where: _rawWhere, ...restOptions } = options;
806
+ const filters = normalizeUserDataFilters(options);
737
807
  return callUserDataTool('user_data_join', {
738
808
  fromTable,
739
809
  joins,
740
- ...options
810
+ ...restOptions,
811
+ ...(filters ? { filters } : {})
741
812
  });
742
813
  }
743
814
 
@@ -815,11 +886,13 @@ export async function updateRows(
815
886
  updatesOrPayload: Record<string, any>,
816
887
  options?: {
817
888
  ids?: number[];
818
- filters?: Record<string, string>;
889
+ filters?: UserDataFilterMap;
890
+ /** @deprecated Use \`filters\` instead. Supported as a fallback alias. */
891
+ where?: UserDataFilterMap;
819
892
  }
820
893
  ) {
821
894
  let updates: Record<string, any>;
822
- let rowOptions: typeof options;
895
+ let rowOptions: { ids?: number[]; filters?: Record<string, string> } | undefined;
823
896
 
824
897
  if (
825
898
  options === undefined &&
@@ -833,13 +906,24 @@ export async function updateRows(
833
906
  const payload = updatesOrPayload as {
834
907
  updates: Record<string, any>;
835
908
  ids?: number[];
836
- filters?: Record<string, string>;
909
+ filters?: UserDataFilterMap;
910
+ where?: UserDataFilterMap;
837
911
  };
838
912
  updates = payload.updates;
839
- rowOptions = { ids: payload.ids, filters: payload.filters };
913
+ const filters = normalizeUserDataFilters(payload);
914
+ rowOptions = {
915
+ ...(payload.ids ? { ids: payload.ids } : {}),
916
+ ...(filters ? { filters } : {})
917
+ };
840
918
  } else {
841
919
  updates = updatesOrPayload;
842
- rowOptions = options;
920
+ const filters = normalizeUserDataFilters(options);
921
+ rowOptions = options
922
+ ? {
923
+ ...(options.ids ? { ids: options.ids } : {}),
924
+ ...(filters ? { filters } : {})
925
+ }
926
+ : undefined;
843
927
  }
844
928
 
845
929
  return callUserDataTool('user_data_update_rows', {
@@ -856,12 +940,17 @@ export async function deleteRows(
856
940
  tableName: string,
857
941
  options: {
858
942
  ids?: number[];
859
- filters?: Record<string, string>;
943
+ filters?: UserDataFilterMap;
944
+ /** @deprecated Use \`filters\` instead. Supported as a fallback alias. */
945
+ where?: UserDataFilterMap;
860
946
  }
861
947
  ) {
948
+ const { filters: _rawFilters, where: _rawWhere, ...restOptions } = options;
949
+ const filters = normalizeUserDataFilters(options);
862
950
  return callUserDataTool('user_data_delete_rows', {
863
951
  tableName,
864
- ...options
952
+ ...restOptions,
953
+ ...(filters ? { filters } : {})
865
954
  });
866
955
  }
867
956
 
@@ -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 5', () => {
76
+ const { helpers } = loadGeneratedHelpersModule();
77
+ strict_1.default.equal(generate_helpers_1.EGDESK_HELPERS_GENERATION_VERSION, '5');
78
+ strict_1.default.equal(helpers.EGDESK_HELPERS_GENERATION_VERSION, '5');
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
+ });
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.184";
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.184';
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.163",
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
  },