@teleporthq/teleport-plugin-next-data-source 0.40.15

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.
Files changed (240) hide show
  1. package/ARRAY_MAPPER_PAGINATION.md +1128 -0
  2. package/LICENSE +21 -0
  3. package/README.md +40 -0
  4. package/SEARCH_IMPLEMENTATION_SUMMARY.md +983 -0
  5. package/__tests__/fetchers.test.ts +545 -0
  6. package/__tests__/integration.test.ts +561 -0
  7. package/__tests__/mocks.ts +241 -0
  8. package/__tests__/pagination.test.ts +31 -0
  9. package/__tests__/plugin.test.ts +577 -0
  10. package/__tests__/utils.test.ts +430 -0
  11. package/__tests__/validation.test.ts +348 -0
  12. package/dist/cjs/array-mapper-pagination.d.ts +32 -0
  13. package/dist/cjs/array-mapper-pagination.d.ts.map +1 -0
  14. package/dist/cjs/array-mapper-pagination.js +77 -0
  15. package/dist/cjs/array-mapper-pagination.js.map +1 -0
  16. package/dist/cjs/count-fetchers.d.ts +12 -0
  17. package/dist/cjs/count-fetchers.d.ts.map +1 -0
  18. package/dist/cjs/count-fetchers.js +46 -0
  19. package/dist/cjs/count-fetchers.js.map +1 -0
  20. package/dist/cjs/data-source-fetchers.d.ts +14 -0
  21. package/dist/cjs/data-source-fetchers.d.ts.map +1 -0
  22. package/dist/cjs/data-source-fetchers.js +185 -0
  23. package/dist/cjs/data-source-fetchers.js.map +1 -0
  24. package/dist/cjs/fetchers/airtable.d.ts +6 -0
  25. package/dist/cjs/fetchers/airtable.d.ts.map +1 -0
  26. package/dist/cjs/fetchers/airtable.js +27 -0
  27. package/dist/cjs/fetchers/airtable.js.map +1 -0
  28. package/dist/cjs/fetchers/clickhouse.d.ts +6 -0
  29. package/dist/cjs/fetchers/clickhouse.d.ts.map +1 -0
  30. package/dist/cjs/fetchers/clickhouse.js +29 -0
  31. package/dist/cjs/fetchers/clickhouse.js.map +1 -0
  32. package/dist/cjs/fetchers/csv-file.d.ts +7 -0
  33. package/dist/cjs/fetchers/csv-file.d.ts.map +1 -0
  34. package/dist/cjs/fetchers/csv-file.js +36 -0
  35. package/dist/cjs/fetchers/csv-file.js.map +1 -0
  36. package/dist/cjs/fetchers/firestore.d.ts +6 -0
  37. package/dist/cjs/fetchers/firestore.d.ts.map +1 -0
  38. package/dist/cjs/fetchers/firestore.js +35 -0
  39. package/dist/cjs/fetchers/firestore.js.map +1 -0
  40. package/dist/cjs/fetchers/google-sheets.d.ts +6 -0
  41. package/dist/cjs/fetchers/google-sheets.d.ts.map +1 -0
  42. package/dist/cjs/fetchers/google-sheets.js +30 -0
  43. package/dist/cjs/fetchers/google-sheets.js.map +1 -0
  44. package/dist/cjs/fetchers/index.d.ts +17 -0
  45. package/dist/cjs/fetchers/index.d.ts.map +1 -0
  46. package/dist/cjs/fetchers/index.js +56 -0
  47. package/dist/cjs/fetchers/index.js.map +1 -0
  48. package/dist/cjs/fetchers/javascript.d.ts +7 -0
  49. package/dist/cjs/fetchers/javascript.d.ts.map +1 -0
  50. package/dist/cjs/fetchers/javascript.js +40 -0
  51. package/dist/cjs/fetchers/javascript.js.map +1 -0
  52. package/dist/cjs/fetchers/mariadb.d.ts +3 -0
  53. package/dist/cjs/fetchers/mariadb.d.ts.map +1 -0
  54. package/dist/cjs/fetchers/mariadb.js +23 -0
  55. package/dist/cjs/fetchers/mariadb.js.map +1 -0
  56. package/dist/cjs/fetchers/mongodb.d.ts +7 -0
  57. package/dist/cjs/fetchers/mongodb.d.ts.map +1 -0
  58. package/dist/cjs/fetchers/mongodb.js +52 -0
  59. package/dist/cjs/fetchers/mongodb.js.map +1 -0
  60. package/dist/cjs/fetchers/mysql.d.ts +3 -0
  61. package/dist/cjs/fetchers/mysql.d.ts.map +1 -0
  62. package/dist/cjs/fetchers/mysql.js +30 -0
  63. package/dist/cjs/fetchers/mysql.js.map +1 -0
  64. package/dist/cjs/fetchers/postgresql.d.ts +3 -0
  65. package/dist/cjs/fetchers/postgresql.d.ts.map +1 -0
  66. package/dist/cjs/fetchers/postgresql.js +25 -0
  67. package/dist/cjs/fetchers/postgresql.js.map +1 -0
  68. package/dist/cjs/fetchers/redis.d.ts +6 -0
  69. package/dist/cjs/fetchers/redis.d.ts.map +1 -0
  70. package/dist/cjs/fetchers/redis.js +46 -0
  71. package/dist/cjs/fetchers/redis.js.map +1 -0
  72. package/dist/cjs/fetchers/redshift.d.ts +2 -0
  73. package/dist/cjs/fetchers/redshift.d.ts.map +1 -0
  74. package/dist/cjs/fetchers/redshift.js +24 -0
  75. package/dist/cjs/fetchers/redshift.js.map +1 -0
  76. package/dist/cjs/fetchers/rest-api.d.ts +6 -0
  77. package/dist/cjs/fetchers/rest-api.d.ts.map +1 -0
  78. package/dist/cjs/fetchers/rest-api.js +58 -0
  79. package/dist/cjs/fetchers/rest-api.js.map +1 -0
  80. package/dist/cjs/fetchers/static-collection.d.ts +7 -0
  81. package/dist/cjs/fetchers/static-collection.d.ts.map +1 -0
  82. package/dist/cjs/fetchers/static-collection.js +24 -0
  83. package/dist/cjs/fetchers/static-collection.js.map +1 -0
  84. package/dist/cjs/fetchers/supabase.d.ts +7 -0
  85. package/dist/cjs/fetchers/supabase.d.ts.map +1 -0
  86. package/dist/cjs/fetchers/supabase.js +42 -0
  87. package/dist/cjs/fetchers/supabase.js.map +1 -0
  88. package/dist/cjs/fetchers/turso.d.ts +6 -0
  89. package/dist/cjs/fetchers/turso.d.ts.map +1 -0
  90. package/dist/cjs/fetchers/turso.js +25 -0
  91. package/dist/cjs/fetchers/turso.js.map +1 -0
  92. package/dist/cjs/index.d.ts +9 -0
  93. package/dist/cjs/index.d.ts.map +1 -0
  94. package/dist/cjs/index.js +325 -0
  95. package/dist/cjs/index.js.map +1 -0
  96. package/dist/cjs/pagination-plugin.d.ts +5 -0
  97. package/dist/cjs/pagination-plugin.d.ts.map +1 -0
  98. package/dist/cjs/pagination-plugin.js +1484 -0
  99. package/dist/cjs/pagination-plugin.js.map +1 -0
  100. package/dist/cjs/pagination-with-count.d.ts +6 -0
  101. package/dist/cjs/pagination-with-count.d.ts.map +1 -0
  102. package/dist/cjs/pagination-with-count.js +63 -0
  103. package/dist/cjs/pagination-with-count.js.map +1 -0
  104. package/dist/cjs/tsconfig.tsbuildinfo +1 -0
  105. package/dist/cjs/utils.d.ts +31 -0
  106. package/dist/cjs/utils.d.ts.map +1 -0
  107. package/dist/cjs/utils.js +763 -0
  108. package/dist/cjs/utils.js.map +1 -0
  109. package/dist/cjs/validation.d.ts +5 -0
  110. package/dist/cjs/validation.d.ts.map +1 -0
  111. package/dist/cjs/validation.js +29 -0
  112. package/dist/cjs/validation.js.map +1 -0
  113. package/dist/esm/array-mapper-pagination.d.ts +32 -0
  114. package/dist/esm/array-mapper-pagination.d.ts.map +1 -0
  115. package/dist/esm/array-mapper-pagination.js +72 -0
  116. package/dist/esm/array-mapper-pagination.js.map +1 -0
  117. package/dist/esm/count-fetchers.d.ts +12 -0
  118. package/dist/esm/count-fetchers.d.ts.map +1 -0
  119. package/dist/esm/count-fetchers.js +35 -0
  120. package/dist/esm/count-fetchers.js.map +1 -0
  121. package/dist/esm/data-source-fetchers.d.ts +14 -0
  122. package/dist/esm/data-source-fetchers.d.ts.map +1 -0
  123. package/dist/esm/data-source-fetchers.js +179 -0
  124. package/dist/esm/data-source-fetchers.js.map +1 -0
  125. package/dist/esm/fetchers/airtable.d.ts +6 -0
  126. package/dist/esm/fetchers/airtable.d.ts.map +1 -0
  127. package/dist/esm/fetchers/airtable.js +22 -0
  128. package/dist/esm/fetchers/airtable.js.map +1 -0
  129. package/dist/esm/fetchers/clickhouse.d.ts +6 -0
  130. package/dist/esm/fetchers/clickhouse.d.ts.map +1 -0
  131. package/dist/esm/fetchers/clickhouse.js +24 -0
  132. package/dist/esm/fetchers/clickhouse.js.map +1 -0
  133. package/dist/esm/fetchers/csv-file.d.ts +7 -0
  134. package/dist/esm/fetchers/csv-file.d.ts.map +1 -0
  135. package/dist/esm/fetchers/csv-file.js +30 -0
  136. package/dist/esm/fetchers/csv-file.js.map +1 -0
  137. package/dist/esm/fetchers/firestore.d.ts +6 -0
  138. package/dist/esm/fetchers/firestore.d.ts.map +1 -0
  139. package/dist/esm/fetchers/firestore.js +30 -0
  140. package/dist/esm/fetchers/firestore.js.map +1 -0
  141. package/dist/esm/fetchers/google-sheets.d.ts +6 -0
  142. package/dist/esm/fetchers/google-sheets.d.ts.map +1 -0
  143. package/dist/esm/fetchers/google-sheets.js +25 -0
  144. package/dist/esm/fetchers/google-sheets.js.map +1 -0
  145. package/dist/esm/fetchers/index.d.ts +17 -0
  146. package/dist/esm/fetchers/index.d.ts.map +1 -0
  147. package/dist/esm/fetchers/index.js +17 -0
  148. package/dist/esm/fetchers/index.js.map +1 -0
  149. package/dist/esm/fetchers/javascript.d.ts +7 -0
  150. package/dist/esm/fetchers/javascript.d.ts.map +1 -0
  151. package/dist/esm/fetchers/javascript.js +34 -0
  152. package/dist/esm/fetchers/javascript.js.map +1 -0
  153. package/dist/esm/fetchers/mariadb.d.ts +3 -0
  154. package/dist/esm/fetchers/mariadb.d.ts.map +1 -0
  155. package/dist/esm/fetchers/mariadb.js +18 -0
  156. package/dist/esm/fetchers/mariadb.js.map +1 -0
  157. package/dist/esm/fetchers/mongodb.d.ts +7 -0
  158. package/dist/esm/fetchers/mongodb.d.ts.map +1 -0
  159. package/dist/esm/fetchers/mongodb.js +46 -0
  160. package/dist/esm/fetchers/mongodb.js.map +1 -0
  161. package/dist/esm/fetchers/mysql.d.ts +3 -0
  162. package/dist/esm/fetchers/mysql.d.ts.map +1 -0
  163. package/dist/esm/fetchers/mysql.js +25 -0
  164. package/dist/esm/fetchers/mysql.js.map +1 -0
  165. package/dist/esm/fetchers/postgresql.d.ts +3 -0
  166. package/dist/esm/fetchers/postgresql.d.ts.map +1 -0
  167. package/dist/esm/fetchers/postgresql.js +20 -0
  168. package/dist/esm/fetchers/postgresql.js.map +1 -0
  169. package/dist/esm/fetchers/redis.d.ts +6 -0
  170. package/dist/esm/fetchers/redis.d.ts.map +1 -0
  171. package/dist/esm/fetchers/redis.js +41 -0
  172. package/dist/esm/fetchers/redis.js.map +1 -0
  173. package/dist/esm/fetchers/redshift.d.ts +2 -0
  174. package/dist/esm/fetchers/redshift.d.ts.map +1 -0
  175. package/dist/esm/fetchers/redshift.js +20 -0
  176. package/dist/esm/fetchers/redshift.js.map +1 -0
  177. package/dist/esm/fetchers/rest-api.d.ts +6 -0
  178. package/dist/esm/fetchers/rest-api.d.ts.map +1 -0
  179. package/dist/esm/fetchers/rest-api.js +53 -0
  180. package/dist/esm/fetchers/rest-api.js.map +1 -0
  181. package/dist/esm/fetchers/static-collection.d.ts +7 -0
  182. package/dist/esm/fetchers/static-collection.d.ts.map +1 -0
  183. package/dist/esm/fetchers/static-collection.js +18 -0
  184. package/dist/esm/fetchers/static-collection.js.map +1 -0
  185. package/dist/esm/fetchers/supabase.d.ts +7 -0
  186. package/dist/esm/fetchers/supabase.d.ts.map +1 -0
  187. package/dist/esm/fetchers/supabase.js +36 -0
  188. package/dist/esm/fetchers/supabase.js.map +1 -0
  189. package/dist/esm/fetchers/turso.d.ts +6 -0
  190. package/dist/esm/fetchers/turso.d.ts.map +1 -0
  191. package/dist/esm/fetchers/turso.js +20 -0
  192. package/dist/esm/fetchers/turso.js.map +1 -0
  193. package/dist/esm/index.d.ts +9 -0
  194. package/dist/esm/index.d.ts.map +1 -0
  195. package/dist/esm/index.js +306 -0
  196. package/dist/esm/index.js.map +1 -0
  197. package/dist/esm/pagination-plugin.d.ts +5 -0
  198. package/dist/esm/pagination-plugin.d.ts.map +1 -0
  199. package/dist/esm/pagination-plugin.js +1457 -0
  200. package/dist/esm/pagination-plugin.js.map +1 -0
  201. package/dist/esm/pagination-with-count.d.ts +6 -0
  202. package/dist/esm/pagination-with-count.d.ts.map +1 -0
  203. package/dist/esm/pagination-with-count.js +34 -0
  204. package/dist/esm/pagination-with-count.js.map +1 -0
  205. package/dist/esm/tsconfig.tsbuildinfo +1 -0
  206. package/dist/esm/utils.d.ts +31 -0
  207. package/dist/esm/utils.d.ts.map +1 -0
  208. package/dist/esm/utils.js +722 -0
  209. package/dist/esm/utils.js.map +1 -0
  210. package/dist/esm/validation.d.ts +5 -0
  211. package/dist/esm/validation.d.ts.map +1 -0
  212. package/dist/esm/validation.js +25 -0
  213. package/dist/esm/validation.js.map +1 -0
  214. package/package.json +33 -0
  215. package/src/array-mapper-pagination.ts +113 -0
  216. package/src/count-fetchers.ts +99 -0
  217. package/src/data-source-fetchers.ts +313 -0
  218. package/src/fetchers/airtable.ts +153 -0
  219. package/src/fetchers/clickhouse.ts +127 -0
  220. package/src/fetchers/csv-file.ts +163 -0
  221. package/src/fetchers/firestore.ts +138 -0
  222. package/src/fetchers/google-sheets.ts +189 -0
  223. package/src/fetchers/index.ts +32 -0
  224. package/src/fetchers/javascript.ts +150 -0
  225. package/src/fetchers/mariadb.ts +230 -0
  226. package/src/fetchers/mongodb.ts +239 -0
  227. package/src/fetchers/mysql.ts +237 -0
  228. package/src/fetchers/postgresql.ts +247 -0
  229. package/src/fetchers/redis.ts +152 -0
  230. package/src/fetchers/redshift.ts +138 -0
  231. package/src/fetchers/rest-api.ts +148 -0
  232. package/src/fetchers/static-collection.ts +149 -0
  233. package/src/fetchers/supabase.ts +246 -0
  234. package/src/fetchers/turso.ts +131 -0
  235. package/src/index.ts +352 -0
  236. package/src/pagination-plugin.ts +2335 -0
  237. package/src/pagination-with-count.ts +89 -0
  238. package/src/utils.ts +1013 -0
  239. package/src/validation.ts +32 -0
  240. package/tsconfig.json +9 -0
