@teleporthq/teleport-plugin-common 0.44.0-alpha.0 → 0.44.1

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 (190) hide show
  1. package/__tests__/builders/html-builders.ts +9 -2
  2. package/__tests__/builders/style-builders.ts +23 -0
  3. package/__tests__/node-handlers/node-to-html/index.ts +2 -0
  4. package/__tests__/node-handlers/node-to-jsx/attribute-value-mapper.ts +77 -0
  5. package/__tests__/node-handlers/node-to-jsx/calendar-events-reviver.ts +176 -0
  6. package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-ecommerce-source.ts +79 -0
  7. package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-loading.ts +122 -0
  8. package/__tests__/node-handlers/node-to-jsx/index.ts +719 -3
  9. package/__tests__/node-handlers/node-to-jsx/url-search-params-expression.ts +59 -0
  10. package/__tests__/node-handlers/node-to-jsx/utils.ts +602 -3
  11. package/__tests__/utils/ast-utils.ts +188 -0
  12. package/__tests__/utils/content-property-sanitiser.ts +156 -0
  13. package/__tests__/utils/page-seeds-state-from-data-source.ts +70 -0
  14. package/__tests__/utils/parse-string-with-template-expressions.ts +82 -0
  15. package/__tests__/utils/resource-auth-scheme.ts +55 -0
  16. package/__tests__/utils/route-utils.ts +118 -0
  17. package/__tests__/utils/style-utils.ts +59 -0
  18. package/__tests__/utils/template-expression-balance.ts +83 -0
  19. package/__tests__/utils/url-query-writer.ts +239 -0
  20. package/__tests__/utils/url-search-param-sync.ts +138 -0
  21. package/__tests__/utils/url-search-params.ts +48 -0
  22. package/dist/cjs/builders/ast-builders.d.ts +2 -0
  23. package/dist/cjs/builders/ast-builders.d.ts.map +1 -1
  24. package/dist/cjs/builders/ast-builders.js +41 -3
  25. package/dist/cjs/builders/ast-builders.js.map +1 -1
  26. package/dist/cjs/builders/hast-builders.d.ts +1 -0
  27. package/dist/cjs/builders/hast-builders.d.ts.map +1 -1
  28. package/dist/cjs/builders/hast-builders.js +11 -1
  29. package/dist/cjs/builders/hast-builders.js.map +1 -1
  30. package/dist/cjs/builders/style-builders.d.ts +8 -2
  31. package/dist/cjs/builders/style-builders.d.ts.map +1 -1
  32. package/dist/cjs/builders/style-builders.js +65 -19
  33. package/dist/cjs/builders/style-builders.js.map +1 -1
  34. package/dist/cjs/index.d.ts +5 -1
  35. package/dist/cjs/index.d.ts.map +1 -1
  36. package/dist/cjs/index.js +9 -1
  37. package/dist/cjs/index.js.map +1 -1
  38. package/dist/cjs/node-handlers/node-to-html/constants.d.ts.map +1 -1
  39. package/dist/cjs/node-handlers/node-to-html/constants.js +2 -0
  40. package/dist/cjs/node-handlers/node-to-html/constants.js.map +1 -1
  41. package/dist/cjs/node-handlers/node-to-html/index.d.ts.map +1 -1
  42. package/dist/cjs/node-handlers/node-to-html/index.js +69 -1
  43. package/dist/cjs/node-handlers/node-to-html/index.js.map +1 -1
  44. package/dist/cjs/node-handlers/node-to-html/types.d.ts +5 -1
  45. package/dist/cjs/node-handlers/node-to-html/types.d.ts.map +1 -1
  46. package/dist/cjs/node-handlers/node-to-html/utils.d.ts +2 -1
  47. package/dist/cjs/node-handlers/node-to-html/utils.d.ts.map +1 -1
  48. package/dist/cjs/node-handlers/node-to-html/utils.js +174 -13
  49. package/dist/cjs/node-handlers/node-to-html/utils.js.map +1 -1
  50. package/dist/cjs/node-handlers/node-to-jsx/index.d.ts.map +1 -1
  51. package/dist/cjs/node-handlers/node-to-jsx/index.js +1461 -66
  52. package/dist/cjs/node-handlers/node-to-jsx/index.js.map +1 -1
  53. package/dist/cjs/node-handlers/node-to-jsx/types.d.ts +60 -6
  54. package/dist/cjs/node-handlers/node-to-jsx/types.d.ts.map +1 -1
  55. package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts +73 -7
  56. package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
  57. package/dist/cjs/node-handlers/node-to-jsx/utils.js +864 -71
  58. package/dist/cjs/node-handlers/node-to-jsx/utils.js.map +1 -1
  59. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  60. package/dist/cjs/utils/ast-utils.d.ts +142 -11
  61. package/dist/cjs/utils/ast-utils.d.ts.map +1 -1
  62. package/dist/cjs/utils/ast-utils.js +931 -75
  63. package/dist/cjs/utils/ast-utils.js.map +1 -1
  64. package/dist/cjs/utils/hast-utils.d.ts +8 -6
  65. package/dist/cjs/utils/hast-utils.d.ts.map +1 -1
  66. package/dist/cjs/utils/hast-utils.js +28 -4
  67. package/dist/cjs/utils/hast-utils.js.map +1 -1
  68. package/dist/cjs/utils/route-utils.d.ts +117 -0
  69. package/dist/cjs/utils/route-utils.d.ts.map +1 -0
  70. package/dist/cjs/utils/route-utils.js +212 -0
  71. package/dist/cjs/utils/route-utils.js.map +1 -0
  72. package/dist/cjs/utils/style-utils.d.ts +1 -0
  73. package/dist/cjs/utils/style-utils.d.ts.map +1 -1
  74. package/dist/cjs/utils/style-utils.js +181 -2
  75. package/dist/cjs/utils/style-utils.js.map +1 -1
  76. package/dist/cjs/utils/template-expression-balance.d.ts +58 -0
  77. package/dist/cjs/utils/template-expression-balance.d.ts.map +1 -0
  78. package/dist/cjs/utils/template-expression-balance.js +181 -0
  79. package/dist/cjs/utils/template-expression-balance.js.map +1 -0
  80. package/dist/cjs/utils/types.d.ts +3 -0
  81. package/dist/cjs/utils/types.d.ts.map +1 -0
  82. package/dist/cjs/utils/types.js +3 -0
  83. package/dist/cjs/utils/types.js.map +1 -0
  84. package/dist/cjs/utils/url-query-writer.d.ts +123 -0
  85. package/dist/cjs/utils/url-query-writer.d.ts.map +1 -0
  86. package/dist/cjs/utils/url-query-writer.js +260 -0
  87. package/dist/cjs/utils/url-query-writer.js.map +1 -0
  88. package/dist/cjs/utils/url-search-param-sync.d.ts +4 -0
  89. package/dist/cjs/utils/url-search-param-sync.d.ts.map +1 -0
  90. package/dist/cjs/utils/url-search-param-sync.js +241 -0
  91. package/dist/cjs/utils/url-search-param-sync.js.map +1 -0
  92. package/dist/cjs/utils/url-search-params.d.ts +48 -0
  93. package/dist/cjs/utils/url-search-params.d.ts.map +1 -0
  94. package/dist/cjs/utils/url-search-params.js +109 -0
  95. package/dist/cjs/utils/url-search-params.js.map +1 -0
  96. package/dist/esm/builders/ast-builders.d.ts +2 -0
  97. package/dist/esm/builders/ast-builders.d.ts.map +1 -1
  98. package/dist/esm/builders/ast-builders.js +40 -4
  99. package/dist/esm/builders/ast-builders.js.map +1 -1
  100. package/dist/esm/builders/hast-builders.d.ts +1 -0
  101. package/dist/esm/builders/hast-builders.d.ts.map +1 -1
  102. package/dist/esm/builders/hast-builders.js +9 -0
  103. package/dist/esm/builders/hast-builders.js.map +1 -1
  104. package/dist/esm/builders/style-builders.d.ts +8 -2
  105. package/dist/esm/builders/style-builders.d.ts.map +1 -1
  106. package/dist/esm/builders/style-builders.js +63 -18
  107. package/dist/esm/builders/style-builders.js.map +1 -1
  108. package/dist/esm/index.d.ts +5 -1
  109. package/dist/esm/index.d.ts.map +1 -1
  110. package/dist/esm/index.js +5 -1
  111. package/dist/esm/index.js.map +1 -1
  112. package/dist/esm/node-handlers/node-to-html/constants.d.ts.map +1 -1
  113. package/dist/esm/node-handlers/node-to-html/constants.js +2 -0
  114. package/dist/esm/node-handlers/node-to-html/constants.js.map +1 -1
  115. package/dist/esm/node-handlers/node-to-html/index.d.ts.map +1 -1
  116. package/dist/esm/node-handlers/node-to-html/index.js +71 -3
  117. package/dist/esm/node-handlers/node-to-html/index.js.map +1 -1
  118. package/dist/esm/node-handlers/node-to-html/types.d.ts +5 -1
  119. package/dist/esm/node-handlers/node-to-html/types.d.ts.map +1 -1
  120. package/dist/esm/node-handlers/node-to-html/utils.d.ts +2 -1
  121. package/dist/esm/node-handlers/node-to-html/utils.d.ts.map +1 -1
  122. package/dist/esm/node-handlers/node-to-html/utils.js +170 -13
  123. package/dist/esm/node-handlers/node-to-html/utils.js.map +1 -1
  124. package/dist/esm/node-handlers/node-to-jsx/index.d.ts.map +1 -1
  125. package/dist/esm/node-handlers/node-to-jsx/index.js +1460 -68
  126. package/dist/esm/node-handlers/node-to-jsx/index.js.map +1 -1
  127. package/dist/esm/node-handlers/node-to-jsx/types.d.ts +60 -6
  128. package/dist/esm/node-handlers/node-to-jsx/types.d.ts.map +1 -1
  129. package/dist/esm/node-handlers/node-to-jsx/utils.d.ts +73 -7
  130. package/dist/esm/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
  131. package/dist/esm/node-handlers/node-to-jsx/utils.js +857 -69
  132. package/dist/esm/node-handlers/node-to-jsx/utils.js.map +1 -1
  133. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  134. package/dist/esm/utils/ast-utils.d.ts +142 -11
  135. package/dist/esm/utils/ast-utils.d.ts.map +1 -1
  136. package/dist/esm/utils/ast-utils.js +911 -75
  137. package/dist/esm/utils/ast-utils.js.map +1 -1
  138. package/dist/esm/utils/hast-utils.d.ts +8 -6
  139. package/dist/esm/utils/hast-utils.d.ts.map +1 -1
  140. package/dist/esm/utils/hast-utils.js +26 -3
  141. package/dist/esm/utils/hast-utils.js.map +1 -1
  142. package/dist/esm/utils/route-utils.d.ts +117 -0
  143. package/dist/esm/utils/route-utils.d.ts.map +1 -0
  144. package/dist/esm/utils/route-utils.js +179 -0
  145. package/dist/esm/utils/route-utils.js.map +1 -0
  146. package/dist/esm/utils/style-utils.d.ts +1 -0
  147. package/dist/esm/utils/style-utils.d.ts.map +1 -1
  148. package/dist/esm/utils/style-utils.js +179 -1
  149. package/dist/esm/utils/style-utils.js.map +1 -1
  150. package/dist/esm/utils/template-expression-balance.d.ts +58 -0
  151. package/dist/esm/utils/template-expression-balance.d.ts.map +1 -0
  152. package/dist/esm/utils/template-expression-balance.js +174 -0
  153. package/dist/esm/utils/template-expression-balance.js.map +1 -0
  154. package/dist/esm/utils/types.d.ts +3 -0
  155. package/dist/esm/utils/types.d.ts.map +1 -0
  156. package/dist/esm/utils/types.js +2 -0
  157. package/dist/esm/utils/types.js.map +1 -0
  158. package/dist/esm/utils/url-query-writer.d.ts +123 -0
  159. package/dist/esm/utils/url-query-writer.d.ts.map +1 -0
  160. package/dist/esm/utils/url-query-writer.js +229 -0
  161. package/dist/esm/utils/url-query-writer.js.map +1 -0
  162. package/dist/esm/utils/url-search-param-sync.d.ts +4 -0
  163. package/dist/esm/utils/url-search-param-sync.d.ts.map +1 -0
  164. package/dist/esm/utils/url-search-param-sync.js +213 -0
  165. package/dist/esm/utils/url-search-param-sync.js.map +1 -0
  166. package/dist/esm/utils/url-search-params.d.ts +48 -0
  167. package/dist/esm/utils/url-search-params.d.ts.map +1 -0
  168. package/dist/esm/utils/url-search-params.js +81 -0
  169. package/dist/esm/utils/url-search-params.js.map +1 -0
  170. package/package.json +4 -4
  171. package/src/builders/ast-builders.ts +80 -3
  172. package/src/builders/hast-builders.ts +11 -0
  173. package/src/builders/style-builders.ts +107 -27
  174. package/src/index.ts +18 -1
  175. package/src/node-handlers/node-to-html/constants.ts +2 -0
  176. package/src/node-handlers/node-to-html/index.ts +126 -6
  177. package/src/node-handlers/node-to-html/types.ts +6 -0
  178. package/src/node-handlers/node-to-html/utils.ts +228 -14
  179. package/src/node-handlers/node-to-jsx/index.ts +2219 -111
  180. package/src/node-handlers/node-to-jsx/types.ts +75 -32
  181. package/src/node-handlers/node-to-jsx/utils.ts +1142 -84
  182. package/src/utils/ast-utils.ts +1223 -127
  183. package/src/utils/hast-utils.ts +37 -9
  184. package/src/utils/route-utils.ts +214 -0
  185. package/src/utils/style-utils.ts +183 -1
  186. package/src/utils/template-expression-balance.ts +196 -0
  187. package/src/utils/types.ts +25 -0
  188. package/src/utils/url-query-writer.ts +318 -0
  189. package/src/utils/url-search-param-sync.ts +303 -0
  190. package/src/utils/url-search-params.ts +122 -0
@@ -33,6 +33,18 @@ var __importStar = (this && this.__importStar) || function (mod) {
33
33
  __setModuleDefault(result, mod);
34
34
  return result;
35
35
  };
36
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
37
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
38
+ if (ar || !(i in from)) {
39
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
40
+ ar[i] = from[i];
41
+ }
42
+ }
43
+ return to.concat(ar || Array.prototype.slice.call(from));
44
+ };
45
+ var __importDefault = (this && this.__importDefault) || function (mod) {
46
+ return (mod && mod.__esModule) ? mod : { "default": mod };
47
+ };
36
48
  Object.defineProperty(exports, "__esModule", { value: true });
37
49
  var types = __importStar(require("@babel/types"));
38
50
  var teleport_shared_1 = require("@teleporthq/teleport-shared");
