@teleporthq/teleport-plugin-common 0.45.5-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 +1439 -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 +1438 -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 +2128 -61
  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
@@ -13,9 +13,19 @@ import {
13
13
  UIDLCMSListRepeaterNode,
14
14
  UIDLCMSMixedTypeNode,
15
15
  UIDLElement,
16
+ UIDLDataSourceItemNode,
17
+ UIDLDataSourceListNode,
18
+ UIDLRawValue,
19
+ UIDLDependency,
16
20
  } from '@teleporthq/teleport-types'
17
21
  import { UIDLUtils, StringUtils } from '@teleporthq/teleport-shared'
18
- import { JSXASTReturnType, JSXGenerationOptions, NodeToJSX } from './types'
22
+ import {
23
+ ConditionalIdentifier,
24
+ JSXASTReturnType,
25
+ JSXGenerationOptions,
26
+ JSXGenerationParams,
27
+ NodeToJSX,
28
+ } from './types'
19
29
 
20
30
  import {
21
31
  addEventHandlerToTag,
@@ -23,6 +33,10 @@ import {
23
33
  createDynamicValueExpression,
24
34
  createConditionalJSXExpression,
25
35
  getRepeatSourceIdentifier,
36
+ resolveGlobalStateName,
37
+ createGlobalStateExpression,
38
+ resolveAndRegisterGlobalStateSource,
39
+ makeControlUncontrolledWhenNoChangeHandler,
26
40
  } from './utils'
27
41
  import {
28
42
  addChildJSXText,
@@ -33,23 +47,776 @@ import {
33
47
  generateDynamicWindowImport,
34
48
  addDynamicExpressionAttributeToJSXTag,
35
49
  resolveObjectValue,
50
+ objectToObjectExpression,
51
+ parseStringWithTemplateExpressions,
52
+ parseJSExpressionAsAST,
53
+ resolveAttributeNameForTag,
54
+ convertValueToLiteral,
55
+ GLOBAL_REF_ID_MAP,
56
+ sanitizeExprContent,
36
57
  } from '../../utils/ast-utils'
37
58
  import { createJSXTag, createSelfClosingJSXTag } from '../../builders/ast-builders'
38
59
  import { DEFAULT_JSX_OPTIONS } from './constants'
39
60
  import { ASTBuilders, ASTUtils } from '../..'
61
+ import ParsedASTNode from '../../utils/parsed-ast'
62
+
63
+ // Runtime predicate that drops a DataProvider filter whose destination
64
+ // resolves to an empty value: `''` / `null` / `undefined`, or an empty
65
+ // array-overlap set (`[]` / `['']`). Selecting a "show all" reset must mean
66
+ // "no filter", not a query that matches zero rows. Kept in sync with the
67
+ // Next.js pages plugin's `buildNonEmptyDestinationPredicate` (duplicated here
68
+ // because teleport-plugin-common must not depend on teleport-plugin-next-data-source).
69
+ const buildNonEmptyFilterDestinationPredicate = (): types.ArrowFunctionExpression => {
70
+ const f = types.identifier('__f')
71
+ const dest = types.memberExpression(f, types.identifier('destination'))
72
+ const isEmptyArray = types.logicalExpression(
73
+ '&&',
74
+ types.callExpression(
75
+ types.memberExpression(types.identifier('Array'), types.identifier('isArray')),
76
+ [dest]
77
+ ),
78
+ types.binaryExpression(
79
+ '===',
80
+ types.memberExpression(
81
+ types.callExpression(types.memberExpression(dest, types.identifier('filter')), [
82
+ types.identifier('Boolean'),
83
+ ]),
84
+ types.identifier('length')
85
+ ),
86
+ types.numericLiteral(0)
87
+ )
88
+ )
89
+ return types.arrowFunctionExpression(
90
+ [f],
91
+ types.logicalExpression(
92
+ '&&',
93
+ types.logicalExpression(
94
+ '&&',
95
+ types.logicalExpression(
96
+ '&&',
97
+ types.binaryExpression('!==', dest, types.stringLiteral('')),
98
+ types.binaryExpression('!==', dest, types.nullLiteral())
99
+ ),
100
+ types.binaryExpression('!==', dest, types.identifier('undefined'))
101
+ ),
102
+ types.unaryExpression('!', isEmptyArray)
103
+ )
104
+ )
105
+ }
106
+
107
+ // Same idea one level up: a filter entry survives if it is a group that still
108
+ // has children, or a condition whose destination resolved to something real.
109
+ const buildSurvivingFilterNodePredicate = (): types.ArrowFunctionExpression => {
110
+ const f = types.identifier('__f')
111
+ const emptyDestination = buildNonEmptyFilterDestinationPredicate().body as types.Expression
112
+ return types.arrowFunctionExpression(
113
+ [f],
114
+ types.conditionalExpression(
115
+ types.binaryExpression(
116
+ '===',
117
+ types.memberExpression(f, types.identifier('type')),
118
+ types.stringLiteral('group')
119
+ ),
120
+ types.binaryExpression(
121
+ '>',
122
+ types.memberExpression(
123
+ types.memberExpression(f, types.identifier('children')),
124
+ types.identifier('length')
125
+ ),
126
+ types.numericLiteral(0)
127
+ ),
128
+ emptyDestination
129
+ )
130
+ )
131
+ }
132
+
133
+ // The inspector authors filters as a TREE — a root `and` group whose children
134
+ // are conditions or nested `or` groups. Emitting the tree (rather than mapping
135
+ // each entry as if it were a condition, which turned every group into an empty
136
+ // `{ source: '', destination: '', operand: '' }` row that the predicate then
137
+ // dropped) is what lets the data-source runtime honour the filter at all.
138
+ const buildFilterNodeExpression = (
139
+ entry: { type?: string; operator?: string; children?: unknown[] } & {
140
+ source?: string
141
+ destination?: unknown
142
+ operand?: string
143
+ },
144
+ dynamicReferencePrefixMap: Record<string, string>
145
+ ): types.Expression => {
146
+ if (entry && entry.type === 'group' && Array.isArray(entry.children)) {
147
+ const childExpressions = entry.children.map((child) =>
148
+ buildFilterNodeExpression(child as never, dynamicReferencePrefixMap)
149
+ )
150
+ return types.objectExpression([
151
+ types.objectProperty(types.identifier('type'), types.stringLiteral('group')),
152
+ types.objectProperty(
153
+ types.identifier('operator'),
154
+ types.stringLiteral(entry.operator === 'or' ? 'or' : 'and')
155
+ ),
156
+ types.objectProperty(
157
+ types.identifier('children'),
158
+ types.callExpression(
159
+ types.memberExpression(
160
+ types.arrayExpression(childExpressions),
161
+ types.identifier('filter')
162
+ ),
163
+ [buildSurvivingFilterNodePredicate()]
164
+ )
165
+ ),
166
+ ])
167
+ }
168
+
169
+ return types.objectExpression([
170
+ types.objectProperty(types.identifier('type'), types.stringLiteral('condition')),
171
+ types.objectProperty(types.identifier('source'), types.stringLiteral(entry?.source || '')),
172
+ types.objectProperty(
173
+ types.identifier('destination'),
174
+ ASTUtils.convertFilterDestinationToExpression(entry?.destination, {
175
+ dynamicReferencePrefixMap,
176
+ })
177
+ ),
178
+ types.objectProperty(types.identifier('operand'), types.stringLiteral(entry?.operand || '')),
179
+ ])
180
+ }
181
+
182
+ // Global references in the UIDL come in two shapes:
183
+ // Shape A: { id: "ecommerce", refPath: ["Cart", "total"] }
184
+ // Shape B: { id: undefined, refPath: ["E-commerce", "Settings", "Delivery", "..."] }
185
+ // This helper normalizes Shape B into Shape A so downstream code can handle
186
+ // both uniformly. The first refPath segment is mapped to a variable name via
187
+ // GLOBAL_REF_ID_MAP (exported from ast-utils so all sites stay in sync).
188
+ // Expression attributes (UIDLExpressionValue) bypass the dynamic-reference
189
+ // tracking in createDynamicValueExpression. When such an expression mentions
190
+ // a known global (currentUser/ecommerce/cart/locale/userIsLoggedIn) we still
191
+ // Plan v15 Layer 4 — junk-name attribute guard.
192
+ // AI fabrication artefacts emit attributes whose KEY is a JS literal
193
+ // (`true="true"`, `false="false"`, `0="x"`, `null="..."`). They survive JSX
194
+ // parsing (treated as string-valued attrs) but break DOM semantics. The
195
+ // upstream Layer 1–3 pipeline should already strip them; this is the final
196
+ // codegen safety net.
197
+ const CODEGEN_JUNK_ATTR_NAMES: ReadonlySet<string> = new Set(['true', 'false', 'null', 'undefined'])
198
+
199
+ function isJunkAttributeName(name: string): boolean {
200
+ if (typeof name !== 'string' || name.length === 0) {
201
+ return true
202
+ }
203
+ const lower = name.toLowerCase()
204
+ if (CODEGEN_JUNK_ATTR_NAMES.has(lower)) {
205
+ return true
206
+ }
207
+ if (/^[0-9]+$/.test(name)) {
208
+ return true
209
+ }
210
+ return false
211
+ }
212
+
213
+ function hasCorruptBindingMarkers(value: string): boolean {
214
+ // Entity-escaped `{` / `}` from upstream serialization that should never
215
+ // reach the JSX output verbatim.
216
+ if (/&#123;|&#125;/.test(value)) {
217
+ return true
218
+ }
219
+ // Unbalanced `{{` (no matching `}}`).
220
+ const opens = (value.match(/\{\{/g) || []).length
221
+ const closes = (value.match(/\}\}/g) || []).length
222
+ if (opens > closes) {
223
+ return true
224
+ }
225
+ return false
226
+ }
227
+
228
+ function truncate(value: string): string {
229
+ if (value.length <= 60) {
230
+ return value
231
+ }
232
+ return value.slice(0, 57) + '...'
233
+ }
234
+
235
+ // need to push it into params.globalReferences so downstream plugins inject
236
+ // the corresponding `useGlobalContext()` destructuring.
237
+ const GLOBAL_EXPRESSION_IDENTIFIERS: Array<{ pattern: RegExp; id: string }> = [
238
+ { pattern: /\bcurrentUser\b/, id: 'currentUser' },
239
+ { pattern: /\buserIsLoggedIn\b/, id: 'userIsLoggedIn' },
240
+ { pattern: /\becommerce\b/, id: 'ecommerce' },
241
+ { pattern: /\bcart\b/, id: 'cart' },
242
+ { pattern: /\blocales?\b/, id: 'locale' },
243
+ ]
244
+
245
+ const trackGlobalRefsInExpression = (expression: string, params: JSXGenerationParams): void => {
246
+ if (!expression) {
247
+ return
248
+ }
249
+ for (const { pattern, id } of GLOBAL_EXPRESSION_IDENTIFIERS) {
250
+ if (pattern.test(expression)) {
251
+ params.globalReferences.push(id as Parameters<typeof params.globalReferences.push>[0])
252
+ }
253
+ }
254
+
255
+ // Global-state identifiers behave the same way: an expression-shaped UIDL
256
+ // attribute (e.g. cms-mixed-type `itemData`) bypasses the dynamic-ref
257
+ // pipeline that registers `useGlobalState()` destructuring, so we walk the
258
+ // raw expression text and re-attach any state name we recognise. The
259
+ // matched names are added to `globalStateReferences` and the
260
+ // next-global-state component plugin destructures them at codegen time.
261
+ const definitions = params.globalStateDefinitions
262
+ if (!definitions || Object.keys(definitions).length === 0) {
263
+ return
264
+ }
265
+ for (const def of Object.values(definitions)) {
266
+ const name = def?.name
267
+ if (!name) {
268
+ continue
269
+ }
270
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
271
+ if (new RegExp(`\\b${escaped}\\b`).test(expression)) {
272
+ params.globalStateReferences.push({ id: def.id, name })
273
+ }
274
+ }
275
+ }
276
+
277
+ // The recognised runtime identifiers a `global` reference's `id` can legitimately
278
+ // already hold (Shape A). Anything else — notably the opaque `TQ_...` node id every
279
+ // dynamic UIDL reference carries for editor bookkeeping — is not a real identifier
280
+ // and must be re-derived from `refPath` (Shape B/C), or code generation would emit
281
+ // an undeclared variable that throws at runtime.
282
+ const KNOWN_GLOBAL_REF_IDS = new Set([
283
+ 'locale',
284
+ 'locales',
285
+ 'company',
286
+ 'currentUser',
287
+ 'userIsLoggedIn',
288
+ 'ecommerce',
289
+ 'cart',
290
+ ])
291
+
292
+ const normalizeGlobalRef = <
293
+ T extends { content: { id: string; refPath?: string[]; referenceType: string } }
294
+ >(
295
+ node: T
296
+ ): T => {
297
+ if (!node.content.refPath || node.content.refPath.length === 0) {
298
+ return node
299
+ }
300
+ if (node.content.id && KNOWN_GLOBAL_REF_IDS.has(node.content.id)) {
301
+ return node
302
+ }
303
+ const firstSeg = node.content.refPath[0]
304
+ const mappedId = GLOBAL_REF_ID_MAP[firstSeg]
305
+ if (!mappedId) {
306
+ return node
307
+ }
308
+ return {
309
+ ...node,
310
+ content: { ...node.content, id: mappedId, refPath: node.content.refPath.slice(1) },
311
+ }
312
+ }
313
+
314
+ const getElementType = (node: UIDLNode): string | null => {
315
+ if (
316
+ node.type === 'element' &&
317
+ node.content &&
318
+ typeof node.content === 'object' &&
319
+ 'elementType' in node.content
320
+ ) {
321
+ return (node.content as any).elementType
322
+ }
323
+ if ((node.type === 'data-source-list' || node.type === 'data-source-item') && node.content) {
324
+ return (node.content as any).elementType || 'DataProvider'
325
+ }
326
+ return null
327
+ }
328
+
329
+ const getClassName = (node: UIDLNode): string | null => {
330
+ if (
331
+ node.type === 'element' &&
332
+ node.content &&
333
+ typeof node.content === 'object' &&
334
+ 'key' in node.content
335
+ ) {
336
+ return (node.content as any).key || null
337
+ }
338
+ return null
339
+ }
340
+
341
+ const REACT_CHARTJS2_CHART_TAGS = new Set([
342
+ 'Line',
343
+ 'Bar',
344
+ 'Doughnut',
345
+ 'Pie',
346
+ 'Radar',
347
+ 'Bubble',
348
+ 'PolarArea',
349
+ 'Scatter',
350
+ ])
351
+
352
+ const isReactChartjs2Chart = (
353
+ dependency: UIDLDependency | undefined,
354
+ elementType: string
355
+ ): boolean => {
356
+ if (dependency?.path !== 'react-chartjs-2') {
357
+ return false
358
+ }
359
+ return REACT_CHARTJS2_CHART_TAGS.has(elementType)
360
+ }
361
+
362
+ /**
363
+ * A chart whose data did not arrive — a query the data source refused, a
364
+ * state still holding an empty fallback — draws an empty chart instead of
365
+ * taking the page down: react-chartjs-2 reads `data.labels` on its first
366
+ * render, and on the server that throw fails the render of the whole page.
367
+ * Rewrites `data={X}` into
368
+ * data={Array.isArray(X?.datasets) ? X : { labels: [], datasets: [] }}
369
+ * A data object written out in place, or hoisted to a constant of the
370
+ * module, needs no guard and is left as is.
371
+ */
372
+ const guardReactChartJs2DataAttr = (
373
+ chartElement: types.JSXElement,
374
+ hoistedConstants: JSXGenerationParams['hoistedConstants']
375
+ ): void => {
376
+ const attr = chartElement.openingElement.attributes.find(
377
+ (a): a is types.JSXAttribute =>
378
+ a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier' && a.name.name === 'data'
379
+ )
380
+ if (!attr || attr.value?.type !== 'JSXExpressionContainer') {
381
+ return
382
+ }
383
+ const source = attr.value.expression
384
+ const hoisted =
385
+ types.isIdentifier(source) && hoistedConstants.some((constant) => constant.name === source.name)
386
+ if (!types.isExpression(source) || types.isObjectExpression(source) || hoisted) {
387
+ return
388
+ }
389
+ attr.value = types.jsxExpressionContainer(
390
+ types.conditionalExpression(
391
+ types.callExpression(
392
+ types.memberExpression(types.identifier('Array'), types.identifier('isArray')),
393
+ [
394
+ types.optionalMemberExpression(
395
+ types.cloneNode(source),
396
+ types.identifier('datasets'),
397
+ false,
398
+ true
399
+ ),
400
+ ]
401
+ ),
402
+ types.cloneNode(source),
403
+ types.objectExpression([
404
+ types.objectProperty(types.identifier('labels'), types.arrayExpression([])),
405
+ types.objectProperty(types.identifier('datasets'), types.arrayExpression([])),
406
+ ])
407
+ )
408
+ )
409
+ }
410
+
411
+ /**
412
+ * Chart.js with maintainAspectRatio:false fills the parent; if height is on the chart
413
+ * component via className, react-chartjs-2 may not apply it to the canvas host correctly
414
+ * inside flex layouts, causing unbounded growth. Wrap in a bounded div and move className
415
+ * to the wrapper; the chart fills with height/width 100%.
416
+ */
417
+ const wrapReactChartJs2Element = (
418
+ chartElement: types.JSXElement,
419
+ _node: UIDLElementNode
420
+ ): types.JSXElement => {
421
+ const attrs = chartElement.openingElement.attributes
422
+ const kept: typeof attrs = []
423
+ let classNameAttr: types.JSXAttribute | null = null
424
+ for (const a of attrs) {
425
+ if (
426
+ a.type === 'JSXAttribute' &&
427
+ a.name.type === 'JSXIdentifier' &&
428
+ a.name.name === 'className'
429
+ ) {
430
+ classNameAttr = a
431
+ } else {
432
+ kept.push(a)
433
+ }
434
+ }
435
+ chartElement.openingElement.attributes = kept
436
+ const hasStyleAttr = kept.some(
437
+ (a) => a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier' && a.name.name === 'style'
438
+ )
439
+ if (!hasStyleAttr) {
440
+ chartElement.openingElement.attributes.push(
441
+ types.jsxAttribute(
442
+ types.jsxIdentifier('style'),
443
+ types.jsxExpressionContainer(
444
+ types.objectExpression([
445
+ types.objectProperty(types.identifier('height'), types.stringLiteral('100%')),
446
+ types.objectProperty(types.identifier('width'), types.stringLiteral('100%')),
447
+ ])
448
+ )
449
+ )
450
+ )
451
+ }
452
+
453
+ const wrapperStyle = types.objectExpression([
454
+ types.objectProperty(types.identifier('position'), types.stringLiteral('relative')),
455
+ types.objectProperty(types.identifier('minHeight'), types.numericLiteral(0)),
456
+ types.objectProperty(types.identifier('flexShrink'), types.numericLiteral(0)),
457
+ types.objectProperty(types.identifier('overflow'), types.stringLiteral('hidden')),
458
+ ])
459
+
460
+ const wrapperAttrs: types.JSXAttribute[] = [
461
+ types.jsxAttribute(types.jsxIdentifier('style'), types.jsxExpressionContainer(wrapperStyle)),
462
+ ]
463
+ if (classNameAttr) {
464
+ wrapperAttrs.push(classNameAttr)
465
+ }
466
+
467
+ return types.jsxElement(
468
+ types.jsxOpeningElement(types.jsxIdentifier('div'), wrapperAttrs),
469
+ types.jsxClosingElement(types.jsxIdentifier('div')),
470
+ [chartElement],
471
+ false
472
+ )
473
+ }
474
+
475
+ const isCalendarKitScheduler = (
476
+ dependency: UIDLDependency | undefined,
477
+ elementType: string
478
+ ): boolean => {
479
+ return dependency?.path === 'calendarkit-basic' && elementType === 'BasicScheduler'
480
+ }
481
+
482
+ /**
483
+ * calendarkit-basic's BasicScheduler requires `start`/`end` to be Date objects
484
+ * (date-fns internals), but UIDL attrs carry them as ISO strings — both for
485
+ * static event arrays and for state-bound arrays populated by workflows.
486
+ * Rewrites `events={X}` into:
487
+ * events={(Array.isArray(X) ? X : []).map((e) => ({ ...e, start: new Date(e.start), end: new Date(e.end) }))}
488
+ * The Array.isArray guard renders zero events instead of crashing when a
489
+ * binding resolves to a non-array (e.g. an unparsed JSON-string fallback).
490
+ * A missing `events` attr is left as-is — the component defaults it to [].
491
+ */
492
+ const wrapCalendarKitEventsAttr = (calendarElement: types.JSXElement): void => {
493
+ const attr = calendarElement.openingElement.attributes.find(
494
+ (a): a is types.JSXAttribute =>
495
+ a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier' && a.name.name === 'events'
496
+ )
497
+
498
+ if (!attr || attr.value?.type !== 'JSXExpressionContainer') {
499
+ return
500
+ }
501
+ const source = attr.value.expression
502
+ if (!types.isExpression(source)) {
503
+ return
504
+ }
505
+
506
+ // A static array literal needs no runtime guard; dynamic references do.
507
+ const guardedSource = types.isArrayExpression(source)
508
+ ? source
509
+ : types.conditionalExpression(
510
+ types.callExpression(
511
+ types.memberExpression(types.identifier('Array'), types.identifier('isArray')),
512
+ [source]
513
+ ),
514
+ types.cloneNode(source),
515
+ types.arrayExpression([])
516
+ )
517
+
518
+ const reviveEvent = types.arrowFunctionExpression(
519
+ [types.identifier('e')],
520
+ types.objectExpression([
521
+ types.spreadElement(types.identifier('e')),
522
+ types.objectProperty(
523
+ types.identifier('start'),
524
+ types.newExpression(types.identifier('Date'), [
525
+ types.memberExpression(types.identifier('e'), types.identifier('start')),
526
+ ])
527
+ ),
528
+ types.objectProperty(
529
+ types.identifier('end'),
530
+ types.newExpression(types.identifier('Date'), [
531
+ types.memberExpression(types.identifier('e'), types.identifier('end')),
532
+ ])
533
+ ),
534
+ ])
535
+ )
536
+
537
+ attr.value = types.jsxExpressionContainer(
538
+ types.callExpression(types.memberExpression(guardedSource, types.identifier('map')), [
539
+ reviveEvent,
540
+ ])
541
+ )
542
+ }
543
+
544
+ const reorderChildrenForSearch = (children: UIDLNode[]): UIDLNode[] => {
545
+ const searchNodes: UIDLNode[] = []
546
+ const dataProviderNodes: UIDLNode[] = []
547
+ const paginationNodes: UIDLNode[] = []
548
+ const otherNodes: UIDLNode[] = []
549
+
550
+ children.forEach((child) => {
551
+ const elementType = getElementType(child)
552
+ const nodeType = child.type
553
+ const className = getClassName(child)
554
+
555
+ // Check for search nodes - use className since elementType is replaced by semanticType
556
+ if (
557
+ className &&
558
+ (className.includes('data-source-search') || className.includes('search-node'))
559
+ ) {
560
+ searchNodes.push(child)
561
+ }
562
+ // Check for DataProvider nodes - these should appear SECOND
563
+ else if (
564
+ nodeType === 'data-source-list' ||
565
+ nodeType === 'data-source-item' ||
566
+ elementType === 'DataProvider'
567
+ ) {
568
+ dataProviderNodes.push(child)
569
+ }
570
+ // Check for pagination nodes - use className since elementType is replaced by semanticType
571
+ else if (
572
+ (elementType &&
573
+ (elementType.includes('pagination') || elementType.includes('cms-pagination'))) ||
574
+ (className && (className.includes('pagination') || className.includes('cms-pagination')))
575
+ ) {
576
+ paginationNodes.push(child)
577
+ }
578
+ // Everything else goes in the middle
579
+ else {
580
+ otherNodes.push(child)
581
+ }
582
+ })
583
+
584
+ // Only reorder if we have search or pagination nodes alongside a DataProvider
585
+ // This ensures we only reorder when there's an actual pagination/search group
586
+ // If there's no search/pagination, keep original order to preserve DataProvider positions
587
+ const hasSearchOrPagination = searchNodes.length > 0 || paginationNodes.length > 0
588
+ const hasDataProvider = dataProviderNodes.length > 0
589
+
590
+ if (hasSearchOrPagination && hasDataProvider) {
591
+ // Order: search nodes first, then data providers, then other nodes, then pagination last
592
+ // This ensures: search input -> DataProvider -> content -> pagination buttons
593
+ return [...searchNodes, ...dataProviderNodes, ...otherNodes, ...paginationNodes]
594
+ } else {
595
+ // No reordering needed - preserve original order
596
+ return children
597
+ }
598
+ }
599
+
600
+ /**
601
+ * Extracts autocomplete context from a thq-autocomplete node's children.
602
+ * Returns the input's field name and the dropdown's isOpen state name,
603
+ * so child option/clear elements can wire up onClick handlers.
604
+ */
605
+ const extractAutocompleteContext = (
606
+ children: UIDLNode[],
607
+ formStateName?: string
608
+ ): JSXGenerationParams['autocompleteContext'] => {
609
+ let fieldName: string | null = null
610
+ let inputHtmlId: string | null = null
611
+ let isOpenStateName: string | null = null
612
+
613
+ for (const child of children) {
614
+ if (child.type === 'element') {
615
+ const content = child.content as UIDLElement
616
+ // Check both original elementType and data-thq attr (elementType may have been resolved)
617
+ const dataThq = content.attrs?.['data-thq']
618
+ const thqValue = dataThq?.type === 'static' ? String(dataThq.content) : ''
619
+ if (
620
+ content.elementType === 'thq-autocomplete-input' ||
621
+ thqValue === 'thq-autocomplete-input'
622
+ ) {
623
+ const nameAttr = content.attrs?.name
624
+ if (nameAttr?.type === 'static' && typeof nameAttr.content === 'string') {
625
+ fieldName = nameAttr.content
626
+ }
627
+ const idAttr = content.attrs?.id
628
+ if (idAttr?.type === 'static' && typeof idAttr.content === 'string') {
629
+ inputHtmlId = idAttr.content
630
+ }
631
+ }
632
+ } else if (child.type === 'conditional') {
633
+ const condContent = child.content as UIDLConditionalNode['content']
634
+ const ref = (condContent as any).reference?.content
635
+ if (ref?.referenceType === 'state' && typeof ref.id === 'string') {
636
+ isOpenStateName = ref.id
637
+ }
638
+ }
639
+ }
640
+
641
+ if (fieldName && isOpenStateName) {
642
+ return { fieldName, inputHtmlId: inputHtmlId || '', formStateName, isOpenStateName }
643
+ }
644
+ return undefined
645
+ }
646
+
647
+ const maybeAddFormStoreFieldBinding = (
648
+ elementTag: types.JSXElement,
649
+ elementName: string,
650
+ attrs: UIDLElement['attrs'] | undefined,
651
+ params: JSXGenerationParams,
652
+ events?: UIDLElement['events']
653
+ ) => {
654
+ const stateKey = params.formStoreStateName
655
+ if (!stateKey || !attrs) {
656
+ return
657
+ }
658
+
659
+ const nameAttr = attrs.name
660
+ if (!nameAttr || nameAttr.type !== 'static' || typeof nameAttr.content !== 'string') {
661
+ return
662
+ }
663
+
664
+ const tag = elementName.toLowerCase()
665
+ const isRichTextEditor = tag === 'richtexteditor'
666
+ if (tag !== 'input' && tag !== 'textarea' && tag !== 'select' && !isRichTextEditor) {
667
+ return
668
+ }
669
+
670
+ // Autocomplete inputs manage their own value through workflows and option onClick handlers.
671
+ // Do NOT bind them to the form store — it causes infinite loops with state-change workflows.
672
+ const dataThq = attrs['data-thq']
673
+ if (dataThq?.type === 'static' && String(dataThq.content) === 'thq-autocomplete-input') {
674
+ return
675
+ }
676
+
677
+ const fieldName = nameAttr.content
678
+ const stateId = types.identifier(stateKey)
679
+ const fieldAccess = types.memberExpression(stateId, types.stringLiteral(fieldName), true)
680
+
681
+ const typeAttr = attrs.type
682
+ const isCheckbox = typeAttr?.type === 'static' && String(typeAttr.content) === 'checkbox'
683
+
684
+ const hasValueInAttrs = Object.prototype.hasOwnProperty.call(attrs, 'value')
685
+ const hasCheckedInAttrs = Object.prototype.hasOwnProperty.call(attrs, 'checked')
686
+
687
+ if (isRichTextEditor) {
688
+ const valueForEditor = types.logicalExpression('||', fieldAccess, types.stringLiteral(''))
689
+ elementTag.openingElement.attributes.push(
690
+ types.jsxAttribute(types.jsxIdentifier('value'), types.jsxExpressionContainer(valueForEditor))
691
+ )
692
+ const setterName = `set${stateKey.charAt(0).toUpperCase()}${stateKey.slice(1)}`
693
+ const richHandler = parseJSExpressionAsAST(
694
+ `(html) => { ${setterName}(prev => ({ ...prev, ['${fieldName}']: html })); }`
695
+ )
696
+ elementTag.openingElement.attributes.push(
697
+ types.jsxAttribute(types.jsxIdentifier('onChange'), types.jsxExpressionContainer(richHandler))
698
+ )
699
+ return
700
+ }
701
+
702
+ if (!hasValueInAttrs && !isCheckbox) {
703
+ const valueExpr = types.logicalExpression('??', fieldAccess, types.stringLiteral(''))
704
+ elementTag.openingElement.attributes.push(
705
+ types.jsxAttribute(types.jsxIdentifier('value'), types.jsxExpressionContainer(valueExpr))
706
+ )
707
+ } else if (isCheckbox && !hasCheckedInAttrs) {
708
+ elementTag.openingElement.attributes.push(
709
+ types.jsxAttribute(types.jsxIdentifier('checked'), types.jsxExpressionContainer(fieldAccess))
710
+ )
711
+ }
712
+
713
+ const hasUidlOnChange = events && Object.prototype.hasOwnProperty.call(events, 'onChange')
714
+ if (!hasUidlOnChange) {
715
+ const setterName = `set${stateKey.charAt(0).toUpperCase()}${stateKey.slice(1)}`
716
+ const handler = parseJSExpressionAsAST(
717
+ `(e) => { const t = e.target; if (t.name) { ${setterName}(prev => ({ ...prev, [t.name]: t.type === 'checkbox' ? t.checked : t.value })); } }`
718
+ )
719
+ elementTag.openingElement.attributes.push(
720
+ types.jsxAttribute(types.jsxIdentifier('onChange'), types.jsxExpressionContainer(handler))
721
+ )
722
+ }
723
+ }
724
+
725
+ // Style plugins (styled-jsx, css-modules, styled-components, react-jss, plugin-css)
726
+ // emit ONE flat, component-scope CSS block/class-map from `element.style`, so a
727
+ // dynamic style value only resolves correctly there when the identifier it needs
728
+ // is reachable from that top-level scope (e.g. `token`/`prop`). A `ctx` reference
729
+ // resolves to the render-prop identifier of the enclosing repeater/data-source —
730
+ // only in scope inside that repeater's own render callback — and other reference
731
+ // types (`state`, `local`, `global`, `globalState`, ...) are never routed through
732
+ // `element.style` by any known UIDL producer either. When one shows up anyway, the
733
+ // only place that still knows the correct enclosing scope is here, while building
734
+ // this exact JSX node, so resolve it into an inline `style` attribute (mirroring
735
+ // how `dynamicStyleBindings` already handles ctx/state-bound styles) and strip it
736
+ // out of `element.style` so no downstream style plugin re-processes — and chokes
737
+ // on — the same entry.
738
+ const resolveScopedDynamicStyleValues = (
739
+ style: UIDLElement['style'],
740
+ elementTag: types.JSXElement,
741
+ params: JSXGenerationParams,
742
+ options: JSXGenerationOptions
743
+ ): void => {
744
+ if (!style) {
745
+ return
746
+ }
747
+
748
+ const inlineStyleOverrides: Record<string, ParsedASTNode> = {}
749
+ for (const cssProperty of Object.keys(style)) {
750
+ const styleValue = style[cssProperty]
751
+ const camelCaseProperty = StringUtils.cssPropertyToInlineStyleKey(cssProperty)
752
+
753
+ // A pre-resolved expression style value (e.g. a data-source-bound style whose
754
+ // mapper already produced the full member-access expression). The UIDL style
755
+ // type is narrowed to static|dynamic, so read the discriminator via a cast.
756
+ // Inline the parsed expression and strip it so no CSS/styled-jsx plugin sees it.
757
+ const rawStyleValue = styleValue as { type?: string; content?: unknown }
758
+ if (rawStyleValue.type === 'expr') {
759
+ const exprContent = rawStyleValue.content
760
+ if (typeof exprContent === 'string' && exprContent.length > 0) {
761
+ inlineStyleOverrides[camelCaseProperty] = new ParsedASTNode(
762
+ parseJSExpressionAsAST(exprContent)
763
+ )
764
+ delete style[cssProperty]
765
+ }
766
+ continue
767
+ }
768
+
769
+ // Skip: `token` → CSS variable (handled by the style plugin); a SIMPLE `prop`
770
+ // (no refPath) → the style plugin's `${props.x}` interpolation. A prop WITH a
771
+ // refPath (an object prop's field, e.g. `product.color`) MUST be inlined here
772
+ // instead — styled-jsx's prop case emits only `props.<id>` and would drop the
773
+ // refPath, producing `props.product` instead of `props.product.color`.
774
+ const isSimpleProp =
775
+ styleValue.type === 'dynamic' &&
776
+ styleValue.content.referenceType === 'prop' &&
777
+ !(styleValue.content.refPath && styleValue.content.refPath.length > 0)
778
+ if (
779
+ styleValue.type !== 'dynamic' ||
780
+ styleValue.content.referenceType === 'token' ||
781
+ isSimpleProp
782
+ ) {
783
+ continue
784
+ }
785
+
786
+ const resolvedExpr = resolveDynamicReferenceExpression(styleValue, params, options)
787
+ const fallback = (styleValue.content as { fallback?: string | number | boolean }).fallback
788
+ const finalExpr =
789
+ fallback !== undefined && fallback !== ''
790
+ ? types.logicalExpression('||', resolvedExpr, convertValueToLiteral(fallback))
791
+ : resolvedExpr
792
+ inlineStyleOverrides[camelCaseProperty] = new ParsedASTNode(finalExpr)
793
+
794
+ delete style[cssProperty]
795
+ }
796
+
797
+ if (Object.keys(inlineStyleOverrides).length > 0) {
798
+ addAttributeToJSXTag(elementTag, 'style', inlineStyleOverrides)
799
+ }
800
+ }
40
801
 
41
802
  const generateElementNode: NodeToJSX<UIDLElementNode, types.JSXElement> = (
42
803
  node,
43
804
  params,
44
805
  jsxOptions
45
806
  ) => {
46
- const { dependencies, nodesLookup, projectResources = {} } = params
47
- const options = { ...DEFAULT_JSX_OPTIONS, ...jsxOptions, projectResources }
48
- const { elementType, selfClosing, children, key, attrs, dependency, events } = node.content
807
+ const { dependencies, nodesLookup } = params
808
+ const options = { ...DEFAULT_JSX_OPTIONS, ...jsxOptions }
809
+ const { elementType, selfClosing, children, key, attrs, dependency, events, style } = node.content
49
810
 
50
811
  const originalElementName = elementType || 'component'
51
812
  let tagName = originalElementName
52
813
 
814
+ // Check if this is a fragment element - normalize to Fragment before processing
815
+ const isFragment = tagName.toLowerCase() === 'fragment'
816
+ if (isFragment) {
817
+ tagName = 'Fragment'
818
+ }
819
+
53
820
  if (dependency) {
54
821
  if (
55
822
  options.dependencyHandling === 'import' ||
@@ -77,31 +844,237 @@ const generateElementNode: NodeToJSX<UIDLElementNode, types.JSXElement> = (
77
844
  const dynamicWindowImport = generateDynamicWindowImport('useEffect', dependency.path)
78
845
  params.windowImports[dependency.path] = dynamicWindowImport
79
846
  }
847
+ } else if (isFragment) {
848
+ // If no dependency was provided but this is a fragment, add Fragment dependency
849
+ if (options.dependencyHandling === 'import') {
850
+ dependencies.Fragment = {
851
+ type: 'package',
852
+ path: 'react',
853
+ version: 'latest',
854
+ meta: {
855
+ namedImport: true,
856
+ },
857
+ }
858
+ }
80
859
  }
81
860
 
82
861
  const elementName =
83
862
  dependency && dependency.type === 'local' && options.customElementTag
84
863
  ? options.customElementTag(tagName)
85
864
  : tagName
865
+
86
866
  const elementTag = selfClosing ? createSelfClosingJSXTag(elementName) : createJSXTag(elementName)
87
867
 
88
868
  if (attrs) {
89
- addAttributesToJSXTag(attrs, elementTag, options)
869
+ addAttributesToJSXTag(
870
+ attrs,
871
+ elementTag,
872
+ options,
873
+ params,
874
+ node.content.semanticType || elementType
875
+ )
90
876
  }
91
877
 
878
+ resolveScopedDynamicStyleValues(style, elementTag, params, options)
879
+
92
880
  if (events) {
93
881
  Object.keys(events).forEach((eventKey) => {
94
882
  addEventHandlerToTag(elementTag, eventKey, events[eventKey], params, options)
95
883
  })
96
884
  }
97
885
 
98
- if (!selfClosing && children) {
99
- children.forEach((child) => {
100
- const childTags = generateNode(child, params, options)
886
+ // Generate onChange handler for form elements with data-store-values-state
887
+ let childParams = params
888
+ if (attrs?.['data-store-values-state']) {
889
+ const storeAttr = attrs['data-store-values-state']
890
+ if (storeAttr.type === 'static' && typeof storeAttr.content === 'string') {
891
+ const stateName = storeAttr.content
892
+ childParams = { ...params, formStoreStateName: stateName }
893
+ const setterName = `set${stateName.charAt(0).toUpperCase()}${stateName.slice(1)}`
894
+ const handler = parseJSExpressionAsAST(
895
+ `(e) => { const t = e.target; if (t.name && t.getAttribute('data-thq') !== 'thq-autocomplete-input') { ${setterName}(prev => ({ ...prev, [t.name]: t.type === 'checkbox' ? t.checked : t.value })); } }`
896
+ )
897
+ elementTag.openingElement.attributes.push(
898
+ types.jsxAttribute(types.jsxIdentifier('onChange'), types.jsxExpressionContainer(handler))
899
+ )
900
+ }
901
+ }
902
+
903
+ maybeAddFormStoreFieldBinding(elementTag, elementName, attrs, childParams, events)
904
+
905
+ // thq-autocomplete-input: make uncontrolled by converting `value` → `defaultValue`
906
+ // A controlled autocomplete input triggers state-change workflows on every keystroke,
907
+ // which normalizes the typed text and prevents free typing for search/filtering.
908
+ const dataThqAttr = attrs?.['data-thq']
909
+ const dataThqValue = dataThqAttr?.type === 'static' ? String(dataThqAttr.content) : ''
910
+
911
+ if (dataThqValue === 'thq-autocomplete-input') {
912
+ const jsxAttrs = elementTag.openingElement.attributes
913
+ const valueIdx = jsxAttrs.findIndex(
914
+ (a) => a.type === 'JSXAttribute' && a.name.type === 'JSXIdentifier' && a.name.name === 'value'
915
+ )
916
+ if (valueIdx !== -1) {
917
+ // Convert value → defaultValue so the input is uncontrolled but has initial value
918
+ const valueAttr = jsxAttrs[valueIdx] as types.JSXAttribute
919
+ jsxAttrs.splice(
920
+ valueIdx,
921
+ 1,
922
+ types.jsxAttribute(types.jsxIdentifier('defaultValue'), valueAttr.value)
923
+ )
924
+ }
925
+ }
926
+
927
+ // A controlled form control (`<input>`/`<textarea>`/`<select>` with a `value`,
928
+ // or a checkbox/radio with `checked`) that has NO change handler is FROZEN by
929
+ // React — the user cannot type, and a console warning is emitted. This is the
930
+ // edit-form failure mode: entity-bound fields rendered as
931
+ // `value={props.item?.title}` with no state mirror (the worker deliberately
932
+ // does NOT mirror entity columns into state — see crud-edit-form contract).
933
+ // Render such controls UNCONTROLLED (`defaultValue`/`defaultChecked`) so they
934
+ // are editable AND the DOM value reflects edits, which is exactly what
935
+ // form-submit workflows read (`document.getElementById(id).value`). Controls
936
+ // that ARE controlled (an onChange was attached above — via events, the
937
+ // form-store binding, or a workflow trigger) keep `value`/`checked`, and
938
+ // read-only/disabled display fields are left untouched.
939
+ makeControlUncontrolledWhenNoChangeHandler(elementTag, elementName)
940
+
941
+ if (dataThqValue === 'thq-autocomplete' && children) {
942
+ const acCtx = extractAutocompleteContext(children, childParams.formStoreStateName)
943
+ if (acCtx) {
944
+ childParams = { ...childParams, autocompleteContext: acCtx }
945
+ }
946
+ }
947
+
948
+ // thq-autocomplete-option: add onClick to select the option value
949
+ if (dataThqValue === 'thq-autocomplete-option' && params.autocompleteContext) {
950
+ const { fieldName, formStateName, isOpenStateName, inputHtmlId } = params.autocompleteContext
951
+ const isOpenSetterName = `set${isOpenStateName.charAt(0).toUpperCase()}${isOpenStateName.slice(
952
+ 1
953
+ )}`
954
+
955
+ let handlerCode: string
956
+ // The autocomplete input is uncontrolled, so always set the DOM value.
957
+ // If form-store mode, also update the form state for form submission.
958
+ const inputLookup = inputHtmlId
959
+ ? `document.getElementById('${inputHtmlId}')`
960
+ : `e.currentTarget.closest('[data-thq="thq-autocomplete"]').querySelector('[data-thq="thq-autocomplete-input"]')`
961
+ const formStoreUpdate = formStateName
962
+ ? `var setter = ${`set${formStateName.charAt(0).toUpperCase()}${formStateName.slice(
963
+ 1
964
+ )}`}; setter(function(prev) { return Object.assign({}, prev, { ['${fieldName}']: text }); });`
965
+ : ''
966
+ handlerCode = `(e) => { var text = (e.currentTarget.textContent || '').trim(); var input = ${inputLookup}; if (input) { input.value = text; } ${formStoreUpdate} ${isOpenSetterName}(false); }`
967
+ const handler = parseJSExpressionAsAST(handlerCode)
968
+ elementTag.openingElement.attributes.push(
969
+ types.jsxAttribute(types.jsxIdentifier('onClick'), types.jsxExpressionContainer(handler))
970
+ )
971
+ }
972
+
973
+ // thq-autocomplete-clear: add onClick to clear the input value and close dropdown
974
+ if (dataThqValue === 'thq-autocomplete-clear' && params.autocompleteContext) {
975
+ const { fieldName, formStateName, isOpenStateName, inputHtmlId } = params.autocompleteContext
976
+ const isOpenSetterName = `set${isOpenStateName.charAt(0).toUpperCase()}${isOpenStateName.slice(
977
+ 1
978
+ )}`
979
+
980
+ let handlerCode: string
981
+ const clearInputLookup = inputHtmlId
982
+ ? `document.getElementById('${inputHtmlId}')`
983
+ : `e.currentTarget.closest('[data-thq="thq-autocomplete"]').querySelector('[data-thq="thq-autocomplete-input"]')`
984
+ const clearFormStoreUpdate = formStateName
985
+ ? `var setter = ${`set${formStateName.charAt(0).toUpperCase()}${formStateName.slice(
986
+ 1
987
+ )}`}; setter(function(prev) { return Object.assign({}, prev, { ['${fieldName}']: '' }); });`
988
+ : ''
989
+ handlerCode = `(e) => { var input = ${clearInputLookup}; if (input) { input.value = ''; } ${clearFormStoreUpdate} ${isOpenSetterName}(false); }`
990
+ const handler = parseJSExpressionAsAST(handlerCode)
991
+ elementTag.openingElement.attributes.push(
992
+ types.jsxAttribute(types.jsxIdentifier('onClick'), types.jsxExpressionContainer(handler))
993
+ )
994
+ }
995
+
996
+ // A markdown-node can carry its rich-text content as a dynamic/expr child
997
+ // (e.g. CMS-bound rich text) rather than as a `raw` attribute. The raw-attribute
998
+ // path is handled in addAttributesToJSXTag; here we handle the children path so
999
+ // the content is injected as HTML (dangerouslySetInnerHTML) instead of being
1000
+ // printed as an escaped raw value by the generic expression handler.
1001
+ const isMarkdownNode =
1002
+ node.content.semanticType === 'markdown-node' || originalElementName === 'markdown-node'
1003
+ const hasRawAttr = attrs
1004
+ ? Object.keys(attrs).some((attrKey) => attrs[attrKey]?.type === 'raw')
1005
+ : false
1006
+
1007
+ let markdownChildrenHandled = false
1008
+ if (isMarkdownNode && !selfClosing && !hasRawAttr && children && children.length > 0) {
1009
+ const markdownChild = children.find(
1010
+ (child) => child.type === 'expr' || child.type === 'dynamic'
1011
+ )
1012
+ let markdownExpr: types.Expression | undefined
1013
+ if (markdownChild?.type === 'expr') {
1014
+ markdownExpr = ASTUtils.getExpressionFromUIDLExpressionNode(markdownChild)
1015
+ } else if (markdownChild?.type === 'dynamic') {
1016
+ markdownExpr = resolveDynamicReferenceExpression(markdownChild, childParams, options)
1017
+ }
1018
+ if (markdownExpr) {
1019
+ injectMarkdownExpression(elementTag, markdownExpr, '', childParams)
1020
+ markdownChildrenHandled = true
1021
+ }
1022
+ }
1023
+
1024
+ // A controlled <textarea> — one carrying a `value` (or `defaultValue`) prop —
1025
+ // must NOT also render children. React's server renderer throws
1026
+ // "If you supply `value` on a <textarea> you must not supply children.", which
1027
+ // aborts static export of the whole page. The details-page / entity binder can
1028
+ // leave the original text content in place when it adds a `value` binding to a
1029
+ // textarea (harmless for <input>, fatal for <textarea>). We still GENERATE the
1030
+ // children below so every UIDL node lands in `nodesLookup` (the styled-jsx pass
1031
+ // requires it), but we do not attach them to the textarea — the value prop is
1032
+ // the single source of truth.
1033
+ const isTextArea =
1034
+ originalElementName.toLowerCase() === 'textarea' || node.content.semanticType === 'textarea'
1035
+ // The check must run against the JSX opening element (not just UIDL attrs):
1036
+ // maybeAddFormStoreFieldBinding injects a `value` attr onto named textareas
1037
+ // inside a data-store-values-state form AFTER UIDL attrs are processed, and
1038
+ // that injected binding makes the textarea controlled all the same.
1039
+ const jsxTagHasControlledValue = elementTag.openingElement.attributes.some(
1040
+ (attr) =>
1041
+ attr.type === 'JSXAttribute' &&
1042
+ attr.name.type === 'JSXIdentifier' &&
1043
+ (attr.name.name === 'value' || attr.name.name === 'defaultValue')
1044
+ )
1045
+ const skipAttachingChildren =
1046
+ isTextArea &&
1047
+ (jsxTagHasControlledValue ||
1048
+ (!!attrs &&
1049
+ (Object.prototype.hasOwnProperty.call(attrs, 'value') ||
1050
+ Object.prototype.hasOwnProperty.call(attrs, 'defaultValue'))))
1051
+
1052
+ if (!markdownChildrenHandled && !selfClosing && children) {
1053
+ // Reorder children to ensure search nodes appear before DataProvider nodes
1054
+ const reorderedChildren = reorderChildrenForSearch(children)
1055
+
1056
+ reorderedChildren.forEach((child) => {
1057
+ const childTags = generateNode(child, childParams, options)
1058
+ if (skipAttachingChildren) {
1059
+ return
1060
+ }
101
1061
  childTags.forEach((childTag) => {
102
1062
  if (typeof childTag === 'string') {
103
1063
  addChildJSXText(elementTag, childTag)
104
1064
  } else if (childTag.type === 'JSXExpressionContainer' || childTag.type === 'JSXElement') {
1065
+ // Backstop for an UNCONTROLLED <textarea> whose value binding arrived
1066
+ // as a child (we only reach here when skipAttachingChildren is false —
1067
+ // the textarea has NO value/defaultValue attr). A <textarea> has no
1068
+ // value attribute in HTML, so React stringifies an element/expression
1069
+ // CHILD to the literal "[object Object]" inside the field (run 97ac2650
1070
+ // Add Note). The primary fix hoists the binding to a value= attribute at
1071
+ // import time (ai-state-binding-preprocessor.hoistTextareaChildBindingToValue);
1072
+ // this net drops any stray dynamic child so it can never render
1073
+ // "[object Object]". Static text children (the typeof-string branch
1074
+ // above) are untouched.
1075
+ if (isTextArea) {
1076
+ return
1077
+ }
105
1078
  addChildJSXTag(elementTag, childTag)
106
1079
  } else {
107
1080
  addChildJSXTag(elementTag, types.jsxExpressionContainer(childTag))
@@ -110,6 +1083,17 @@ const generateElementNode: NodeToJSX<UIDLElementNode, types.JSXElement> = (
110
1083
  })
111
1084
  }
112
1085
 
1086
+ if (dependency && isReactChartjs2Chart(dependency, originalElementName)) {
1087
+ guardReactChartJs2DataAttr(elementTag, params.hoistedConstants)
1088
+ const wrapped = wrapReactChartJs2Element(elementTag, node)
1089
+ nodesLookup[key] = wrapped
1090
+ return wrapped
1091
+ }
1092
+
1093
+ if (dependency && isCalendarKitScheduler(dependency, originalElementName)) {
1094
+ wrapCalendarKitEventsAttr(elementTag)
1095
+ }
1096
+
113
1097
  nodesLookup[key] = elementTag
114
1098
  return elementTag
115
1099
  }
@@ -119,27 +1103,167 @@ export default generateElementNode
119
1103
  const addAttributesToJSXTag = (
120
1104
  attrs: UIDLElement['attrs'],
121
1105
  elementTag: types.JSXElement,
122
- options: JSXGenerationOptions
1106
+ options: JSXGenerationOptions,
1107
+ params: JSXGenerationParams,
1108
+ elementName?: string
123
1109
  ) => {
124
- Object.keys(attrs).forEach((attrKey) => {
1110
+ Object.keys(attrs ?? {}).forEach((attrKey) => {
125
1111
  const attributeValue = attrs[attrKey]
126
1112
 
1113
+ if (!attributeValue.type) {
1114
+ return
1115
+ }
1116
+
1117
+ // Skip code-gen directives - handled in generateElementNode
1118
+ if (attrKey === 'data-store-values-state') {
1119
+ return
1120
+ }
1121
+
1122
+ // Plan v15 Layer 4 — codegen safety net.
1123
+ //
1124
+ // Drop attributes that look like AI fabrication artefacts even when the
1125
+ // upstream pipeline missed them. These never produce valid DOM/JSX:
1126
+ // 1. attr names that are pure JS literals (`true`, `false`, bare
1127
+ // numbers, `null`, `undefined`) — e.g. the `true="true"` that
1128
+ // shipped with the broken Navigation in the 2026-05-24 run.
1129
+ // 2. static string values that contain entity-escaped binding markers
1130
+ // (`&#123;` / `&#125;`) — emitting them produces broken DOM text.
1131
+ // 3. static string values that contain an UNBALANCED `{{` (no
1132
+ // matching `}}`) — always garbage, never valid.
1133
+ if (isJunkAttributeName(attrKey)) {
1134
+ // eslint-disable-next-line no-console
1135
+ console.warn(
1136
+ `[codegen safety net] dropping junk-name attribute "${attrKey}" on <${
1137
+ elementName ?? 'element'
1138
+ }>`
1139
+ )
1140
+ return
1141
+ }
1142
+ if (attributeValue.type === 'static') {
1143
+ const staticContent = (attributeValue as { content?: unknown }).content
1144
+ if (typeof staticContent === 'string' && hasCorruptBindingMarkers(staticContent)) {
1145
+ // eslint-disable-next-line no-console
1146
+ console.warn(
1147
+ `[codegen safety net] dropping attribute "${attrKey}" on <${
1148
+ elementName ?? 'element'
1149
+ }> — value has entity-escaped or truncated binding markers (${truncate(staticContent)})`
1150
+ )
1151
+ return
1152
+ }
1153
+ }
1154
+
1155
+ // React takes `style` as an object, never as text: a `style="color: red"`
1156
+ // attribute (a custom attribute typed in the editor) throws React error #62
1157
+ // while the page prerenders and fails the whole build. The text becomes the
1158
+ // object it meant; a value that is not plain CSS text is dropped.
1159
+ if (attrKey === 'style') {
1160
+ const inlineStyle =
1161
+ attributeValue.type === 'static'
1162
+ ? parseInlineStyleText((attributeValue as { content?: unknown }).content)
1163
+ : undefined
1164
+ if (inlineStyle && Object.keys(inlineStyle).length > 0) {
1165
+ addAttributeToJSXTag(elementTag, 'style', inlineStyle)
1166
+ } else {
1167
+ // eslint-disable-next-line no-console
1168
+ console.warn(
1169
+ `[codegen safety net] dropping "style" attribute on <${
1170
+ elementName ?? 'element'
1171
+ }> — React takes style as an object, and this value is not CSS text`
1172
+ )
1173
+ }
1174
+ return
1175
+ }
1176
+
127
1177
  switch (attributeValue.type) {
128
1178
  case 'dynamic':
1179
+ const dynamicRef = attributeValue as UIDLDynamicReference
129
1180
  const {
130
1181
  content: { referenceType },
131
- } = attributeValue
1182
+ } = dynamicRef
1183
+
1184
+ if (referenceType === 'global') {
1185
+ const normRef = normalizeGlobalRef(dynamicRef)
1186
+ params.globalReferences.push(
1187
+ normRef.content.id as Parameters<typeof params.globalReferences.push>[0]
1188
+ )
1189
+ // Use the normalized ref to generate the attribute expression
1190
+ const globalExpr = createDynamicValueExpression(normRef, options)
1191
+ elementTag.openingElement.attributes.push(
1192
+ types.jsxAttribute(
1193
+ types.jsxIdentifier(resolveAttributeNameForTag(elementTag, attrKey)),
1194
+ types.jsxExpressionContainer(globalExpr)
1195
+ )
1196
+ )
1197
+ break
1198
+ }
1199
+
1200
+ if ((referenceType as string) === 'globalState') {
1201
+ const gsName = resolveGlobalStateName(
1202
+ dynamicRef.content.id,
1203
+ params.globalStateDefinitions
1204
+ )
1205
+ params.globalStateReferences.push({ id: dynamicRef.content.id, name: gsName })
1206
+ const expr = createGlobalStateExpression(dynamicRef as any, params.globalStateDefinitions)
1207
+ elementTag.openingElement.attributes.push(
1208
+ types.jsxAttribute(
1209
+ types.jsxIdentifier(resolveAttributeNameForTag(elementTag, attrKey)),
1210
+ types.jsxExpressionContainer(expr)
1211
+ )
1212
+ )
1213
+ break
1214
+ }
1215
+
1216
+ // A translated attribute (`placeholder`, `alt`, `title`, `aria-label`, …).
1217
+ // It cannot be emitted the way a translated CHILD is — that path produces a
1218
+ // `<span>` the framework plugin fills through `dangerouslySetInnerHTML`, and
1219
+ // an attribute needs a plain string. So the attribute is written with the
1220
+ // main-language text (carried on the reference's `fallback`) and recorded on
1221
+ // `params.localeAttributeReferences`; the target framework's i18n plugin
1222
+ // rewrites the recorded attributes into its own translation lookup — see
1223
+ // `createNextInternationalizationPlugin`. A framework without such a plugin
1224
+ // keeps the main-language string, which is valid, readable markup.
1225
+ if (referenceType === 'locale') {
1226
+ const translationKey = dynamicRef.content.id
1227
+ if (!translationKey) {
1228
+ break
1229
+ }
1230
+
1231
+ // `fallback` only exists on the plain reference member of the union, and
1232
+ // narrowing happened on the destructured `referenceType`, not on the ref.
1233
+ const { fallback } = dynamicRef.content as { fallback?: string | number | boolean }
1234
+ const attribute = types.jsxAttribute(
1235
+ types.jsxIdentifier(resolveAttributeNameForTag(elementTag, attrKey)),
1236
+ types.stringLiteral(StringUtils.encode(fallback === undefined ? '' : String(fallback)))
1237
+ )
1238
+ elementTag.openingElement.attributes.push(attribute)
1239
+ params.localeAttributeReferences.push({ attribute, key: translationKey })
1240
+ break
1241
+ }
1242
+
1243
+ // A value read through a mapper (`aria-pressed` from a filter's state, a
1244
+ // formatted date) renders through it, as a text binding does. Emitted as
1245
+ // the bare reference, the attribute carried the raw value.
1246
+ if ((dynamicRef.content as { valueMapper?: string }).valueMapper?.trim()) {
1247
+ elementTag.openingElement.attributes.push(
1248
+ types.jsxAttribute(
1249
+ types.jsxIdentifier(resolveAttributeNameForTag(elementTag, attrKey)),
1250
+ types.jsxExpressionContainer(
1251
+ createDynamicValueExpression(dynamicRef, options) as types.Expression
1252
+ )
1253
+ )
1254
+ )
1255
+ break
1256
+ }
132
1257
 
133
1258
  switch (referenceType) {
134
1259
  default:
135
1260
  const prefix =
136
- options.dynamicReferencePrefixMap[referenceType as 'prop' | 'state' | 'local']
137
- addDynamicAttributeToJSXTag(
138
- elementTag,
139
- attrKey,
140
- (attributeValue as UIDLDynamicReference).content.id,
141
- prefix
1261
+ options.dynamicReferencePrefixMap[referenceType as 'prop' | 'state' | 'local'] || ''
1262
+ const idWithRefPath = UIDLUtils.generateIdWithRefPath(
1263
+ dynamicRef.content.id,
1264
+ dynamicRef.content.refPath
142
1265
  )
1266
+ addDynamicAttributeToJSXTag(elementTag, attrKey, idWithRefPath, prefix)
143
1267
 
144
1268
  break
145
1269
  }
@@ -147,16 +1271,83 @@ const addAttributesToJSXTag = (
147
1271
  case 'import':
148
1272
  addDynamicAttributeToJSXTag(elementTag, attrKey, attributeValue.content.id)
149
1273
  break
150
- case 'raw':
1274
+ case 'raw': {
1275
+ const rawValue = attributeValue as UIDLRawValue
1276
+ if (elementName === 'markdown-node') {
1277
+ if (rawValue.dynamic) {
1278
+ applyDynamicMarkdownInjection(elementTag, rawValue, params, options)
1279
+ } else {
1280
+ applyStaticMarkdownInjection(elementTag, rawValue, params)
1281
+ }
1282
+ break
1283
+ }
1284
+ if (elementName === 'rich-text-editor-node') {
1285
+ applyRichTextEditorRawAttribute(elementTag, attrKey, rawValue, params, options)
1286
+ break
1287
+ }
1288
+ if (rawValue.dynamic) {
1289
+ applyDynamicHtmlInjection(elementTag, rawValue, params, options)
1290
+ break
1291
+ }
151
1292
  addRawAttributeToJSXTag(elementTag, attrKey, attributeValue)
152
1293
  break
1294
+ }
153
1295
  case 'comp-style':
154
- case 'static':
155
1296
  addAttributeToJSXTag(elementTag, attrKey, attributeValue.content)
156
1297
  break
1298
+ case 'static':
1299
+ if (
1300
+ typeof attributeValue.content === 'object' &&
1301
+ attributeValue.content !== null &&
1302
+ !Array.isArray(attributeValue.content)
1303
+ ) {
1304
+ const constName = `__staticProp${params.hoistedConstants.length}`
1305
+ const expression = objectToObjectExpression(
1306
+ attributeValue.content as Record<string, unknown>
1307
+ )
1308
+ params.hoistedConstants.push({ name: constName, expression })
1309
+ elementTag.openingElement.attributes.push(
1310
+ types.jsxAttribute(
1311
+ types.jsxIdentifier(resolveAttributeNameForTag(elementTag, attrKey)),
1312
+ types.jsxExpressionContainer(types.identifier(constName))
1313
+ )
1314
+ )
1315
+ } else {
1316
+ addAttributeToJSXTag(elementTag, attrKey, attributeValue.content)
1317
+ }
1318
+ break
157
1319
  case 'expr':
158
1320
  addDynamicExpressionAttributeToJSXTag(elementTag, attributeValue, attrKey)
1321
+ // Scan the *sanitized* content so any globals introduced by the
1322
+ // repair (e.g. `/profile/${}` → `/profile/${currentUser?.id}`) still
1323
+ // trigger the downstream useGlobalContext() wiring.
1324
+ trackGlobalRefsInExpression(
1325
+ sanitizeExprContent(String(attributeValue.content), attrKey),
1326
+ params
1327
+ )
1328
+ break
1329
+
1330
+ case 'element':
1331
+ addAttributeToJSXTag(
1332
+ elementTag,
1333
+ attrKey,
1334
+ generateElementNode(attributeValue, params, options)
1335
+ )
1336
+
1337
+ break
1338
+
1339
+ case 'object': {
1340
+ const content = attributeValue.content
1341
+ if (typeof content !== 'object') {
1342
+ return
1343
+ }
1344
+ const expression = objectToObjectExpression(content as Record<string, unknown>)
1345
+ elementTag.openingElement.attributes.push(
1346
+ types.jsxAttribute(types.jsxIdentifier(attrKey), types.jsxExpressionContainer(expression))
1347
+ )
159
1348
  break
1349
+ }
1350
+
160
1351
  default:
161
1352
  throw new Error(
162
1353
  `generateElementNode could not generate code for attribute of type ${JSON.stringify(
@@ -164,7 +1355,39 @@ const addAttributesToJSXTag = (
164
1355
  )}`
165
1356
  )
166
1357
  }
167
- })
1358
+ })
1359
+ }
1360
+
1361
+ /**
1362
+ * Converts text containing {{ expr }} templates into a mix of JSX text and expression containers.
1363
+ * e.g. "x{{ (state.score / 10) || '0' }}" → ["x", JSXExpressionContainer((score / 10) || '0')]
1364
+ *
1365
+ * Uses parseStringWithTemplateExpressions to parse the template into a TemplateLiteral AST,
1366
+ * then converts its quasis (text parts) and expressions into JSX children.
1367
+ */
1368
+ const convertTextTemplateToJSX = (text: string): JSXASTReturnType[] => {
1369
+ try {
1370
+ const templateLiteral = parseStringWithTemplateExpressions(text)
1371
+ const result: JSXASTReturnType[] = []
1372
+
1373
+ for (let i = 0; i < templateLiteral.quasis.length; i++) {
1374
+ const quasi = templateLiteral.quasis[i]
1375
+ const textPart = quasi.value.cooked || quasi.value.raw
1376
+ if (textPart) {
1377
+ result.push(StringUtils.encode(textPart))
1378
+ }
1379
+ if (i < templateLiteral.expressions.length) {
1380
+ result.push(
1381
+ types.jsxExpressionContainer(templateLiteral.expressions[i] as types.Expression)
1382
+ )
1383
+ }
1384
+ }
1385
+
1386
+ return result.length > 0 ? result : [StringUtils.encode(text)]
1387
+ } catch {
1388
+ // If parsing fails, fall back to encoded text
1389
+ return [StringUtils.encode(text)]
1390
+ }
168
1391
  }
169
1392
 
170
1393
  const generateNode: NodeToJSX<UIDLNode, JSXASTReturnType[]> = (node, params, options) => {
@@ -172,25 +1395,108 @@ const generateNode: NodeToJSX<UIDLNode, JSXASTReturnType[]> = (node, params, opt
172
1395
  case 'expr':
173
1396
  return [generateExpressionNode(node, params, options)]
174
1397
 
175
- case 'raw':
1398
+ case 'raw': {
1399
+ const rawNode = node as UIDLRawValue
1400
+ if (rawNode.dynamic) {
1401
+ const dynamicExpr = resolveDynamicReferenceExpression(rawNode.dynamic, params, options)
1402
+ const fallback = rawNode.fallback || rawNode.content
1403
+ return [ASTBuilders.createDynamicDOMInjectionNode(dynamicExpr, fallback)]
1404
+ }
176
1405
  return [
177
1406
  options.domHTMLInjection
178
1407
  ? options.domHTMLInjection(node.content.toString())
179
1408
  : node.content.toString(),
180
1409
  ]
1410
+ }
181
1411
 
182
1412
  case 'inject':
183
1413
  if (node?.dependency) {
184
- /* tslint:disable:no-string-literal */
185
- params.dependencies['Script'] = node.dependency
1414
+ params.dependencies.Script = node.dependency
186
1415
  }
187
1416
  return [node.content.toString()]
188
1417
 
189
- case 'static':
190
- return [StringUtils.encode(node.content.toString())]
1418
+ case 'static': {
1419
+ const textContent = node.content.toString()
1420
+ // Check if the text contains {{ }} template expressions
1421
+ if (/\{\{/.test(textContent)) {
1422
+ return convertTextTemplateToJSX(textContent)
1423
+ }
1424
+ return [StringUtils.encode(textContent)]
1425
+ }
191
1426
 
192
1427
  case 'dynamic':
193
- return [createDynamicValueExpression(node, options, undefined)]
1428
+ switch (node.content.referenceType) {
1429
+ case 'prop': {
1430
+ // If the dynamic node is a prop and has a default value of type UIDLElementNode,
1431
+ // we should use it with a logical expression.
1432
+ const prop = params.propDefinitions[node.content.id]
1433
+ if (prop?.type === 'element' && prop.defaultValue) {
1434
+ const prefix = options.dynamicReferencePrefixMap[node.content.referenceType] || ''
1435
+
1436
+ const propDefault = prop.defaultValue as UIDLElementNode
1437
+ const jsxNode = params.nodesLookup[propDefault.content.key]
1438
+
1439
+ if (jsxNode === undefined) {
1440
+ throw Error(`Prop ${node.content.id} is of type element \n
1441
+ The JSXNode of the prop-${node.content.id} is missing from the nodesLookup`)
1442
+ }
1443
+
1444
+ return [
1445
+ types.logicalExpression(
1446
+ '??',
1447
+ prefix === ''
1448
+ ? types.identifier(node.content.id)
1449
+ : types.memberExpression(
1450
+ types.identifier(prefix),
1451
+ types.identifier(node.content.id)
1452
+ ),
1453
+ jsxNode as types.JSXElement
1454
+ ),
1455
+ ]
1456
+ }
1457
+
1458
+ return [createDynamicValueExpression(node, options)]
1459
+ }
1460
+
1461
+ case 'locale': {
1462
+ // Locale is not handled the same in all frameworks.
1463
+ // So, we need to handle it differently using individual plugins for each framework.
1464
+ const emptyExpression = types.jsxEmptyExpression()
1465
+ emptyExpression.innerComments = [
1466
+ {
1467
+ type: 'CommentBlock',
1468
+ value: `locale-${node.content.id}`,
1469
+ },
1470
+ ]
1471
+ const expression = types.jsxExpressionContainer(emptyExpression)
1472
+ const jsxTag = createJSXTag('span')
1473
+ addChildJSXTag(jsxTag, expression)
1474
+
1475
+ params.localeReferences.push(jsxTag)
1476
+ return [jsxTag]
1477
+ }
1478
+
1479
+ case 'global': {
1480
+ const globalNode = normalizeGlobalRef(node)
1481
+ params.globalReferences.push(
1482
+ globalNode.content.id as Parameters<typeof params.globalReferences.push>[0]
1483
+ )
1484
+ return [createDynamicValueExpression(globalNode, options)]
1485
+ }
1486
+
1487
+ default:
1488
+ if ((node.content.referenceType as string) === 'globalState') {
1489
+ const gsName = resolveGlobalStateName(node.content.id, params.globalStateDefinitions)
1490
+ params.globalStateReferences.push({ id: node.content.id, name: gsName })
1491
+ return [
1492
+ createGlobalStateExpression(
1493
+ node as any,
1494
+ params.globalStateDefinitions
1495
+ ) as JSXASTReturnType,
1496
+ ]
1497
+ }
1498
+ return [createDynamicValueExpression(node, options)]
1499
+ }
194
1500
 
195
1501
  case 'cms-item':
196
1502
  case 'cms-list':
@@ -202,8 +1508,37 @@ const generateNode: NodeToJSX<UIDLNode, JSXASTReturnType[]> = (node, params, opt
202
1508
  case 'cms-mixed-type':
203
1509
  return generateCMSMixedTypeNode(node, params, options)
204
1510
 
205
- case 'element':
206
- return [generateElementNode(node, params, options)]
1511
+ case 'data-source-item':
1512
+ case 'data-source-list':
1513
+ return generateDataSourceNode(node, params, options)
1514
+
1515
+ case 'element': {
1516
+ // Check if this element node is wrapping a data-source node
1517
+ if (
1518
+ node.content &&
1519
+ typeof node.content === 'object' &&
1520
+ 'type' in node.content &&
1521
+ (node.content.type === 'data-source-item' || node.content.type === 'data-source-list')
1522
+ ) {
1523
+ // Treat it as a data-source node
1524
+ // tslint:disable-next-line:no-any
1525
+ return generateDataSourceNode(node.content as any, params, options)
1526
+ }
1527
+ const elementTag = generateElementNode(node, params, options)
1528
+ const renderingConditions = (node.content as UIDLElement | undefined)?.renderingConditions
1529
+ if (renderingConditions) {
1530
+ return [
1531
+ wrapWithConditional(
1532
+ elementTag,
1533
+ renderingConditions.reference,
1534
+ renderingConditions.condition,
1535
+ params,
1536
+ options
1537
+ ),
1538
+ ]
1539
+ }
1540
+ return [elementTag]
1541
+ }
207
1542
 
208
1543
  case 'repeat':
209
1544
  return generateRepeatNode(node, params, options)
@@ -233,7 +1568,26 @@ const generateExpressionNode: NodeToJSX<UIDLExpressionValue, types.JSXExpression
233
1568
  node
234
1569
  ) => {
235
1570
  const expression = ASTUtils.getExpressionFromUIDLExpressionNode(node)
236
- return types.jsxExpressionContainer(expression)
1571
+
1572
+ // Wrap expression to safely handle objects/arrays: (typeof val === 'object' && val !== null) ? JSON.stringify(val) : val
1573
+ const safeExpression = types.conditionalExpression(
1574
+ types.logicalExpression(
1575
+ '&&',
1576
+ types.binaryExpression(
1577
+ '===',
1578
+ types.unaryExpression('typeof', expression, true),
1579
+ types.stringLiteral('object')
1580
+ ),
1581
+ types.binaryExpression('!==', expression, types.nullLiteral())
1582
+ ),
1583
+ types.callExpression(
1584
+ types.memberExpression(types.identifier('JSON'), types.identifier('stringify')),
1585
+ [expression]
1586
+ ),
1587
+ expression
1588
+ )
1589
+
1590
+ return types.jsxExpressionContainer(safeExpression)
237
1591
  }
238
1592
 
239
1593
  const generateCMSMixedTypeNode: NodeToJSX<UIDLCMSMixedTypeNode, types.JSXElement[]> = (
@@ -254,7 +1608,7 @@ const generateCMSMixedTypeNode: NodeToJSX<UIDLCMSMixedTypeNode, types.JSXElement
254
1608
  const mappingsObject: types.ObjectProperty[] = []
255
1609
 
256
1610
  if (attrs) {
257
- addAttributesToJSXTag(attrs, cmsMixedNode, options)
1611
+ addAttributesToJSXTag(attrs, cmsMixedNode, options, params)
258
1612
  }
259
1613
 
260
1614
  if (dependency) {
@@ -265,7 +1619,7 @@ const generateCMSMixedTypeNode: NodeToJSX<UIDLCMSMixedTypeNode, types.JSXElement
265
1619
  const element = generateElementNode(mappings[key], params, options)
266
1620
  mappingsObject.push(
267
1621
  types.objectProperty(
268
- types.identifier(key),
1622
+ types.identifier(`"${key}"`),
269
1623
  types.arrowFunctionExpression([types.identifier(renderPropIdentifier)], element)
270
1624
  )
271
1625
  )
@@ -340,6 +1694,12 @@ const generateCMSNode: NodeToJSX<UIDLCMSListNode | UIDLCMSItemNode, types.JSXEle
340
1694
 
341
1695
  const cmsNode = ASTBuilders.createJSXTag(jsxTag, [], true)
342
1696
 
1697
+ const cmsDataNodeIdAttr = (node.content as { attrs?: { dataNodeId?: { content?: string } } })
1698
+ .attrs?.dataNodeId
1699
+ if (cmsDataNodeIdAttr?.content) {
1700
+ addAttributeToJSXTag(cmsNode, 'dataNodeId', cmsDataNodeIdAttr.content)
1701
+ }
1702
+
343
1703
  if (node.type === 'cms-item') {
344
1704
  cmsNode.openingElement.attributes.push(
345
1705
  types.jsxAttribute(
@@ -347,7 +1707,10 @@ const generateCMSNode: NodeToJSX<UIDLCMSListNode | UIDLCMSItemNode, types.JSXEle
347
1707
  types.jsxExpressionContainer(
348
1708
  types.arrowFunctionExpression(
349
1709
  [types.identifier(renderPropIdentifier)],
350
- generateNode(success, params, options)[0] as types.JSXElement
1710
+ generateNode(success, params, {
1711
+ ...options,
1712
+ localIdentifier: renderPropIdentifier,
1713
+ })[0] as types.JSXElement
351
1714
  )
352
1715
  )
353
1716
  )
@@ -398,16 +1761,20 @@ const generateCMSNode: NodeToJSX<UIDLCMSListNode | UIDLCMSItemNode, types.JSXEle
398
1761
  )
399
1762
  }
400
1763
 
401
- if (initialData && initialData.content.referenceType === 'prop') {
1764
+ if (initialData && initialData.content.referenceType) {
1765
+ const refType = initialData.content.referenceType as 'prop' | 'state' | 'local'
1766
+ const initialDataExpr =
1767
+ refType === 'prop'
1768
+ ? types.memberExpression(
1769
+ types.identifier(options.dynamicReferencePrefixMap[refType]),
1770
+ types.identifier(initialData.content.id)
1771
+ )
1772
+ : types.identifier(initialData.content.id)
1773
+
402
1774
  cmsNode.openingElement.attributes.push(
403
1775
  types.jsxAttribute(
404
1776
  types.jsxIdentifier('initialData'),
405
- types.jsxExpressionContainer(
406
- types.memberExpression(
407
- types.identifier(options.dynamicReferencePrefixMap[initialData.content.referenceType]),
408
- types.identifier(initialData.content.id)
409
- )
410
- )
1777
+ types.jsxExpressionContainer(initialDataExpr)
411
1778
  )
412
1779
  )
413
1780
 
@@ -418,22 +1785,24 @@ const generateCMSNode: NodeToJSX<UIDLCMSListNode | UIDLCMSItemNode, types.JSXEle
418
1785
  )
419
1786
  )
420
1787
 
421
- let keyValue = 'props?.pagination?.page'
1788
+ if (refType === 'prop') {
1789
+ let keyValue = 'props?.pagination?.page'
422
1790
 
423
- if (node.type === 'cms-item') {
424
- const { entityKeyProperty } = node.content
425
- const entityName = initialData.content.id
426
- keyValue = entityKeyProperty
427
- ? `props?.${entityName}?.${entityKeyProperty}`
428
- : `props?.${entityName}?.id`
429
- }
1791
+ if (node.type === 'cms-item') {
1792
+ const { entityKeyProperty } = node.content
1793
+ const entityName = initialData.content.id
1794
+ keyValue = entityKeyProperty
1795
+ ? `props?.${entityName}?.${entityKeyProperty}`
1796
+ : `props?.${entityName}?.id`
1797
+ }
430
1798
 
431
- cmsNode.openingElement.attributes.push(
432
- types.jsxAttribute(
433
- types.jsxIdentifier('key'),
434
- types.jsxExpressionContainer(types.identifier(keyValue))
1799
+ cmsNode.openingElement.attributes.push(
1800
+ types.jsxAttribute(
1801
+ types.jsxIdentifier('key'),
1802
+ types.jsxExpressionContainer(types.identifier(keyValue))
1803
+ )
435
1804
  )
436
- )
1805
+ }
437
1806
  }
438
1807
 
439
1808
  if (Object.keys(resourceParams || {}).length > 0) {
@@ -482,15 +1851,250 @@ const generateCMSNode: NodeToJSX<UIDLCMSListNode | UIDLCMSItemNode, types.JSXEle
482
1851
  return [cmsNode]
483
1852
  }
484
1853
 
1854
+ const generateDataSourceNode: NodeToJSX<
1855
+ UIDLDataSourceItemNode | UIDLDataSourceListNode,
1856
+ types.JSXElement[]
1857
+ > = (node, params, options) => {
1858
+ const { renderPropIdentifier, elementType, dependency, resourceDefinition } = node.content
1859
+
1860
+ const key = node.content.key || `ds-${resourceDefinition.dataSourceId}-${Date.now()}`
1861
+ const name = node.content.name || renderPropIdentifier
1862
+
1863
+ // tslint:disable-next-line:no-any
1864
+ const children =
1865
+ node.content.children && node.content.children.length > 0
1866
+ ? node.content.children
1867
+ : (node.content as any).nodes?.success
1868
+ ? [(node.content as any).nodes.success]
1869
+ : []
1870
+
1871
+ const jsxTag = StringUtils.dashCaseToUpperCamelCase(elementType)
1872
+
1873
+ if (dependency && options.dependencyHandling === 'import') {
1874
+ params.dependencies[elementType] = dependency
1875
+ }
1876
+
1877
+ const dataSourceNode = ASTBuilders.createJSXTag(jsxTag, [], true)
1878
+
1879
+ const dataSourceDataNodeIdAttr = (
1880
+ node.content as { attrs?: { dataNodeId?: { content?: string } } }
1881
+ ).attrs?.dataNodeId
1882
+ if (dataSourceDataNodeIdAttr?.content) {
1883
+ addAttributeToJSXTag(dataSourceNode, 'dataNodeId', dataSourceDataNodeIdAttr.content)
1884
+ }
1885
+
1886
+ dataSourceNode.openingElement.attributes.push(
1887
+ types.jsxAttribute(
1888
+ types.jsxIdentifier('resourceDefinition'),
1889
+ types.jsxExpressionContainer(
1890
+ types.objectExpression([
1891
+ types.objectProperty(
1892
+ types.stringLiteral('type'),
1893
+ types.stringLiteral('external-data-source')
1894
+ ),
1895
+ types.objectProperty(
1896
+ types.stringLiteral('dataSourceId'),
1897
+ types.stringLiteral(resourceDefinition.dataSourceId)
1898
+ ),
1899
+ types.objectProperty(
1900
+ types.stringLiteral('tableName'),
1901
+ types.stringLiteral(resourceDefinition.tableName)
1902
+ ),
1903
+ types.objectProperty(
1904
+ types.stringLiteral('dataSourceType'),
1905
+ types.stringLiteral(resourceDefinition.dataSourceType)
1906
+ ),
1907
+ ])
1908
+ )
1909
+ )
1910
+ )
1911
+
1912
+ dataSourceNode.openingElement.attributes.push(
1913
+ types.jsxAttribute(
1914
+ types.jsxIdentifier('name'),
1915
+ types.jsxExpressionContainer(types.stringLiteral(name))
1916
+ )
1917
+ )
1918
+
1919
+ if (children && children.length > 0) {
1920
+ // Pass the render prop identifier as the 'ctx' prefix for data source context references
1921
+ // and as the localIdentifier so conditional nodes resolve local refs correctly
1922
+ const childOptions = {
1923
+ ...options,
1924
+ localIdentifier: renderPropIdentifier,
1925
+ dynamicReferencePrefixMap: {
1926
+ ...options.dynamicReferencePrefixMap,
1927
+ ctx: renderPropIdentifier,
1928
+ },
1929
+ }
1930
+ const childrenNodes = children.flatMap((child) => generateNode(child, params, childOptions))
1931
+ const renderFunction = types.arrowFunctionExpression(
1932
+ [types.identifier(renderPropIdentifier)],
1933
+ types.jsxFragment(
1934
+ types.jsxOpeningFragment(),
1935
+ types.jsxClosingFragment(),
1936
+ childrenNodes as types.JSXElement[]
1937
+ )
1938
+ )
1939
+ dataSourceNode.openingElement.attributes.push(
1940
+ types.jsxAttribute(
1941
+ types.jsxIdentifier('renderSuccess'),
1942
+ types.jsxExpressionContainer(renderFunction)
1943
+ )
1944
+ )
1945
+ }
1946
+
1947
+ // tslint:disable-next-line:no-any
1948
+ if ((node.content as any).nodes?.loading) {
1949
+ // tslint:disable-next-line:no-any
1950
+ const loadingNode = generateNode((node.content as any).nodes.loading, params, options)[0]
1951
+ dataSourceNode.openingElement.attributes.push(
1952
+ types.jsxAttribute(
1953
+ types.jsxIdentifier('renderLoading'),
1954
+ types.jsxExpressionContainer(
1955
+ types.arrowFunctionExpression([], loadingNode as types.JSXElement)
1956
+ )
1957
+ )
1958
+ )
1959
+ }
1960
+
1961
+ // tslint:disable-next-line:no-any
1962
+ if ((node.content as any).nodes?.error) {
1963
+ // tslint:disable-next-line:no-any
1964
+ const errorNode = generateNode((node.content as any).nodes.error, params, options)[0]
1965
+ dataSourceNode.openingElement.attributes.push(
1966
+ types.jsxAttribute(
1967
+ types.jsxIdentifier('renderError'),
1968
+ types.jsxExpressionContainer(
1969
+ types.arrowFunctionExpression([], errorNode as types.JSXElement)
1970
+ )
1971
+ )
1972
+ )
1973
+ }
1974
+
1975
+ // Add resource params if they exist
1976
+ // tslint:disable-next-line:no-any
1977
+ const resourceParams = (node.content as any).resource?.params
1978
+ if (resourceParams && Object.keys(resourceParams).length > 0) {
1979
+ const nodeParams: types.ObjectProperty[] = Object.keys(resourceParams).reduce(
1980
+ (acc: types.ObjectProperty[], attrKey) => {
1981
+ const property = resourceParams[attrKey]
1982
+
1983
+ if (property.type === 'static') {
1984
+ // Special handling for filters array - convert dynamic destinations
1985
+ if (attrKey === 'filters' && Array.isArray(property.content)) {
1986
+ const filterEntries = property.content.map((filter: never) =>
1987
+ buildFilterNodeExpression(filter, options.dynamicReferencePrefixMap)
1988
+ )
1989
+ // Drop conditions whose destination resolves to an empty value at
1990
+ // runtime (empty string / null / undefined, or an empty
1991
+ // array-overlap set) so a "show all" reset means no filter rather
1992
+ // than a query that matches zero rows. Mirrors the Next.js pages
1993
+ // path's `buildNonEmptyDestinationPredicate` (kept inline here
1994
+ // because teleport-plugin-common must not depend on the
1995
+ // next-data-source plugin).
1996
+ // JSON.stringify because these params are handed to
1997
+ // `new URLSearchParams(params)`, which would otherwise stringify the
1998
+ // array to '[object Object]' and lose every filter in transit.
1999
+ acc.push(
2000
+ types.objectProperty(
2001
+ types.stringLiteral(attrKey),
2002
+ types.callExpression(
2003
+ types.memberExpression(types.identifier('JSON'), types.identifier('stringify')),
2004
+ [
2005
+ types.callExpression(
2006
+ types.memberExpression(
2007
+ types.arrayExpression(filterEntries),
2008
+ types.identifier('filter')
2009
+ ),
2010
+ [buildSurvivingFilterNodePredicate()]
2011
+ ),
2012
+ ]
2013
+ )
2014
+ )
2015
+ )
2016
+ } else {
2017
+ acc.push(
2018
+ types.objectProperty(types.stringLiteral(attrKey), resolveObjectValue(property))
2019
+ )
2020
+ }
2021
+ }
2022
+
2023
+ if (property.type === 'expr') {
2024
+ const expression = ASTUtils.getExpressionFromUIDLExpressionNode(property)
2025
+ acc.push(types.objectProperty(types.stringLiteral(attrKey), expression))
2026
+ }
2027
+
2028
+ if (property.type === 'dynamic') {
2029
+ const refType = property.content.referenceType as 'prop' | 'state' | 'local'
2030
+ acc.push(
2031
+ types.objectProperty(
2032
+ types.stringLiteral(attrKey),
2033
+ property.content.referenceType === 'prop'
2034
+ ? types.memberExpression(
2035
+ types.identifier(options.dynamicReferencePrefixMap[refType]),
2036
+ types.identifier(property.content.id)
2037
+ )
2038
+ : types.identifier(property.content.id)
2039
+ )
2040
+ )
2041
+ }
2042
+
2043
+ return acc
2044
+ },
2045
+ []
2046
+ )
2047
+ dataSourceNode.openingElement.attributes.push(
2048
+ types.jsxAttribute(
2049
+ types.jsxIdentifier('params'),
2050
+ types.jsxExpressionContainer(types.objectExpression(nodeParams))
2051
+ )
2052
+ )
2053
+ }
2054
+
2055
+ // Add initialData if the UIDL node has it (similar to CMS nodes)
2056
+ // tslint:disable-next-line:no-any
2057
+ const nodeInitialData = (node.content as any).initialData
2058
+ if (nodeInitialData && nodeInitialData.content?.referenceType) {
2059
+ const refType = nodeInitialData.content.referenceType as 'prop' | 'state' | 'local'
2060
+ const initialDataExpr =
2061
+ refType === 'prop'
2062
+ ? types.memberExpression(
2063
+ types.identifier(options.dynamicReferencePrefixMap[refType]),
2064
+ types.identifier(nodeInitialData.content.id)
2065
+ )
2066
+ : types.identifier(nodeInitialData.content.id)
2067
+
2068
+ dataSourceNode.openingElement.attributes.push(
2069
+ types.jsxAttribute(
2070
+ types.jsxIdentifier('initialData'),
2071
+ types.jsxExpressionContainer(initialDataExpr)
2072
+ )
2073
+ )
2074
+
2075
+ dataSourceNode.openingElement.attributes.push(
2076
+ types.jsxAttribute(
2077
+ types.jsxIdentifier('persistDataDuringLoading'),
2078
+ types.jsxExpressionContainer(types.booleanLiteral(true))
2079
+ )
2080
+ )
2081
+ }
2082
+
2083
+ params.nodesLookup[key] = dataSourceNode
2084
+ return [dataSourceNode]
2085
+ }
2086
+
485
2087
  const generateRepeatNode: NodeToJSX<UIDLRepeatNode, types.JSXExpressionContainer[]> = (
486
2088
  node,
487
2089
  params,
488
2090
  options
489
2091
  ) => {
490
2092
  const { node: repeatContent, dataSource, meta } = node.content
491
- const contentASTs = generateNode(repeatContent, params, options) as types.JSXElement[]
492
-
493
2093
  const { iteratorName, iteratorKey } = UIDLUtils.getRepeatIteratorNameAndKey(meta)
2094
+ const contentASTs = generateNode(repeatContent, params, {
2095
+ ...options,
2096
+ localIdentifier: iteratorName,
2097
+ }) as types.JSXElement[]
494
2098
 
495
2099
  const localIteratorPrefix = options.dynamicReferencePrefixMap.local
496
2100
  contentASTs.forEach((contentAST) => {
@@ -513,14 +2117,74 @@ const generateRepeatNode: NodeToJSX<UIDLRepeatNode, types.JSXExpressionContainer
513
2117
  )
514
2118
  }
515
2119
 
2120
+ // Tracks a condition reference's global / globalState usage on params and
2121
+ // resolves it to a ConditionalIdentifier. Shared by the top-level reference
2122
+ // and the optional per-entry references of a conditional expression.
2123
+ const trackAndResolveConditionIdentifier = (
2124
+ reference: UIDLConditionalNode['content']['reference'],
2125
+ params: JSXGenerationParams,
2126
+ options: JSXGenerationOptions
2127
+ ): ConditionalIdentifier => {
2128
+ if (
2129
+ reference.type === 'dynamic' &&
2130
+ 'referenceType' in reference.content &&
2131
+ reference.content.referenceType === 'global'
2132
+ ) {
2133
+ const normCondRef = normalizeGlobalRef(reference as any)
2134
+ params.globalReferences.push(
2135
+ normCondRef.content.id as Parameters<typeof params.globalReferences.push>[0]
2136
+ )
2137
+ }
2138
+
2139
+ if (
2140
+ reference.type === 'dynamic' &&
2141
+ 'referenceType' in reference.content &&
2142
+ (reference.content.referenceType as string) === 'globalState'
2143
+ ) {
2144
+ const gsName = resolveGlobalStateName(reference.content.id, params.globalStateDefinitions)
2145
+ params.globalStateReferences.push({ id: reference.content.id, name: gsName })
2146
+ }
2147
+
2148
+ const effectiveRef =
2149
+ reference.type === 'dynamic' &&
2150
+ 'referenceType' in reference.content &&
2151
+ reference.content.referenceType === 'global'
2152
+ ? (normalizeGlobalRef(reference as any) as typeof reference)
2153
+ : reference
2154
+ return createConditionIdentifier(effectiveRef, params, options)
2155
+ }
2156
+
2157
+ // Shared between UIDLConditionalNode (wraps a child subtree) and the inline
2158
+ // `renderingConditions` property on UIDLElement content. Tracks global and
2159
+ // globalState references on params, resolves the condition identifier — plus
2160
+ // one identifier per entry that carries its own `reference` — and builds the
2161
+ // `condition && <content/>` logical expression.
2162
+ const wrapWithConditional = (
2163
+ subTree: JSXASTReturnType,
2164
+ reference: UIDLConditionalNode['content']['reference'],
2165
+ condition: UIDLConditionalExpression,
2166
+ params: JSXGenerationParams,
2167
+ options: JSXGenerationOptions
2168
+ ): types.LogicalExpression => {
2169
+ const conditionIdentifier = trackAndResolveConditionIdentifier(reference, params, options)
2170
+ return createConditionalJSXExpression(subTree, condition, conditionIdentifier, {
2171
+ localIdentifier: options.localIdentifier,
2172
+ detailsPageExposeAsName: options.detailsPageExposeAsName || params.detailsPageExposeAsName,
2173
+ // Leaf entries (any nesting depth) with their own left side resolve —
2174
+ // and globals-track — through the same path as the top-level reference.
2175
+ resolveEntryIdentifier: (conditionEntry) =>
2176
+ conditionEntry.reference
2177
+ ? trackAndResolveConditionIdentifier(conditionEntry.reference, params, options)
2178
+ : undefined,
2179
+ })
2180
+ }
2181
+
516
2182
  const generateConditionalNode: NodeToJSX<UIDLConditionalNode, types.LogicalExpression[]> = (
517
2183
  node,
518
2184
  params,
519
2185
  options
520
2186
  ) => {
521
2187
  const { reference, value } = node.content
522
- const conditionIdentifier = createConditionIdentifier(reference, params, options)
523
-
524
2188
  const subTrees = generateNode(node.content.node, params, options)
525
2189
 
526
2190
  const condition: UIDLConditionalExpression =
@@ -529,11 +2193,16 @@ const generateConditionalNode: NodeToJSX<UIDLConditionalNode, types.LogicalExpre
529
2193
  : node.content.condition
530
2194
 
531
2195
  return subTrees.map((subTree) =>
532
- createConditionalJSXExpression(subTree, condition, conditionIdentifier)
2196
+ wrapWithConditional(subTree, reference, condition, params, options)
533
2197
  )
534
2198
  }
535
2199
 
536
- const generateCMSListRepeaterNode: NodeToJSX<UIDLCMSListRepeaterNode, types.JSXElement[]> = (
2200
+ // The repeater renders its `loading` branch INSTEAD of itself when the node
2201
+ // carries an `isLoading` signal. Hence `JSXASTReturnType[]` rather than
2202
+ // `types.JSXElement[]`: that form is a conditional EXPRESSION, which the parent
2203
+ // element loop wraps in a `{ … }` container the same way it already does for a
2204
+ // conditional node's logical expression.
2205
+ const generateCMSListRepeaterNode: NodeToJSX<UIDLCMSListRepeaterNode, JSXASTReturnType[]> = (
537
2206
  node,
538
2207
  params,
539
2208
  options
@@ -541,20 +2210,152 @@ const generateCMSListRepeaterNode: NodeToJSX<UIDLCMSListRepeaterNode, types.JSXE
541
2210
  const jsxTag = StringUtils.dashCaseToUpperCamelCase(node.content.elementType)
542
2211
  const repeaterNode = ASTBuilders.createJSXTag(jsxTag, [], true)
543
2212
 
2213
+ const dataNodeIdAttr = (node.content as { attrs?: { dataNodeId?: { content?: string } } }).attrs
2214
+ ?.dataNodeId
2215
+ if (dataNodeIdAttr?.content) {
2216
+ addAttributeToJSXTag(repeaterNode, 'dataNodeId', dataNodeIdAttr.content)
2217
+ }
2218
+
2219
+ // When the repeater source is a global context like "ecommerce", resolve to
2220
+ // the appropriate array from the ecommerce context based on what the repeater
2221
+ // iterates over (determined by renderPropIdentifier). The editor's mapper
2222
+ // keeps only the global's id, not the array's path, so the identifier is the
2223
+ // whole contract: every e-commerce list the editor builds names its context
2224
+ // after one of these keys.
2225
+ let repeaterItemsExpr: types.Expression
2226
+ const source = node.content.source ?? 'params'
2227
+ if (source === 'ecommerce') {
2228
+ const rpId = node.content.renderPropIdentifier || ''
2229
+ // Map renderPropIdentifier to the correct ecommerce context path
2230
+ const ecommercePathMap: Record<string, string[]> = {
2231
+ paymentProvider: ['paymentProviders'],
2232
+ // The providers a cart holding a subscription is offered — the checkout's
2233
+ // second method list. Same fallthrough hazard as `shippingMethod`.
2234
+ subscriptionPaymentProvider: ['subscriptionPaymentProviders'],
2235
+ storeLocation: ['storeLocations'],
2236
+ // The checkout's shipping-method list (`Cart.shippingOptions`). Without
2237
+ // this entry it fell to the cart items below and offered the buyer their
2238
+ // own products as shipping methods.
2239
+ shippingMethod: ['Cart', 'shippingOptions'],
2240
+ // The checkout's "Choose your discount" list, in each fulfilment shape.
2241
+ discountOption: ['Cart', 'discountOptions'],
2242
+ discountOptionPickup: ['Cart', 'discountOptionsPickup'],
2243
+ }
2244
+ // Default: cart items for orderItem, cartItem, or any unrecognized identifier
2245
+ const path = ecommercePathMap[rpId] || ['Cart', 'items']
2246
+
2247
+ let expr: types.Expression = types.identifier('ecommerce')
2248
+ for (const seg of path) {
2249
+ expr = types.optionalMemberExpression(expr, types.identifier(seg), false, true)
2250
+ }
2251
+ repeaterItemsExpr = types.logicalExpression('||', expr, types.arrayExpression([]))
2252
+ params.globalReferences.push('ecommerce' as Parameters<typeof params.globalReferences.push>[0])
2253
+ } else if (source === 'ecommerceCategories') {
2254
+ // The `E-Commerce Categories` global (the nested category tree) is baked
2255
+ // onto the ecommerce context as `ecommerce.ecommerceCategories`. Fixed
2256
+ // one-segment path (independent of the item name) → `ecommerce?.ecommerceCategories || []`.
2257
+ const expr = types.optionalMemberExpression(
2258
+ types.identifier('ecommerce'),
2259
+ types.identifier('ecommerceCategories'),
2260
+ false,
2261
+ true
2262
+ )
2263
+ repeaterItemsExpr = types.logicalExpression('||', expr, types.arrayExpression([]))
2264
+ params.globalReferences.push('ecommerce' as Parameters<typeof params.globalReferences.push>[0])
2265
+ } else if (source === 'blogCategories') {
2266
+ // The `Blog Categories` global. Unlike the store's taxonomy this one is NOT
2267
+ // on a provider context — the generated `@/blog-context` module exposes it
2268
+ // through a memoized `useBlogCategories()` hook, which the component plugin
2269
+ // destructures into a plain `blogCategories` identifier when it sees this
2270
+ // reference. → `blogCategories || []`.
2271
+ repeaterItemsExpr = types.logicalExpression(
2272
+ '||',
2273
+ types.identifier('blogCategories'),
2274
+ types.arrayExpression([])
2275
+ )
2276
+ params.globalReferences.push(
2277
+ 'blogCategories' as Parameters<typeof params.globalReferences.push>[0]
2278
+ )
2279
+ } else if (source === 'helpCategories') {
2280
+ // The Help Center's taxonomy, exposed by the same module as `useHelpCategories()`.
2281
+ repeaterItemsExpr = types.logicalExpression(
2282
+ '||',
2283
+ types.identifier('helpCategories'),
2284
+ types.arrayExpression([])
2285
+ )
2286
+ params.globalReferences.push(
2287
+ 'helpCategories' as Parameters<typeof params.globalReferences.push>[0]
2288
+ )
2289
+ } else if (source === 'bookingCategories') {
2290
+ // The `Booking Categories` global, like the blog's: the generated
2291
+ // `@/booking-context` module's `useBookingCategories()` hook, destructured
2292
+ // into a plain `bookingCategories` identifier. → `bookingCategories || []`.
2293
+ repeaterItemsExpr = types.logicalExpression(
2294
+ '||',
2295
+ types.identifier('bookingCategories'),
2296
+ types.arrayExpression([])
2297
+ )
2298
+ params.globalReferences.push(
2299
+ 'bookingCategories' as Parameters<typeof params.globalReferences.push>[0]
2300
+ )
2301
+ } else {
2302
+ // Resolve any global-state reference encoded in `source` and register it
2303
+ // so the `next-global-state` component plugin destructures the matching
2304
+ // identifier from `useGlobalState()`. Without this, sources emitted as
2305
+ // either `<globalStateName> || []` (modern) or `globalState_<defId>`
2306
+ // (legacy) compile to a `ReferenceError` at render time because the
2307
+ // identifier never enters scope.
2308
+ const resolvedSource = resolveAndRegisterGlobalStateSource(source, params)
2309
+ repeaterItemsExpr = types.identifier(resolvedSource)
2310
+ }
2311
+
544
2312
  repeaterNode.openingElement.attributes.push(
545
2313
  types.jsxAttribute(
546
2314
  types.jsxIdentifier('items'),
547
- types.jsxExpressionContainer(types.identifier(node.content.source ?? 'params'))
2315
+ types.jsxExpressionContainer(repeaterItemsExpr)
2316
+ )
2317
+ )
2318
+
2319
+ const listElement = generateNode(node.content.nodes.list, params, {
2320
+ ...options,
2321
+ localIdentifier: node.content.renderPropIdentifier,
2322
+ dynamicReferencePrefixMap: {
2323
+ ...options.dynamicReferencePrefixMap,
2324
+ ctx: node.content.renderPropIdentifier,
2325
+ },
2326
+ })[0] as types.JSXElement
2327
+
2328
+ // Create key as template literal: `${item?.id}${index}`
2329
+ const keyAttribute = types.jsxAttribute(
2330
+ types.jsxIdentifier('key'),
2331
+ types.jsxExpressionContainer(
2332
+ types.templateLiteral(
2333
+ [
2334
+ types.templateElement({ raw: '', cooked: '' }, false),
2335
+ types.templateElement({ raw: '', cooked: '' }, false),
2336
+ types.templateElement({ raw: '', cooked: '' }, true),
2337
+ ],
2338
+ [
2339
+ types.optionalMemberExpression(
2340
+ types.identifier(node.content.renderPropIdentifier),
2341
+ types.identifier('id'),
2342
+ false,
2343
+ true
2344
+ ),
2345
+ types.identifier('index'),
2346
+ ]
2347
+ )
548
2348
  )
549
2349
  )
2350
+ listElement.openingElement.attributes.push(keyAttribute)
550
2351
 
551
2352
  repeaterNode.openingElement.attributes.push(
552
2353
  types.jsxAttribute(
553
2354
  types.jSXIdentifier('renderItem'),
554
2355
  types.jsxExpressionContainer(
555
2356
  types.arrowFunctionExpression(
556
- [types.identifier(node.content.renderPropIdentifier)],
557
- generateNode(node.content.nodes.list, params, options)[0] as types.JSXElement
2357
+ [types.identifier(node.content.renderPropIdentifier), types.identifier('index')],
2358
+ listElement
558
2359
  )
559
2360
  )
560
2361
  )
@@ -574,10 +2375,58 @@ const generateCMSListRepeaterNode: NodeToJSX<UIDLCMSListRepeaterNode, types.JSXE
574
2375
  )
575
2376
  }
576
2377
 
2378
+ // Generated on EVERY repeater for its side effects — `nodesLookup` registration,
2379
+ // style classes, and the head snippets a loading template rides out on (a
2380
+ // skeleton card's `@keyframes`). Whether the result is also RENDERED depends on
2381
+ // `isLoading` below.
2382
+ let loadingElement: JSXASTReturnType | undefined
2383
+ if ('loading' in node.content.nodes) {
2384
+ loadingElement = generateNode(node.content.nodes.loading, params, options)[0]
2385
+ }
2386
+
577
2387
  if (node.content?.dependency && options.dependencyHandling === 'import') {
578
2388
  params.dependencies[jsxTag] = node.content.dependency
579
2389
  }
580
2390
 
2391
+ // A repeater fed by a DATA SOURCE never carries `isLoading`: it sits inside a
2392
+ // `DataProvider` that owns the fetch, and its loading branch is hoisted onto
2393
+ // that provider's `renderLoading` (`hoistLoadingFromRepeaterToDataSource`).
2394
+ // Emitting it here as well would draw the same branch twice. A repeater fed by
2395
+ // a plain STATE has no provider, so this is the only thing that can tell it a
2396
+ // fetch is in flight — without it the `loading` branch is generated and then
2397
+ // thrown away, which is why a state-backed list used to show its EMPTY branch
2398
+ // for the whole duration of the fetch.
2399
+ const { isLoading } = node.content
2400
+ if (
2401
+ isLoading &&
2402
+ loadingElement &&
2403
+ typeof loadingElement !== 'string' &&
2404
+ // A `JSXExpressionContainer` is only legal as a CHILD, never as a ternary
2405
+ // branch. The loading root is a fragment or an element, so this never fires
2406
+ // in practice — it is here so a future node type cannot emit invalid code.
2407
+ loadingElement.type !== 'JSXExpressionContainer'
2408
+ ) {
2409
+ // `String(x) === 'true'`, never a bare truthiness test. The flag is a page
2410
+ // state, and a generated string state holds the STRING `'false'` when it is
2411
+ // off — which is truthy. `String()` equally accepts a real boolean.
2412
+ const flag =
2413
+ isLoading.type === 'expr'
2414
+ ? ASTUtils.getExpressionFromUIDLExpressionNode(isLoading)
2415
+ : types.stringLiteral(String(isLoading.content))
2416
+
2417
+ return [
2418
+ types.conditionalExpression(
2419
+ types.binaryExpression(
2420
+ '===',
2421
+ types.callExpression(types.identifier('String'), [flag]),
2422
+ types.stringLiteral('true')
2423
+ ),
2424
+ loadingElement,
2425
+ repeaterNode
2426
+ ),
2427
+ ]
2428
+ }
2429
+
581
2430
  return [repeaterNode]
582
2431
  }
583
2432
 
@@ -645,3 +2494,221 @@ const generateNativeSlotNode: NodeToJSX<UIDLSlotNode, types.JSXElement> = (
645
2494
 
646
2495
  return slotNode
647
2496
  }
2497
+
2498
+ const resolveDynamicReferenceExpression = (
2499
+ dynamicRef: UIDLDynamicReference,
2500
+ params: JSXGenerationParams,
2501
+ options: JSXGenerationOptions
2502
+ ): types.Expression => {
2503
+ const { referenceType } = dynamicRef.content
2504
+
2505
+ if (referenceType === 'global') {
2506
+ const normDynRef = normalizeGlobalRef(dynamicRef)
2507
+ params.globalReferences.push(
2508
+ normDynRef.content.id as Parameters<typeof params.globalReferences.push>[0]
2509
+ )
2510
+ return createDynamicValueExpression(normDynRef, options)
2511
+ }
2512
+
2513
+ if ((referenceType as string) === 'globalState') {
2514
+ const gsName = resolveGlobalStateName(dynamicRef.content.id, params.globalStateDefinitions)
2515
+ params.globalStateReferences.push({ id: dynamicRef.content.id, name: gsName })
2516
+ return createGlobalStateExpression(
2517
+ dynamicRef as any,
2518
+ params.globalStateDefinitions
2519
+ ) as types.Expression
2520
+ }
2521
+
2522
+ return createDynamicValueExpression(dynamicRef, options)
2523
+ }
2524
+
2525
+ const applyDynamicHtmlInjection = (
2526
+ elementTag: types.JSXElement,
2527
+ rawValue: UIDLRawValue,
2528
+ params: JSXGenerationParams,
2529
+ options: JSXGenerationOptions
2530
+ ) => {
2531
+ const dynamicExpr = resolveDynamicReferenceExpression(rawValue.dynamic, params, options)
2532
+ const fallbackContent = rawValue.fallback || rawValue.content
2533
+ const fallbackExpr = types.stringLiteral(fallbackContent)
2534
+ const valueExpr = types.logicalExpression('||', dynamicExpr, fallbackExpr)
2535
+
2536
+ ;(elementTag.openingElement.name as types.JSXIdentifier).name = 'span'
2537
+ if (elementTag.closingElement) {
2538
+ ;(elementTag.closingElement.name as types.JSXIdentifier).name = 'span'
2539
+ }
2540
+ elementTag.openingElement.selfClosing = true
2541
+ elementTag.closingElement = null
2542
+ elementTag.children = []
2543
+
2544
+ elementTag.openingElement.attributes.push(
2545
+ types.jsxAttribute(
2546
+ types.jsxIdentifier('dangerouslySetInnerHTML'),
2547
+ types.jsxExpressionContainer(
2548
+ types.objectExpression([types.objectProperty(types.identifier('__html'), valueExpr)])
2549
+ )
2550
+ )
2551
+ )
2552
+
2553
+ Object.keys(params.dependencies).forEach((key) => {
2554
+ if (params.dependencies[key]?.path?.includes('dangerous-html')) {
2555
+ delete params.dependencies[key]
2556
+ }
2557
+ })
2558
+ }
2559
+
2560
+ const applyStaticMarkdownInjection = (
2561
+ elementTag: types.JSXElement,
2562
+ rawValue: UIDLRawValue,
2563
+ params: JSXGenerationParams
2564
+ ) => {
2565
+ injectMarkdownExpression(elementTag, types.stringLiteral(rawValue.content || ''), '', params)
2566
+ }
2567
+
2568
+ const applyDynamicMarkdownInjection = (
2569
+ elementTag: types.JSXElement,
2570
+ rawValue: UIDLRawValue,
2571
+ params: JSXGenerationParams,
2572
+ options: JSXGenerationOptions
2573
+ ) => {
2574
+ const dynamicExpr = resolveDynamicReferenceExpression(rawValue.dynamic, params, options)
2575
+ const fallbackContent = rawValue.fallback || rawValue.content
2576
+ injectMarkdownExpression(elementTag, dynamicExpr, fallbackContent, params)
2577
+ }
2578
+
2579
+ /**
2580
+ * Renders a markdown-node's rich-text content through the `markdown-to-jsx` <Markdown>
2581
+ * component (the React generator's mapping for markdown-node).
2582
+ *
2583
+ * markdown-to-jsx parses BOTH markdown syntax AND embedded HTML, so it renders correctly
2584
+ * whether the CMS field returns markdown (`# Heading`) or HTML markup (`<p>…</p>`). A raw
2585
+ * HTML approach (dangerouslySetInnerHTML) would ignore markdown, and a markdown-only
2586
+ * renderer (react-markdown) escapes HTML — markdown-to-jsx covers both at once.
2587
+ *
2588
+ * Shared by every way a markdown-node can carry its content:
2589
+ * - a static `raw` attribute (see applyStaticMarkdownInjection)
2590
+ * - a `raw` attribute holding a dynamic reference (see applyDynamicMarkdownInjection)
2591
+ * - a dynamic/expr child, e.g. CMS-bound rich text (see generateElementNode)
2592
+ *
2593
+ * Produces: <Markdown>{expr || fallback}</Markdown>
2594
+ */
2595
+ const injectMarkdownExpression = (
2596
+ elementTag: types.JSXElement,
2597
+ expression: types.Expression,
2598
+ fallbackContent: string,
2599
+ params: JSXGenerationParams
2600
+ ) => {
2601
+ // markdown-to-jsx requires a string child; guard dynamic expressions with a fallback so
2602
+ // a nullish CMS value renders as empty rather than throwing. Static literals need no guard.
2603
+ const childExpr = types.isStringLiteral(expression)
2604
+ ? expression
2605
+ : types.logicalExpression('||', expression, types.stringLiteral(fallbackContent || ''))
2606
+
2607
+ ;(elementTag.openingElement.name as types.JSXIdentifier).name = 'Markdown'
2608
+ elementTag.openingElement.selfClosing = false
2609
+ if (!elementTag.closingElement) {
2610
+ elementTag.closingElement = types.jsxClosingElement(types.jsxIdentifier('Markdown'))
2611
+ } else {
2612
+ ;(elementTag.closingElement.name as types.JSXIdentifier).name = 'Markdown'
2613
+ }
2614
+ elementTag.children = [types.jsxExpressionContainer(childExpr)]
2615
+
2616
+ params.dependencies.Markdown = {
2617
+ type: 'package',
2618
+ path: 'markdown-to-jsx',
2619
+ version: '7.7.12',
2620
+ }
2621
+ }
2622
+
2623
+ /**
2624
+ * Handles raw attributes on a rich-text-editor-node element.
2625
+ *
2626
+ * - `html` attribute → becomes a `value` prop (static string or dynamic expression with fallback)
2627
+ * - `quillFormats` attribute → parsed from JSON string into a JS array expression
2628
+ */
2629
+ const applyRichTextEditorRawAttribute = (
2630
+ elementTag: types.JSXElement,
2631
+ attrKey: string,
2632
+ rawValue: UIDLRawValue,
2633
+ params: JSXGenerationParams,
2634
+ options: JSXGenerationOptions
2635
+ ) => {
2636
+ if (attrKey === 'html' && params.formStoreStateName) {
2637
+ return
2638
+ }
2639
+
2640
+ if (attrKey === 'html') {
2641
+ if (rawValue.dynamic) {
2642
+ const dynamicExpr = resolveDynamicReferenceExpression(rawValue.dynamic, params, options)
2643
+ const fallbackContent = rawValue.fallback || rawValue.content || ''
2644
+ const valueExpr = types.logicalExpression(
2645
+ '||',
2646
+ dynamicExpr,
2647
+ types.stringLiteral(fallbackContent)
2648
+ )
2649
+ elementTag.openingElement.attributes.push(
2650
+ types.jsxAttribute(types.jsxIdentifier('value'), types.jsxExpressionContainer(valueExpr))
2651
+ )
2652
+ } else {
2653
+ const content = rawValue.content || ''
2654
+ addAttributeToJSXTag(elementTag, 'value', content)
2655
+ }
2656
+ return
2657
+ }
2658
+
2659
+ if (attrKey === 'quillFormats') {
2660
+ let formats: string[] | null = null
2661
+ try {
2662
+ const parsed = JSON.parse(rawValue.content)
2663
+ if (Array.isArray(parsed)) {
2664
+ formats = parsed
2665
+ }
2666
+ } catch {
2667
+ // Parsing failed → don't add the attribute; component will use all formats
2668
+ }
2669
+
2670
+ if (formats === null) {
2671
+ // Parse failure or not an array → omit attribute so component uses all formats
2672
+ return
2673
+ }
2674
+
2675
+ const arrayExpr = types.arrayExpression(formats.map((f) => types.stringLiteral(f)))
2676
+ elementTag.openingElement.attributes.push(
2677
+ types.jsxAttribute(
2678
+ types.jsxIdentifier('quillFormats'),
2679
+ types.jsxExpressionContainer(arrayExpr)
2680
+ )
2681
+ )
2682
+ return
2683
+ }
2684
+
2685
+ // Any other raw attribute on rich-text-editor-node: fall through to default handling
2686
+ addRawAttributeToJSXTag(elementTag, attrKey, rawValue)
2687
+ }
2688
+
2689
+ /**
2690
+ * `color: red; margin-top: 4px` → `{ color: 'red', marginTop: '4px' }`, the
2691
+ * shape React wants for `style`. Custom properties keep their `--name`.
2692
+ */
2693
+ function parseInlineStyleText(value: unknown): Record<string, string> | undefined {
2694
+ if (typeof value !== 'string') {
2695
+ return undefined
2696
+ }
2697
+ const inlineStyle: Record<string, string> = {}
2698
+ value.split(';').forEach((declaration) => {
2699
+ const separator = declaration.indexOf(':')
2700
+ if (separator < 1) {
2701
+ return
2702
+ }
2703
+ const property = declaration.slice(0, separator).trim()
2704
+ const propertyValue = declaration.slice(separator + 1).trim()
2705
+ if (!property || !propertyValue) {
2706
+ return
2707
+ }
2708
+ const key = property.startsWith('--')
2709
+ ? property
2710
+ : StringUtils.cssPropertyToInlineStyleKey(property)
2711
+ inlineStyle[key] = propertyValue
2712
+ })
2713
+ return inlineStyle
2714
+ }