@teleporthq/teleport-plugin-common 0.45.3-alpha.0 → 0.45.13

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