@@ -41,12 +53,500 @@ var ast_utils_1 = require("../../utils/ast-utils");
41
53
  var ast_builders_1 = require("../../builders/ast-builders");
42
54
  var constants_1 = require("./constants");
43
55
  var __1 = require("../..");
56
+ var parsed_ast_1 = __importDefault(require("../../utils/parsed-ast"));
57
+ // Runtime predicate that drops a DataProvider filter whose destination
58
+ // resolves to an empty value: `''` / `null` / `undefined`, or an empty
59
+ // array-overlap set (`[]` / `['']`). Selecting a "show all" reset must mean
60
+ // "no filter", not a query that matches zero rows. Kept in sync with the
61
+ // Next.js pages plugin's `buildNonEmptyDestinationPredicate` (duplicated here
62
+ // because teleport-plugin-common must not depend on teleport-plugin-next-data-source).
63
+ var buildNonEmptyFilterDestinationPredicate = function () {
64
+ var f = types.identifier('__f');
65
+ var dest = types.memberExpression(f, types.identifier('destination'));
66
+ var isEmptyArray = types.logicalExpression('&&', types.callExpression(types.memberExpression(types.identifier('Array'), types.identifier('isArray')), [dest]), types.binaryExpression('===', types.memberExpression(types.callExpression(types.memberExpression(dest, types.identifier('filter')), [
67
+ types.identifier('Boolean'),
68
+ ]), types.identifier('length')), types.numericLiteral(0)));
69
+ return types.arrowFunctionExpression([f], types.logicalExpression('&&', types.logicalExpression('&&', types.logicalExpression('&&', types.binaryExpression('!==', dest, types.stringLiteral('')), types.binaryExpression('!==', dest, types.nullLiteral())), types.binaryExpression('!==', dest, types.identifier('undefined'))), types.unaryExpression('!', isEmptyArray)));
70
+ };
71
+ // Same idea one level up: a filter entry survives if it is a group that still
72
+ // has children, or a condition whose destination resolved to something real.
73
+ var buildSurvivingFilterNodePredicate = function () {
74
+ var f = types.identifier('__f');
75
+ var emptyDestination = buildNonEmptyFilterDestinationPredicate().body;
76
+ return types.arrowFunctionExpression([f], types.conditionalExpression(types.binaryExpression('===', types.memberExpression(f, types.identifier('type')), types.stringLiteral('group')), types.binaryExpression('>', types.memberExpression(types.memberExpression(f, types.identifier('children')), types.identifier('length')), types.numericLiteral(0)), emptyDestination));
77
+ };
78
+ // The inspector authors filters as a TREE — a root `and` group whose children
79
+ // are conditions or nested `or` groups. Emitting the tree (rather than mapping
80
+ // each entry as if it were a condition, which turned every group into an empty
81
+ // `{ source: '', destination: '', operand: '' }` row that the predicate then
82
+ // dropped) is what lets the data-source runtime honour the filter at all.
83
+ var buildFilterNodeExpression = function (entry, dynamicReferencePrefixMap) {
84
+ if (entry && entry.type === 'group' && Array.isArray(entry.children)) {
85
+ var childExpressions = entry.children.map(function (child) {
86
+ return buildFilterNodeExpression(child, dynamicReferencePrefixMap);
87
+ });
88
+ return types.objectExpression([
89
+ types.objectProperty(types.identifier('type'), types.stringLiteral('group')),
90
+ types.objectProperty(types.identifier('operator'), types.stringLiteral(entry.operator === 'or' ? 'or' : 'and')),
91
+ types.objectProperty(types.identifier('children'), types.callExpression(types.memberExpression(types.arrayExpression(childExpressions), types.identifier('filter')), [buildSurvivingFilterNodePredicate()])),
92
+ ]);
93
+ }
94
+ return types.objectExpression([
95
+ types.objectProperty(types.identifier('type'), types.stringLiteral('condition')),
96
+ types.objectProperty(types.identifier('source'), types.stringLiteral((entry === null || entry === void 0 ? void 0 : entry.source) || '')),
97
+ types.objectProperty(types.identifier('destination'), __1.ASTUtils.convertFilterDestinationToExpression(entry === null || entry === void 0 ? void 0 : entry.destination, {
98
+ dynamicReferencePrefixMap: dynamicReferencePrefixMap,
99
+ })),
100
+ types.objectProperty(types.identifier('operand'), types.stringLiteral((entry === null || entry === void 0 ? void 0 : entry.operand) || '')),
101
+ ]);
102
+ };
103
+ // Global references in the UIDL come in two shapes:
104
+ // Shape A: { id: "ecommerce", refPath: ["Cart", "total"] }
105
+ // Shape B: { id: undefined, refPath: ["E-commerce", "Settings", "Delivery", "..."] }
106
+ // This helper normalizes Shape B into Shape A so downstream code can handle
107
+ // both uniformly. The first refPath segment is mapped to a variable name via
108
+ // GLOBAL_REF_ID_MAP (exported from ast-utils so all sites stay in sync).
109
+ // Expression attributes (UIDLExpressionValue) bypass the dynamic-reference
110
+ // tracking in createDynamicValueExpression. When such an expression mentions
111
+ // a known global (currentUser/ecommerce/cart/locale/userIsLoggedIn) we still
112
+ // Plan v15 Layer 4 — junk-name attribute guard.
113
+ // AI fabrication artefacts emit attributes whose KEY is a JS literal
114
+ // (`true="true"`, `false="false"`, `0="x"`, `null="..."`). They survive JSX
115
+ // parsing (treated as string-valued attrs) but break DOM semantics. The
116
+ // upstream Layer 1–3 pipeline should already strip them; this is the final
117
+ // codegen safety net.
118
+ var CODEGEN_JUNK_ATTR_NAMES = new Set(['true', 'false', 'null', 'undefined']);
119
+ function isJunkAttributeName(name) {
120
+ if (typeof name !== 'string' || name.length === 0) {
121
+ return true;
122
+ }
123
+ var lower = name.toLowerCase();
124
+ if (CODEGEN_JUNK_ATTR_NAMES.has(lower)) {
125
+ return true;
126
+ }
127
+ if (/^[0-9]+$/.test(name)) {
128
+ return true;
129
+ }
130
+ return false;
131
+ }
132
+ function hasCorruptBindingMarkers(value) {
133
+ // Entity-escaped `{` / `}` from upstream serialization that should never
134
+ // reach the JSX output verbatim.
135
+ if (/&#123;|&#125;/.test(value)) {
136
+ return true;
137
+ }
138
+ // Unbalanced `{{` (no matching `}}`).
139
+ var opens = (value.match(/\{\{/g) || []).length;
140
+ var closes = (value.match(/\}\}/g) || []).length;
141
+ if (opens > closes) {
142
+ return true;
143
+ }
144
+ return false;
145
+ }
146
+ function truncate(value) {
147
+ if (value.length <= 60) {
148
+ return value;
149
+ }
150
+ return value.slice(0, 57) + '...';
151
+ }
152
+ // need to push it into params.globalReferences so downstream plugins inject
153
+ // the corresponding `useGlobalContext()` destructuring.
154
+ var GLOBAL_EXPRESSION_IDENTIFIERS = [
155
+ { pattern: /\bcurrentUser\b/, id: 'currentUser' },
156
+ { pattern: /\buserIsLoggedIn\b/, id: 'userIsLoggedIn' },
157
+ { pattern: /\becommerce\b/, id: 'ecommerce' },
158
+ { pattern: /\bcart\b/, id: 'cart' },
159
+ { pattern: /\blocales?\b/, id: 'locale' },
160
+ ];
161
+ var trackGlobalRefsInExpression = function (expression, params) {
162
+ if (!expression) {
163
+ return;
164
+ }
165
+ for (var _i = 0, GLOBAL_EXPRESSION_IDENTIFIERS_1 = GLOBAL_EXPRESSION_IDENTIFIERS; _i < GLOBAL_EXPRESSION_IDENTIFIERS_1.length; _i++) {
166
+ var _a = GLOBAL_EXPRESSION_IDENTIFIERS_1[_i], pattern = _a.pattern, id = _a.id;
167
+ if (pattern.test(expression)) {
168
+ params.globalReferences.push(id);
169
+ }
170
+ }
171
+ // Global-state identifiers behave the same way: an expression-shaped UIDL
172
+ // attribute (e.g. cms-mixed-type `itemData`) bypasses the dynamic-ref
173
+ // pipeline that registers `useGlobalState()` destructuring, so we walk the
174
+ // raw expression text and re-attach any state name we recognise. The
175
+ // matched names are added to `globalStateReferences` and the
176
+ // next-global-state component plugin destructures them at codegen time.
177
+ var definitions = params.globalStateDefinitions;
178
+ if (!definitions || Object.keys(definitions).length === 0) {
179
+ return;
180
+ }
181
+ for (var _b = 0, _c = Object.values(definitions); _b < _c.length; _b++) {
182
+ var def = _c[_b];
183
+ var name_1 = def === null || def === void 0 ? void 0 : def.name;
184
+ if (!name_1) {
185
+ continue;
186
+ }
187
+ var escaped = name_1.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
188
+ if (new RegExp("\\b".concat(escaped, "\\b")).test(expression)) {
189
+ params.globalStateReferences.push({ id: def.id, name: name_1 });
190
+ }
191
+ }
192
+ };
193
+ // The recognised runtime identifiers a `global` reference's `id` can legitimately
194
+ // already hold (Shape A). Anything else — notably the opaque `TQ_...` node id every
195
+ // dynamic UIDL reference carries for editor bookkeeping — is not a real identifier
196
+ // and must be re-derived from `refPath` (Shape B/C), or code generation would emit
197
+ // an undeclared variable that throws at runtime.
198
+ var KNOWN_GLOBAL_REF_IDS = new Set([
199
+ 'locale',
200
+ 'locales',
201
+ 'currentUser',
202
+ 'userIsLoggedIn',
203
+ 'ecommerce',
204
+ 'cart',
205
+ ]);
206
+ var normalizeGlobalRef = function (node) {
207
+ if (!node.content.refPath || node.content.refPath.length === 0) {
208
+ return node;
209
+ }
210
+ if (node.content.id && KNOWN_GLOBAL_REF_IDS.has(node.content.id)) {
211
+ return node;
212
+ }
213
+ var firstSeg = node.content.refPath[0];
214
+ var mappedId = ast_utils_1.GLOBAL_REF_ID_MAP[firstSeg];
215
+ if (!mappedId) {
216
+ return node;
217
+ }
218
+ return __assign(__assign({}, node), { content: __assign(__assign({}, node.content), { id: mappedId, refPath: node.content.refPath.slice(1) }) });
219
+ };
220
+ var getElementType = function (node) {
221
+ if (node.type === 'element' &&
222
+ node.content &&
223
+ typeof node.content === 'object' &&
224
+ 'elementType' in node.content) {
225
+ return node.content.elementType;
226
+ }
227
+ if ((node.type === 'data-source-list' || node.type === 'data-source-item') && node.content) {
228
+ return node.content.elementType || 'DataProvider';
229
+ }
230
+ return null;
231
+ };
232
+ var getClassName = function (node) {
233
+ if (node.type === 'element' &&
234
+ node.content &&
235
+ typeof node.content === 'object' &&
236
+ 'key' in node.content) {
237
+ return node.content.key || null;
238
+ }
239
+ return null;
240
+ };
241
+ var REACT_CHARTJS2_CHART_TAGS = new Set([
242
+ 'Line',
243
+ 'Bar',
244
+ 'Doughnut',
245
+ 'Pie',
246
+ 'Radar',
247
+ 'Bubble',
248
+ 'PolarArea',
249
+ 'Scatter',
250
+ ]);
251
+ var isReactChartjs2Chart = function (dependency, elementType) {
252
+ if ((dependency === null || dependency === void 0 ? void 0 : dependency.path) !== 'react-chartjs-2') {
253
+ return false;
254
+ }
255
+ return REACT_CHARTJS2_CHART_TAGS.has(elementType);
256
+ };
257
+ /**
258
+ * Chart.js with maintainAspectRatio:false fills the parent; if height is on the chart
259
+ * component via className, react-chartjs-2 may not apply it to the canvas host correctly
260
+ * inside flex layouts, causing unbounded growth. Wrap in a bounded div and move className
261
+ * to the wrapper; the chart fills with height/width 100%.
262
+ */
263
+ var wrapReactChartJs2Element = function (chartElement, _node) {
264
+ var attrs = chartElement.openingElement.attributes;
265
+ var kept = [];
266
+ var classNameAttr = null;
267
+ for (var _i = 0, attrs_1 = attrs; _i < attrs_1.length; _i++) {
268
+ var a = attrs_1[_i];
269
+ if (a.type === 'JSXAttribute' &&
270
+ a.name.type === 'JSXIdentifier' &&
271
+ a.name.name === 'className') {
272
+ classNameAttr = a;
273
+ }
274
+ else {
275
+ kept.push(a);
276
+ }
277
+ }
278
+ chartElement.openingElement.attributes = kept;
279
+ var hasStyleAttr = kept.some(function (a) { return a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier' && a.name.name === 'style'; });
280
+ if (!hasStyleAttr) {
281
+ chartElement.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('style'), types.jsxExpressionContainer(types.objectExpression([
282
+ types.objectProperty(types.identifier('height'), types.stringLiteral('100%')),
283
+ types.objectProperty(types.identifier('width'), types.stringLiteral('100%')),
284
+ ]))));
285
+ }
286
+ var wrapperStyle = types.objectExpression([
287
+ types.objectProperty(types.identifier('position'), types.stringLiteral('relative')),
288
+ types.objectProperty(types.identifier('minHeight'), types.numericLiteral(0)),
289
+ types.objectProperty(types.identifier('flexShrink'), types.numericLiteral(0)),
290
+ types.objectProperty(types.identifier('overflow'), types.stringLiteral('hidden')),
291
+ ]);
292
+ var wrapperAttrs = [
293
+ types.jsxAttribute(types.jsxIdentifier('style'), types.jsxExpressionContainer(wrapperStyle)),
294
+ ];
295
+ if (classNameAttr) {
296
+ wrapperAttrs.push(classNameAttr);
297
+ }
298
+ return types.jsxElement(types.jsxOpeningElement(types.jsxIdentifier('div'), wrapperAttrs), types.jsxClosingElement(types.jsxIdentifier('div')), [chartElement], false);
299
+ };
300
+ var isCalendarKitScheduler = function (dependency, elementType) {
301
+ return (dependency === null || dependency === void 0 ? void 0 : dependency.path) === 'calendarkit-basic' && elementType === 'BasicScheduler';
302
+ };
303
+ /**
304
+ * calendarkit-basic's BasicScheduler requires `start`/`end` to be Date objects
305
+ * (date-fns internals), but UIDL attrs carry them as ISO strings — both for
306
+ * static event arrays and for state-bound arrays populated by workflows.
307
+ * Rewrites `events={X}` into:
308
+ * events={(Array.isArray(X) ? X : []).map((e) => ({ ...e, start: new Date(e.start), end: new Date(e.end) }))}
309
+ * The Array.isArray guard renders zero events instead of crashing when a
310
+ * binding resolves to a non-array (e.g. an unparsed JSON-string fallback).
311
+ * A missing `events` attr is left as-is — the component defaults it to [].
312
+ */
313
+ var wrapCalendarKitEventsAttr = function (calendarElement) {
314
+ var _a;
315
+ var attr = calendarElement.openingElement.attributes.find(function (a) {
316
+ return a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier' && a.name.name === 'events';
317
+ });
318
+ if (!attr || ((_a = attr.value) === null || _a === void 0 ? void 0 : _a.type) !== 'JSXExpressionContainer') {
319
+ return;
320
+ }
321
+ var source = attr.value.expression;
322
+ if (!types.isExpression(source)) {
323
+ return;
324
+ }
325
+ // A static array literal needs no runtime guard; dynamic references do.
326
+ var guardedSource = types.isArrayExpression(source)
327
+ ? source
328
+ : types.conditionalExpression(types.callExpression(types.memberExpression(types.identifier('Array'), types.identifier('isArray')), [source]), types.cloneNode(source), types.arrayExpression([]));
329
+ var reviveEvent = types.arrowFunctionExpression([types.identifier('e')], types.objectExpression([
330
+ types.spreadElement(types.identifier('e')),
331
+ types.objectProperty(types.identifier('start'), types.newExpression(types.identifier('Date'), [
332
+ types.memberExpression(types.identifier('e'), types.identifier('start')),
333
+ ])),
334
+ types.objectProperty(types.identifier('end'), types.newExpression(types.identifier('Date'), [
335
+ types.memberExpression(types.identifier('e'), types.identifier('end')),
336
+ ])),
337
+ ]));
338
+ attr.value = types.jsxExpressionContainer(types.callExpression(types.memberExpression(guardedSource, types.identifier('map')), [
339
+ reviveEvent,
340
+ ]));
341
+ };
342
+ var reorderChildrenForSearch = function (children) {
343
+ var searchNodes = [];
344
+ var dataProviderNodes = [];
345
+ var paginationNodes = [];
346
+ var otherNodes = [];
347
+ children.forEach(function (child) {
348
+ var elementType = getElementType(child);
349
+ var nodeType = child.type;
350
+ var className = getClassName(child);
351
+ // Check for search nodes - use className since elementType is replaced by semanticType
352
+ if (className &&
353
+ (className.includes('data-source-search') || className.includes('search-node'))) {
354
+ searchNodes.push(child);
355
+ }
356
+ // Check for DataProvider nodes - these should appear SECOND
357
+ else if (nodeType === 'data-source-list' ||
358
+ nodeType === 'data-source-item' ||
359
+ elementType === 'DataProvider') {
360
+ dataProviderNodes.push(child);
361
+ }
362
+ // Check for pagination nodes - use className since elementType is replaced by semanticType
363
+ else if ((elementType &&
364
+ (elementType.includes('pagination') || elementType.includes('cms-pagination'))) ||
365
+ (className && (className.includes('pagination') || className.includes('cms-pagination')))) {
366
+ paginationNodes.push(child);
367
+ }
368
+ // Everything else goes in the middle
369
+ else {
370
+ otherNodes.push(child);
371
+ }
372
+ });
373
+ // Only reorder if we have search or pagination nodes alongside a DataProvider
374
+ // This ensures we only reorder when there's an actual pagination/search group
375
+ // If there's no search/pagination, keep original order to preserve DataProvider positions
376
+ var hasSearchOrPagination = searchNodes.length > 0 || paginationNodes.length > 0;
377
+ var hasDataProvider = dataProviderNodes.length > 0;
378
+ if (hasSearchOrPagination && hasDataProvider) {
379
+ // Order: search nodes first, then data providers, then other nodes, then pagination last
380
+ // This ensures: search input -> DataProvider -> content -> pagination buttons
381
+ return __spreadArray(__spreadArray(__spreadArray(__spreadArray([], searchNodes, true), dataProviderNodes, true), otherNodes, true), paginationNodes, true);
382
+ }
383
+ else {
384
+ // No reordering needed - preserve original order
385
+ return children;
386
+ }
387
+ };
388
+ /**
389
+ * Extracts autocomplete context from a thq-autocomplete node's children.
390
+ * Returns the input's field name and the dropdown's isOpen state name,
391
+ * so child option/clear elements can wire up onClick handlers.
392
+ */
393
+ var extractAutocompleteContext = function (children, formStateName) {
394
+ var _a, _b, _c, _d;
395
+ var fieldName = null;
396
+ var inputHtmlId = null;
397
+ var isOpenStateName = null;
398
+ for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
399
+ var child = children_1[_i];
400
+ if (child.type === 'element') {
401
+ var content = child.content;
402
+ // Check both original elementType and data-thq attr (elementType may have been resolved)
403
+ var dataThq = (_a = content.attrs) === null || _a === void 0 ? void 0 : _a['data-thq'];
404
+ var thqValue = (dataThq === null || dataThq === void 0 ? void 0 : dataThq.type) === 'static' ? String(dataThq.content) : '';
405
+ if (content.elementType === 'thq-autocomplete-input' ||
406
+ thqValue === 'thq-autocomplete-input') {
407
+ var nameAttr = (_b = content.attrs) === null || _b === void 0 ? void 0 : _b.name;
408
+ if ((nameAttr === null || nameAttr === void 0 ? void 0 : nameAttr.type) === 'static' && typeof nameAttr.content === 'string') {
409
+ fieldName = nameAttr.content;
410
+ }
411
+ var idAttr = (_c = content.attrs) === null || _c === void 0 ? void 0 : _c.id;
412
+ if ((idAttr === null || idAttr === void 0 ? void 0 : idAttr.type) === 'static' && typeof idAttr.content === 'string') {
413
+ inputHtmlId = idAttr.content;
414
+ }
415
+ }
416
+ }
417
+ else if (child.type === 'conditional') {
418
+ var condContent = child.content;
419
+ var ref = (_d = condContent.reference) === null || _d === void 0 ? void 0 : _d.content;
420
+ if ((ref === null || ref === void 0 ? void 0 : ref.referenceType) === 'state' && typeof ref.id === 'string') {
421
+ isOpenStateName = ref.id;
422
+ }
423
+ }
424
+ }
425
+ if (fieldName && isOpenStateName) {
426
+ return { fieldName: fieldName, inputHtmlId: inputHtmlId || '', formStateName: formStateName, isOpenStateName: isOpenStateName };
427
+ }
428
+ return undefined;
429
+ };
430
+ var maybeAddFormStoreFieldBinding = function (elementTag, elementName, attrs, params, events) {
431
+ var stateKey = params.formStoreStateName;
432
+ if (!stateKey || !attrs) {
433
+ return;
434
+ }
435
+ var nameAttr = attrs.name;
436
+ if (!nameAttr || nameAttr.type !== 'static' || typeof nameAttr.content !== 'string') {
437
+ return;
438
+ }
439
+ var tag = elementName.toLowerCase();
440
+ var isRichTextEditor = tag === 'richtexteditor';
441
+ if (tag !== 'input' && tag !== 'textarea' && tag !== 'select' && !isRichTextEditor) {
442
+ return;
443
+ }
444
+ // Autocomplete inputs manage their own value through workflows and option onClick handlers.
445
+ // Do NOT bind them to the form store — it causes infinite loops with state-change workflows.
446
+ var dataThq = attrs['data-thq'];
447
+ if ((dataThq === null || dataThq === void 0 ? void 0 : dataThq.type) === 'static' && String(dataThq.content) === 'thq-autocomplete-input') {
448
+ return;
449
+ }
450
+ var fieldName = nameAttr.content;
451
+ var stateId = types.identifier(stateKey);
452
+ var fieldAccess = types.memberExpression(stateId, types.stringLiteral(fieldName), true);
453
+ var typeAttr = attrs.type;
454
+ var isCheckbox = (typeAttr === null || typeAttr === void 0 ? void 0 : typeAttr.type) === 'static' && String(typeAttr.content) === 'checkbox';
455
+ var hasValueInAttrs = Object.prototype.hasOwnProperty.call(attrs, 'value');
456
+ var hasCheckedInAttrs = Object.prototype.hasOwnProperty.call(attrs, 'checked');
457
+ if (isRichTextEditor) {
458
+ var valueForEditor = types.logicalExpression('||', fieldAccess, types.stringLiteral(''));
459
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('value'), types.jsxExpressionContainer(valueForEditor)));
460
+ var setterName = "set".concat(stateKey.charAt(0).toUpperCase()).concat(stateKey.slice(1));
461
+ var richHandler = (0, ast_utils_1.parseJSExpressionAsAST)("(html) => { ".concat(setterName, "(prev => ({ ...prev, ['").concat(fieldName, "']: html })); }"));
462
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('onChange'), types.jsxExpressionContainer(richHandler)));
463
+ return;
464
+ }
465
+ if (!hasValueInAttrs && !isCheckbox) {
466
+ var valueExpr = types.logicalExpression('??', fieldAccess, types.stringLiteral(''));
467
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('value'), types.jsxExpressionContainer(valueExpr)));
468
+ }
469
+ else if (isCheckbox && !hasCheckedInAttrs) {
470
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('checked'), types.jsxExpressionContainer(fieldAccess)));
471
+ }
472
+ var hasUidlOnChange = events && Object.prototype.hasOwnProperty.call(events, 'onChange');
473
+ if (!hasUidlOnChange) {
474
+ var setterName = "set".concat(stateKey.charAt(0).toUpperCase()).concat(stateKey.slice(1));
475
+ var handler = (0, ast_utils_1.parseJSExpressionAsAST)("(e) => { const t = e.target; if (t.name) { ".concat(setterName, "(prev => ({ ...prev, [t.name]: t.type === 'checkbox' ? t.checked : t.value })); } }"));
476
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('onChange'), types.jsxExpressionContainer(handler)));
477
+ }
478
+ };
479
+ // Style plugins (styled-jsx, css-modules, styled-components, react-jss, plugin-css)
480
+ // emit ONE flat, component-scope CSS block/class-map from `element.style`, so a
481
+ // dynamic style value only resolves correctly there when the identifier it needs
482
+ // is reachable from that top-level scope (e.g. `token`/`prop`). A `ctx` reference
483
+ // resolves to the render-prop identifier of the enclosing repeater/data-source —
484
+ // only in scope inside that repeater's own render callback — and other reference
485
+ // types (`state`, `local`, `global`, `globalState`, ...) are never routed through
486
+ // `element.style` by any known UIDL producer either. When one shows up anyway, the
487
+ // only place that still knows the correct enclosing scope is here, while building
488
+ // this exact JSX node, so resolve it into an inline `style` attribute (mirroring
489
+ // how `dynamicStyleBindings` already handles ctx/state-bound styles) and strip it
490
+ // out of `element.style` so no downstream style plugin re-processes — and chokes
491
+ // on — the same entry.
492
+ var resolveScopedDynamicStyleValues = function (style, elementTag, params, options) {
493
+ if (!style) {
494
+ return;
495
+ }
496
+ var inlineStyleOverrides = {};
497
+ for (var _i = 0, _a = Object.keys(style); _i < _a.length; _i++) {
498
+ var cssProperty = _a[_i];
499
+ var styleValue = style[cssProperty];
500
+ var camelCaseProperty = teleport_shared_1.StringUtils.cssPropertyToInlineStyleKey(cssProperty);
501
+ // A pre-resolved expression style value (e.g. a data-source-bound style whose
502
+ // mapper already produced the full member-access expression). The UIDL style
503
+ // type is narrowed to static|dynamic, so read the discriminator via a cast.
504
+ // Inline the parsed expression and strip it so no CSS/styled-jsx plugin sees it.
505
+ var rawStyleValue = styleValue;
506
+ if (rawStyleValue.type === 'expr') {
507
+ var exprContent = rawStyleValue.content;
508
+ if (typeof exprContent === 'string' && exprContent.length > 0) {
509
+ inlineStyleOverrides[camelCaseProperty] = new parsed_ast_1.default((0, ast_utils_1.parseJSExpressionAsAST)(exprContent));
510
+ delete style[cssProperty];
511
+ }
512
+ continue;
513
+ }
514
+ // Skip: `token` → CSS variable (handled by the style plugin); a SIMPLE `prop`
515
+ // (no refPath) → the style plugin's `${props.x}` interpolation. A prop WITH a
516
+ // refPath (an object prop's field, e.g. `product.color`) MUST be inlined here
517
+ // instead — styled-jsx's prop case emits only `props.<id>` and would drop the
518
+ // refPath, producing `props.product` instead of `props.product.color`.
519
+ var isSimpleProp = styleValue.type === 'dynamic' &&
520
+ styleValue.content.referenceType === 'prop' &&
521
+ !(styleValue.content.refPath && styleValue.content.refPath.length > 0);
522
+ if (styleValue.type !== 'dynamic' ||
523
+ styleValue.content.referenceType === 'token' ||
524
+ isSimpleProp) {
525
+ continue;
526
+ }
527
+ var resolvedExpr = resolveDynamicReferenceExpression(styleValue, params, options);
528
+ var fallback = styleValue.content.fallback;
529
+ var finalExpr = fallback !== undefined && fallback !== ''
530
+ ? types.logicalExpression('||', resolvedExpr, (0, ast_utils_1.convertValueToLiteral)(fallback))
531
+ : resolvedExpr;
532
+ inlineStyleOverrides[camelCaseProperty] = new parsed_ast_1.default(finalExpr);
533
+ delete style[cssProperty];
534
+ }
535
+ if (Object.keys(inlineStyleOverrides).length > 0) {
536
+ (0, ast_utils_1.addAttributeToJSXTag)(elementTag, 'style', inlineStyleOverrides);
537
+ }
538
+ };
44
539
  var generateElementNode = function (node, params, jsxOptions) {
45
- var dependencies = params.dependencies, nodesLookup = params.nodesLookup, _a = params.projectResources, projectResources = _a === void 0 ? {} : _a;
46
- var options = __assign(__assign(__assign({}, constants_1.DEFAULT_JSX_OPTIONS), jsxOptions), { projectResources: projectResources });
47
- var _b = node.content, elementType = _b.elementType, selfClosing = _b.selfClosing, children = _b.children, key = _b.key, attrs = _b.attrs, dependency = _b.dependency, events = _b.events;
540
+ var dependencies = params.dependencies, nodesLookup = params.nodesLookup;
541
+ var options = __assign(__assign({}, constants_1.DEFAULT_JSX_OPTIONS), jsxOptions);
542
+ var _a = node.content, elementType = _a.elementType, selfClosing = _a.selfClosing, children = _a.children, key = _a.key, attrs = _a.attrs, dependency = _a.dependency, events = _a.events, style = _a.style;
48
543
  var originalElementName = elementType || 'component';
49
544
  var tagName = originalElementName;
545
+ // Check if this is a fragment element - normalize to Fragment before processing
546
+ var isFragment = tagName.toLowerCase() === 'fragment';
547
+ if (isFragment) {
548
+ tagName = 'Fragment';
549
+ }
50
550
  if (dependency) {
51
551
  if (options.dependencyHandling === 'import' ||
52
552
  (options.dependencyHandling === 'ignore' && (dependency === null || dependency === void 0 ? void 0 : dependency.type) === 'package')) {
@@ -65,54 +565,187 @@ var generateElementNode = function (node, params, jsxOptions) {
65
565
  params.windowImports[dependency.path] = dynamicWindowImport;
66
566
  }
67
567
  }
568
+ else if (isFragment) {
569
+ // If no dependency was provided but this is a fragment, add Fragment dependency
570
+ if (options.dependencyHandling === 'import') {
571
+ dependencies.Fragment = {
572
+ type: 'package',
573
+ path: 'react',
574
+ version: 'latest',
575
+ meta: {
576
+ namedImport: true,
577
+ },
578
+ };
579
+ }
580
+ }
68
581
  var elementName = dependency && dependency.type === 'local' && options.customElementTag
69
582
  ? options.customElementTag(tagName)
70
583
  : tagName;
71
584
  var elementTag = selfClosing ? (0, ast_builders_1.createSelfClosingJSXTag)(elementName) : (0, ast_builders_1.createJSXTag)(elementName);
72
585
  if (attrs) {
73
- Object.keys(attrs).forEach(function (attrKey) {
74
- var attributeValue = attrs[attrKey];
75
- switch (attributeValue.type) {
76
- case 'dynamic':
77
- var referenceType = attributeValue.content.referenceType;
78
- switch (referenceType) {
79
- default:
80
- var prefix = options.dynamicReferencePrefixMap[referenceType];
81
- (0, ast_utils_1.addDynamicAttributeToJSXTag)(elementTag, attrKey, attributeValue.content.id, prefix);
82
- break;
83
- }
84
- break;
85
- case 'import':
86
- (0, ast_utils_1.addDynamicAttributeToJSXTag)(elementTag, attrKey, attributeValue.content.id);
87
- break;
88
- case 'raw':
89
- (0, ast_utils_1.addRawAttributeToJSXTag)(elementTag, attrKey, attributeValue);
90
- break;
91
- case 'comp-style':
92
- case 'static':
93
- (0, ast_utils_1.addAttributeToJSXTag)(elementTag, attrKey, attributeValue.content);
94
- break;
95
- case 'expr':
96
- (0, ast_utils_1.addDynamicExpressionAttributeToJSXTag)(elementTag, attributeValue, attrKey);
97
- break;
98
- default:
99
- throw new Error("generateElementNode could not generate code for attribute of type ".concat(JSON.stringify(attributeValue)));
100
- }
101
- });
586
+ addAttributesToJSXTag(attrs, elementTag, options, params, node.content.semanticType || elementType);
102
587
  }
588
+ resolveScopedDynamicStyleValues(style, elementTag, params, options);
103
589
  if (events) {
104
590
  Object.keys(events).forEach(function (eventKey) {
105
591
  (0, utils_1.addEventHandlerToTag)(elementTag, eventKey, events[eventKey], params, options);
106
592
  });
107
593
  }
108
- if (!selfClosing && children) {
109
- children.forEach(function (child) {
110
- var childTags = generateNode(child, params, options);
594
+ // Generate onChange handler for form elements with data-store-values-state
595
+ var childParams = params;
596
+ if (attrs === null || attrs === void 0 ? void 0 : attrs['data-store-values-state']) {
597
+ var storeAttr = attrs['data-store-values-state'];
598
+ if (storeAttr.type === 'static' && typeof storeAttr.content === 'string') {
599
+ var stateName = storeAttr.content;
600
+ childParams = __assign(__assign({}, params), { formStoreStateName: stateName });
601
+ var setterName = "set".concat(stateName.charAt(0).toUpperCase()).concat(stateName.slice(1));
602
+ var handler = (0, ast_utils_1.parseJSExpressionAsAST)("(e) => { const t = e.target; if (t.name && t.getAttribute('data-thq') !== 'thq-autocomplete-input') { ".concat(setterName, "(prev => ({ ...prev, [t.name]: t.type === 'checkbox' ? t.checked : t.value })); } }"));
603
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('onChange'), types.jsxExpressionContainer(handler)));
604
+ }
605
+ }
606
+ maybeAddFormStoreFieldBinding(elementTag, elementName, attrs, childParams, events);
607
+ // thq-autocomplete-input: make uncontrolled by converting `value` → `defaultValue`
608
+ // A controlled autocomplete input triggers state-change workflows on every keystroke,
609
+ // which normalizes the typed text and prevents free typing for search/filtering.
610
+ var dataThqAttr = attrs === null || attrs === void 0 ? void 0 : attrs['data-thq'];
611
+ var dataThqValue = (dataThqAttr === null || dataThqAttr === void 0 ? void 0 : dataThqAttr.type) === 'static' ? String(dataThqAttr.content) : '';
612
+ if (dataThqValue === 'thq-autocomplete-input') {
613
+ var jsxAttrs = elementTag.openingElement.attributes;
614
+ var valueIdx = jsxAttrs.findIndex(function (a) { return a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier' && a.name.name === 'value'; });
615
+ if (valueIdx !== -1) {
616
+ // Convert value → defaultValue so the input is uncontrolled but has initial value
617
+ var valueAttr = jsxAttrs[valueIdx];
618
+ jsxAttrs.splice(valueIdx, 1, types.jsxAttribute(types.jsxIdentifier('defaultValue'), valueAttr.value));
619
+ }
620
+ }
621
+ // A controlled form control (`<input>`/`<textarea>`/`<select>` with a `value`,
622
+ // or a checkbox/radio with `checked`) that has NO change handler is FROZEN by
623
+ // React — the user cannot type, and a console warning is emitted. This is the
624
+ // edit-form failure mode: entity-bound fields rendered as
625
+ // `value={props.item?.title}` with no state mirror (the worker deliberately
626
+ // does NOT mirror entity columns into state — see crud-edit-form contract).
627
+ // Render such controls UNCONTROLLED (`defaultValue`/`defaultChecked`) so they
628
+ // are editable AND the DOM value reflects edits, which is exactly what
629
+ // form-submit workflows read (`document.getElementById(id).value`). Controls
630
+ // that ARE controlled (an onChange was attached above — via events, the
631
+ // form-store binding, or a workflow trigger) keep `value`/`checked`, and
632
+ // read-only/disabled display fields are left untouched.
633
+ (0, utils_1.makeControlUncontrolledWhenNoChangeHandler)(elementTag, elementName);
634
+ if (dataThqValue === 'thq-autocomplete' && children) {
635
+ var acCtx = extractAutocompleteContext(children, childParams.formStoreStateName);
636
+ if (acCtx) {
637
+ childParams = __assign(__assign({}, childParams), { autocompleteContext: acCtx });
638
+ }
639
+ }
640
+ // thq-autocomplete-option: add onClick to select the option value
641
+ if (dataThqValue === 'thq-autocomplete-option' && params.autocompleteContext) {
642
+ var _b = params.autocompleteContext, fieldName = _b.fieldName, formStateName = _b.formStateName, isOpenStateName = _b.isOpenStateName, inputHtmlId = _b.inputHtmlId;
643
+ var isOpenSetterName = "set".concat(isOpenStateName.charAt(0).toUpperCase()).concat(isOpenStateName.slice(1));
644
+ var handlerCode
645
+ // The autocomplete input is uncontrolled, so always set the DOM value.
646
+ // If form-store mode, also update the form state for form submission.
647
+ = void 0;
648
+ // The autocomplete input is uncontrolled, so always set the DOM value.
649
+ // If form-store mode, also update the form state for form submission.
650
+ var inputLookup = inputHtmlId
651
+ ? "document.getElementById('".concat(inputHtmlId, "')")
652
+ : "e.currentTarget.closest('[data-thq=\"thq-autocomplete\"]').querySelector('[data-thq=\"thq-autocomplete-input\"]')";
653
+ var formStoreUpdate = formStateName
654
+ ? "var setter = ".concat("set".concat(formStateName.charAt(0).toUpperCase()).concat(formStateName.slice(1)), "; setter(function(prev) { return Object.assign({}, prev, { ['").concat(fieldName, "']: text }); });")
655
+ : '';
656
+ handlerCode = "(e) => { var text = (e.currentTarget.textContent || '').trim(); var input = ".concat(inputLookup, "; if (input) { input.value = text; } ").concat(formStoreUpdate, " ").concat(isOpenSetterName, "(false); }");
657
+ var handler = (0, ast_utils_1.parseJSExpressionAsAST)(handlerCode);
658
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('onClick'), types.jsxExpressionContainer(handler)));
659
+ }
660
+ // thq-autocomplete-clear: add onClick to clear the input value and close dropdown
661
+ if (dataThqValue === 'thq-autocomplete-clear' && params.autocompleteContext) {
662
+ var _c = params.autocompleteContext, fieldName = _c.fieldName, formStateName = _c.formStateName, isOpenStateName = _c.isOpenStateName, inputHtmlId = _c.inputHtmlId;
663
+ var isOpenSetterName = "set".concat(isOpenStateName.charAt(0).toUpperCase()).concat(isOpenStateName.slice(1));
664
+ var handlerCode = void 0;
665
+ var clearInputLookup = inputHtmlId
666
+ ? "document.getElementById('".concat(inputHtmlId, "')")
667
+ : "e.currentTarget.closest('[data-thq=\"thq-autocomplete\"]').querySelector('[data-thq=\"thq-autocomplete-input\"]')";
668
+ var clearFormStoreUpdate = formStateName
669
+ ? "var setter = ".concat("set".concat(formStateName.charAt(0).toUpperCase()).concat(formStateName.slice(1)), "; setter(function(prev) { return Object.assign({}, prev, { ['").concat(fieldName, "']: '' }); });")
670
+ : '';
671
+ handlerCode = "(e) => { var input = ".concat(clearInputLookup, "; if (input) { input.value = ''; } ").concat(clearFormStoreUpdate, " ").concat(isOpenSetterName, "(false); }");
672
+ var handler = (0, ast_utils_1.parseJSExpressionAsAST)(handlerCode);
673
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('onClick'), types.jsxExpressionContainer(handler)));
674
+ }
675
+ // A markdown-node can carry its rich-text content as a dynamic/expr child
676
+ // (e.g. CMS-bound rich text) rather than as a `raw` attribute. The raw-attribute
677
+ // path is handled in addAttributesToJSXTag; here we handle the children path so
678
+ // the content is injected as HTML (dangerouslySetInnerHTML) instead of being
679
+ // printed as an escaped raw value by the generic expression handler.
680
+ var isMarkdownNode = node.content.semanticType === 'markdown-node' || originalElementName === 'markdown-node';
681
+ var hasRawAttr = attrs
682
+ ? Object.keys(attrs).some(function (attrKey) { var _a; return ((_a = attrs[attrKey]) === null || _a === void 0 ? void 0 : _a.type) === 'raw'; })
683
+ : false;
684
+ var markdownChildrenHandled = false;
685
+ if (isMarkdownNode && !selfClosing && !hasRawAttr && children && children.length > 0) {
686
+ var markdownChild = children.find(function (child) { return child.type === 'expr' || child.type === 'dynamic'; });
687
+ var markdownExpr = void 0;
688
+ if ((markdownChild === null || markdownChild === void 0 ? void 0 : markdownChild.type) === 'expr') {
689
+ markdownExpr = __1.ASTUtils.getExpressionFromUIDLExpressionNode(markdownChild);
690
+ }
691
+ else if ((markdownChild === null || markdownChild === void 0 ? void 0 : markdownChild.type) === 'dynamic') {
692
+ markdownExpr = resolveDynamicReferenceExpression(markdownChild, childParams, options);
693
+ }
694
+ if (markdownExpr) {
695
+ injectMarkdownExpression(elementTag, markdownExpr, '', childParams);
696
+ markdownChildrenHandled = true;
697
+ }
698
+ }
699
+ // A controlled <textarea> — one carrying a `value` (or `defaultValue`) prop —
700
+ // must NOT also render children. React's server renderer throws
701
+ // "If you supply `value` on a <textarea> you must not supply children.", which
702
+ // aborts static export of the whole page. The details-page / entity binder can
703
+ // leave the original text content in place when it adds a `value` binding to a
704
+ // textarea (harmless for <input>, fatal for <textarea>). We still GENERATE the
705
+ // children below so every UIDL node lands in `nodesLookup` (the styled-jsx pass
706
+ // requires it), but we do not attach them to the textarea — the value prop is
707
+ // the single source of truth.
708
+ var isTextArea = originalElementName.toLowerCase() === 'textarea' || node.content.semanticType === 'textarea';
709
+ // The check must run against the JSX opening element (not just UIDL attrs):
710
+ // maybeAddFormStoreFieldBinding injects a `value` attr onto named textareas
711
+ // inside a data-store-values-state form AFTER UIDL attrs are processed, and
712
+ // that injected binding makes the textarea controlled all the same.
713
+ var jsxTagHasControlledValue = elementTag.openingElement.attributes.some(function (attr) {
714
+ return attr.type === 'JSXAttribute' &&
715
+ attr.name.type === 'JSXIdentifier' &&
716
+ (attr.name.name === 'value' || attr.name.name === 'defaultValue');
717
+ });
718
+ var skipAttachingChildren = isTextArea &&
719
+ (jsxTagHasControlledValue ||
720
+ (!!attrs &&
721
+ (Object.prototype.hasOwnProperty.call(attrs, 'value') ||
722
+ Object.prototype.hasOwnProperty.call(attrs, 'defaultValue'))));
723
+ if (!markdownChildrenHandled && !selfClosing && children) {
724
+ // Reorder children to ensure search nodes appear before DataProvider nodes
725
+ var reorderedChildren = reorderChildrenForSearch(children);
726
+ reorderedChildren.forEach(function (child) {
727
+ var childTags = generateNode(child, childParams, options);
728
+ if (skipAttachingChildren) {
729
+ return;
730
+ }
111
731
  childTags.forEach(function (childTag) {
112
732
  if (typeof childTag === 'string') {
113
733
  (0, ast_utils_1.addChildJSXText)(elementTag, childTag);
114
734
  }
115
735
  else if (childTag.type === 'JSXExpressionContainer' || childTag.type === 'JSXElement') {
736
+ // Backstop for an UNCONTROLLED <textarea> whose value binding arrived
737
+ // as a child (we only reach here when skipAttachingChildren is false —
738
+ // the textarea has NO value/defaultValue attr). A <textarea> has no
739
+ // value attribute in HTML, so React stringifies an element/expression
740
+ // CHILD to the literal "[object Object]" inside the field (run 97ac2650
741
+ // Add Note). The primary fix hoists the binding to a value= attribute at
742
+ // import time (ai-state-binding-preprocessor.hoistTextareaChildBindingToValue);
743
+ // this net drops any stray dynamic child so it can never render
744
+ // "[object Object]". Static text children (the typeof-string branch
745
+ // above) are untouched.
746
+ if (isTextArea) {
747
+ return;
748
+ }
116
749
  (0, ast_utils_1.addChildJSXTag)(elementTag, childTag);
117
750
  }
118
751
  else {
@@ -121,41 +754,335 @@ var generateElementNode = function (node, params, jsxOptions) {
121
754
  });
122
755
  });
123
756
  }
757
+ if (dependency && isReactChartjs2Chart(dependency, originalElementName)) {
758
+ var wrapped = wrapReactChartJs2Element(elementTag, node);
759
+ nodesLookup[key] = wrapped;
760
+ return wrapped;
761
+ }
762
+ if (dependency && isCalendarKitScheduler(dependency, originalElementName)) {
763
+ wrapCalendarKitEventsAttr(elementTag);
764
+ }
124
765
  nodesLookup[key] = elementTag;
125
766
  return elementTag;
126
767
  };
127
768
  exports.default = generateElementNode;
769
+ var addAttributesToJSXTag = function (attrs, elementTag, options, params, elementName) {
770
+ Object.keys(attrs !== null && attrs !== void 0 ? attrs : {}).forEach(function (attrKey) {
771
+ var _a;
772
+ var attributeValue = attrs[attrKey];
773
+ if (!attributeValue.type) {
774
+ return;
775
+ }
776
+ // Skip code-gen directives - handled in generateElementNode
777
+ if (attrKey === 'data-store-values-state') {
778
+ return;
779
+ }
780
+ // Plan v15 Layer 4 — codegen safety net.
781
+ //
782
+ // Drop attributes that look like AI fabrication artefacts even when the
783
+ // upstream pipeline missed them. These never produce valid DOM/JSX:
784
+ // 1. attr names that are pure JS literals (`true`, `false`, bare
785
+ // numbers, `null`, `undefined`) — e.g. the `true="true"` that
786
+ // shipped with the broken Navigation in the 2026-05-24 run.
787
+ // 2. static string values that contain entity-escaped binding markers
788
+ // (`&#123;` / `&#125;`) — emitting them produces broken DOM text.
789
+ // 3. static string values that contain an UNBALANCED `{{` (no
790
+ // matching `}}`) — always garbage, never valid.
791
+ if (isJunkAttributeName(attrKey)) {
792
+ // eslint-disable-next-line no-console
793
+ console.warn("[codegen safety net] dropping junk-name attribute \"".concat(attrKey, "\" on <").concat(elementName !== null && elementName !== void 0 ? elementName : 'element', ">"));
794
+ return;
795
+ }
796
+ if (attributeValue.type === 'static') {
797
+ var staticContent = attributeValue.content;
798
+ if (typeof staticContent === 'string' && hasCorruptBindingMarkers(staticContent)) {
799
+ // eslint-disable-next-line no-console
800
+ console.warn("[codegen safety net] dropping attribute \"".concat(attrKey, "\" on <").concat(elementName !== null && elementName !== void 0 ? elementName : 'element', "> \u2014 value has entity-escaped or truncated binding markers (").concat(truncate(staticContent), ")"));
801
+ return;
802
+ }
803
+ }
804
+ // React takes `style` as an object, never as text: a `style="color: red"`
805
+ // attribute (a custom attribute typed in the editor) throws React error #62
806
+ // while the page prerenders and fails the whole build. The text becomes the
807
+ // object it meant; a value that is not plain CSS text is dropped.
808
+ if (attrKey === 'style') {
809
+ var inlineStyle = attributeValue.type === 'static'
810
+ ? parseInlineStyleText(attributeValue.content)
811
+ : undefined;
812
+ if (inlineStyle && Object.keys(inlineStyle).length > 0) {
813
+ (0, ast_utils_1.addAttributeToJSXTag)(elementTag, 'style', inlineStyle);
814
+ }
815
+ else {
816
+ // eslint-disable-next-line no-console
817
+ console.warn("[codegen safety net] dropping \"style\" attribute on <".concat(elementName !== null && elementName !== void 0 ? elementName : 'element', "> \u2014 React takes style as an object, and this value is not CSS text"));
818
+ }
819
+ return;
820
+ }
821
+ switch (attributeValue.type) {
822
+ case 'dynamic':
823
+ var dynamicRef = attributeValue;
824
+ var referenceType = dynamicRef.content.referenceType;
825
+ if (referenceType === 'global') {
826
+ var normRef = normalizeGlobalRef(dynamicRef);
827
+ params.globalReferences.push(normRef.content.id);
828
+ // Use the normalized ref to generate the attribute expression
829
+ var globalExpr = (0, utils_1.createDynamicValueExpression)(normRef, options);
830
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier((0, ast_utils_1.resolveAttributeNameForTag)(elementTag, attrKey)), types.jsxExpressionContainer(globalExpr)));
831
+ break;
832
+ }
833
+ if (referenceType === 'globalState') {
834
+ var gsName = (0, utils_1.resolveGlobalStateName)(dynamicRef.content.id, params.globalStateDefinitions);
835
+ params.globalStateReferences.push({ id: dynamicRef.content.id, name: gsName });
836
+ var expr = (0, utils_1.createGlobalStateExpression)(dynamicRef, params.globalStateDefinitions);
837
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier((0, ast_utils_1.resolveAttributeNameForTag)(elementTag, attrKey)), types.jsxExpressionContainer(expr)));
838
+ break;
839
+ }
840
+ // A translated attribute (`placeholder`, `alt`, `title`, `aria-label`, …).
841
+ // It cannot be emitted the way a translated CHILD is — that path produces a
842
+ // `<span>` the framework plugin fills through `dangerouslySetInnerHTML`, and
843
+ // an attribute needs a plain string. So the attribute is written with the
844
+ // main-language text (carried on the reference's `fallback`) and recorded on
845
+ // `params.localeAttributeReferences`; the target framework's i18n plugin
846
+ // rewrites the recorded attributes into its own translation lookup — see
847
+ // `createNextInternationalizationPlugin`. A framework without such a plugin
848
+ // keeps the main-language string, which is valid, readable markup.
849
+ if (referenceType === 'locale') {
850
+ var translationKey = dynamicRef.content.id;
851
+ if (!translationKey) {
852
+ break;
853
+ }
854
+ // `fallback` only exists on the plain reference member of the union, and
855
+ // narrowing happened on the destructured `referenceType`, not on the ref.
856
+ var fallback = dynamicRef.content.fallback;
857
+ var attribute = types.jsxAttribute(types.jsxIdentifier((0, ast_utils_1.resolveAttributeNameForTag)(elementTag, attrKey)), types.stringLiteral(teleport_shared_1.StringUtils.encode(fallback === undefined ? '' : String(fallback))));
858
+ elementTag.openingElement.attributes.push(attribute);
859
+ params.localeAttributeReferences.push({ attribute: attribute, key: translationKey });
860
+ break;
861
+ }
862
+ // A value read through a mapper (`aria-pressed` from a filter's state, a
863
+ // formatted date) renders through it, as a text binding does. Emitted as
864
+ // the bare reference, the attribute carried the raw value.
865
+ if ((_a = dynamicRef.content.valueMapper) === null || _a === void 0 ? void 0 : _a.trim()) {
866
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier((0, ast_utils_1.resolveAttributeNameForTag)(elementTag, attrKey)), types.jsxExpressionContainer((0, utils_1.createDynamicValueExpression)(dynamicRef, options))));
867
+ break;
868
+ }
869
+ switch (referenceType) {
870
+ default:
871
+ var prefix = options.dynamicReferencePrefixMap[referenceType] || '';
872
+ var idWithRefPath = teleport_shared_1.UIDLUtils.generateIdWithRefPath(dynamicRef.content.id, dynamicRef.content.refPath);
873
+ (0, ast_utils_1.addDynamicAttributeToJSXTag)(elementTag, attrKey, idWithRefPath, prefix);
874
+ break;
875
+ }
876
+ break;
877
+ case 'import':
878
+ (0, ast_utils_1.addDynamicAttributeToJSXTag)(elementTag, attrKey, attributeValue.content.id);
879
+ break;
880
+ case 'raw': {
881
+ var rawValue = attributeValue;
882
+ if (elementName === 'markdown-node') {
883
+ if (rawValue.dynamic) {
884
+ applyDynamicMarkdownInjection(elementTag, rawValue, params, options);
885
+ }
886
+ else {
887
+ applyStaticMarkdownInjection(elementTag, rawValue, params);
888
+ }
889
+ break;
890
+ }
891
+ if (elementName === 'rich-text-editor-node') {
892
+ applyRichTextEditorRawAttribute(elementTag, attrKey, rawValue, params, options);
893
+ break;
894
+ }
895
+ if (rawValue.dynamic) {
896
+ applyDynamicHtmlInjection(elementTag, rawValue, params, options);
897
+ break;
898
+ }
899
+ (0, ast_utils_1.addRawAttributeToJSXTag)(elementTag, attrKey, attributeValue);
900
+ break;
901
+ }
902
+ case 'comp-style':
903
+ (0, ast_utils_1.addAttributeToJSXTag)(elementTag, attrKey, attributeValue.content);
904
+ break;
905
+ case 'static':
906
+ if (typeof attributeValue.content === 'object' &&
907
+ attributeValue.content !== null &&
908
+ !Array.isArray(attributeValue.content)) {
909
+ var constName = "__staticProp".concat(params.hoistedConstants.length);
910
+ var expression = (0, ast_utils_1.objectToObjectExpression)(attributeValue.content);
911
+ params.hoistedConstants.push({ name: constName, expression: expression });
912
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier((0, ast_utils_1.resolveAttributeNameForTag)(elementTag, attrKey)), types.jsxExpressionContainer(types.identifier(constName))));
913
+ }
914
+ else {
915
+ (0, ast_utils_1.addAttributeToJSXTag)(elementTag, attrKey, attributeValue.content);
916
+ }
917
+ break;
918
+ case 'expr':
919
+ (0, ast_utils_1.addDynamicExpressionAttributeToJSXTag)(elementTag, attributeValue, attrKey);
920
+ // Scan the *sanitized* content so any globals introduced by the
921
+ // repair (e.g. `/profile/${}` → `/profile/${currentUser?.id}`) still
922
+ // trigger the downstream useGlobalContext() wiring.
923
+ trackGlobalRefsInExpression((0, ast_utils_1.sanitizeExprContent)(String(attributeValue.content), attrKey), params);
924
+ break;
925
+ case 'element':
926
+ (0, ast_utils_1.addAttributeToJSXTag)(elementTag, attrKey, generateElementNode(attributeValue, params, options));
927
+ break;
928
+ case 'object': {
929
+ var content = attributeValue.content;
930
+ if (typeof content !== 'object') {
931
+ return;
932
+ }
933
+ var expression = (0, ast_utils_1.objectToObjectExpression)(content);
934
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier(attrKey), types.jsxExpressionContainer(expression)));
935
+ break;
936
+ }
937
+ default:
938
+ throw new Error("generateElementNode could not generate code for attribute of type ".concat(JSON.stringify(attributeValue)));
939
+ }
940
+ });
941
+ };
942
+ /**
943
+ * Converts text containing {{ expr }} templates into a mix of JSX text and expression containers.
944
+ * e.g. "x{{ (state.score / 10) || '0' }}" → ["x", JSXExpressionContainer((score / 10) || '0')]
945
+ *
946
+ * Uses parseStringWithTemplateExpressions to parse the template into a TemplateLiteral AST,
947
+ * then converts its quasis (text parts) and expressions into JSX children.
948
+ */
949
+ var convertTextTemplateToJSX = function (text) {
950
+ try {
951
+ var templateLiteral = (0, ast_utils_1.parseStringWithTemplateExpressions)(text);
952
+ var result = [];
953
+ for (var i = 0; i < templateLiteral.quasis.length; i++) {
954
+ var quasi = templateLiteral.quasis[i];
955
+ var textPart = quasi.value.cooked || quasi.value.raw;
956
+ if (textPart) {
957
+ result.push(teleport_shared_1.StringUtils.encode(textPart));
958
+ }
959
+ if (i < templateLiteral.expressions.length) {
960
+ result.push(types.jsxExpressionContainer(templateLiteral.expressions[i]));
961
+ }
962
+ }
963
+ return result.length > 0 ? result : [teleport_shared_1.StringUtils.encode(text)];
964
+ }
965
+ catch (_a) {
966
+ // If parsing fails, fall back to encoded text
967
+ return [teleport_shared_1.StringUtils.encode(text)];
968
+ }
969
+ };
128
970
  var generateNode = function (node, params, options) {
971
+ var _a;
129
972
  switch (node.type) {
130
973
  case 'expr':
131
974
  return [generateExpressionNode(node, params, options)];
132
- case 'raw':
975
+ case 'raw': {
976
+ var rawNode = node;
977
+ if (rawNode.dynamic) {
978
+ var dynamicExpr = resolveDynamicReferenceExpression(rawNode.dynamic, params, options);
979
+ var fallback = rawNode.fallback || rawNode.content;
980
+ return [__1.ASTBuilders.createDynamicDOMInjectionNode(dynamicExpr, fallback)];
981
+ }
133
982
  return [
134
983
  options.domHTMLInjection
135
984
  ? options.domHTMLInjection(node.content.toString())
136
985
  : node.content.toString(),
137
986
  ];
987
+ }
138
988
  case 'inject':
139
989
  if (node === null || node === void 0 ? void 0 : node.dependency) {
140
- /* tslint:disable:no-string-literal */
141
- params.dependencies['Script'] = node.dependency;
990
+ params.dependencies.Script = node.dependency;
142
991
  }
143
992
  return [node.content.toString()];
144
- case 'static':
145
- return [teleport_shared_1.StringUtils.encode(node.content.toString())];
993
+ case 'static': {
994
+ var textContent = node.content.toString();
995
+ // Check if the text contains {{ }} template expressions
996
+ if (/\{\{/.test(textContent)) {
997
+ return convertTextTemplateToJSX(textContent);
998
+ }
999
+ return [teleport_shared_1.StringUtils.encode(textContent)];
1000
+ }
146
1001
  case 'dynamic':
147
- return [(0, utils_1.createDynamicValueExpression)(node, options, undefined)];
1002
+ switch (node.content.referenceType) {
1003
+ case 'prop': {
1004
+ // If the dynamic node is a prop and has a default value of type UIDLElementNode,
1005
+ // we should use it with a logical expression.
1006
+ var prop = params.propDefinitions[node.content.id];
1007
+ if ((prop === null || prop === void 0 ? void 0 : prop.type) === 'element' && prop.defaultValue) {
1008
+ var prefix = options.dynamicReferencePrefixMap[node.content.referenceType] || '';
1009
+ var propDefault = prop.defaultValue;
1010
+ var jsxNode = params.nodesLookup[propDefault.content.key];
1011
+ if (jsxNode === undefined) {
1012
+ throw Error("Prop ".concat(node.content.id, " is of type element \n\n The JSXNode of the prop-").concat(node.content.id, " is missing from the nodesLookup"));
1013
+ }
1014
+ return [
1015
+ types.logicalExpression('??', prefix === ''
1016
+ ? types.identifier(node.content.id)
1017
+ : types.memberExpression(types.identifier(prefix), types.identifier(node.content.id)), jsxNode),
1018
+ ];
1019
+ }
1020
+ return [(0, utils_1.createDynamicValueExpression)(node, options)];
1021
+ }
1022
+ case 'locale': {
1023
+ // Locale is not handled the same in all frameworks.
1024
+ // So, we need to handle it differently using individual plugins for each framework.
1025
+ var emptyExpression = types.jsxEmptyExpression();
1026
+ emptyExpression.innerComments = [
1027
+ {
1028
+ type: 'CommentBlock',
1029
+ value: "locale-".concat(node.content.id),
1030
+ },
1031
+ ];
1032
+ var expression = types.jsxExpressionContainer(emptyExpression);
1033
+ var jsxTag = (0, ast_builders_1.createJSXTag)('span');
1034
+ (0, ast_utils_1.addChildJSXTag)(jsxTag, expression);
1035
+ params.localeReferences.push(jsxTag);
1036
+ return [jsxTag];
1037
+ }
1038
+ case 'global': {
1039
+ var globalNode = normalizeGlobalRef(node);
1040
+ params.globalReferences.push(globalNode.content.id);
1041
+ return [(0, utils_1.createDynamicValueExpression)(globalNode, options)];
1042
+ }
1043
+ default:
1044
+ if (node.content.referenceType === 'globalState') {
1045
+ var gsName = (0, utils_1.resolveGlobalStateName)(node.content.id, params.globalStateDefinitions);
1046
+ params.globalStateReferences.push({ id: node.content.id, name: gsName });
1047
+ return [
1048
+ (0, utils_1.createGlobalStateExpression)(node, params.globalStateDefinitions),
1049
+ ];
1050
+ }
1051
+ return [(0, utils_1.createDynamicValueExpression)(node, options)];
1052
+ }
148
1053
  case 'cms-item':
149
1054
  case 'cms-list':
150
1055
  return generateCMSNode(node, params, options);
151
- case 'element':
152
- return [generateElementNode(node, params, options)];
1056
+ case 'cms-list-repeater':
1057
+ return generateCMSListRepeaterNode(node, params, options);
1058
+ case 'cms-mixed-type':
1059
+ return generateCMSMixedTypeNode(node, params, options);
1060
+ case 'data-source-item':
1061
+ case 'data-source-list':
1062
+ return generateDataSourceNode(node, params, options);
1063
+ case 'element': {
1064
+ // Check if this element node is wrapping a data-source node
1065
+ if (node.content &&
1066
+ typeof node.content === 'object' &&
1067
+ 'type' in node.content &&
1068
+ (node.content.type === 'data-source-item' || node.content.type === 'data-source-list')) {
1069
+ // Treat it as a data-source node
1070
+ // tslint:disable-next-line:no-any
1071
+ return generateDataSourceNode(node.content, params, options);
1072
+ }
1073
+ var elementTag = generateElementNode(node, params, options);
1074
+ var renderingConditions = (_a = node.content) === null || _a === void 0 ? void 0 : _a.renderingConditions;
1075
+ if (renderingConditions) {
1076
+ return [
1077
+ wrapWithConditional(elementTag, renderingConditions.reference, renderingConditions.condition, params, options),
1078
+ ];
1079
+ }
1080
+ return [elementTag];
1081
+ }
153
1082
  case 'repeat':
154
1083
  return generateRepeatNode(node, params, options);
155
1084
  case 'conditional':
156
1085
  return generateConditionalNode(node, params, options);
157
- case 'cms-list-repeater':
158
- return generateCMSListRepeaterNode(node, params, options);
159
1086
  case 'slot':
160
1087
  if (options.slotHandling === 'native') {
161
1088
  return [generateNativeSlotNode(node, params, options)];
@@ -169,11 +1096,38 @@ var generateNode = function (node, params, options) {
169
1096
  };
170
1097
  var generateExpressionNode = function (node) {
171
1098
  var expression = __1.ASTUtils.getExpressionFromUIDLExpressionNode(node);
172
- return types.jsxExpressionContainer(expression);
1099
+ // Wrap expression to safely handle objects/arrays: (typeof val === 'object' && val !== null) ? JSON.stringify(val) : val
1100
+ var safeExpression = types.conditionalExpression(types.logicalExpression('&&', types.binaryExpression('===', types.unaryExpression('typeof', expression, true), types.stringLiteral('object')), types.binaryExpression('!==', expression, types.nullLiteral())), types.callExpression(types.memberExpression(types.identifier('JSON'), types.identifier('stringify')), [expression]), expression);
1101
+ return types.jsxExpressionContainer(safeExpression);
1102
+ };
1103
+ var generateCMSMixedTypeNode = function (node, params, options) {
1104
+ var _a = node.content, _b = _a.nodes, error = _b.error, fallback = _b.fallback, elementType = _a.elementType, renderPropIdentifier = _a.renderPropIdentifier, _c = _a.mappings, mappings = _c === void 0 ? {} : _c, attrs = _a.attrs, dependency = _a.dependency;
1105
+ var jsxTag = teleport_shared_1.StringUtils.dashCaseToUpperCamelCase(elementType);
1106
+ var cmsMixedNode = __1.ASTBuilders.createJSXTag(jsxTag, [], true);
1107
+ var mappingsObject = [];
1108
+ if (attrs) {
1109
+ addAttributesToJSXTag(attrs, cmsMixedNode, options, params);
1110
+ }
1111
+ if (dependency) {
1112
+ params.dependencies[elementType] = dependency;
1113
+ }
1114
+ Object.keys(mappings).forEach(function (key) {
1115
+ var element = generateElementNode(mappings[key], params, options);
1116
+ mappingsObject.push(types.objectProperty(types.identifier("\"".concat(key, "\"")), types.arrowFunctionExpression([types.identifier(renderPropIdentifier)], element)));
1117
+ });
1118
+ cmsMixedNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('mappingConfiguration'), types.jsxExpressionContainer(types.objectExpression(mappingsObject))));
1119
+ if (fallback) {
1120
+ cmsMixedNode.openingElement.attributes.push(types.jSXAttribute(types.jsxIdentifier('renderDefault'), types.jsxExpressionContainer(types.arrowFunctionExpression([types.identifier(renderPropIdentifier)], generateElementNode(fallback, params, options)))));
1121
+ }
1122
+ if (error) {
1123
+ cmsMixedNode.openingElement.attributes.push(types.jSXAttribute(types.jsxIdentifier('renderError'), types.jsxExpressionContainer(types.arrowFunctionExpression([types.identifier(renderPropIdentifier)], generateElementNode(error, params, options)))));
1124
+ }
1125
+ return [cmsMixedNode];
173
1126
  };
174
1127
  var generateCMSNode = function (node, params, options) {
175
- var _a = node.content, initialData = _a.initialData, key = _a.key, renderPropIdentifier = _a.renderPropIdentifier, _b = _a.resource, _c = _b === void 0 ? {} : _b, resourceParams = _c.params, router = _a.router, elementType = _a.elementType, dependency = _a.dependency;
176
- var _d = node.content.nodes, loading = _d.loading, error = _d.error, success = _d.success;
1128
+ var _a;
1129
+ var _b = node.content, initialData = _b.initialData, key = _b.key, renderPropIdentifier = _b.renderPropIdentifier, _c = _b.resource, _d = _c === void 0 ? {} : _c, resourceParams = _d.params, router = _b.router, elementType = _b.elementType, dependency = _b.dependency;
1130
+ var _e = node.content.nodes, loading = _e.loading, error = _e.error, success = _e.success;
177
1131
  var jsxTag = teleport_shared_1.StringUtils.dashCaseToUpperCamelCase(elementType);
178
1132
  if (router && (options === null || options === void 0 ? void 0 : options.dependencyHandling) === 'import') {
179
1133
  params.dependencies.useRouter = router;
@@ -185,8 +1139,13 @@ var generateCMSNode = function (node, params, options) {
185
1139
  params.dependencies[elementType] = dependency;
186
1140
  }
187
1141
  var cmsNode = __1.ASTBuilders.createJSXTag(jsxTag, [], true);
1142
+ var cmsDataNodeIdAttr = (_a = node.content
1143
+ .attrs) === null || _a === void 0 ? void 0 : _a.dataNodeId;
1144
+ if (cmsDataNodeIdAttr === null || cmsDataNodeIdAttr === void 0 ? void 0 : cmsDataNodeIdAttr.content) {
1145
+ (0, ast_utils_1.addAttributeToJSXTag)(cmsNode, 'dataNodeId', cmsDataNodeIdAttr.content);
1146
+ }
188
1147
  if (node.type === 'cms-item') {
189
- cmsNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('renderSuccess'), types.jsxExpressionContainer(types.arrowFunctionExpression([types.identifier(renderPropIdentifier)], generateNode(success, params, options)[0]))));
1148
+ cmsNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('renderSuccess'), types.jsxExpressionContainer(types.arrowFunctionExpression([types.identifier(renderPropIdentifier)], generateNode(success, params, __assign(__assign({}, options), { localIdentifier: renderPropIdentifier }))[0]))));
190
1149
  }
191
1150
  if (node.type === 'cms-list') {
192
1151
  cmsNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('renderSuccess'), types.jsxExpressionContainer(types.arrowFunctionExpression([types.identifier('params')], generateNode(success, params, options)[0]))));