@@ -0,0 +1,1484 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __generator = (this && this.__generator) || function (thisArg, body) {
35
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
+ function verb(n) { return function (v) { return step([n, v]); }; }
38
+ function step(op) {
39
+ if (f) throw new TypeError("Generator is already executing.");
40
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
41
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
42
+ if (y = 0, t) op = [op[0] & 2, t.value];
43
+ switch (op[0]) {
44
+ case 0: case 1: t = op; break;
45
+ case 4: _.label++; return { value: op[1], done: false };
46
+ case 5: _.label++; y = op[1]; op = [0]; continue;
47
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
+ default:
49
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
+ if (t[2]) _.ops.pop();
54
+ _.trys.pop(); continue;
55
+ }
56
+ op = body.call(thisArg, _);
57
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
+ }
60
+ };
61
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
62
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
63
+ if (ar || !(i in from)) {
64
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
65
+ ar[i] = from[i];
66
+ }
67
+ }
68
+ return to.concat(ar || Array.prototype.slice.call(from));
69
+ };
70
+ Object.defineProperty(exports, "__esModule", { value: true });
71
+ exports.createNextArrayMapperPaginationPlugin = void 0;
72
+ var teleport_types_1 = require("@teleporthq/teleport-types");
73
+ var types = __importStar(require("@babel/types"));
74
+ var array_mapper_pagination_1 = require("./array-mapper-pagination");
75
+ var utils_1 = require("./utils");
76
+ var createNextArrayMapperPaginationPlugin = function () {
77
+ var paginationPlugin = function (structure) { return __awaiter(void 0, void 0, void 0, function () {
78
+ var uidl, chunks, dependencies, options, componentChunk, variableDeclaration, declarator, arrowFunction, blockStatement, _a, paginatedMappers, searchOnlyMappers, paginationOnlyMappers, detectedPaginations, detectedSearchOnly, paginationInfos, getStaticPropsChunk, isPage, isComponent, opts, perPageMap, searchConfigMap, queryColumnsMap, hasSearchEnabled, firstReturnIndex, insertIndex, dataSourceToInfos_1, searchOnlyDataSources;
79
+ var _b, _c, _d;
80
+ return __generator(this, function (_e) {
81
+ uidl = structure.uidl, chunks = structure.chunks, dependencies = structure.dependencies, options = structure.options;
82
+ componentChunk = chunks.find(function (chunk) { return chunk.name === 'jsx-component'; });
83
+ if (!componentChunk || componentChunk.type !== teleport_types_1.ChunkType.AST) {
84
+ return [2 /*return*/, structure];
85
+ }
86
+ if (!options || !options.dataSources || !options.extractedResources) {
87
+ return [2 /*return*/, structure];
88
+ }
89
+ variableDeclaration = componentChunk.content;
90
+ if (!variableDeclaration.declarations || variableDeclaration.declarations.length === 0) {
91
+ return [2 /*return*/, structure];
92
+ }
93
+ declarator = variableDeclaration.declarations[0];
94
+ if (!declarator.init) {
95
+ return [2 /*return*/, structure];
96
+ }
97
+ arrowFunction = declarator.init;
98
+ if (!arrowFunction.body) {
99
+ return [2 /*return*/, structure];
100
+ }
101
+ blockStatement = arrowFunction.body;
102
+ _a = detectPaginationsAndSearchFromJSX(blockStatement, uidl.node), paginatedMappers = _a.paginatedMappers, searchOnlyMappers = _a.searchOnlyMappers, paginationOnlyMappers = _a.paginationOnlyMappers;
103
+ if (paginatedMappers.length === 0 &&
104
+ searchOnlyMappers.length === 0 &&
105
+ paginationOnlyMappers.length === 0) {
106
+ return [2 /*return*/, structure];
107
+ }
108
+ detectedPaginations = __spreadArray(__spreadArray([], paginatedMappers, true), paginationOnlyMappers, true);
109
+ detectedSearchOnly = searchOnlyMappers;
110
+ if (!dependencies.useState) {
111
+ dependencies.useState = {
112
+ type: 'library',
113
+ path: 'react',
114
+ version: '',
115
+ meta: {
116
+ namedImport: true,
117
+ },
118
+ };
119
+ }
120
+ if (!dependencies.useMemo) {
121
+ dependencies.useMemo = {
122
+ type: 'library',
123
+ path: 'react',
124
+ version: '',
125
+ meta: {
126
+ namedImport: true,
127
+ },
128
+ };
129
+ }
130
+ if (!dependencies.useCallback) {
131
+ dependencies.useCallback = {
132
+ type: 'library',
133
+ path: 'react',
134
+ version: '',
135
+ meta: {
136
+ namedImport: true,
137
+ },
138
+ };
139
+ }
140
+ if (!dependencies.useRef) {
141
+ dependencies.useRef = {
142
+ type: 'library',
143
+ path: 'react',
144
+ version: '',
145
+ meta: {
146
+ namedImport: true,
147
+ },
148
+ };
149
+ }
150
+ if (!componentChunk.meta) {
151
+ componentChunk.meta = {};
152
+ }
153
+ componentChunk.meta.isClientComponent = true;
154
+ paginationInfos = [];
155
+ getStaticPropsChunk = chunks.find(function (chunk) { return chunk.name === 'getStaticProps'; });
156
+ isPage = !!getStaticPropsChunk;
157
+ isComponent = !isPage;
158
+ opts = options;
159
+ perPageMap = ((_b = opts.paginationConfig) === null || _b === void 0 ? void 0 : _b.perPageMap) || new Map();
160
+ searchConfigMap = ((_c = opts.paginationConfig) === null || _c === void 0 ? void 0 : _c.searchConfigMap) || new Map();
161
+ queryColumnsMap = ((_d = opts.paginationConfig) === null || _d === void 0 ? void 0 : _d.queryColumnsMap) || new Map();
162
+ detectedPaginations.forEach(function (detected, index) {
163
+ var paginationNodeId = "pg_".concat(index);
164
+ // Use arrayMapperRenderProp if available, otherwise fall back to dataSourceIdentifier
165
+ var lookupKey = detected.arrayMapperRenderProp || detected.dataSourceIdentifier;
166
+ var perPage = perPageMap.get(lookupKey) || 10;
167
+ var searchConfig = searchConfigMap.get(lookupKey);
168
+ // queryColumns is keyed by dataSourceIdentifier, not array mapper render prop
169
+ var queryColumns = queryColumnsMap.get(detected.dataSourceIdentifier);
170
+ var info = (0, array_mapper_pagination_1.generatePaginationLogic)(paginationNodeId, detected.dataSourceIdentifier, perPage, searchConfig, queryColumns);
171
+ paginationInfos.push(info);
172
+ // If both pagination and search are enabled, combine them into a single state object
173
+ if (info.searchEnabled && info.searchQueryVar && info.setSearchQueryVar) {
174
+ // Combined state: { page: 1, debouncedQuery: '' }
175
+ var combinedStateVar = "paginationState_pg_".concat(index);
176
+ var setCombinedStateVar = "setPaginationState_pg_".concat(index);
177
+ var combinedStateAST = types.variableDeclaration('const', [
178
+ types.variableDeclarator(types.arrayPattern([
179
+ types.identifier(combinedStateVar),
180
+ types.identifier(setCombinedStateVar),
181
+ ]), types.callExpression(types.identifier('useState'), [
182
+ types.objectExpression([
183
+ types.objectProperty(types.identifier('page'), types.numericLiteral(1)),
184
+ types.objectProperty(types.identifier('debouncedQuery'), types.stringLiteral('')),
185
+ ]),
186
+ ])),
187
+ ]);
188
+ blockStatement.body.unshift(combinedStateAST);
189
+ // Still need the immediate search query state for the input
190
+ var searchStateAST = types.variableDeclaration('const', [
191
+ types.variableDeclarator(types.arrayPattern([
192
+ types.identifier(info.searchQueryVar),
193
+ types.identifier(info.setSearchQueryVar),
194
+ ]), types.callExpression(types.identifier('useState'), [types.stringLiteral('')])),
195
+ ]);
196
+ blockStatement.body.unshift(searchStateAST);
197
+ info.combinedStateVar = combinedStateVar;
198
+ info.setCombinedStateVar = setCombinedStateVar;
199
+ }
200
+ else {
201
+ // If search is not enabled, just add regular page state
202
+ var pageStateAST = types.variableDeclaration('const', [
203
+ types.variableDeclarator(types.arrayPattern([
204
+ types.identifier(info.pageStateVar),
205
+ types.identifier(info.setPageStateVar),
206
+ ]), types.callExpression(types.identifier('useState'), [types.numericLiteral(1)])),
207
+ ]);
208
+ blockStatement.body.unshift(pageStateAST);
209
+ }
210
+ // Add maxPages state
211
+ var maxPagesStateVar = "".concat(info.pageStateVar.replace('_page', ''), "_maxPages");
212
+ var setMaxPagesStateVar = "set".concat(maxPagesStateVar.charAt(0).toUpperCase() + maxPagesStateVar.slice(1));
213
+ // For pages: initialize from props (with pagination-specific prop name), for components: initialize to 0
214
+ var maxPagesInitValue = isPage
215
+ ? types.logicalExpression('||', types.optionalMemberExpression(types.identifier('props'), types.identifier("".concat(info.dataSourceIdentifier, "_pg_").concat(index, "_maxPages")), false, true), types.numericLiteral(0))
216
+ : types.numericLiteral(0);
217
+ var maxPagesStateAST = types.variableDeclaration('const', [
218
+ types.variableDeclarator(types.arrayPattern([
219
+ types.identifier(maxPagesStateVar),
220
+ types.identifier(setMaxPagesStateVar),
221
+ ]), types.callExpression(types.identifier('useState'), [maxPagesInitValue])),
222
+ ]);
223
+ blockStatement.body.unshift(maxPagesStateAST);
224
+ info.maxPagesStateVar = maxPagesStateVar;
225
+ info.setMaxPagesStateVar = setMaxPagesStateVar;
226
+ // Add refs to track first render for each useEffect
227
+ if (info.searchEnabled) {
228
+ var skipDebounceOnMountRefVar = "skipDebounceOnMount_pg_".concat(index);
229
+ var skipDebounceRefAST = types.variableDeclaration('const', [
230
+ types.variableDeclarator(types.identifier(skipDebounceOnMountRefVar), types.callExpression(types.identifier('useRef'), [types.booleanLiteral(true)])),
231
+ ]);
232
+ blockStatement.body.unshift(skipDebounceRefAST);
233
+ info.skipDebounceOnMountRefVar = skipDebounceOnMountRefVar;
234
+ var skipCountFetchOnMountRefVar = "skipCountFetchOnMount_pg_".concat(index);
235
+ var skipCountFetchRefAST = types.variableDeclaration('const', [
236
+ types.variableDeclarator(types.identifier(skipCountFetchOnMountRefVar), types.callExpression(types.identifier('useRef'), [types.booleanLiteral(true)])),
237
+ ]);
238
+ blockStatement.body.unshift(skipCountFetchRefAST);
239
+ info.skipCountFetchOnMountRefVar = skipCountFetchOnMountRefVar;
240
+ }
241
+ });
242
+ hasSearchEnabled = paginationInfos.some(function (info) { return info.searchEnabled; });
243
+ if (hasSearchEnabled && !dependencies.useEffect) {
244
+ dependencies.useEffect = {
245
+ type: 'library',
246
+ path: 'react',
247
+ version: '',
248
+ meta: {
249
+ namedImport: true,
250
+ },
251
+ };
252
+ }
253
+ firstReturnIndex = blockStatement.body.findIndex(function (stmt) { return stmt.type === 'ReturnStatement'; });
254
+ insertIndex = firstReturnIndex !== -1 ? firstReturnIndex : blockStatement.body.length;
255
+ // Add effects in reverse order so they appear in correct order
256
+ paginationInfos.forEach(function (info) {
257
+ if (info.searchEnabled &&
258
+ info.searchQueryVar &&
259
+ info.debouncedSearchQueryVar &&
260
+ info.setDebouncedSearchQueryVar) {
261
+ // Add effect that updates debounced search after delay
262
+ var skipDebounceOnMountRefVar = info.skipDebounceOnMountRefVar;
263
+ var setCombinedStateVar = info.setCombinedStateVar;
264
+ var debounceEffect = types.expressionStatement(types.callExpression(types.identifier('useEffect'), [
265
+ types.arrowFunctionExpression([], types.blockStatement([
266
+ types.ifStatement(types.memberExpression(types.identifier(skipDebounceOnMountRefVar), types.identifier('current')), types.blockStatement([
267
+ types.expressionStatement(types.assignmentExpression('=', types.memberExpression(types.identifier(skipDebounceOnMountRefVar), types.identifier('current')), types.booleanLiteral(false))),
268
+ types.returnStatement(),
269
+ ])),
270
+ types.variableDeclaration('const', [
271
+ types.variableDeclarator(types.identifier('timer'), types.callExpression(types.identifier('setTimeout'), [
272
+ types.arrowFunctionExpression([], types.blockStatement([
273
+ types.expressionStatement(types.callExpression(types.identifier(setCombinedStateVar), [
274
+ types.objectExpression([
275
+ types.objectProperty(types.identifier('page'), types.numericLiteral(1)),
276
+ types.objectProperty(types.identifier('debouncedQuery'), types.identifier(info.searchQueryVar)),
277
+ ]),
278
+ ])),
279
+ ])),
280
+ types.numericLiteral(info.searchDebounce || 300),
281
+ ])),
282
+ ]),
283
+ types.returnStatement(types.arrowFunctionExpression([], types.callExpression(types.identifier('clearTimeout'), [
284
+ types.identifier('timer'),
285
+ ]))),
286
+ ])),
287
+ types.arrayExpression([types.identifier(info.searchQueryVar)]),
288
+ ]));
289
+ blockStatement.body.splice(insertIndex, 0, debounceEffect);
290
+ // Add useEffect to refetch count when search changes (for both pages and components)
291
+ if (info.queryColumns && info.queryColumns.length > 0) {
292
+ var detected = detectedPaginations.find(function (d) { return d.dataSourceIdentifier === info.dataSourceIdentifier; });
293
+ if (!detected) {
294
+ return;
295
+ }
296
+ var resourceDefAttr = detected.dataProviderJSX.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'resourceDefinition'; });
297
+ if (resourceDefAttr &&
298
+ resourceDefAttr.value &&
299
+ resourceDefAttr.value.type === 'JSXExpressionContainer') {
300
+ var resourceDef = resourceDefAttr.value.expression;
301
+ if (resourceDef.type === 'ObjectExpression') {
302
+ var dataSourceIdProp = resourceDef.properties.find(function (p) { return p.type === 'ObjectProperty' && p.key.value === 'dataSourceId'; });
303
+ var tableNameProp = resourceDef.properties.find(function (p) { return p.type === 'ObjectProperty' && p.key.value === 'tableName'; });
304
+ var dataSourceTypeProp = resourceDef.properties.find(function (p) { return p.type === 'ObjectProperty' && p.key.value === 'dataSourceType'; });
305
+ if (dataSourceIdProp && tableNameProp && dataSourceTypeProp) {
306
+ var dataSourceId = dataSourceIdProp.value.value;
307
+ var tableName = tableNameProp.value.value;
308
+ var dataSourceType = dataSourceTypeProp.value.value;
309
+ var fileName = "".concat(dataSourceType, "-").concat(tableName, "-").concat(dataSourceId.substring(0, 8));
310
+ var setMaxPagesStateVar = info.setMaxPagesStateVar;
311
+ // Create useEffect to refetch count when debounced search changes
312
+ var skipCountFetchOnMountRefVar = info.skipCountFetchOnMountRefVar;
313
+ var combinedStateVar = info.combinedStateVar;
314
+ var refetchCountEffect = types.expressionStatement(types.callExpression(types.identifier('useEffect'), [
315
+ types.arrowFunctionExpression([], types.blockStatement([
316
+ types.ifStatement(types.memberExpression(types.identifier(skipCountFetchOnMountRefVar), types.identifier('current')), types.blockStatement([
317
+ types.expressionStatement(types.assignmentExpression('=', types.memberExpression(types.identifier(skipCountFetchOnMountRefVar), types.identifier('current')), types.booleanLiteral(false))),
318
+ types.returnStatement(),
319
+ ])),
320
+ types.expressionStatement(types.callExpression(types.memberExpression(types.callExpression(types.memberExpression(types.callExpression(types.identifier('fetch'), [
321
+ types.templateLiteral([
322
+ types.templateElement({
323
+ raw: "/api/".concat(fileName, "-count?"),
324
+ cooked: "/api/".concat(fileName, "-count?"),
325
+ }),
326
+ types.templateElement({ raw: '', cooked: '' }),
327
+ ], [
328
+ types.newExpression(types.identifier('URLSearchParams'), [
329
+ types.objectExpression([
330
+ types.objectProperty(types.identifier('query'), types.memberExpression(types.identifier(combinedStateVar), types.identifier('debouncedQuery'))),
331
+ types.objectProperty(types.identifier('queryColumns'), types.callExpression(types.memberExpression(types.identifier('JSON'), types.identifier('stringify')), [
332
+ types.arrayExpression(info.queryColumns.map(function (col) {
333
+ return types.stringLiteral(col);
334
+ })),
335
+ ])),
336
+ ]),
337
+ ]),
338
+ ]),
339
+ ]), types.identifier('then')), [
340
+ types.arrowFunctionExpression([types.identifier('res')], types.callExpression(types.memberExpression(types.identifier('res'), types.identifier('json')), [])),
341
+ ]), types.identifier('then')), [
342
+ types.arrowFunctionExpression([types.identifier('data')], types.blockStatement([
343
+ types.ifStatement(types.logicalExpression('&&', types.identifier('data'), types.binaryExpression('in', types.stringLiteral('count'), types.identifier('data'))), types.blockStatement([
344
+ types.expressionStatement(types.callExpression(types.identifier(setMaxPagesStateVar), [
345
+ types.conditionalExpression(types.binaryExpression('===', types.memberExpression(types.identifier('data'), types.identifier('count')), types.numericLiteral(0)), types.numericLiteral(0), types.callExpression(types.memberExpression(types.identifier('Math'), types.identifier('ceil')), [
346
+ types.binaryExpression('/', types.memberExpression(types.identifier('data'), types.identifier('count')), types.numericLiteral(info.perPage)),
347
+ ])),
348
+ ])),
349
+ ])),
350
+ ])),
351
+ ])),
352
+ ])),
353
+ types.arrayExpression([
354
+ types.memberExpression(types.identifier(combinedStateVar), types.identifier('debouncedQuery')),
355
+ ]),
356
+ ]));
357
+ blockStatement.body.splice(insertIndex, 0, refetchCountEffect);
358
+ }
359
+ }
360
+ }
361
+ }
362
+ }
363
+ });
364
+ // For components, add useEffect to fetch count on mount
365
+ if (isComponent) {
366
+ if (!dependencies.useEffect) {
367
+ dependencies.useEffect = {
368
+ type: 'library',
369
+ path: 'react',
370
+ version: '',
371
+ meta: {
372
+ namedImport: true,
373
+ },
374
+ };
375
+ }
376
+ dataSourceToInfos_1 = new Map();
377
+ paginationInfos.forEach(function (info) {
378
+ var detected = detectedPaginations.find(function (d) { return d.dataSourceIdentifier === info.dataSourceIdentifier; });
379
+ if (!detected) {
380
+ return;
381
+ }
382
+ var resourceDefAttr = detected.dataProviderJSX.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'resourceDefinition'; });
383
+ if (!resourceDefAttr ||
384
+ !resourceDefAttr.value ||
385
+ resourceDefAttr.value.type !== 'JSXExpressionContainer') {
386
+ return;
387
+ }
388
+ var resourceDef = resourceDefAttr.value.expression;
389
+ if (resourceDef.type !== 'ObjectExpression') {
390
+ return;
391
+ }
392
+ var dataSourceIdProp = resourceDef.properties.find(function (p) { return p.type === 'ObjectProperty' && p.key.value === 'dataSourceId'; });
393
+ var tableNameProp = resourceDef.properties.find(function (p) { return p.type === 'ObjectProperty' && p.key.value === 'tableName'; });
394
+ var dataSourceTypeProp = resourceDef.properties.find(function (p) { return p.type === 'ObjectProperty' && p.key.value === 'dataSourceType'; });
395
+ if (!dataSourceIdProp || !tableNameProp || !dataSourceTypeProp) {
396
+ return;
397
+ }
398
+ var dataSourceId = dataSourceIdProp.value.value;
399
+ var tableName = tableNameProp.value.value;
400
+ var dataSourceType = dataSourceTypeProp.value.value;
401
+ var fileName = "".concat(dataSourceType, "-").concat(tableName, "-").concat(dataSourceId.substring(0, 8));
402
+ // Group by data source identifier
403
+ if (!dataSourceToInfos_1.has(info.dataSourceIdentifier)) {
404
+ dataSourceToInfos_1.set(info.dataSourceIdentifier, []);
405
+ }
406
+ dataSourceToInfos_1.get(info.dataSourceIdentifier).push({ info: info, detected: detected, fileName: fileName });
407
+ });
408
+ // Create ONE useEffect per unique data source
409
+ dataSourceToInfos_1.forEach(function (infos) {
410
+ var fileName = infos[0].fileName;
411
+ // Create array of setState calls - one for each pagination using this data source
412
+ var setStateStatements = infos.map(function (_a) {
413
+ var info = _a.info;
414
+ var setMaxPagesStateVar = info.setMaxPagesStateVar;
415
+ return types.expressionStatement(types.callExpression(types.identifier(setMaxPagesStateVar), [
416
+ types.callExpression(types.memberExpression(types.identifier('Math'), types.identifier('ceil')), [
417
+ types.binaryExpression('/', types.memberExpression(types.identifier('data'), types.identifier('count')), types.numericLiteral(info.perPage)),
418
+ ]),
419
+ ]));
420
+ });
421
+ // Create useEffect to fetch count on mount - sets ALL maxPages for this data source
422
+ var useEffectAST = types.expressionStatement(types.callExpression(types.identifier('useEffect'), [
423
+ types.arrowFunctionExpression([], types.blockStatement([
424
+ types.expressionStatement(types.callExpression(types.memberExpression(types.callExpression(types.memberExpression(types.callExpression(types.identifier('fetch'), [
425
+ types.stringLiteral("/api/".concat(fileName, "-count")),
426
+ ]), types.identifier('then')), [
427
+ types.arrowFunctionExpression([types.identifier('res')], types.callExpression(types.memberExpression(types.identifier('res'), types.identifier('json')), [])),
428
+ ]), types.identifier('then')), [
429
+ types.arrowFunctionExpression([types.identifier('data')], types.blockStatement([
430
+ types.ifStatement(types.logicalExpression('&&', types.identifier('data'), types.memberExpression(types.identifier('data'), types.identifier('count'))), types.blockStatement(setStateStatements)),
431
+ ])),
432
+ ])),
433
+ ])),
434
+ types.arrayExpression([]),
435
+ ]));
436
+ blockStatement.body.unshift(useEffectAST);
437
+ });
438
+ }
439
+ createAPIRoutesForPaginatedDataSources(uidl.node, options.dataSources, componentChunk, options.extractedResources, paginationInfos, isComponent);
440
+ detectedPaginations.forEach(function (detected, index) {
441
+ addPaginationParamsToDataProvider(detected.dataProviderJSX, paginationInfos[index], index);
442
+ });
443
+ modifyPaginationButtons(blockStatement, detectedPaginations, paginationInfos);
444
+ modifySearchInputs(blockStatement, detectedPaginations, paginationInfos);
445
+ if (isPage) {
446
+ modifyGetStaticPropsForPagination(chunks, paginationInfos);
447
+ }
448
+ searchOnlyDataSources = detectedSearchOnly;
449
+ if (searchOnlyDataSources.length > 0) {
450
+ handleSearchOnlyArrayMappers(blockStatement, searchOnlyDataSources, searchConfigMap, queryColumnsMap, insertIndex, dependencies);
451
+ // Create API routes for search-only data sources
452
+ createAPIRoutesForSearchOnlyDataSources(uidl.node, options.dataSources, componentChunk, options.extractedResources, searchOnlyDataSources);
453
+ }
454
+ return [2 /*return*/, structure];
455
+ });
456
+ }); };
457
+ return paginationPlugin;
458
+ };
459
+ exports.createNextArrayMapperPaginationPlugin = createNextArrayMapperPaginationPlugin;
460
+ function detectPaginationsAndSearchFromJSX(blockStatement, uidlNode) {
461
+ var dataProviderMap = new Map();
462
+ var arrayMapperInfoMap = new Map();
463
+ if (uidlNode) {
464
+ var collectArrayMapperInfo_1 = function (node) {
465
+ var _a, _b, _c, _d, _e;
466
+ if (!node) {
467
+ return;
468
+ }
469
+ if (node.type === 'data-source-list' && ((_a = node.content) === null || _a === void 0 ? void 0 : _a.renderPropIdentifier)) {
470
+ var dataSourceIdentifier_1 = node.content.renderPropIdentifier;
471
+ if ((_d = (_c = (_b = node.content.nodes) === null || _b === void 0 ? void 0 : _b.success) === null || _c === void 0 ? void 0 : _c.content) === null || _d === void 0 ? void 0 : _d.children) {
472
+ node.content.nodes.success.content.children.forEach(function (child) {
473
+ var _a;
474
+ if (child.type === 'cms-list-repeater' && ((_a = child.content) === null || _a === void 0 ? void 0 : _a.renderPropIdentifier)) {
475
+ var arrayMapperRenderProp = child.content.renderPropIdentifier;
476
+ // Key by array mapper render prop (unique), not data source identifier
477
+ arrayMapperInfoMap.set(arrayMapperRenderProp, {
478
+ dataSourceIdentifier: dataSourceIdentifier_1,
479
+ renderProp: arrayMapperRenderProp,
480
+ paginated: child.content.paginated || false,
481
+ searchEnabled: child.content.searchEnabled || false,
482
+ });
483
+ }
484
+ });
485
+ }
486
+ }
487
+ if ((_e = node.content) === null || _e === void 0 ? void 0 : _e.children) {
488
+ node.content.children.forEach(function (child) { return collectArrayMapperInfo_1(child); });
489
+ }
490
+ if (node.children && Array.isArray(node.children)) {
491
+ node.children.forEach(function (child) { return collectArrayMapperInfo_1(child); });
492
+ }
493
+ };
494
+ collectArrayMapperInfo_1(uidlNode);
495
+ }
496
+ var dataProvidersWithParents = [];
497
+ var findDataProvidersAndParents = function (node, parent) {
498
+ var _a, _b;
499
+ if (parent === void 0) { parent = null; }
500
+ if (!node) {
501
+ return;
502
+ }
503
+ // Check if this is a DataProvider
504
+ if (node.type === 'JSXElement' && ((_b = (_a = node.openingElement) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.name) === 'DataProvider') {
505
+ dataProvidersWithParents.push({
506
+ dataProvider: node,
507
+ parent: parent,
508
+ });
509
+ }
510
+ // Only recurse through JSX structure, not into embedded expressions or code
511
+ if (node.type === 'ReturnStatement' && node.argument) {
512
+ findDataProvidersAndParents(node.argument, parent);
513
+ }
514
+ else if (node.type === 'JSXElement' || node.type === 'JSXFragment') {
515
+ // Recurse through JSX children
516
+ if (node.children && Array.isArray(node.children)) {
517
+ node.children.forEach(function (child) { return findDataProvidersAndParents(child, node); });
518
+ }
519
+ }
520
+ else if (node.type === 'JSXExpressionContainer') {
521
+ // For expression containers, continue but don't go into the expression itself
522
+ if (node.expression &&
523
+ (node.expression.type === 'JSXElement' || node.expression.type === 'JSXFragment')) {
524
+ findDataProvidersAndParents(node.expression, parent);
525
+ }
526
+ }
527
+ else if (node.type === 'BlockStatement') {
528
+ // For block statements (function bodies), look through body array
529
+ if (node.body && Array.isArray(node.body)) {
530
+ node.body.forEach(function (stmt) { return findDataProvidersAndParents(stmt, node); });
531
+ }
532
+ }
533
+ else if (node.type === 'ConditionalExpression') {
534
+ // Check both branches of conditional
535
+ findDataProvidersAndParents(node.consequent, parent);
536
+ findDataProvidersAndParents(node.alternate, parent);
537
+ }
538
+ };
539
+ findDataProvidersAndParents(blockStatement);
540
+ // Now process each DataProvider and find its siblings
541
+ dataProvidersWithParents.forEach(function (_a) {
542
+ var _b, _c;
543
+ var dataProvider = _a.dataProvider, parent = _a.parent;
544
+ var nameAttr = dataProvider.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'name'; });
545
+ // Find the array mapper render prop by looking inside renderSuccess -> Repeater -> renderItem param
546
+ var renderSuccessAttr = dataProvider.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'renderSuccess'; });
547
+ var arrayMapperRenderProp;
548
+ if (renderSuccessAttr && ((_b = renderSuccessAttr.value) === null || _b === void 0 ? void 0 : _b.type) === 'JSXExpressionContainer') {
549
+ var renderFunc = renderSuccessAttr.value.expression;
550
+ if (renderFunc.type === 'ArrowFunctionExpression') {
551
+ // Look for Repeater inside the render function
552
+ var findRepeater_1 = function (node) {
553
+ var _a, _b;
554
+ if (!node) {
555
+ return null;
556
+ }
557
+ if (node.type === 'JSXElement' && ((_b = (_a = node.openingElement) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.name) === 'Repeater') {
558
+ return node;
559
+ }
560
+ if (node.body) {
561
+ return findRepeater_1(node.body);
562
+ }
563
+ if (node.children && Array.isArray(node.children)) {
564
+ for (var _i = 0, _c = node.children; _i < _c.length; _i++) {
565
+ var child = _c[_i];
566
+ var result = findRepeater_1(child);
567
+ if (result) {
568
+ return result;
569
+ }
570
+ }
571
+ }
572
+ if (node.type === 'JSXFragment' || node.type === 'JSXElement') {
573
+ if (node.children && Array.isArray(node.children)) {
574
+ for (var _d = 0, _e = node.children; _d < _e.length; _d++) {
575
+ var child = _e[_d];
576
+ var result = findRepeater_1(child);
577
+ if (result) {
578
+ return result;
579
+ }
580
+ }
581
+ }
582
+ }
583
+ if (node.type === 'JSXExpressionContainer') {
584
+ return findRepeater_1(node.expression);
585
+ }
586
+ if (node.expression) {
587
+ return findRepeater_1(node.expression);
588
+ }
589
+ if (node.consequent) {
590
+ var result = findRepeater_1(node.consequent);
591
+ if (result) {
592
+ return result;
593
+ }
594
+ }
595
+ if (node.alternate) {
596
+ return findRepeater_1(node.alternate);
597
+ }
598
+ return null;
599
+ };
600
+ var repeater = findRepeater_1(renderFunc);
601
+ if (repeater) {
602
+ // Find renderItem attribute on Repeater
603
+ var renderItemAttr = repeater.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'renderItem'; });
604
+ if (renderItemAttr && ((_c = renderItemAttr.value) === null || _c === void 0 ? void 0 : _c.type) === 'JSXExpressionContainer') {
605
+ var renderItemFunc = renderItemAttr.value.expression;
606
+ if (renderItemFunc.type === 'ArrowFunctionExpression' &&
607
+ renderItemFunc.params &&
608
+ renderItemFunc.params.length > 0) {
609
+ var param = renderItemFunc.params[0];
610
+ if (param.type === 'Identifier') {
611
+ arrayMapperRenderProp = param.name;
612
+ }
613
+ }
614
+ }
615
+ }
616
+ }
617
+ }
618
+ if (!nameAttr ||
619
+ !nameAttr.value ||
620
+ nameAttr.value.type !== 'JSXExpressionContainer' ||
621
+ !arrayMapperRenderProp) {
622
+ return;
623
+ }
624
+ var dataProviderIdentifier = nameAttr.value.expression.value;
625
+ var paginationNodeInfo = null;
626
+ var searchInputInfo = null;
627
+ // Look through parent's children for siblings
628
+ if (parent && parent.children && Array.isArray(parent.children)) {
629
+ parent.children.forEach(function (sibling) {
630
+ var _a, _b, _c;
631
+ if (sibling === dataProvider) {
632
+ return;
633
+ }
634
+ if (sibling.type === 'JSXElement') {
635
+ var siblingClassName = getClassName(((_a = sibling.openingElement) === null || _a === void 0 ? void 0 : _a.attributes) || []);
636
+ var siblingElementName = (_c = (_b = sibling.openingElement) === null || _b === void 0 ? void 0 : _b.name) === null || _c === void 0 ? void 0 : _c.name;
637
+ // Found pagination node
638
+ if (siblingClassName && siblingClassName.includes('cms-pagination-node')) {
639
+ var prevClass = findChildWithClass(sibling, 'previous');
640
+ var nextClass = findChildWithClass(sibling, 'next');
641
+ if (prevClass || nextClass) {
642
+ paginationNodeInfo = {
643
+ class: siblingClassName,
644
+ prevClass: prevClass,
645
+ nextClass: nextClass,
646
+ };
647
+ }
648
+ }
649
+ // Found search container - search for input inside it
650
+ if (siblingClassName && siblingClassName.includes('data-source-search-node')) {
651
+ if (sibling.children && Array.isArray(sibling.children)) {
652
+ sibling.children.forEach(function (searchChild) {
653
+ var _a, _b, _c;
654
+ if (searchChild.type === 'JSXElement') {
655
+ var searchChildElementName = (_b = (_a = searchChild.openingElement) === null || _a === void 0 ? void 0 : _a.name) === null || _b === void 0 ? void 0 : _b.name;
656
+ var searchChildClassName = getClassName(((_c = searchChild.openingElement) === null || _c === void 0 ? void 0 : _c.attributes) || []);
657
+ if (searchChildClassName &&
658
+ searchChildClassName.includes('search-input') &&
659
+ searchChildElementName === 'input') {
660
+ searchInputInfo = {
661
+ class: searchChildClassName,
662
+ jsx: searchChild,
663
+ };
664
+ }
665
+ }
666
+ });
667
+ }
668
+ }
669
+ // Also check if search input is a direct sibling
670
+ if (siblingClassName &&
671
+ siblingClassName.includes('search-input') &&
672
+ siblingElementName === 'input') {
673
+ searchInputInfo = {
674
+ class: siblingClassName,
675
+ jsx: sibling,
676
+ };
677
+ }
678
+ }
679
+ });
680
+ }
681
+ // Record the DataProvider with its pagination/search info
682
+ var uniqueKey = "".concat(dataProviderIdentifier, "__").concat(arrayMapperRenderProp);
683
+ dataProviderMap.set(uniqueKey, {
684
+ identifier: dataProviderIdentifier,
685
+ dataProvider: dataProvider,
686
+ arrayMapperRenderProp: arrayMapperRenderProp,
687
+ paginationNode: paginationNodeInfo || undefined,
688
+ searchInput: searchInputInfo || undefined,
689
+ hasPagination: !!paginationNodeInfo,
690
+ hasSearch: !!searchInputInfo,
691
+ });
692
+ });
693
+ // Categorize data providers
694
+ var paginatedMappers = [];
695
+ var searchOnlyMappers = [];
696
+ var paginationOnlyMappers = [];
697
+ var plainMappers = [];
698
+ dataProviderMap.forEach(function (info) {
699
+ var _a, _b, _c, _d;
700
+ if (info.hasPagination && info.hasSearch) {
701
+ // Pagination + Search
702
+ paginatedMappers.push({
703
+ paginationNodeClass: info.paginationNode.class,
704
+ prevButtonClass: info.paginationNode.prevClass,
705
+ nextButtonClass: info.paginationNode.nextClass,
706
+ dataSourceIdentifier: info.identifier,
707
+ dataProviderJSX: info.dataProvider,
708
+ arrayMapperRenderProp: info.arrayMapperRenderProp,
709
+ searchInputClass: (_a = info.searchInput) === null || _a === void 0 ? void 0 : _a.class,
710
+ searchInputJSX: (_b = info.searchInput) === null || _b === void 0 ? void 0 : _b.jsx,
711
+ });
712
+ }
713
+ else if (info.hasPagination && !info.hasSearch) {
714
+ // Pagination only
715
+ paginationOnlyMappers.push({
716
+ paginationNodeClass: info.paginationNode.class,
717
+ prevButtonClass: info.paginationNode.prevClass,
718
+ nextButtonClass: info.paginationNode.nextClass,
719
+ dataSourceIdentifier: info.identifier,
720
+ dataProviderJSX: info.dataProvider,
721
+ arrayMapperRenderProp: info.arrayMapperRenderProp,
722
+ searchInputClass: undefined,
723
+ searchInputJSX: undefined,
724
+ });
725
+ }
726
+ else if (!info.hasPagination && info.hasSearch) {
727
+ // Search only
728
+ searchOnlyMappers.push({
729
+ paginationNodeClass: '',
730
+ prevButtonClass: null,
731
+ nextButtonClass: null,
732
+ dataSourceIdentifier: info.identifier,
733
+ dataProviderJSX: info.dataProvider,
734
+ arrayMapperRenderProp: info.arrayMapperRenderProp,
735
+ searchInputClass: (_c = info.searchInput) === null || _c === void 0 ? void 0 : _c.class,
736
+ searchInputJSX: (_d = info.searchInput) === null || _d === void 0 ? void 0 : _d.jsx,
737
+ });
738
+ }
739
+ else {
740
+ // Plain (no pagination, no search)
741
+ plainMappers.push({
742
+ paginationNodeClass: '',
743
+ prevButtonClass: null,
744
+ nextButtonClass: null,
745
+ dataSourceIdentifier: info.identifier,
746
+ dataProviderJSX: info.dataProvider,
747
+ arrayMapperRenderProp: info.arrayMapperRenderProp,
748
+ searchInputClass: undefined,
749
+ searchInputJSX: undefined,
750
+ });
751
+ }
752
+ });
753
+ return { paginatedMappers: paginatedMappers, searchOnlyMappers: searchOnlyMappers, paginationOnlyMappers: paginationOnlyMappers, plainMappers: plainMappers };
754
+ }
755
+ function handleSearchOnlyArrayMappers(blockStatement, searchOnlyDataSources, searchConfigMap, queryColumnsMap, insertIndex, dependencies) {
756
+ searchOnlyDataSources.forEach(function (detected, index) {
757
+ var searchId = "search_".concat(index);
758
+ var searchQueryVar = "".concat(searchId, "_query");
759
+ var setSearchQueryVar = "set".concat(searchQueryVar.charAt(0).toUpperCase() + searchQueryVar.slice(1));
760
+ var debouncedSearchQueryVar = "debounced".concat(searchQueryVar.charAt(0).toUpperCase() + searchQueryVar.slice(1));
761
+ var setDebouncedSearchQueryVar = "set".concat(debouncedSearchQueryVar.charAt(0).toUpperCase() + debouncedSearchQueryVar.slice(1));
762
+ var skipDebounceOnMountRefVar = "skipDebounceOnMount".concat(searchId);
763
+ var searchConfig = searchConfigMap.get(detected.dataSourceIdentifier);
764
+ var searchDebounce = (searchConfig === null || searchConfig === void 0 ? void 0 : searchConfig.searchDebounce) || 300;
765
+ var queryColumns = queryColumnsMap.get(detected.dataSourceIdentifier);
766
+ // Add search query state
767
+ var searchStateAST = types.variableDeclaration('const', [
768
+ types.variableDeclarator(types.arrayPattern([types.identifier(searchQueryVar), types.identifier(setSearchQueryVar)]), types.callExpression(types.identifier('useState'), [types.stringLiteral('')])),
769
+ ]);
770
+ blockStatement.body.unshift(searchStateAST);
771
+ // Add debounced search state
772
+ var debouncedSearchStateAST = types.variableDeclaration('const', [
773
+ types.variableDeclarator(types.arrayPattern([
774
+ types.identifier(debouncedSearchQueryVar),
775
+ types.identifier(setDebouncedSearchQueryVar),
776
+ ]), types.callExpression(types.identifier('useState'), [types.stringLiteral('')])),
777
+ ]);
778
+ blockStatement.body.unshift(debouncedSearchStateAST);
779
+ // Add skip ref
780
+ var skipRefAST = types.variableDeclaration('const', [
781
+ types.variableDeclarator(types.identifier(skipDebounceOnMountRefVar), types.callExpression(types.identifier('useRef'), [types.booleanLiteral(true)])),
782
+ ]);
783
+ blockStatement.body.unshift(skipRefAST);
784
+ // Add useEffect for debouncing
785
+ if (!dependencies.useEffect) {
786
+ dependencies.useEffect = {
787
+ type: 'library',
788
+ path: 'react',
789
+ version: '',
790
+ meta: {
791
+ namedImport: true,
792
+ },
793
+ };
794
+ }
795
+ var debounceEffect = types.expressionStatement(types.callExpression(types.identifier('useEffect'), [
796
+ types.arrowFunctionExpression([], types.blockStatement([
797
+ types.ifStatement(types.memberExpression(types.identifier(skipDebounceOnMountRefVar), types.identifier('current')), types.blockStatement([
798
+ types.expressionStatement(types.assignmentExpression('=', types.memberExpression(types.identifier(skipDebounceOnMountRefVar), types.identifier('current')), types.booleanLiteral(false))),
799
+ types.returnStatement(),
800
+ ])),
801
+ types.variableDeclaration('const', [
802
+ types.variableDeclarator(types.identifier('timer'), types.callExpression(types.identifier('setTimeout'), [
803
+ types.arrowFunctionExpression([], types.blockStatement([
804
+ types.expressionStatement(types.callExpression(types.identifier(setDebouncedSearchQueryVar), [
805
+ types.identifier(searchQueryVar),
806
+ ])),
807
+ ])),
808
+ types.numericLiteral(searchDebounce),
809
+ ])),
810
+ ]),
811
+ types.returnStatement(types.arrowFunctionExpression([], types.callExpression(types.identifier('clearTimeout'), [types.identifier('timer')]))),
812
+ ])),
813
+ types.arrayExpression([types.identifier(searchQueryVar)]),
814
+ ]));
815
+ blockStatement.body.splice(insertIndex, 0, debounceEffect);
816
+ // Modify DataProvider to include search params (even without queryColumns)
817
+ if (detected.dataProviderJSX) {
818
+ addSearchParamsToDataProvider(detected.dataProviderJSX, {
819
+ debouncedSearchQueryVar: debouncedSearchQueryVar,
820
+ queryColumns: queryColumns || [],
821
+ });
822
+ }
823
+ // Modify search input
824
+ if (detected.searchInputJSX) {
825
+ addSearchInputHandlers(detected.searchInputJSX, {
826
+ searchQueryVar: searchQueryVar,
827
+ setSearchQueryVar: setSearchQueryVar,
828
+ searchEnabled: true,
829
+ });
830
+ }
831
+ });
832
+ }
833
+ function addSearchParamsToDataProvider(dataProviderJSX, config) {
834
+ var _a, _b;
835
+ if (!dataProviderJSX || !dataProviderJSX.openingElement) {
836
+ return;
837
+ }
838
+ var debouncedSearchQueryVar = config.debouncedSearchQueryVar, queryColumns = config.queryColumns;
839
+ // 1. Update params to be wrapped in useMemo
840
+ var existingParamsAttr = dataProviderJSX.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'params'; });
841
+ if (existingParamsAttr && ((_a = existingParamsAttr.value) === null || _a === void 0 ? void 0 : _a.type) === 'JSXExpressionContainer') {
842
+ var paramsObj = existingParamsAttr.value.expression;
843
+ if (paramsObj.type === 'ObjectExpression') {
844
+ // Add query to existing params properties
845
+ paramsObj.properties.push(types.objectProperty(types.identifier('query'), types.identifier(debouncedSearchQueryVar)));
846
+ // Add queryColumns only if they exist
847
+ if (queryColumns.length > 0) {
848
+ paramsObj.properties.push(types.objectProperty(types.identifier('queryColumns'), types.callExpression(types.memberExpression(types.identifier('JSON'), types.identifier('stringify')), [types.arrayExpression(queryColumns.map(function (col) { return types.stringLiteral(col); }))])));
849
+ }
850
+ // Wrap in useMemo with debouncedSearchQueryVar as dependency
851
+ var memoizedParamsValue = types.callExpression(types.identifier('useMemo'), [
852
+ types.arrowFunctionExpression([], paramsObj),
853
+ types.arrayExpression([types.identifier(debouncedSearchQueryVar)]),
854
+ ]);
855
+ existingParamsAttr.value.expression = memoizedParamsValue;
856
+ }
857
+ }
858
+ // 2. Update initialData to be conditional on empty search
859
+ var existingInitialDataAttr = dataProviderJSX.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'initialData'; });
860
+ if (existingInitialDataAttr && ((_b = existingInitialDataAttr.value) === null || _b === void 0 ? void 0 : _b.type) === 'JSXExpressionContainer') {
861
+ var currentInitialData = existingInitialDataAttr.value.expression;
862
+ // Make it conditional: only use initialData if search is empty
863
+ existingInitialDataAttr.value.expression = types.conditionalExpression(types.unaryExpression('!', types.identifier(debouncedSearchQueryVar), true), currentInitialData, types.identifier('undefined'));
864
+ }
865
+ // 3. Update key to include search query
866
+ var existingKeyAttr = dataProviderJSX.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'key'; });
867
+ var keyExpression = types.templateLiteral([
868
+ types.templateElement({ raw: 'search-', cooked: 'search-' }),
869
+ types.templateElement({ raw: '', cooked: '' }),
870
+ ], [types.identifier(debouncedSearchQueryVar)]);
871
+ var keyAttr = types.jsxAttribute(types.jsxIdentifier('key'), types.jsxExpressionContainer(keyExpression));
872
+ if (existingKeyAttr) {
873
+ var index = dataProviderJSX.openingElement.attributes.indexOf(existingKeyAttr);
874
+ dataProviderJSX.openingElement.attributes[index] = keyAttr;
875
+ }
876
+ else {
877
+ dataProviderJSX.openingElement.attributes.push(keyAttr);
878
+ }
879
+ }
880
+ function addPaginationParamsToDataProvider(dataProviderJSX, info, paginationIndex) {
881
+ var _a;
882
+ if (!dataProviderJSX || !dataProviderJSX.openingElement) {
883
+ return;
884
+ }
885
+ var combinedStateVar = info.combinedStateVar;
886
+ var paramsProperties;
887
+ var dependencies;
888
+ if (info.searchEnabled && combinedStateVar) {
889
+ // Use combined state for both page and query
890
+ paramsProperties = [
891
+ types.objectProperty(types.identifier('page'), types.memberExpression(types.identifier(combinedStateVar), types.identifier('page'))),
892
+ types.objectProperty(types.identifier('perPage'), types.numericLiteral(info.perPage)),
893
+ types.objectProperty(types.identifier('query'), types.memberExpression(types.identifier(combinedStateVar), types.identifier('debouncedQuery'))),
894
+ ];
895
+ if (info.queryColumns && info.queryColumns.length > 0) {
896
+ paramsProperties.push(types.objectProperty(types.identifier('queryColumns'), types.callExpression(types.memberExpression(types.identifier('JSON'), types.identifier('stringify')), [types.arrayExpression(info.queryColumns.map(function (col) { return types.stringLiteral(col); }))])));
897
+ }
898
+ // Single dependency: the combined state object
899
+ dependencies = [types.identifier(combinedStateVar)];
900
+ }
901
+ else {
902
+ // Pagination only (no search)
903
+ paramsProperties = [
904
+ types.objectProperty(types.identifier('page'), types.identifier(info.pageStateVar)),
905
+ types.objectProperty(types.identifier('perPage'), types.numericLiteral(info.perPage)),
906
+ ];
907
+ dependencies = [types.identifier(info.pageStateVar)];
908
+ }
909
+ // Wrap params in useMemo to prevent unnecessary refetches
910
+ var memoizedParamsValue = types.callExpression(types.identifier('useMemo'), [
911
+ types.arrowFunctionExpression([], types.objectExpression(paramsProperties)),
912
+ types.arrayExpression(dependencies),
913
+ ]);
914
+ var paramsAttr = types.jsxAttribute(types.jsxIdentifier('params'), types.jsxExpressionContainer(memoizedParamsValue));
915
+ var existingParamsAttr = dataProviderJSX.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'params'; });
916
+ if (existingParamsAttr) {
917
+ var index = dataProviderJSX.openingElement.attributes.indexOf(existingParamsAttr);
918
+ dataProviderJSX.openingElement.attributes[index] = paramsAttr;
919
+ }
920
+ else {
921
+ dataProviderJSX.openingElement.attributes.push(paramsAttr);
922
+ }
923
+ var existingInitialDataAttr = dataProviderJSX.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'initialData'; });
924
+ if (existingInitialDataAttr && existingInitialDataAttr.value) {
925
+ // Update initialData to use the paginated prop name
926
+ var paginatedPropName = "".concat(info.dataSourceIdentifier, "_pg_").concat(paginationIndex);
927
+ // If search is enabled, use combined state; otherwise use page state
928
+ var condition = void 0;
929
+ if (info.searchEnabled && combinedStateVar) {
930
+ condition = types.logicalExpression('&&', types.binaryExpression('===', types.memberExpression(types.identifier(combinedStateVar), types.identifier('page')), types.numericLiteral(1)), types.unaryExpression('!', types.memberExpression(types.identifier(combinedStateVar), types.identifier('debouncedQuery')), true));
931
+ }
932
+ else {
933
+ condition = types.binaryExpression('===', types.identifier(info.pageStateVar), types.numericLiteral(1));
934
+ }
935
+ existingInitialDataAttr.value.expression = types.conditionalExpression(condition, types.optionalMemberExpression(types.identifier('props'), types.identifier(paginatedPropName), false, true), types.identifier('undefined'));
936
+ }
937
+ var existingKeyAttr = dataProviderJSX.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'key'; });
938
+ // Include page and search in key to trigger refetch when they change
939
+ var keyExpression;
940
+ if (info.searchEnabled && combinedStateVar) {
941
+ keyExpression = types.templateLiteral([
942
+ types.templateElement({
943
+ raw: "".concat(info.dataSourceIdentifier, "-page-"),
944
+ cooked: "".concat(info.dataSourceIdentifier, "-page-"),
945
+ }),
946
+ types.templateElement({ raw: '-search-', cooked: '-search-' }),
947
+ types.templateElement({ raw: '', cooked: '' }),
948
+ ], [
949
+ types.memberExpression(types.identifier(combinedStateVar), types.identifier('page')),
950
+ types.memberExpression(types.identifier(combinedStateVar), types.identifier('debouncedQuery')),
951
+ ]);
952
+ }
953
+ else {
954
+ keyExpression = types.templateLiteral([
955
+ types.templateElement({
956
+ raw: "".concat(info.dataSourceIdentifier, "-"),
957
+ cooked: "".concat(info.dataSourceIdentifier, "-"),
958
+ }),
959
+ types.templateElement({ raw: '', cooked: '' }),
960
+ ], [types.identifier(info.pageStateVar)]);
961
+ }
962
+ var keyAttr = types.jsxAttribute(types.jsxIdentifier('key'), types.jsxExpressionContainer(keyExpression));
963
+ if (existingKeyAttr) {
964
+ var index = dataProviderJSX.openingElement.attributes.indexOf(existingKeyAttr);
965
+ dataProviderJSX.openingElement.attributes[index] = keyAttr;
966
+ }
967
+ else {
968
+ dataProviderJSX.openingElement.attributes.push(keyAttr);
969
+ }
970
+ // For pagination, always create a fresh fetchData that calls the API route
971
+ // Get the resource definition to build the API URL
972
+ var resourceDefAttr = dataProviderJSX.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'resourceDefinition'; });
973
+ if (resourceDefAttr && ((_a = resourceDefAttr.value) === null || _a === void 0 ? void 0 : _a.type) === 'JSXExpressionContainer') {
974
+ var resourceDef = resourceDefAttr.value.expression;
975
+ if (resourceDef.type === 'ObjectExpression') {
976
+ var dataSourceIdProp = resourceDef.properties.find(function (p) { return p.type === 'ObjectProperty' && p.key.value === 'dataSourceId'; });
977
+ var tableNameProp = resourceDef.properties.find(function (p) { return p.type === 'ObjectProperty' && p.key.value === 'tableName'; });
978
+ var dataSourceTypeProp = resourceDef.properties.find(function (p) { return p.type === 'ObjectProperty' && p.key.value === 'dataSourceType'; });
979
+ if (dataSourceIdProp && tableNameProp && dataSourceTypeProp) {
980
+ var dataSourceId = dataSourceIdProp.value.value;
981
+ var tableName = tableNameProp.value.value;
982
+ var dataSourceType = dataSourceTypeProp.value.value;
983
+ var fileName = "".concat(dataSourceType, "-").concat(tableName, "-").concat(dataSourceId.substring(0, 8));
984
+ // Create fetchData attribute with proper fetch chain wrapped in useCallback
985
+ var fetchDataValue = types.callExpression(types.identifier('useCallback'), [
986
+ types.arrowFunctionExpression([types.identifier('params')], types.callExpression(types.memberExpression(types.callExpression(types.memberExpression(types.callExpression(types.identifier('fetch'), [
987
+ types.templateLiteral([
988
+ types.templateElement({
989
+ raw: "/api/".concat(fileName, "?"),
990
+ cooked: "/api/".concat(fileName, "?"),
991
+ }),
992
+ types.templateElement({ raw: '', cooked: '' }),
993
+ ], [
994
+ types.newExpression(types.identifier('URLSearchParams'), [
995
+ types.identifier('params'),
996
+ ]),
997
+ ]),
998
+ types.objectExpression([
999
+ types.objectProperty(types.identifier('headers'), types.objectExpression([
1000
+ types.objectProperty(types.stringLiteral('Content-Type'), types.stringLiteral('application/json')),
1001
+ ])),
1002
+ ]),
1003
+ ]), types.identifier('then')), [
1004
+ types.arrowFunctionExpression([types.identifier('res')], types.callExpression(types.memberExpression(types.identifier('res'), types.identifier('json')), [])),
1005
+ ]), types.identifier('then')), [
1006
+ types.arrowFunctionExpression([types.identifier('response')], types.optionalMemberExpression(types.identifier('response'), types.identifier('data'), false, true)),
1007
+ ])),
1008
+ types.arrayExpression([]),
1009
+ ]);
1010
+ var newFetchDataAttr = types.jsxAttribute(types.jsxIdentifier('fetchData'), types.jsxExpressionContainer(fetchDataValue));
1011
+ // Remove existing fetchData attribute if present
1012
+ var existingFetchDataIndex = dataProviderJSX.openingElement.attributes.findIndex(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'fetchData'; });
1013
+ if (existingFetchDataIndex !== -1) {
1014
+ dataProviderJSX.openingElement.attributes[existingFetchDataIndex] = newFetchDataAttr;
1015
+ }
1016
+ else {
1017
+ dataProviderJSX.openingElement.attributes.push(newFetchDataAttr);
1018
+ }
1019
+ }
1020
+ }
1021
+ }
1022
+ }
1023
+ function findChildWithClass(node, classSubstring) {
1024
+ var _a;
1025
+ if (!node) {
1026
+ return null;
1027
+ }
1028
+ if (node.type === 'JSXElement') {
1029
+ var className = getClassName(((_a = node.openingElement) === null || _a === void 0 ? void 0 : _a.attributes) || []);
1030
+ if (className && className.includes(classSubstring)) {
1031
+ return className;
1032
+ }
1033
+ }
1034
+ if (node.children) {
1035
+ for (var _i = 0, _b = node.children; _i < _b.length; _i++) {
1036
+ var child = _b[_i];
1037
+ var found = findChildWithClass(child, classSubstring);
1038
+ if (found) {
1039
+ return found;
1040
+ }
1041
+ }
1042
+ }
1043
+ if (typeof node === 'object') {
1044
+ for (var _c = 0, _d = Object.values(node); _c < _d.length; _c++) {
1045
+ var value = _d[_c];
1046
+ if (Array.isArray(value)) {
1047
+ for (var _e = 0, value_1 = value; _e < value_1.length; _e++) {
1048
+ var item = value_1[_e];
1049
+ var found = findChildWithClass(item, classSubstring);
1050
+ if (found) {
1051
+ return found;
1052
+ }
1053
+ }
1054
+ }
1055
+ else if (typeof value === 'object') {
1056
+ var found = findChildWithClass(value, classSubstring);
1057
+ if (found) {
1058
+ return found;
1059
+ }
1060
+ }
1061
+ }
1062
+ }
1063
+ return null;
1064
+ }
1065
+ function modifyPaginationButtons(blockStatement, detectedPaginations, paginationInfos) {
1066
+ var modifyNode = function (node) {
1067
+ if (!node) {
1068
+ return;
1069
+ }
1070
+ if (node.type === 'JSXElement') {
1071
+ var openingElement = node.openingElement;
1072
+ if (openingElement && openingElement.name && openingElement.name.type === 'JSXIdentifier') {
1073
+ var className_1 = getClassName(openingElement.attributes);
1074
+ if (className_1) {
1075
+ detectedPaginations.forEach(function (detected, index) {
1076
+ var info = paginationInfos[index];
1077
+ if (!info) {
1078
+ return;
1079
+ }
1080
+ if (className_1 === detected.prevButtonClass) {
1081
+ convertToButton(node, info, 'prev');
1082
+ }
1083
+ else if (className_1 === detected.nextButtonClass) {
1084
+ convertToButton(node, info, 'next');
1085
+ }
1086
+ });
1087
+ }
1088
+ }
1089
+ }
1090
+ if (typeof node === 'object') {
1091
+ Object.values(node).forEach(function (value) {
1092
+ if (Array.isArray(value)) {
1093
+ value.forEach(function (item) { return modifyNode(item); });
1094
+ }
1095
+ else if (typeof value === 'object') {
1096
+ modifyNode(value);
1097
+ }
1098
+ });
1099
+ }
1100
+ };
1101
+ modifyNode(blockStatement);
1102
+ }
1103
+ function modifySearchInputs(blockStatement, detectedPaginations, paginationInfos) {
1104
+ var modifyNode = function (node) {
1105
+ if (!node) {
1106
+ return;
1107
+ }
1108
+ if (node.type === 'JSXElement') {
1109
+ var openingElement = node.openingElement;
1110
+ if (openingElement && openingElement.name && openingElement.name.type === 'JSXIdentifier') {
1111
+ var className_2 = getClassName(openingElement.attributes);
1112
+ if (className_2) {
1113
+ detectedPaginations.forEach(function (detected, index) {
1114
+ var info = paginationInfos[index];
1115
+ if (!info || !info.searchEnabled) {
1116
+ return;
1117
+ }
1118
+ if (className_2 === detected.searchInputClass) {
1119
+ addSearchInputHandlers(node, info);
1120
+ }
1121
+ else if (className_2 && className_2.includes('search-input')) {
1122
+ // Fallback: match any input with 'search-input' in class
1123
+ addSearchInputHandlers(node, info);
1124
+ }
1125
+ });
1126
+ }
1127
+ }
1128
+ }
1129
+ if (typeof node === 'object') {
1130
+ Object.values(node).forEach(function (value) {
1131
+ if (Array.isArray(value)) {
1132
+ value.forEach(function (item) { return modifyNode(item); });
1133
+ }
1134
+ else if (typeof value === 'object') {
1135
+ modifyNode(value);
1136
+ }
1137
+ });
1138
+ }
1139
+ };
1140
+ modifyNode(blockStatement);
1141
+ }
1142
+ function addSearchInputHandlers(jsxElement, info) {
1143
+ if (!info.searchQueryVar || !info.setSearchQueryVar) {
1144
+ return;
1145
+ }
1146
+ var openingElement = jsxElement.openingElement;
1147
+ removeAttribute(openingElement.attributes, 'onChange');
1148
+ removeAttribute(openingElement.attributes, 'value');
1149
+ var onChangeHandler = types.arrowFunctionExpression([types.identifier('e')], types.callExpression(types.identifier(info.setSearchQueryVar), [
1150
+ types.memberExpression(types.memberExpression(types.identifier('e'), types.identifier('target')), types.identifier('value')),
1151
+ ]));
1152
+ openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('onChange'), types.jsxExpressionContainer(onChangeHandler)));
1153
+ openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('value'), types.jsxExpressionContainer(types.identifier(info.searchQueryVar))));
1154
+ }
1155
+ function convertToButton(jsxElement, info, buttonType) {
1156
+ var openingElement = jsxElement.openingElement;
1157
+ if (openingElement.name.type === 'JSXIdentifier') {
1158
+ openingElement.name.name = 'button';
1159
+ }
1160
+ if (jsxElement.closingElement && jsxElement.closingElement.name.type === 'JSXIdentifier') {
1161
+ jsxElement.closingElement.name.name = 'button';
1162
+ }
1163
+ removeAttribute(openingElement.attributes, 'onClick');
1164
+ removeAttribute(openingElement.attributes, 'disabled');
1165
+ removeAttribute(openingElement.attributes, 'type');
1166
+ var combinedStateVar = info.combinedStateVar;
1167
+ var setCombinedStateVar = info.setCombinedStateVar;
1168
+ var onClickHandler;
1169
+ if (info.searchEnabled && combinedStateVar && setCombinedStateVar) {
1170
+ // Use combined state: update only the page property
1171
+ onClickHandler =
1172
+ buttonType === 'prev'
1173
+ ? types.arrowFunctionExpression([], types.callExpression(types.identifier(setCombinedStateVar), [
1174
+ types.arrowFunctionExpression([types.identifier('state')], types.objectExpression([
1175
+ types.spreadElement(types.identifier('state')),
1176
+ types.objectProperty(types.identifier('page'), types.callExpression(types.memberExpression(types.identifier('Math'), types.identifier('max')), [
1177
+ types.numericLiteral(1),
1178
+ types.binaryExpression('-', types.memberExpression(types.identifier('state'), types.identifier('page')), types.numericLiteral(1)),
1179
+ ])),
1180
+ ])),
1181
+ ]))
1182
+ : types.arrowFunctionExpression([], types.callExpression(types.identifier(setCombinedStateVar), [
1183
+ types.arrowFunctionExpression([types.identifier('state')], types.objectExpression([
1184
+ types.spreadElement(types.identifier('state')),
1185
+ types.objectProperty(types.identifier('page'), types.binaryExpression('+', types.memberExpression(types.identifier('state'), types.identifier('page')), types.numericLiteral(1))),
1186
+ ])),
1187
+ ]));
1188
+ }
1189
+ else {
1190
+ // Regular pagination (no search)
1191
+ onClickHandler =
1192
+ buttonType === 'prev'
1193
+ ? types.arrowFunctionExpression([], types.callExpression(types.identifier(info.setPageStateVar), [
1194
+ types.arrowFunctionExpression([types.identifier('p')], types.callExpression(types.memberExpression(types.identifier('Math'), types.identifier('max')), [
1195
+ types.numericLiteral(1),
1196
+ types.binaryExpression('-', types.identifier('p'), types.numericLiteral(1)),
1197
+ ])),
1198
+ ]))
1199
+ : types.arrowFunctionExpression([], types.callExpression(types.identifier(info.setPageStateVar), [
1200
+ types.arrowFunctionExpression([types.identifier('p')], types.binaryExpression('+', types.identifier('p'), types.numericLiteral(1))),
1201
+ ]));
1202
+ }
1203
+ openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('onClick'), types.jsxExpressionContainer(onClickHandler)));
1204
+ openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('type'), types.stringLiteral('button')));
1205
+ // Add disabled attribute with simple page number checks
1206
+ var maxPagesStateVar = info.maxPagesStateVar;
1207
+ var disabledExpr;
1208
+ if (info.searchEnabled && combinedStateVar) {
1209
+ disabledExpr =
1210
+ buttonType === 'prev'
1211
+ ? types.binaryExpression('<=', types.memberExpression(types.identifier(combinedStateVar), types.identifier('page')), types.numericLiteral(1))
1212
+ : types.binaryExpression('>=', types.memberExpression(types.identifier(combinedStateVar), types.identifier('page')), types.identifier(maxPagesStateVar));
1213
+ }
1214
+ else {
1215
+ disabledExpr =
1216
+ buttonType === 'prev'
1217
+ ? types.binaryExpression('<=', types.identifier(info.pageStateVar), types.numericLiteral(1))
1218
+ : types.binaryExpression('>=', types.identifier(info.pageStateVar), types.identifier(maxPagesStateVar));
1219
+ }
1220
+ openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('disabled'), types.jsxExpressionContainer(disabledExpr)));
1221
+ }
1222
+ function getClassName(attributes) {
1223
+ var classNameAttr = attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === 'className'; });
1224
+ if (classNameAttr && classNameAttr.value && classNameAttr.value.type === 'StringLiteral') {
1225
+ return classNameAttr.value.value;
1226
+ }
1227
+ return null;
1228
+ }
1229
+ function removeAttribute(attrs, attributeName) {
1230
+ var index = attrs.findIndex(function (attr) { return attr.type === 'JSXAttribute' && attr.name.name === attributeName; });
1231
+ if (index !== -1) {
1232
+ attrs.splice(index, 1);
1233
+ }
1234
+ }
1235
+ function modifyGetStaticPropsForPagination(chunks, paginationInfos) {
1236
+ var _a;
1237
+ var getStaticPropsChunk = chunks.find(function (chunk) { return chunk.name === 'getStaticProps'; });
1238
+ if (!getStaticPropsChunk || getStaticPropsChunk.type !== 'ast') {
1239
+ return;
1240
+ }
1241
+ var exportDeclaration = getStaticPropsChunk.content;
1242
+ if (!exportDeclaration || exportDeclaration.type !== 'ExportNamedDeclaration') {
1243
+ return;
1244
+ }
1245
+ var functionDeclaration = exportDeclaration.declaration;
1246
+ if (!functionDeclaration || functionDeclaration.type !== 'FunctionDeclaration') {
1247
+ return;
1248
+ }
1249
+ // Find Promise.all and add NEW fetchData calls for each paginated DataProvider
1250
+ var functionBody = functionDeclaration.body.body;
1251
+ var tryBlock = functionBody.find(function (stmt) { return stmt.type === 'TryStatement'; });
1252
+ if (!tryBlock) {
1253
+ return;
1254
+ }
1255
+ var tryBody = tryBlock.block.body;
1256
+ // Find the Promise.all statement
1257
+ var promiseAllStmt = tryBody.find(function (stmt) {
1258
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t;
1259
+ return stmt.type === 'VariableDeclaration' &&
1260
+ ((_c = (_b = (_a = stmt.declarations) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.init) === null || _c === void 0 ? void 0 : _c.type) === 'AwaitExpression' &&
1261
+ ((_g = (_f = (_e = (_d = stmt.declarations) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.init) === null || _f === void 0 ? void 0 : _f.argument) === null || _g === void 0 ? void 0 : _g.type) === 'CallExpression' &&
1262
+ ((_m = (_l = (_k = (_j = (_h = stmt.declarations) === null || _h === void 0 ? void 0 : _h[0]) === null || _j === void 0 ? void 0 : _j.init) === null || _k === void 0 ? void 0 : _k.argument) === null || _l === void 0 ? void 0 : _l.callee) === null || _m === void 0 ? void 0 : _m.type) === 'MemberExpression' &&
1263
+ ((_t = (_s = (_r = (_q = (_p = (_o = stmt.declarations) === null || _o === void 0 ? void 0 : _o[0]) === null || _p === void 0 ? void 0 : _p.init) === null || _q === void 0 ? void 0 : _q.argument) === null || _r === void 0 ? void 0 : _r.callee) === null || _s === void 0 ? void 0 : _s.property) === null || _t === void 0 ? void 0 : _t.name) === 'all';
1264
+ });
1265
+ if (!promiseAllStmt) {
1266
+ return;
1267
+ }
1268
+ var awaitExpr = promiseAllStmt.declarations[0].init;
1269
+ var promiseAllCall = awaitExpr.argument;
1270
+ var promiseArray = promiseAllCall.arguments[0];
1271
+ var destructuringPattern = promiseAllStmt.declarations[0].id;
1272
+ // Map import names to data source identifiers from existing fetchData calls
1273
+ // Also track which indices to remove (non-paginated calls that will be replaced)
1274
+ var importToDataSource = new Map();
1275
+ var indicesToRemove = [];
1276
+ promiseArray.elements.forEach(function (element, index) {
1277
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
1278
+ if (element && element.type === 'CallExpression') {
1279
+ var fetchCallExpr = element;
1280
+ // If wrapped in .catch(), unwrap it
1281
+ if (((_a = element.callee) === null || _a === void 0 ? void 0 : _a.type) === 'MemberExpression' &&
1282
+ ((_c = (_b = element.callee) === null || _b === void 0 ? void 0 : _b.property) === null || _c === void 0 ? void 0 : _c.name) === 'catch' &&
1283
+ ((_e = (_d = element.callee) === null || _d === void 0 ? void 0 : _d.object) === null || _e === void 0 ? void 0 : _e.type) === 'CallExpression') {
1284
+ fetchCallExpr = element.callee.object;
1285
+ }
1286
+ // Now find the .fetchData() call
1287
+ if (((_f = fetchCallExpr.callee) === null || _f === void 0 ? void 0 : _f.type) === 'MemberExpression' &&
1288
+ ((_h = (_g = fetchCallExpr.callee) === null || _g === void 0 ? void 0 : _g.property) === null || _h === void 0 ? void 0 : _h.name) === 'fetchData' &&
1289
+ ((_k = (_j = fetchCallExpr.callee) === null || _j === void 0 ? void 0 : _j.object) === null || _k === void 0 ? void 0 : _k.type) === 'Identifier') {
1290
+ var importName = fetchCallExpr.callee.object.name;
1291
+ var dataSourceVar_1 = destructuringPattern.elements[index].name;
1292
+ // Check if this fetchData call has page/perPage params
1293
+ var params = fetchCallExpr.arguments[0];
1294
+ var hasPageParam = params &&
1295
+ params.type === 'ObjectExpression' &&
1296
+ params.properties.some(function (prop) {
1297
+ return prop.type === 'ObjectProperty' &&
1298
+ (prop.key.name === 'page' || prop.key.name === 'perPage');
1299
+ });
1300
+ // If this is a data source that will be paginated but this call has NO pagination params,
1301
+ // mark it for removal
1302
+ if (!hasPageParam &&
1303
+ paginationInfos.some(function (info) { return info.dataSourceIdentifier === dataSourceVar_1; })) {
1304
+ indicesToRemove.push(index);
1305
+ }
1306
+ importToDataSource.set(importName, dataSourceVar_1);
1307
+ }
1308
+ }
1309
+ });
1310
+ // Remove non-paginated fetchData calls in reverse order to preserve indices
1311
+ indicesToRemove.reverse().forEach(function (index) {
1312
+ var _a, _b;
1313
+ // Get the prop name BEFORE removing it
1314
+ var propToRemove = (_a = destructuringPattern.elements[index]) === null || _a === void 0 ? void 0 : _a.name;
1315
+ promiseArray.elements.splice(index, 1);
1316
+ destructuringPattern.elements.splice(index, 1);
1317
+ // Also remove from props in return statement
1318
+ if (propToRemove) {
1319
+ var foundReturnStmt = tryBody.find(function (stmt) { return stmt.type === 'ReturnStatement'; });
1320
+ if (foundReturnStmt && ((_b = foundReturnStmt.argument) === null || _b === void 0 ? void 0 : _b.type) === 'ObjectExpression') {
1321
+ var propsProperty = foundReturnStmt.argument.properties.find(function (prop) {
1322
+ return prop.type === 'ObjectProperty' && prop.key.name === 'props';
1323
+ });
1324
+ if (propsProperty && propsProperty.value.type === 'ObjectExpression') {
1325
+ var propsObject = propsProperty.value;
1326
+ var propIndex = propsObject.properties.findIndex(function (prop) {
1327
+ return prop.type === 'ObjectProperty' && prop.key.name === propToRemove;
1328
+ });
1329
+ if (propIndex !== -1) {
1330
+ propsObject.properties.splice(propIndex, 1);
1331
+ }
1332
+ }
1333
+ }
1334
+ }
1335
+ });
1336
+ // Add NEW fetchData calls for each paginated DataProvider
1337
+ paginationInfos.forEach(function (info, index) {
1338
+ var _a, _b;
1339
+ // Try exact match first, then case-insensitive match
1340
+ var importName = (_a = Array.from(importToDataSource.entries()).find(function (_a) {
1341
+ var _ = _a[0], dataSourceVar = _a[1];
1342
+ return dataSourceVar === info.dataSourceIdentifier;
1343
+ })) === null || _a === void 0 ? void 0 : _a[0];
1344
+ if (!importName) {
1345
+ // Try case-insensitive match
1346
+ var normalizedIdentifier_1 = info.dataSourceIdentifier.toLowerCase().replace(/[_-]/g, '');
1347
+ importName = (_b = Array.from(importToDataSource.entries()).find(function (_a) {
1348
+ var _ = _a[0], dataSourceVar = _a[1];
1349
+ return dataSourceVar.toLowerCase().replace(/[_-]/g, '') === normalizedIdentifier_1;
1350
+ })) === null || _b === void 0 ? void 0 : _b[0];
1351
+ }
1352
+ if (importName) {
1353
+ var paginatedVarName = "".concat(info.dataSourceIdentifier, "_pg_").concat(index);
1354
+ var fetchParams = [
1355
+ types.objectProperty(types.identifier('page'), types.numericLiteral(1)),
1356
+ types.objectProperty(types.identifier('perPage'), types.numericLiteral(info.perPage)),
1357
+ ];
1358
+ // Add queryColumns if they exist
1359
+ if (info.queryColumns && info.queryColumns.length > 0) {
1360
+ fetchParams.push(types.objectProperty(types.identifier('queryColumns'), types.arrayExpression(info.queryColumns.map(function (col) { return types.stringLiteral(col); }))));
1361
+ }
1362
+ // Create new fetchData call with pagination params
1363
+ var newFetchDataCall = types.callExpression(types.memberExpression(types.callExpression(types.memberExpression(types.identifier(importName), types.identifier('fetchData')), [types.objectExpression(fetchParams)]), types.identifier('catch')), [
1364
+ types.arrowFunctionExpression([types.identifier('error')], types.blockStatement([
1365
+ types.expressionStatement(types.callExpression(types.memberExpression(types.identifier('console'), types.identifier('error')), [
1366
+ types.stringLiteral("Error fetching ".concat(paginatedVarName, ":")),
1367
+ types.identifier('error'),
1368
+ ])),
1369
+ types.returnStatement(types.arrayExpression([])),
1370
+ ])),
1371
+ ]);
1372
+ promiseArray.elements.push(newFetchDataCall);
1373
+ destructuringPattern.elements.push(types.identifier(paginatedVarName));
1374
+ }
1375
+ });
1376
+ // Add fetchCount calls for paginated data sources (deduplicated by data source)
1377
+ // Deduplicate by data source identifier
1378
+ var uniqueDataSources = new Set(paginationInfos.map(function (info) { return info.dataSourceIdentifier; }));
1379
+ var addedCountFetches = new Set();
1380
+ uniqueDataSources.forEach(function (dataSourceId) {
1381
+ var _a, _b;
1382
+ var importName = (_a = Array.from(importToDataSource.entries()).find(function (_a) {
1383
+ var _ = _a[0], dataSourceVar = _a[1];
1384
+ return dataSourceVar === dataSourceId;
1385
+ })) === null || _a === void 0 ? void 0 : _a[0];
1386
+ if (!importName) {
1387
+ // Try case-insensitive match
1388
+ var normalizedIdentifier_2 = dataSourceId.toLowerCase().replace(/[_-]/g, '');
1389
+ importName = (_b = Array.from(importToDataSource.entries()).find(function (_a) {
1390
+ var _ = _a[0], dataSourceVar = _a[1];
1391
+ return dataSourceVar.toLowerCase().replace(/[_-]/g, '') === normalizedIdentifier_2;
1392
+ })) === null || _b === void 0 ? void 0 : _b[0];
1393
+ }
1394
+ if (importName && !addedCountFetches.has(dataSourceId)) {
1395
+ var fetchCountCall = types.callExpression(types.memberExpression(types.identifier(importName), types.identifier('fetchCount')), []);
1396
+ promiseArray.elements.push(fetchCountCall);
1397
+ destructuringPattern.elements.push(types.identifier("".concat(dataSourceId, "_count")));
1398
+ addedCountFetches.add(dataSourceId);
1399
+ }
1400
+ });
1401
+ // Calculate and add maxPages before return
1402
+ var returnStmt = tryBody.find(function (stmt) { return stmt.type === 'ReturnStatement'; });
1403
+ if (returnStmt && ((_a = returnStmt.argument) === null || _a === void 0 ? void 0 : _a.type) === 'ObjectExpression') {
1404
+ var propsProperty = returnStmt.argument.properties.find(function (prop) {
1405
+ return prop.type === 'ObjectProperty' && prop.key.name === 'props';
1406
+ });
1407
+ if (propsProperty && propsProperty.value.type === 'ObjectExpression') {
1408
+ var propsObject_1 = propsProperty.value;
1409
+ var returnIndex_1 = tryBody.indexOf(returnStmt);
1410
+ paginationInfos.forEach(function (info, index) {
1411
+ var paginatedVarName = "".concat(info.dataSourceIdentifier, "_pg_").concat(index);
1412
+ var countVarName = "".concat(info.dataSourceIdentifier, "_count");
1413
+ var maxPagesVarName = "".concat(info.dataSourceIdentifier, "_pg_").concat(index, "_maxPages");
1414
+ var maxPagesCalc = types.variableDeclaration('const', [
1415
+ types.variableDeclarator(types.identifier(maxPagesVarName), types.callExpression(types.memberExpression(types.identifier('Math'), types.identifier('ceil')), [
1416
+ types.binaryExpression('/', types.logicalExpression('||', types.identifier(countVarName), types.numericLiteral(0)), types.numericLiteral(info.perPage)),
1417
+ ])),
1418
+ ]);
1419
+ tryBody.splice(returnIndex_1, 0, maxPagesCalc);
1420
+ // Add both the paginated data and maxPages to props
1421
+ propsObject_1.properties.push(types.objectProperty(types.identifier(paginatedVarName), types.identifier(paginatedVarName)));
1422
+ propsObject_1.properties.push(types.objectProperty(types.identifier(maxPagesVarName), types.identifier(maxPagesVarName)));
1423
+ });
1424
+ }
1425
+ }
1426
+ }
1427
+ function createAPIRoutesForPaginatedDataSources(uidlNode, dataSources, componentChunk, extractedResources, paginationInfos, isComponent) {
1428
+ var paginatedDataSourceIds = new Set(paginationInfos.map(function (info) { return info.dataSourceIdentifier; }));
1429
+ var traverseForDataSources = function (node) {
1430
+ var _a;
1431
+ if (!node) {
1432
+ return;
1433
+ }
1434
+ if (node.type === 'data-source-list' || node.type === 'data-source-item') {
1435
+ var renderProp = node.content.renderPropIdentifier;
1436
+ if (renderProp && paginatedDataSourceIds.has(renderProp)) {
1437
+ (0, utils_1.extractDataSourceIntoNextAPIFolder)(node, dataSources, componentChunk, extractedResources);
1438
+ // For components, also create count API route
1439
+ if (isComponent) {
1440
+ var resourceDef = node.content.resourceDefinition;
1441
+ if (resourceDef) {
1442
+ var dataSourceId = resourceDef.dataSourceId;
1443
+ var tableName = resourceDef.tableName;
1444
+ var dataSourceType = resourceDef.dataSourceType;
1445
+ var fileName = "".concat(dataSourceType, "-").concat(tableName, "-").concat(dataSourceId.substring(0, 8));
1446
+ var countFileName = "".concat(fileName, "-count");
1447
+ // Create count API route that exports getCount handler
1448
+ extractedResources["api/".concat(countFileName)] = {
1449
+ fileName: countFileName,
1450
+ fileType: teleport_types_1.FileType.JS,
1451
+ path: ['pages', 'api'],
1452
+ content: "import dataSource from '../../utils/data-sources/".concat(fileName, "'\n\nexport default dataSource.getCount\n"),
1453
+ };
1454
+ }
1455
+ }
1456
+ }
1457
+ }
1458
+ if ((_a = node.content) === null || _a === void 0 ? void 0 : _a.children) {
1459
+ node.content.children.forEach(function (child) { return traverseForDataSources(child); });
1460
+ }
1461
+ };
1462
+ traverseForDataSources(uidlNode);
1463
+ }
1464
+ function createAPIRoutesForSearchOnlyDataSources(uidlNode, dataSources, componentChunk, extractedResources, searchOnlyDataSources) {
1465
+ var searchOnlyDataSourceIds = new Set(searchOnlyDataSources.map(function (info) { return info.dataSourceIdentifier; }));
1466
+ var traverseForDataSources = function (node) {
1467
+ var _a;
1468
+ if (!node) {
1469
+ return;
1470
+ }
1471
+ if (node.type === 'data-source-list' || node.type === 'data-source-item') {
1472
+ var renderProp = node.content.renderPropIdentifier;
1473
+ if (renderProp && searchOnlyDataSourceIds.has(renderProp)) {
1474
+ (0, utils_1.extractDataSourceIntoNextAPIFolder)(node, dataSources, componentChunk, extractedResources);
1475
+ }
1476
+ }
1477
+ if ((_a = node.content) === null || _a === void 0 ? void 0 : _a.children) {
1478
+ node.content.children.forEach(function (child) { return traverseForDataSources(child); });
1479
+ }
1480
+ };
1481
+ traverseForDataSources(uidlNode);
1482
+ }
1483
+ exports.default = (0, exports.createNextArrayMapperPaginationPlugin)();
1484
+ //# sourceMappingURL=pagination-plugin.js.map