@@ -200,18 +1159,24 @@ var generateCMSNode = function (node, params, options) {
200
1159
  if (error) {
201
1160
  cmsNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('renderError'), types.jsxExpressionContainer(types.arrowFunctionExpression([], generateNode(error, params, options)[0]))));
202
1161
  }
203
- if (initialData && initialData.content.referenceType === 'prop') {
204
- cmsNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('initialData'), types.jsxExpressionContainer(types.memberExpression(types.identifier(options.dynamicReferencePrefixMap[initialData.content.referenceType]), types.identifier(initialData.content.id)))));
1162
+ if (initialData && initialData.content.referenceType) {
1163
+ var refType = initialData.content.referenceType;
1164
+ var initialDataExpr = refType === 'prop'
1165
+ ? types.memberExpression(types.identifier(options.dynamicReferencePrefixMap[refType]), types.identifier(initialData.content.id))
1166
+ : types.identifier(initialData.content.id);
1167
+ cmsNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('initialData'), types.jsxExpressionContainer(initialDataExpr)));
205
1168
  cmsNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('persistDataDuringLoading'), types.jsxExpressionContainer(types.booleanLiteral(true))));
206
- var keyValue = 'props?.pagination?.page';
207
- if (node.type === 'cms-item') {
208
- var entityKeyProperty = node.content.entityKeyProperty;
209
- var entityName = initialData.content.id;
210
- keyValue = entityKeyProperty
211
- ? "props?.".concat(entityName, "?.").concat(entityKeyProperty)
212
- : "props?.".concat(entityName, "?.id");
1169
+ if (refType === 'prop') {
1170
+ var keyValue = 'props?.pagination?.page';
1171
+ if (node.type === 'cms-item') {
1172
+ var entityKeyProperty = node.content.entityKeyProperty;
1173
+ var entityName = initialData.content.id;
1174
+ keyValue = entityKeyProperty
1175
+ ? "props?.".concat(entityName, "?.").concat(entityKeyProperty)
1176
+ : "props?.".concat(entityName, "?.id");
1177
+ }
1178
+ cmsNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('key'), types.jsxExpressionContainer(types.identifier(keyValue))));
213
1179
  }
214
- cmsNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('key'), types.jsxExpressionContainer(types.identifier(keyValue))));
215
1180
  }
216
1181
  if (Object.keys(resourceParams || {}).length > 0) {
217
1182
  var nodeParams = Object.keys(resourceParams).reduce(function (acc, attrKey) {
@@ -235,10 +1200,115 @@ var generateCMSNode = function (node, params, options) {
235
1200
  params.nodesLookup[key] = cmsNode;
236
1201
  return [cmsNode];
237
1202
  };
1203
+ var generateDataSourceNode = function (node, params, options) {
1204
+ var _a, _b, _c, _d, _e, _f;
1205
+ var _g = node.content, renderPropIdentifier = _g.renderPropIdentifier, elementType = _g.elementType, dependency = _g.dependency, resourceDefinition = _g.resourceDefinition;
1206
+ var key = node.content.key || "ds-".concat(resourceDefinition.dataSourceId, "-").concat(Date.now());
1207
+ var name = node.content.name || renderPropIdentifier;
1208
+ // tslint:disable-next-line:no-any
1209
+ var children = node.content.children && node.content.children.length > 0
1210
+ ? node.content.children
1211
+ : ((_a = node.content.nodes) === null || _a === void 0 ? void 0 : _a.success)
1212
+ ? [node.content.nodes.success]
1213
+ : [];
1214
+ var jsxTag = teleport_shared_1.StringUtils.dashCaseToUpperCamelCase(elementType);
1215
+ if (dependency && options.dependencyHandling === 'import') {
1216
+ params.dependencies[elementType] = dependency;
1217
+ }
1218
+ var dataSourceNode = __1.ASTBuilders.createJSXTag(jsxTag, [], true);
1219
+ var dataSourceDataNodeIdAttr = (_b = node.content.attrs) === null || _b === void 0 ? void 0 : _b.dataNodeId;
1220
+ if (dataSourceDataNodeIdAttr === null || dataSourceDataNodeIdAttr === void 0 ? void 0 : dataSourceDataNodeIdAttr.content) {
1221
+ (0, ast_utils_1.addAttributeToJSXTag)(dataSourceNode, 'dataNodeId', dataSourceDataNodeIdAttr.content);
1222
+ }
1223
+ dataSourceNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('resourceDefinition'), types.jsxExpressionContainer(types.objectExpression([
1224
+ types.objectProperty(types.stringLiteral('type'), types.stringLiteral('external-data-source')),
1225
+ types.objectProperty(types.stringLiteral('dataSourceId'), types.stringLiteral(resourceDefinition.dataSourceId)),
1226
+ types.objectProperty(types.stringLiteral('tableName'), types.stringLiteral(resourceDefinition.tableName)),
1227
+ types.objectProperty(types.stringLiteral('dataSourceType'), types.stringLiteral(resourceDefinition.dataSourceType)),
1228
+ ]))));
1229
+ dataSourceNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('name'), types.jsxExpressionContainer(types.stringLiteral(name))));
1230
+ if (children && children.length > 0) {
1231
+ // Pass the render prop identifier as the 'ctx' prefix for data source context references
1232
+ // and as the localIdentifier so conditional nodes resolve local refs correctly
1233
+ var childOptions_1 = __assign(__assign({}, options), { localIdentifier: renderPropIdentifier, dynamicReferencePrefixMap: __assign(__assign({}, options.dynamicReferencePrefixMap), { ctx: renderPropIdentifier }) });
1234
+ var childrenNodes = children.flatMap(function (child) { return generateNode(child, params, childOptions_1); });
1235
+ var renderFunction = types.arrowFunctionExpression([types.identifier(renderPropIdentifier)], types.jsxFragment(types.jsxOpeningFragment(), types.jsxClosingFragment(), childrenNodes));
1236
+ dataSourceNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('renderSuccess'), types.jsxExpressionContainer(renderFunction)));
1237
+ }
1238
+ // tslint:disable-next-line:no-any
1239
+ if ((_c = node.content.nodes) === null || _c === void 0 ? void 0 : _c.loading) {
1240
+ // tslint:disable-next-line:no-any
1241
+ var loadingNode = generateNode(node.content.nodes.loading, params, options)[0];
1242
+ dataSourceNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('renderLoading'), types.jsxExpressionContainer(types.arrowFunctionExpression([], loadingNode))));
1243
+ }
1244
+ // tslint:disable-next-line:no-any
1245
+ if ((_d = node.content.nodes) === null || _d === void 0 ? void 0 : _d.error) {
1246
+ // tslint:disable-next-line:no-any
1247
+ var errorNode = generateNode(node.content.nodes.error, params, options)[0];
1248
+ dataSourceNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('renderError'), types.jsxExpressionContainer(types.arrowFunctionExpression([], errorNode))));
1249
+ }
1250
+ // Add resource params if they exist
1251
+ // tslint:disable-next-line:no-any
1252
+ var resourceParams = (_e = node.content.resource) === null || _e === void 0 ? void 0 : _e.params;
1253
+ if (resourceParams && Object.keys(resourceParams).length > 0) {
1254
+ var nodeParams = Object.keys(resourceParams).reduce(function (acc, attrKey) {
1255
+ var property = resourceParams[attrKey];
1256
+ if (property.type === 'static') {
1257
+ // Special handling for filters array - convert dynamic destinations
1258
+ if (attrKey === 'filters' && Array.isArray(property.content)) {
1259
+ var filterEntries = property.content.map(function (filter) {
1260
+ return buildFilterNodeExpression(filter, options.dynamicReferencePrefixMap);
1261
+ });
1262
+ // Drop conditions whose destination resolves to an empty value at
1263
+ // runtime (empty string / null / undefined, or an empty
1264
+ // array-overlap set) so a "show all" reset means no filter rather
1265
+ // than a query that matches zero rows. Mirrors the Next.js pages
1266
+ // path's `buildNonEmptyDestinationPredicate` (kept inline here
1267
+ // because teleport-plugin-common must not depend on the
1268
+ // next-data-source plugin).
1269
+ // JSON.stringify because these params are handed to
1270
+ // `new URLSearchParams(params)`, which would otherwise stringify the
1271
+ // array to '[object Object]' and lose every filter in transit.
1272
+ acc.push(types.objectProperty(types.stringLiteral(attrKey), types.callExpression(types.memberExpression(types.identifier('JSON'), types.identifier('stringify')), [
1273
+ types.callExpression(types.memberExpression(types.arrayExpression(filterEntries), types.identifier('filter')), [buildSurvivingFilterNodePredicate()]),
1274
+ ])));
1275
+ }
1276
+ else {
1277
+ acc.push(types.objectProperty(types.stringLiteral(attrKey), (0, ast_utils_1.resolveObjectValue)(property)));
1278
+ }
1279
+ }
1280
+ if (property.type === 'expr') {
1281
+ var expression = __1.ASTUtils.getExpressionFromUIDLExpressionNode(property);
1282
+ acc.push(types.objectProperty(types.stringLiteral(attrKey), expression));
1283
+ }
1284
+ if (property.type === 'dynamic') {
1285
+ var refType = property.content.referenceType;
1286
+ acc.push(types.objectProperty(types.stringLiteral(attrKey), property.content.referenceType === 'prop'
1287
+ ? types.memberExpression(types.identifier(options.dynamicReferencePrefixMap[refType]), types.identifier(property.content.id))
1288
+ : types.identifier(property.content.id)));
1289
+ }
1290
+ return acc;
1291
+ }, []);
1292
+ dataSourceNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('params'), types.jsxExpressionContainer(types.objectExpression(nodeParams))));
1293
+ }
1294
+ // Add initialData if the UIDL node has it (similar to CMS nodes)
1295
+ // tslint:disable-next-line:no-any
1296
+ var nodeInitialData = node.content.initialData;
1297
+ if (nodeInitialData && ((_f = nodeInitialData.content) === null || _f === void 0 ? void 0 : _f.referenceType)) {
1298
+ var refType = nodeInitialData.content.referenceType;
1299
+ var initialDataExpr = refType === 'prop'
1300
+ ? types.memberExpression(types.identifier(options.dynamicReferencePrefixMap[refType]), types.identifier(nodeInitialData.content.id))
1301
+ : types.identifier(nodeInitialData.content.id);
1302
+ dataSourceNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('initialData'), types.jsxExpressionContainer(initialDataExpr)));
1303
+ dataSourceNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('persistDataDuringLoading'), types.jsxExpressionContainer(types.booleanLiteral(true))));
1304
+ }
1305
+ params.nodesLookup[key] = dataSourceNode;
1306
+ return [dataSourceNode];
1307
+ };
238
1308
  var generateRepeatNode = function (node, params, options) {
239
1309
  var _a = node.content, repeatContent = _a.node, dataSource = _a.dataSource, meta = _a.meta;
240
- var contentASTs = generateNode(repeatContent, params, options);
241
1310
  var _b = teleport_shared_1.UIDLUtils.getRepeatIteratorNameAndKey(meta), iteratorName = _b.iteratorName, iteratorKey = _b.iteratorKey;
1311
+ var contentASTs = generateNode(repeatContent, params, __assign(__assign({}, options), { localIdentifier: iteratorName }));
242
1312
  var localIteratorPrefix = options.dynamicReferencePrefixMap.local;
243
1313
  contentASTs.forEach(function (contentAST) {
244
1314
  (0, ast_utils_1.addDynamicAttributeToJSXTag)(contentAST, 'key', iteratorKey, localIteratorPrefix);
@@ -254,25 +1324,198 @@ var generateRepeatNode = function (node, params, options) {
254
1324
  ]));
255
1325
  });
256
1326
  };
1327
+ // Tracks a condition reference's global / globalState usage on params and
1328
+ // resolves it to a ConditionalIdentifier. Shared by the top-level reference
1329
+ // and the optional per-entry references of a conditional expression.
1330
+ var trackAndResolveConditionIdentifier = function (reference, params, options) {
1331
+ if (reference.type === 'dynamic' &&
1332
+ 'referenceType' in reference.content &&
1333
+ reference.content.referenceType === 'global') {
1334
+ var normCondRef = normalizeGlobalRef(reference);
1335
+ params.globalReferences.push(normCondRef.content.id);
1336
+ }
1337
+ if (reference.type === 'dynamic' &&
1338
+ 'referenceType' in reference.content &&
1339
+ reference.content.referenceType === 'globalState') {
1340
+ var gsName = (0, utils_1.resolveGlobalStateName)(reference.content.id, params.globalStateDefinitions);
1341
+ params.globalStateReferences.push({ id: reference.content.id, name: gsName });
1342
+ }
1343
+ var effectiveRef = reference.type === 'dynamic' &&
1344
+ 'referenceType' in reference.content &&
1345
+ reference.content.referenceType === 'global'
1346
+ ? normalizeGlobalRef(reference)
1347
+ : reference;
1348
+ return (0, utils_1.createConditionIdentifier)(effectiveRef, params, options);
1349
+ };
1350
+ // Shared between UIDLConditionalNode (wraps a child subtree) and the inline
1351
+ // `renderingConditions` property on UIDLElement content. Tracks global and
1352
+ // globalState references on params, resolves the condition identifier — plus
1353
+ // one identifier per entry that carries its own `reference` — and builds the
1354
+ // `condition && <content/>` logical expression.
1355
+ var wrapWithConditional = function (subTree, reference, condition, params, options) {
1356
+ var conditionIdentifier = trackAndResolveConditionIdentifier(reference, params, options);
1357
+ return (0, utils_1.createConditionalJSXExpression)(subTree, condition, conditionIdentifier, {
1358
+ localIdentifier: options.localIdentifier,
1359
+ detailsPageExposeAsName: options.detailsPageExposeAsName || params.detailsPageExposeAsName,
1360
+ // Leaf entries (any nesting depth) with their own left side resolve —
1361
+ // and globals-track — through the same path as the top-level reference.
1362
+ resolveEntryIdentifier: function (conditionEntry) {
1363
+ return conditionEntry.reference
1364
+ ? trackAndResolveConditionIdentifier(conditionEntry.reference, params, options)
1365
+ : undefined;
1366
+ },
1367
+ });
1368
+ };
257
1369
  var generateConditionalNode = function (node, params, options) {
258
1370
  var _a = node.content, reference = _a.reference, value = _a.value;
259
- var conditionIdentifier = (0, utils_1.createConditionIdentifier)(reference, params, options);
260
1371
  var subTrees = generateNode(node.content.node, params, options);
261
1372
  var condition = value !== undefined && value !== null
262
1373
  ? { conditions: [{ operand: value, operation: '===' }] }
263
1374
  : node.content.condition;
264
1375
  return subTrees.map(function (subTree) {
265
- return (0, utils_1.createConditionalJSXExpression)(subTree, condition, conditionIdentifier);
1376
+ return wrapWithConditional(subTree, reference, condition, params, options);
266
1377
  });
267
1378
  };
1379
+ // The repeater renders its `loading` branch INSTEAD of itself when the node
1380
+ // carries an `isLoading` signal. Hence `JSXASTReturnType[]` rather than
1381
+ // `types.JSXElement[]`: that form is a conditional EXPRESSION, which the parent
1382
+ // element loop wraps in a `{ … }` container the same way it already does for a
1383
+ // conditional node's logical expression.
268
1384
  var generateCMSListRepeaterNode = function (node, params, options) {
269
- var _a;
270
- var repeaterNode = __1.ASTBuilders.createJSXTag('Repeater', [], true);
271
- repeaterNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('items'), types.jsxExpressionContainer(types.identifier((_a = node.content.source) !== null && _a !== void 0 ? _a : 'params'))));
272
- repeaterNode.openingElement.attributes.push(types.jsxAttribute(types.jSXIdentifier('renderItem'), types.jsxExpressionContainer(types.arrowFunctionExpression([types.identifier(node.content.renderPropIdentifier)], generateNode(node.content.nodes.list, params, options)[0]))));
1385
+ var _a, _b, _c;
1386
+ var jsxTag = teleport_shared_1.StringUtils.dashCaseToUpperCamelCase(node.content.elementType);
1387
+ var repeaterNode = __1.ASTBuilders.createJSXTag(jsxTag, [], true);
1388
+ var dataNodeIdAttr = (_a = node.content.attrs) === null || _a === void 0 ? void 0 : _a.dataNodeId;
1389
+ if (dataNodeIdAttr === null || dataNodeIdAttr === void 0 ? void 0 : dataNodeIdAttr.content) {
1390
+ (0, ast_utils_1.addAttributeToJSXTag)(repeaterNode, 'dataNodeId', dataNodeIdAttr.content);
1391
+ }
1392
+ // When the repeater source is a global context like "ecommerce", resolve to
1393
+ // the appropriate array from the ecommerce context based on what the repeater
1394
+ // iterates over (determined by renderPropIdentifier). The editor's mapper
1395
+ // keeps only the global's id, not the array's path, so the identifier is the
1396
+ // whole contract: every e-commerce list the editor builds names its context
1397
+ // after one of these keys.
1398
+ var repeaterItemsExpr;
1399
+ var source = (_b = node.content.source) !== null && _b !== void 0 ? _b : 'params';
1400
+ if (source === 'ecommerce') {
1401
+ var rpId = node.content.renderPropIdentifier || '';
1402
+ // Map renderPropIdentifier to the correct ecommerce context path
1403
+ var ecommercePathMap = {
1404
+ paymentProvider: ['paymentProviders'],
1405
+ // The providers a cart holding a subscription is offered — the checkout's
1406
+ // second method list. Same fallthrough hazard as `shippingMethod`.
1407
+ subscriptionPaymentProvider: ['subscriptionPaymentProviders'],
1408
+ storeLocation: ['storeLocations'],
1409
+ // The checkout's shipping-method list (`Cart.shippingOptions`). Without
1410
+ // this entry it fell to the cart items below and offered the buyer their
1411
+ // own products as shipping methods.
1412
+ shippingMethod: ['Cart', 'shippingOptions'],
1413
+ // The checkout's "Choose your discount" list, in each fulfilment shape.
1414
+ discountOption: ['Cart', 'discountOptions'],
1415
+ discountOptionPickup: ['Cart', 'discountOptionsPickup'],
1416
+ };
1417
+ // Default: cart items for orderItem, cartItem, or any unrecognized identifier
1418
+ var path = ecommercePathMap[rpId] || ['Cart', 'items'];
1419
+ var expr = types.identifier('ecommerce');
1420
+ for (var _i = 0, path_1 = path; _i < path_1.length; _i++) {
1421
+ var seg = path_1[_i];
1422
+ expr = types.optionalMemberExpression(expr, types.identifier(seg), false, true);
1423
+ }
1424
+ repeaterItemsExpr = types.logicalExpression('||', expr, types.arrayExpression([]));
1425
+ params.globalReferences.push('ecommerce');
1426
+ }
1427
+ else if (source === 'ecommerceCategories') {
1428
+ // The `E-Commerce Categories` global (the nested category tree) is baked
1429
+ // onto the ecommerce context as `ecommerce.ecommerceCategories`. Fixed
1430
+ // one-segment path (independent of the item name) → `ecommerce?.ecommerceCategories || []`.
1431
+ var expr = types.optionalMemberExpression(types.identifier('ecommerce'), types.identifier('ecommerceCategories'), false, true);
1432
+ repeaterItemsExpr = types.logicalExpression('||', expr, types.arrayExpression([]));
1433
+ params.globalReferences.push('ecommerce');
1434
+ }
1435
+ else if (source === 'blogCategories') {
1436
+ // The `Blog Categories` global. Unlike the store's taxonomy this one is NOT
1437
+ // on a provider context — the generated `@/blog-context` module exposes it
1438
+ // through a memoized `useBlogCategories()` hook, which the component plugin
1439
+ // destructures into a plain `blogCategories` identifier when it sees this
1440
+ // reference. → `blogCategories || []`.
1441
+ repeaterItemsExpr = types.logicalExpression('||', types.identifier('blogCategories'), types.arrayExpression([]));
1442
+ params.globalReferences.push('blogCategories');
1443
+ }
1444
+ else if (source === 'helpCategories') {
1445
+ // The Help Center's taxonomy, exposed by the same module as `useHelpCategories()`.
1446
+ repeaterItemsExpr = types.logicalExpression('||', types.identifier('helpCategories'), types.arrayExpression([]));
1447
+ params.globalReferences.push('helpCategories');
1448
+ }
1449
+ else if (source === 'bookingCategories') {
1450
+ // The `Booking Categories` global, like the blog's: the generated
1451
+ // `@/booking-context` module's `useBookingCategories()` hook, destructured
1452
+ // into a plain `bookingCategories` identifier. → `bookingCategories || []`.
1453
+ repeaterItemsExpr = types.logicalExpression('||', types.identifier('bookingCategories'), types.arrayExpression([]));
1454
+ params.globalReferences.push('bookingCategories');
1455
+ }
1456
+ else {
1457
+ // Resolve any global-state reference encoded in `source` and register it
1458
+ // so the `next-global-state` component plugin destructures the matching
1459
+ // identifier from `useGlobalState()`. Without this, sources emitted as
1460
+ // either `<globalStateName> || []` (modern) or `globalState_<defId>`
1461
+ // (legacy) compile to a `ReferenceError` at render time because the
1462
+ // identifier never enters scope.
1463
+ var resolvedSource = (0, utils_1.resolveAndRegisterGlobalStateSource)(source, params);
1464
+ repeaterItemsExpr = types.identifier(resolvedSource);
1465
+ }
1466
+ repeaterNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('items'), types.jsxExpressionContainer(repeaterItemsExpr)));
1467
+ var listElement = generateNode(node.content.nodes.list, params, __assign(__assign({}, options), { localIdentifier: node.content.renderPropIdentifier, dynamicReferencePrefixMap: __assign(__assign({}, options.dynamicReferencePrefixMap), { ctx: node.content.renderPropIdentifier }) }))[0];
1468
+ // Create key as template literal: `${item?.id}${index}`
1469
+ var keyAttribute = types.jsxAttribute(types.jsxIdentifier('key'), types.jsxExpressionContainer(types.templateLiteral([
1470
+ types.templateElement({ raw: '', cooked: '' }, false),
1471
+ types.templateElement({ raw: '', cooked: '' }, false),
1472
+ types.templateElement({ raw: '', cooked: '' }, true),
1473
+ ], [
1474
+ types.optionalMemberExpression(types.identifier(node.content.renderPropIdentifier), types.identifier('id'), false, true),
1475
+ types.identifier('index'),
1476
+ ])));
1477
+ listElement.openingElement.attributes.push(keyAttribute);
1478
+ repeaterNode.openingElement.attributes.push(types.jsxAttribute(types.jSXIdentifier('renderItem'), types.jsxExpressionContainer(types.arrowFunctionExpression([types.identifier(node.content.renderPropIdentifier), types.identifier('index')], listElement))));
273
1479
  if ('empty' in node.content.nodes) {
274
1480
  repeaterNode.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('renderEmpty'), types.jsxExpressionContainer(types.arrowFunctionExpression([], generateNode(node.content.nodes.empty, params, options)[0]))));
275
1481
  }
1482
+ // Generated on EVERY repeater for its side effects — `nodesLookup` registration,
1483
+ // style classes, and the head snippets a loading template rides out on (a
1484
+ // skeleton card's `@keyframes`). Whether the result is also RENDERED depends on
1485
+ // `isLoading` below.
1486
+ var loadingElement;
1487
+ if ('loading' in node.content.nodes) {
1488
+ loadingElement = generateNode(node.content.nodes.loading, params, options)[0];
1489
+ }
1490
+ if (((_c = node.content) === null || _c === void 0 ? void 0 : _c.dependency) && options.dependencyHandling === 'import') {
1491
+ params.dependencies[jsxTag] = node.content.dependency;
1492
+ }
1493
+ // A repeater fed by a DATA SOURCE never carries `isLoading`: it sits inside a
1494
+ // `DataProvider` that owns the fetch, and its loading branch is hoisted onto
1495
+ // that provider's `renderLoading` (`hoistLoadingFromRepeaterToDataSource`).
1496
+ // Emitting it here as well would draw the same branch twice. A repeater fed by
1497
+ // a plain STATE has no provider, so this is the only thing that can tell it a
1498
+ // fetch is in flight — without it the `loading` branch is generated and then
1499
+ // thrown away, which is why a state-backed list used to show its EMPTY branch
1500
+ // for the whole duration of the fetch.
1501
+ var isLoading = node.content.isLoading;
1502
+ if (isLoading &&
1503
+ loadingElement &&
1504
+ typeof loadingElement !== 'string' &&
1505
+ // A `JSXExpressionContainer` is only legal as a CHILD, never as a ternary
1506
+ // branch. The loading root is a fragment or an element, so this never fires
1507
+ // in practice — it is here so a future node type cannot emit invalid code.
1508
+ loadingElement.type !== 'JSXExpressionContainer') {
1509
+ // `String(x) === 'true'`, never a bare truthiness test. The flag is a page
1510
+ // state, and a generated string state holds the STRING `'false'` when it is
1511
+ // off — which is truthy. `String()` equally accepts a real boolean.
1512
+ var flag = isLoading.type === 'expr'
1513
+ ? __1.ASTUtils.getExpressionFromUIDLExpressionNode(isLoading)
1514
+ : types.stringLiteral(String(isLoading.content));
1515
+ return [
1516
+ types.conditionalExpression(types.binaryExpression('===', types.callExpression(types.identifier('String'), [flag]), types.stringLiteral('true')), loadingElement, repeaterNode),
1517
+ ];
1518
+ }
276
1519
  return [repeaterNode];
277
1520
  };
278
1521
  var generatePropsSlotNode = function (node, params, options) {
@@ -320,4 +1563,156 @@ var generateNativeSlotNode = function (node, params, options) {
320
1563
  }
321
1564
  return slotNode;
322
1565
  };
1566
+ var resolveDynamicReferenceExpression = function (dynamicRef, params, options) {
1567
+ var referenceType = dynamicRef.content.referenceType;
1568
+ if (referenceType === 'global') {
1569
+ var normDynRef = normalizeGlobalRef(dynamicRef);
1570
+ params.globalReferences.push(normDynRef.content.id);
1571
+ return (0, utils_1.createDynamicValueExpression)(normDynRef, options);
1572
+ }
1573
+ if (referenceType === 'globalState') {
1574
+ var gsName = (0, utils_1.resolveGlobalStateName)(dynamicRef.content.id, params.globalStateDefinitions);
1575
+ params.globalStateReferences.push({ id: dynamicRef.content.id, name: gsName });
1576
+ return (0, utils_1.createGlobalStateExpression)(dynamicRef, params.globalStateDefinitions);
1577
+ }
1578
+ return (0, utils_1.createDynamicValueExpression)(dynamicRef, options);
1579
+ };
1580
+ var applyDynamicHtmlInjection = function (elementTag, rawValue, params, options) {
1581
+ var dynamicExpr = resolveDynamicReferenceExpression(rawValue.dynamic, params, options);
1582
+ var fallbackContent = rawValue.fallback || rawValue.content;
1583
+ var fallbackExpr = types.stringLiteral(fallbackContent);
1584
+ var valueExpr = types.logicalExpression('||', dynamicExpr, fallbackExpr);
1585
+ elementTag.openingElement.name.name = 'span';
1586
+ if (elementTag.closingElement) {
1587
+ ;
1588
+ elementTag.closingElement.name.name = 'span';
1589
+ }
1590
+ elementTag.openingElement.selfClosing = true;
1591
+ elementTag.closingElement = null;
1592
+ elementTag.children = [];
1593
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('dangerouslySetInnerHTML'), types.jsxExpressionContainer(types.objectExpression([types.objectProperty(types.identifier('__html'), valueExpr)]))));
1594
+ Object.keys(params.dependencies).forEach(function (key) {
1595
+ var _a, _b;
1596
+ if ((_b = (_a = params.dependencies[key]) === null || _a === void 0 ? void 0 : _a.path) === null || _b === void 0 ? void 0 : _b.includes('dangerous-html')) {
1597
+ delete params.dependencies[key];
1598
+ }
1599
+ });
1600
+ };
1601
+ var applyStaticMarkdownInjection = function (elementTag, rawValue, params) {
1602
+ injectMarkdownExpression(elementTag, types.stringLiteral(rawValue.content || ''), '', params);
1603
+ };
1604
+ var applyDynamicMarkdownInjection = function (elementTag, rawValue, params, options) {
1605
+ var dynamicExpr = resolveDynamicReferenceExpression(rawValue.dynamic, params, options);
1606
+ var fallbackContent = rawValue.fallback || rawValue.content;
1607
+ injectMarkdownExpression(elementTag, dynamicExpr, fallbackContent, params);
1608
+ };
1609
+ /**
1610
+ * Renders a markdown-node's rich-text content through the `markdown-to-jsx` <Markdown>
1611
+ * component (the React generator's mapping for markdown-node).
1612
+ *
1613
+ * markdown-to-jsx parses BOTH markdown syntax AND embedded HTML, so it renders correctly
1614
+ * whether the CMS field returns markdown (`# Heading`) or HTML markup (`<p>…</p>`). A raw
1615
+ * HTML approach (dangerouslySetInnerHTML) would ignore markdown, and a markdown-only
1616
+ * renderer (react-markdown) escapes HTML — markdown-to-jsx covers both at once.
1617
+ *
1618
+ * Shared by every way a markdown-node can carry its content:
1619
+ * - a static `raw` attribute (see applyStaticMarkdownInjection)
1620
+ * - a `raw` attribute holding a dynamic reference (see applyDynamicMarkdownInjection)
1621
+ * - a dynamic/expr child, e.g. CMS-bound rich text (see generateElementNode)
1622
+ *
1623
+ * Produces: <Markdown>{expr || fallback}</Markdown>
1624
+ */
1625
+ var injectMarkdownExpression = function (elementTag, expression, fallbackContent, params) {
1626
+ // markdown-to-jsx requires a string child; guard dynamic expressions with a fallback so
1627
+ // a nullish CMS value renders as empty rather than throwing. Static literals need no guard.
1628
+ var childExpr = types.isStringLiteral(expression)
1629
+ ? expression
1630
+ : types.logicalExpression('||', expression, types.stringLiteral(fallbackContent || ''));
1631
+ elementTag.openingElement.name.name = 'Markdown';
1632
+ elementTag.openingElement.selfClosing = false;
1633
+ if (!elementTag.closingElement) {
1634
+ elementTag.closingElement = types.jsxClosingElement(types.jsxIdentifier('Markdown'));
1635
+ }
1636
+ else {
1637
+ ;
1638
+ elementTag.closingElement.name.name = 'Markdown';
1639
+ }
1640
+ elementTag.children = [types.jsxExpressionContainer(childExpr)];
1641
+ params.dependencies.Markdown = {
1642
+ type: 'package',
1643
+ path: 'markdown-to-jsx',
1644
+ version: '7.7.12',
1645
+ };
1646
+ };
1647
+ /**
1648
+ * Handles raw attributes on a rich-text-editor-node element.
1649
+ *
1650
+ * - `html` attribute → becomes a `value` prop (static string or dynamic expression with fallback)
1651
+ * - `quillFormats` attribute → parsed from JSON string into a JS array expression
1652
+ */
1653
+ var applyRichTextEditorRawAttribute = function (elementTag, attrKey, rawValue, params, options) {
1654
+ if (attrKey === 'html' && params.formStoreStateName) {
1655
+ return;
1656
+ }
1657
+ if (attrKey === 'html') {
1658
+ if (rawValue.dynamic) {
1659
+ var dynamicExpr = resolveDynamicReferenceExpression(rawValue.dynamic, params, options);
1660
+ var fallbackContent = rawValue.fallback || rawValue.content || '';
1661
+ var valueExpr = types.logicalExpression('||', dynamicExpr, types.stringLiteral(fallbackContent));
1662
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('value'), types.jsxExpressionContainer(valueExpr)));
1663
+ }
1664
+ else {
1665
+ var content = rawValue.content || '';
1666
+ (0, ast_utils_1.addAttributeToJSXTag)(elementTag, 'value', content);
1667
+ }
1668
+ return;
1669
+ }
1670
+ if (attrKey === 'quillFormats') {
1671
+ var formats = null;
1672
+ try {
1673
+ var parsed = JSON.parse(rawValue.content);
1674
+ if (Array.isArray(parsed)) {
1675
+ formats = parsed;
1676
+ }
1677
+ }
1678
+ catch (_a) {
1679
+ // Parsing failed → don't add the attribute; component will use all formats
1680
+ }
1681
+ if (formats === null) {
1682
+ // Parse failure or not an array → omit attribute so component uses all formats
1683
+ return;
1684
+ }
1685
+ var arrayExpr = types.arrayExpression(formats.map(function (f) { return types.stringLiteral(f); }));
1686
+ elementTag.openingElement.attributes.push(types.jsxAttribute(types.jsxIdentifier('quillFormats'), types.jsxExpressionContainer(arrayExpr)));
1687
+ return;
1688
+ }
1689
+ // Any other raw attribute on rich-text-editor-node: fall through to default handling
1690
+ (0, ast_utils_1.addRawAttributeToJSXTag)(elementTag, attrKey, rawValue);
1691
+ };
1692
+ /**
1693
+ * `color: red; margin-top: 4px` → `{ color: 'red', marginTop: '4px' }`, the
1694
+ * shape React wants for `style`. Custom properties keep their `--name`.
1695
+ */
1696
+ function parseInlineStyleText(value) {
1697
+ if (typeof value !== 'string') {
1698
+ return undefined;
1699
+ }
1700
+ var inlineStyle = {};
1701
+ value.split(';').forEach(function (declaration) {
1702
+ var separator = declaration.indexOf(':');
1703
+ if (separator < 1) {
1704
+ return;
1705
+ }
1706
+ var property = declaration.slice(0, separator).trim();
1707
+ var propertyValue = declaration.slice(separator + 1).trim();
1708
+ if (!property || !propertyValue) {
1709
+ return;
1710
+ }
1711
+ var key = property.startsWith('--')
1712
+ ? property
1713
+ : teleport_shared_1.StringUtils.cssPropertyToInlineStyleKey(property);
1714
+ inlineStyle[key] = propertyValue;
1715
+ });
1716
+ return inlineStyle;
1717
+ }
323
1718
  //# sourceMappingURL=index.js.map