@teleporthq/teleport-plugin-common 0.44.0-alpha.0 → 0.44.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/builders/html-builders.ts +9 -2
- package/__tests__/builders/style-builders.ts +23 -0
- package/__tests__/node-handlers/node-to-html/index.ts +2 -0
- package/__tests__/node-handlers/node-to-jsx/attribute-value-mapper.ts +77 -0
- package/__tests__/node-handlers/node-to-jsx/calendar-events-reviver.ts +176 -0
- package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-ecommerce-source.ts +79 -0
- package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-loading.ts +122 -0
- package/__tests__/node-handlers/node-to-jsx/index.ts +719 -3
- package/__tests__/node-handlers/node-to-jsx/url-search-params-expression.ts +59 -0
- package/__tests__/node-handlers/node-to-jsx/utils.ts +602 -3
- package/__tests__/utils/ast-utils.ts +188 -0
- package/__tests__/utils/content-property-sanitiser.ts +156 -0
- package/__tests__/utils/page-seeds-state-from-data-source.ts +70 -0
- package/__tests__/utils/parse-string-with-template-expressions.ts +82 -0
- package/__tests__/utils/resource-auth-scheme.ts +55 -0
- package/__tests__/utils/route-utils.ts +118 -0
- package/__tests__/utils/style-utils.ts +59 -0
- package/__tests__/utils/template-expression-balance.ts +83 -0
- package/__tests__/utils/url-query-writer.ts +239 -0
- package/__tests__/utils/url-search-param-sync.ts +138 -0
- package/__tests__/utils/url-search-params.ts +48 -0
- package/dist/cjs/builders/ast-builders.d.ts +2 -0
- package/dist/cjs/builders/ast-builders.d.ts.map +1 -1
- package/dist/cjs/builders/ast-builders.js +41 -3
- package/dist/cjs/builders/ast-builders.js.map +1 -1
- package/dist/cjs/builders/hast-builders.d.ts +1 -0
- package/dist/cjs/builders/hast-builders.d.ts.map +1 -1
- package/dist/cjs/builders/hast-builders.js +11 -1
- package/dist/cjs/builders/hast-builders.js.map +1 -1
- package/dist/cjs/builders/style-builders.d.ts +8 -2
- package/dist/cjs/builders/style-builders.d.ts.map +1 -1
- package/dist/cjs/builders/style-builders.js +65 -19
- package/dist/cjs/builders/style-builders.js.map +1 -1
- package/dist/cjs/index.d.ts +5 -1
- package/dist/cjs/index.d.ts.map +1 -1
- package/dist/cjs/index.js +9 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/constants.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/constants.js +2 -0
- package/dist/cjs/node-handlers/node-to-html/constants.js.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/index.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/index.js +69 -1
- package/dist/cjs/node-handlers/node-to-html/index.js.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/types.d.ts +5 -1
- package/dist/cjs/node-handlers/node-to-html/types.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/utils.d.ts +2 -1
- package/dist/cjs/node-handlers/node-to-html/utils.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-html/utils.js +174 -13
- package/dist/cjs/node-handlers/node-to-html/utils.js.map +1 -1
- package/dist/cjs/node-handlers/node-to-jsx/index.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-jsx/index.js +1461 -66
- package/dist/cjs/node-handlers/node-to-jsx/index.js.map +1 -1
- package/dist/cjs/node-handlers/node-to-jsx/types.d.ts +60 -6
- package/dist/cjs/node-handlers/node-to-jsx/types.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts +73 -7
- package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
- package/dist/cjs/node-handlers/node-to-jsx/utils.js +864 -71
- package/dist/cjs/node-handlers/node-to-jsx/utils.js.map +1 -1
- package/dist/cjs/tsconfig.tsbuildinfo +1 -1
- package/dist/cjs/utils/ast-utils.d.ts +142 -11
- package/dist/cjs/utils/ast-utils.d.ts.map +1 -1
- package/dist/cjs/utils/ast-utils.js +931 -75
- package/dist/cjs/utils/ast-utils.js.map +1 -1
- package/dist/cjs/utils/hast-utils.d.ts +8 -6
- package/dist/cjs/utils/hast-utils.d.ts.map +1 -1
- package/dist/cjs/utils/hast-utils.js +28 -4
- package/dist/cjs/utils/hast-utils.js.map +1 -1
- package/dist/cjs/utils/route-utils.d.ts +117 -0
- package/dist/cjs/utils/route-utils.d.ts.map +1 -0
- package/dist/cjs/utils/route-utils.js +212 -0
- package/dist/cjs/utils/route-utils.js.map +1 -0
- package/dist/cjs/utils/style-utils.d.ts +1 -0
- package/dist/cjs/utils/style-utils.d.ts.map +1 -1
- package/dist/cjs/utils/style-utils.js +181 -2
- package/dist/cjs/utils/style-utils.js.map +1 -1
- package/dist/cjs/utils/template-expression-balance.d.ts +58 -0
- package/dist/cjs/utils/template-expression-balance.d.ts.map +1 -0
- package/dist/cjs/utils/template-expression-balance.js +181 -0
- package/dist/cjs/utils/template-expression-balance.js.map +1 -0
- package/dist/cjs/utils/types.d.ts +3 -0
- package/dist/cjs/utils/types.d.ts.map +1 -0
- package/dist/cjs/utils/types.js +3 -0
- package/dist/cjs/utils/types.js.map +1 -0
- package/dist/cjs/utils/url-query-writer.d.ts +123 -0
- package/dist/cjs/utils/url-query-writer.d.ts.map +1 -0
- package/dist/cjs/utils/url-query-writer.js +260 -0
- package/dist/cjs/utils/url-query-writer.js.map +1 -0
- package/dist/cjs/utils/url-search-param-sync.d.ts +4 -0
- package/dist/cjs/utils/url-search-param-sync.d.ts.map +1 -0
- package/dist/cjs/utils/url-search-param-sync.js +241 -0
- package/dist/cjs/utils/url-search-param-sync.js.map +1 -0
- package/dist/cjs/utils/url-search-params.d.ts +48 -0
- package/dist/cjs/utils/url-search-params.d.ts.map +1 -0
- package/dist/cjs/utils/url-search-params.js +109 -0
- package/dist/cjs/utils/url-search-params.js.map +1 -0
- package/dist/esm/builders/ast-builders.d.ts +2 -0
- package/dist/esm/builders/ast-builders.d.ts.map +1 -1
- package/dist/esm/builders/ast-builders.js +40 -4
- package/dist/esm/builders/ast-builders.js.map +1 -1
- package/dist/esm/builders/hast-builders.d.ts +1 -0
- package/dist/esm/builders/hast-builders.d.ts.map +1 -1
- package/dist/esm/builders/hast-builders.js +9 -0
- package/dist/esm/builders/hast-builders.js.map +1 -1
- package/dist/esm/builders/style-builders.d.ts +8 -2
- package/dist/esm/builders/style-builders.d.ts.map +1 -1
- package/dist/esm/builders/style-builders.js +63 -18
- package/dist/esm/builders/style-builders.js.map +1 -1
- package/dist/esm/index.d.ts +5 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +5 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node-handlers/node-to-html/constants.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-html/constants.js +2 -0
- package/dist/esm/node-handlers/node-to-html/constants.js.map +1 -1
- package/dist/esm/node-handlers/node-to-html/index.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-html/index.js +71 -3
- package/dist/esm/node-handlers/node-to-html/index.js.map +1 -1
- package/dist/esm/node-handlers/node-to-html/types.d.ts +5 -1
- package/dist/esm/node-handlers/node-to-html/types.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-html/utils.d.ts +2 -1
- package/dist/esm/node-handlers/node-to-html/utils.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-html/utils.js +170 -13
- package/dist/esm/node-handlers/node-to-html/utils.js.map +1 -1
- package/dist/esm/node-handlers/node-to-jsx/index.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-jsx/index.js +1460 -68
- package/dist/esm/node-handlers/node-to-jsx/index.js.map +1 -1
- package/dist/esm/node-handlers/node-to-jsx/types.d.ts +60 -6
- package/dist/esm/node-handlers/node-to-jsx/types.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-jsx/utils.d.ts +73 -7
- package/dist/esm/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
- package/dist/esm/node-handlers/node-to-jsx/utils.js +857 -69
- package/dist/esm/node-handlers/node-to-jsx/utils.js.map +1 -1
- package/dist/esm/tsconfig.tsbuildinfo +1 -1
- package/dist/esm/utils/ast-utils.d.ts +142 -11
- package/dist/esm/utils/ast-utils.d.ts.map +1 -1
- package/dist/esm/utils/ast-utils.js +911 -75
- package/dist/esm/utils/ast-utils.js.map +1 -1
- package/dist/esm/utils/hast-utils.d.ts +8 -6
- package/dist/esm/utils/hast-utils.d.ts.map +1 -1
- package/dist/esm/utils/hast-utils.js +26 -3
- package/dist/esm/utils/hast-utils.js.map +1 -1
- package/dist/esm/utils/route-utils.d.ts +117 -0
- package/dist/esm/utils/route-utils.d.ts.map +1 -0
- package/dist/esm/utils/route-utils.js +179 -0
- package/dist/esm/utils/route-utils.js.map +1 -0
- package/dist/esm/utils/style-utils.d.ts +1 -0
- package/dist/esm/utils/style-utils.d.ts.map +1 -1
- package/dist/esm/utils/style-utils.js +179 -1
- package/dist/esm/utils/style-utils.js.map +1 -1
- package/dist/esm/utils/template-expression-balance.d.ts +58 -0
- package/dist/esm/utils/template-expression-balance.d.ts.map +1 -0
- package/dist/esm/utils/template-expression-balance.js +174 -0
- package/dist/esm/utils/template-expression-balance.js.map +1 -0
- package/dist/esm/utils/types.d.ts +3 -0
- package/dist/esm/utils/types.d.ts.map +1 -0
- package/dist/esm/utils/types.js +2 -0
- package/dist/esm/utils/types.js.map +1 -0
- package/dist/esm/utils/url-query-writer.d.ts +123 -0
- package/dist/esm/utils/url-query-writer.d.ts.map +1 -0
- package/dist/esm/utils/url-query-writer.js +229 -0
- package/dist/esm/utils/url-query-writer.js.map +1 -0
- package/dist/esm/utils/url-search-param-sync.d.ts +4 -0
- package/dist/esm/utils/url-search-param-sync.d.ts.map +1 -0
- package/dist/esm/utils/url-search-param-sync.js +213 -0
- package/dist/esm/utils/url-search-param-sync.js.map +1 -0
- package/dist/esm/utils/url-search-params.d.ts +48 -0
- package/dist/esm/utils/url-search-params.d.ts.map +1 -0
- package/dist/esm/utils/url-search-params.js +81 -0
- package/dist/esm/utils/url-search-params.js.map +1 -0
- package/package.json +4 -4
- package/src/builders/ast-builders.ts +80 -3
- package/src/builders/hast-builders.ts +11 -0
- package/src/builders/style-builders.ts +107 -27
- package/src/index.ts +18 -1
- package/src/node-handlers/node-to-html/constants.ts +2 -0
- package/src/node-handlers/node-to-html/index.ts +126 -6
- package/src/node-handlers/node-to-html/types.ts +6 -0
- package/src/node-handlers/node-to-html/utils.ts +228 -14
- package/src/node-handlers/node-to-jsx/index.ts +2219 -111
- package/src/node-handlers/node-to-jsx/types.ts +75 -32
- package/src/node-handlers/node-to-jsx/utils.ts +1142 -84
- package/src/utils/ast-utils.ts +1223 -127
- package/src/utils/hast-utils.ts +37 -9
- package/src/utils/route-utils.ts +214 -0
- package/src/utils/style-utils.ts +183 -1
- package/src/utils/template-expression-balance.ts +196 -0
- package/src/utils/types.ts +25 -0
- package/src/utils/url-query-writer.ts +318 -0
- package/src/utils/url-search-param-sync.ts +303 -0
- package/src/utils/url-search-params.ts +122 -0
package/src/utils/ast-utils.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as types from '@babel/types'
|
|
2
2
|
import { parse } from '@babel/core'
|
|
3
3
|
import ParsedASTNode from './parsed-ast'
|
|
4
|
-
import { StringUtils } from '@teleporthq/teleport-shared'
|
|
4
|
+
import { JSIdentifiers, StringUtils, UIDLUtils } from '@teleporthq/teleport-shared'
|
|
5
5
|
import {
|
|
6
6
|
UIDLStateDefinition,
|
|
7
7
|
UIDLPropDefinition,
|
|
@@ -12,25 +12,77 @@ import {
|
|
|
12
12
|
UIDLPropValue,
|
|
13
13
|
UIDLExpressionValue,
|
|
14
14
|
UIDLStateValue,
|
|
15
|
+
HastNode,
|
|
15
16
|
} from '@teleporthq/teleport-types'
|
|
16
17
|
import babelPresetReact from '@babel/preset-react'
|
|
17
|
-
import {
|
|
18
|
+
import { UnaryOperation, BinaryOperator } from './types'
|
|
19
|
+
import { balanceExpression, countUnclosedStaticParens } from './template-expression-balance'
|
|
18
20
|
|
|
19
21
|
/**
|
|
20
|
-
*
|
|
22
|
+
* Converts HTML attribute names to React/JSX camelCase format
|
|
23
|
+
* Preserves data-* and aria-* attributes as-is
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* React sets attributes on CUSTOM ELEMENTS (dash-named tags) verbatim, so
|
|
27
|
+
* camelCasing them is not just unnecessary — it breaks the element:
|
|
28
|
+
* `camera-controls` camelCased to `cameraControls` reaches the DOM as the
|
|
29
|
+
* meaningless `cameracontrols`. Web-component tags keep their attribute
|
|
30
|
+
* spelling untouched.
|
|
31
|
+
*/
|
|
32
|
+
export const isCustomElementTagName = (jsxNode: types.JSXElement): boolean => {
|
|
33
|
+
const name = jsxNode.openingElement.name
|
|
34
|
+
return name.type === 'JSXIdentifier' && name.name.includes('-')
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const resolveAttributeNameForTag = (jsxNode: types.JSXElement, attrName: string): string => {
|
|
38
|
+
return isCustomElementTagName(jsxNode) ? attrName : convertToReactAttributeName(attrName)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const convertToReactAttributeName = (attrName: string): string => {
|
|
42
|
+
if (attrName.startsWith('data-') || attrName.startsWith('aria-')) {
|
|
43
|
+
return attrName
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const htmlToReact: Record<string, string> = {
|
|
47
|
+
colspan: 'colSpan',
|
|
48
|
+
rowspan: 'rowSpan',
|
|
49
|
+
maxlength: 'maxLength',
|
|
50
|
+
minlength: 'minLength',
|
|
51
|
+
readonly: 'readOnly',
|
|
52
|
+
autocomplete: 'autoComplete',
|
|
53
|
+
autofocus: 'autoFocus',
|
|
54
|
+
tabindex: 'tabIndex',
|
|
55
|
+
contenteditable: 'contentEditable',
|
|
56
|
+
spellcheck: 'spellCheck',
|
|
57
|
+
}
|
|
58
|
+
if (htmlToReact[attrName]) {
|
|
59
|
+
return htmlToReact[attrName]
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
return attrName.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Adds a CSS class definition string to an existing string of classes
|
|
21
67
|
*/
|
|
22
68
|
export const addClassStringOnJSXTag = (
|
|
23
69
|
jsxNode: types.JSXElement,
|
|
24
70
|
classString: string,
|
|
25
71
|
classAttributeName?: string,
|
|
26
|
-
dynamicValues: Array<types.MemberExpression | types.Identifier> = []
|
|
72
|
+
dynamicValues: Array<types.MemberExpression | types.Identifier | types.ConditionalExpression> = []
|
|
27
73
|
) => {
|
|
28
|
-
|
|
74
|
+
if (classString === '' && dynamicValues.length === 0) {
|
|
75
|
+
return
|
|
76
|
+
}
|
|
29
77
|
|
|
78
|
+
const classAttribute = getClassAttribute(jsxNode, { createIfNotFound: true, classAttributeName })
|
|
30
79
|
if (dynamicValues.length === 0) {
|
|
31
80
|
if (classAttribute.value && classAttribute.value.type === 'StringLiteral') {
|
|
32
81
|
const classArray = classAttribute.value.value.split(' ')
|
|
33
|
-
|
|
82
|
+
if (classString) {
|
|
83
|
+
classArray.push(classString)
|
|
84
|
+
}
|
|
85
|
+
classArray.filter((item) => item)
|
|
34
86
|
classAttribute.value.value = classArray.join(' ').trim()
|
|
35
87
|
} else {
|
|
36
88
|
throw new Error(
|
|
@@ -43,7 +95,9 @@ export const addClassStringOnJSXTag = (
|
|
|
43
95
|
if (classAttribute.value && classAttribute.value.type === 'StringLiteral') {
|
|
44
96
|
const classArray = classAttribute.value.value.split(' ')
|
|
45
97
|
const quasis: types.TemplateElement[] = []
|
|
46
|
-
const expression: Array<
|
|
98
|
+
const expression: Array<
|
|
99
|
+
types.MemberExpression | types.Identifier | types.ConditionalExpression
|
|
100
|
+
> = []
|
|
47
101
|
|
|
48
102
|
quasis.push(
|
|
49
103
|
types.templateElement({
|
|
@@ -102,13 +156,19 @@ export const addDynamicAttributeToJSXTag = (
|
|
|
102
156
|
prefix: string = '',
|
|
103
157
|
t = types
|
|
104
158
|
) => {
|
|
159
|
+
const reactName = resolveAttributeNameForTag(jsxASTNode, name)
|
|
160
|
+
// Same rule as `createDynamicValueExpression`: with no prefix the value IS the
|
|
161
|
+
// binding (React hooks state), so it must match the sanitised name
|
|
162
|
+
// `createStateHookAST` declared — `value={class}` does not parse. With a
|
|
163
|
+
// prefix it is `props.class` / `this.class`, where the UIDL spelling is legal
|
|
164
|
+
// AND load-bearing, so it is left alone.
|
|
105
165
|
const content =
|
|
106
166
|
prefix === ''
|
|
107
|
-
? t.identifier(value)
|
|
167
|
+
? t.identifier(JSIdentifiers.createSafeJSIdentifierPath(value))
|
|
108
168
|
: t.memberExpression(t.identifier(prefix), t.identifier(value))
|
|
109
169
|
|
|
110
170
|
jsxASTNode.openingElement.attributes.push(
|
|
111
|
-
t.jsxAttribute(t.jsxIdentifier(
|
|
171
|
+
t.jsxAttribute(t.jsxIdentifier(reactName), t.jsxExpressionContainer(content))
|
|
112
172
|
)
|
|
113
173
|
}
|
|
114
174
|
|
|
@@ -118,6 +178,53 @@ export const addDynamicAttributeToJSXTag = (
|
|
|
118
178
|
* the corresponding value from the contexts for now
|
|
119
179
|
* and in the future with other sources.
|
|
120
180
|
*/
|
|
181
|
+
/**
|
|
182
|
+
* UIDL `expr` values are opaque JavaScript expressions, but authoring tools
|
|
183
|
+
* (notably Teleport-GUI while the differentiator-navlink contract is mid-
|
|
184
|
+
* migration) occasionally emit malformed template literals with empty
|
|
185
|
+
* substitutions like `` `/profile/${}` ``. Babel rejects these and the whole
|
|
186
|
+
* generation run fails.
|
|
187
|
+
*
|
|
188
|
+
* We only repair a narrow set of known-safe patterns to avoid silently
|
|
189
|
+
* masking real UIDL bugs:
|
|
190
|
+
* 1. `/profile/${}` → `/profile/${currentUser?.id}` (My Profile navlink
|
|
191
|
+
* per the dual-mode profile page contract).
|
|
192
|
+
* 2. any remaining empty `${}` → `${''}` — at least the output parses and
|
|
193
|
+
* the placeholder is visibly empty at runtime.
|
|
194
|
+
* Each repair logs a warning so the upstream UIDL bug remains visible.
|
|
195
|
+
*/
|
|
196
|
+
export const sanitizeExprContent = (content: string, attrKey?: string): string => {
|
|
197
|
+
if (typeof content !== 'string' || !content.includes('${}')) {
|
|
198
|
+
return content
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let repaired = content
|
|
202
|
+
|
|
203
|
+
// My Profile navlink: the differentiator is always the session user's id.
|
|
204
|
+
repaired = repaired.replace(
|
|
205
|
+
/`([^`]*\/profile\/)\$\{\}([^`]*)`/g,
|
|
206
|
+
'`$1' + '$' + '{' + 'currentUser?.id}' + '$2`'
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
// Generic fallback: any other empty `${}` becomes an empty string literal so
|
|
210
|
+
// downstream Babel parsing succeeds. This is intentionally lossy — the goal
|
|
211
|
+
// is not to guess the original intent, just to keep the build from crashing.
|
|
212
|
+
if (repaired.includes('${}')) {
|
|
213
|
+
repaired = repaired.replace(/\$\{\}/g, '$' + '{' + "'" + "'" + '}')
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
if (repaired !== content) {
|
|
217
|
+
// tslint:disable-next-line:no-console
|
|
218
|
+
console.warn(
|
|
219
|
+
`[teleport] Repaired malformed empty template substitution in expr${
|
|
220
|
+
attrKey ? ` attribute "${attrKey}"` : ''
|
|
221
|
+
}: ${content} → ${repaired}`
|
|
222
|
+
)
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
return repaired
|
|
226
|
+
}
|
|
227
|
+
|
|
121
228
|
export const addDynamicExpressionAttributeToJSXTag = (
|
|
122
229
|
jsxASTNode: types.JSXElement,
|
|
123
230
|
dynamicRef: UIDLExpressionValue,
|
|
@@ -129,7 +236,7 @@ export const addDynamicExpressionAttributeToJSXTag = (
|
|
|
129
236
|
throw new Error(`This method only works with dynamic nodes that have code expressions`)
|
|
130
237
|
}
|
|
131
238
|
|
|
132
|
-
const code = dynamicContent
|
|
239
|
+
const code = sanitizeExprContent(dynamicContent, attrKey)
|
|
133
240
|
const options = {
|
|
134
241
|
sourceType: 'module' as const,
|
|
135
242
|
}
|
|
@@ -148,10 +255,33 @@ export const addDynamicExpressionAttributeToJSXTag = (
|
|
|
148
255
|
throw new Error(`Expr dynamic attribute only support expressions statements at the moment.`)
|
|
149
256
|
}
|
|
150
257
|
|
|
258
|
+
let expression = theStatementOnlyWihtoutTheProgram.expression
|
|
259
|
+
|
|
260
|
+
// When an expression accesses `.value` on a simple identifier (e.g. `galleryImage?.value`),
|
|
261
|
+
// wrap it with a typeof check so that if the item is already a string we use it directly:
|
|
262
|
+
// `typeof galleryImage === 'string' ? galleryImage : galleryImage?.value`
|
|
263
|
+
if (
|
|
264
|
+
(expression.type === 'OptionalMemberExpression' || expression.type === 'MemberExpression') &&
|
|
265
|
+
expression.object.type === 'Identifier' &&
|
|
266
|
+
expression.property.type === 'Identifier' &&
|
|
267
|
+
expression.property.name === 'value'
|
|
268
|
+
) {
|
|
269
|
+
const varName = expression.object.name
|
|
270
|
+
expression = t.conditionalExpression(
|
|
271
|
+
t.binaryExpression(
|
|
272
|
+
'===',
|
|
273
|
+
t.unaryExpression('typeof', t.identifier(varName)),
|
|
274
|
+
t.stringLiteral('string')
|
|
275
|
+
),
|
|
276
|
+
t.identifier(varName),
|
|
277
|
+
expression
|
|
278
|
+
)
|
|
279
|
+
}
|
|
280
|
+
|
|
151
281
|
jsxASTNode.openingElement.attributes.push(
|
|
152
282
|
t.jsxAttribute(
|
|
153
|
-
t.jsxIdentifier(attrKey),
|
|
154
|
-
t.jsxExpressionContainer(
|
|
283
|
+
t.jsxIdentifier(convertToReactAttributeName(attrKey)),
|
|
284
|
+
t.jsxExpressionContainer(expression)
|
|
155
285
|
)
|
|
156
286
|
)
|
|
157
287
|
}
|
|
@@ -164,17 +294,21 @@ export const addDynamicExpressionAttributeToJSXTag = (
|
|
|
164
294
|
export const addMultipleDynamicAttributesToJSXTag = (
|
|
165
295
|
jsxASTNode: types.JSXElement,
|
|
166
296
|
name: string,
|
|
167
|
-
attrValues: Array<types.MemberExpression | types.Identifier> = [],
|
|
297
|
+
attrValues: Array<types.MemberExpression | types.Identifier | types.StringLiteral> = [],
|
|
168
298
|
t = types
|
|
169
299
|
) => {
|
|
170
|
-
const memberExpressions: Array<types.Identifier | types.MemberExpression> =
|
|
300
|
+
const memberExpressions: Array<types.Identifier | types.MemberExpression | types.StringLiteral> =
|
|
301
|
+
[]
|
|
171
302
|
const templateElements: types.TemplateElement[] = []
|
|
172
|
-
|
|
173
303
|
if (attrValues.length === 0) {
|
|
174
304
|
return
|
|
175
305
|
}
|
|
176
306
|
|
|
177
|
-
let content:
|
|
307
|
+
let content:
|
|
308
|
+
| types.TemplateLiteral
|
|
309
|
+
| types.MemberExpression
|
|
310
|
+
| types.Identifier
|
|
311
|
+
| types.StringLiteral
|
|
178
312
|
if (attrValues.length === 1) {
|
|
179
313
|
content = attrValues[0]
|
|
180
314
|
} else {
|
|
@@ -210,26 +344,242 @@ export const stringAsTemplateLiteral = (str: string): types.TemplateLiteral => {
|
|
|
210
344
|
return container.expression as types.TemplateLiteral
|
|
211
345
|
}
|
|
212
346
|
|
|
347
|
+
/**
|
|
348
|
+
* Checks if a string contains {{ expression }} template patterns
|
|
349
|
+
*/
|
|
350
|
+
export const containsTemplateExpression = (str: string): boolean => {
|
|
351
|
+
return /\{\{.+?\}\}/.test(str)
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Parses a JavaScript expression string into an AST Expression node.
|
|
356
|
+
* e.g. "item.type || 'coin'" → LogicalExpression AST
|
|
357
|
+
*/
|
|
358
|
+
export const parseJSExpressionAsAST = (expr: string): types.Expression => {
|
|
359
|
+
const ast = parse(`(${expr})`, {
|
|
360
|
+
sourceType: 'module',
|
|
361
|
+
})
|
|
362
|
+
|
|
363
|
+
if (!ast || !('program' in ast)) {
|
|
364
|
+
throw new Error(`Failed to parse expression: ${expr}`)
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
return (ast.program.body[0] as types.ExpressionStatement).expression
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Parses a string containing {{ expr }} template patterns into a TemplateLiteral AST node.
|
|
372
|
+
* e.g. "translate({{ enemy.x || '0' }}px)" → `translate(${enemy.x || '0'}px)`
|
|
373
|
+
*/
|
|
374
|
+
export const parseStringWithTemplateExpressions = (str: string): types.TemplateLiteral => {
|
|
375
|
+
// Step 1: Normalize state references: state.xxx → xxx
|
|
376
|
+
const normalized = str.replace(/state\.(\w+)/g, '$1')
|
|
377
|
+
|
|
378
|
+
// Step 2: Convert well-formed {{ expr }} to ${expr}
|
|
379
|
+
//
|
|
380
|
+
// The expression is BALANCED on the way in. A binding that lost a closing
|
|
381
|
+
// paren upstream (`-(cameraX || ''`) produces source Babel cannot parse, and
|
|
382
|
+
// no amount of patching the static text around it can help — the repair has
|
|
383
|
+
// to happen inside the interpolation, which is the only place the bracket is
|
|
384
|
+
// actually missing.
|
|
385
|
+
let templateStr = normalized.replace(
|
|
386
|
+
/\{\{\s*(.+?)\s*\}\}/g,
|
|
387
|
+
(_, expr: string) => '${' + balanceExpression(expr.trim()) + '}'
|
|
388
|
+
)
|
|
389
|
+
|
|
390
|
+
// Step 3: Handle unclosed {{ expr (no closing }})
|
|
391
|
+
// After step 2, any remaining {{ was not well-formed
|
|
392
|
+
if (/\{\{/.test(templateStr)) {
|
|
393
|
+
templateStr = templateStr.replace(
|
|
394
|
+
/\{\{\s*(.+?)$/gm,
|
|
395
|
+
(_, expr: string) => '${' + balanceExpression(expr.trim()) + '}'
|
|
396
|
+
)
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// Step 4: Detect and fix incomplete CSS function calls
|
|
400
|
+
// If the original string contained a CSS function like translateX(...) or translate(...)
|
|
401
|
+
// but the template expression consumed the closing, we need to re-close it.
|
|
402
|
+
//
|
|
403
|
+
// Counted over the STATIC text only. Including the parentheses inside `${…}`
|
|
404
|
+
// made an imbalance in the expression look like an unclosed CSS function, so
|
|
405
|
+
// this step appended a unit and a `)` to the end of a string whose real fault
|
|
406
|
+
// was several characters earlier and inside the interpolation.
|
|
407
|
+
const missingStaticCloses = countUnclosedStaticParens(templateStr)
|
|
408
|
+
if (missingStaticCloses > 0) {
|
|
409
|
+
// Determine the CSS unit by:
|
|
410
|
+
// 1. Looking for existing units already in the string (e.g. "translate(${x}px, ${y" → px)
|
|
411
|
+
// 2. Inferring from the CSS function name
|
|
412
|
+
const existingUnit = templateStr.match(/(px|deg|em|rem|%|vh|vw)[),\s]/)
|
|
413
|
+
let unit = 'px' // default
|
|
414
|
+
if (existingUnit) {
|
|
415
|
+
unit = existingUnit[1]
|
|
416
|
+
} else {
|
|
417
|
+
// Infer unit from the CSS function name
|
|
418
|
+
const fnMatch = templateStr.match(/\b(rotate|skew|skewX|skewY)\s*\(/)
|
|
419
|
+
if (fnMatch) {
|
|
420
|
+
unit = 'deg'
|
|
421
|
+
}
|
|
422
|
+
const noUnitFns = /\b(scale|scaleX|scaleY|scale3d|opacity)\s*\(/
|
|
423
|
+
if (noUnitFns.test(templateStr)) {
|
|
424
|
+
unit = ''
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
templateStr += unit + ')'.repeat(missingStaticCloses)
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// Step 5: Parse — and NEVER let a single malformed binding abort the build.
|
|
432
|
+
//
|
|
433
|
+
// The inline-style caller has no error handling of its own, so an
|
|
434
|
+
// unparseable template used to escape as a raw Babel SyntaxError and take the
|
|
435
|
+
// whole project generation down with it. A UIDL can always carry a binding
|
|
436
|
+
// this module cannot rescue (hand-edited, produced by an older pipeline, or
|
|
437
|
+
// broken in a way `balanceExpression` refuses to guess at), and the right
|
|
438
|
+
// answer is to degrade that ONE value: emit the original text as a plain
|
|
439
|
+
// string so the property still renders and the other 99 pages still build.
|
|
440
|
+
try {
|
|
441
|
+
const ast = parse('const x = `' + templateStr + '`', {
|
|
442
|
+
sourceType: 'module',
|
|
443
|
+
})
|
|
444
|
+
|
|
445
|
+
if (ast && 'program' in ast) {
|
|
446
|
+
const decl = ast.program.body[0] as types.VariableDeclaration
|
|
447
|
+
return decl.declarations[0].init as types.TemplateLiteral
|
|
448
|
+
}
|
|
449
|
+
} catch {
|
|
450
|
+
// Fall through to the static fallback below.
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
return staticTemplateLiteral(stripTemplateExpressions(str))
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* Drop every `{{ … }}` binding from a string, keeping any `'literal'` fallback
|
|
458
|
+
* it declared. `translateX({{ -(x || 0) }}px)` → `translateX(px)` is useless as
|
|
459
|
+
* a style value, but `{{ name || 'Guest' }}` → `Guest` keeps the text the
|
|
460
|
+
* author intended. Used only when the expression could not be parsed at all.
|
|
461
|
+
*/
|
|
462
|
+
const stripTemplateExpressions = (value: string): string =>
|
|
463
|
+
value.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, (_, expr: string) => {
|
|
464
|
+
const literalFallback = /\|\|\s*(['"])([\s\S]*?)\1\s*$/.exec(expr)
|
|
465
|
+
return literalFallback ? literalFallback[2] : ''
|
|
466
|
+
})
|
|
467
|
+
|
|
468
|
+
/** A TemplateLiteral with no interpolations, holding `value` verbatim. */
|
|
469
|
+
const staticTemplateLiteral = (value: string): types.TemplateLiteral =>
|
|
470
|
+
types.templateLiteral(
|
|
471
|
+
[types.templateElement({ raw: value.replace(/[\\`]/g, '\\$&'), cooked: value }, true)],
|
|
472
|
+
[]
|
|
473
|
+
)
|
|
474
|
+
|
|
475
|
+
const REACT_BOOLEAN_DOM_PROPS = new Set([
|
|
476
|
+
'disabled',
|
|
477
|
+
'required',
|
|
478
|
+
'readOnly',
|
|
479
|
+
'checked',
|
|
480
|
+
'multiple',
|
|
481
|
+
'hidden',
|
|
482
|
+
'autoFocus',
|
|
483
|
+
'muted',
|
|
484
|
+
'loop',
|
|
485
|
+
'playsInline',
|
|
486
|
+
'autoPlay',
|
|
487
|
+
'controls',
|
|
488
|
+
'async',
|
|
489
|
+
'defer',
|
|
490
|
+
'inert',
|
|
491
|
+
'scoped',
|
|
492
|
+
'reversed',
|
|
493
|
+
'allowFullScreen',
|
|
494
|
+
'defaultChecked',
|
|
495
|
+
'selected',
|
|
496
|
+
'formNoValidate',
|
|
497
|
+
'noValidate',
|
|
498
|
+
])
|
|
499
|
+
|
|
213
500
|
export const addAttributeToJSXTag = (
|
|
214
501
|
jsxNode: types.JSXElement,
|
|
215
502
|
attrName: string,
|
|
216
503
|
attrValue?: boolean | unknown,
|
|
217
504
|
t = types
|
|
218
505
|
) => {
|
|
219
|
-
const
|
|
506
|
+
const reactAttrName = resolveAttributeNameForTag(jsxNode, attrName)
|
|
507
|
+
const nameOfAttribute = t.jsxIdentifier(reactAttrName)
|
|
220
508
|
let attributeDefinition
|
|
221
|
-
|
|
509
|
+
let normalizedValue: boolean | unknown = attrValue
|
|
510
|
+
if (
|
|
511
|
+
typeof attrValue === 'string' &&
|
|
512
|
+
(attrValue === 'true' || attrValue === 'false') &&
|
|
513
|
+
REACT_BOOLEAN_DOM_PROPS.has(reactAttrName)
|
|
514
|
+
) {
|
|
515
|
+
normalizedValue = attrValue === 'true'
|
|
516
|
+
}
|
|
517
|
+
if (typeof normalizedValue === 'boolean') {
|
|
222
518
|
attributeDefinition = t.jsxAttribute(
|
|
223
519
|
nameOfAttribute,
|
|
224
|
-
|
|
520
|
+
normalizedValue === true
|
|
521
|
+
? undefined
|
|
522
|
+
: t.jsxExpressionContainer(t.booleanLiteral(normalizedValue))
|
|
225
523
|
)
|
|
524
|
+
} else if (t.isNode(attrValue) && t.isJSXElement(attrValue)) {
|
|
525
|
+
attributeDefinition = t.jsxAttribute(nameOfAttribute, t.jsxExpressionContainer(attrValue))
|
|
226
526
|
} else {
|
|
227
527
|
attributeDefinition = t.jsxAttribute(
|
|
228
528
|
nameOfAttribute,
|
|
229
|
-
getProperAttributeValueAssignment(
|
|
529
|
+
getProperAttributeValueAssignment(normalizedValue)
|
|
230
530
|
)
|
|
231
531
|
}
|
|
232
532
|
|
|
533
|
+
const attribute: types.JSXAttribute = jsxNode.openingElement.attributes.find((attr) => {
|
|
534
|
+
if (attr.type === 'JSXAttribute') {
|
|
535
|
+
return attr.name.name === reactAttrName
|
|
536
|
+
}
|
|
537
|
+
}) as types.JSXAttribute
|
|
538
|
+
|
|
539
|
+
if (attribute && attribute.value && attribute.value.type === 'StringLiteral') {
|
|
540
|
+
attribute.value.value = `${attribute.value.value} ${attrValue}`
|
|
541
|
+
return
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// An object-valued attribute (e.g. `style={{ ... }}`) can be contributed by
|
|
545
|
+
// more than one independent code path — e.g. a ctx-scoped dynamic style value
|
|
546
|
+
// resolved at JSX-build time, and a `dynamicStyleBindings` inline style added
|
|
547
|
+
// later by a style plugin. Pushing a second `style` JSXAttribute would silently
|
|
548
|
+
// drop one of the two (JS keeps only the last of duplicate object keys once
|
|
549
|
+
// transpiled), so merge into the existing ObjectExpression instead, replacing
|
|
550
|
+
// any property with a matching key so the newer value wins.
|
|
551
|
+
if (
|
|
552
|
+
attribute &&
|
|
553
|
+
attribute.value?.type === 'JSXExpressionContainer' &&
|
|
554
|
+
attribute.value.expression.type === 'ObjectExpression' &&
|
|
555
|
+
attributeDefinition.value?.type === 'JSXExpressionContainer' &&
|
|
556
|
+
attributeDefinition.value.expression.type === 'ObjectExpression'
|
|
557
|
+
) {
|
|
558
|
+
const existingProps = attribute.value.expression.properties
|
|
559
|
+
attributeDefinition.value.expression.properties.forEach((newProp) => {
|
|
560
|
+
if (newProp.type !== 'ObjectProperty' || newProp.key.type === 'PrivateName') {
|
|
561
|
+
existingProps.push(newProp)
|
|
562
|
+
return
|
|
563
|
+
}
|
|
564
|
+
const newKeyName =
|
|
565
|
+
newProp.key.type === 'Identifier' ? newProp.key.name : String((newProp.key as any).value)
|
|
566
|
+
const existingIndex = existingProps.findIndex((prop) => {
|
|
567
|
+
if (prop.type !== 'ObjectProperty' || prop.key.type === 'PrivateName') {
|
|
568
|
+
return false
|
|
569
|
+
}
|
|
570
|
+
const existingKeyName =
|
|
571
|
+
prop.key.type === 'Identifier' ? prop.key.name : String((prop.key as any).value)
|
|
572
|
+
return existingKeyName === newKeyName
|
|
573
|
+
})
|
|
574
|
+
if (existingIndex >= 0) {
|
|
575
|
+
existingProps[existingIndex] = newProp
|
|
576
|
+
} else {
|
|
577
|
+
existingProps.push(newProp)
|
|
578
|
+
}
|
|
579
|
+
})
|
|
580
|
+
return
|
|
581
|
+
}
|
|
582
|
+
|
|
233
583
|
jsxNode.openingElement.attributes.push(attributeDefinition)
|
|
234
584
|
}
|
|
235
585
|
|
|
@@ -239,26 +589,50 @@ export const addRawAttributeToJSXTag = (
|
|
|
239
589
|
attrValue: UIDLRawValue,
|
|
240
590
|
t = types
|
|
241
591
|
) => {
|
|
592
|
+
// The content is expected to be pre-escaped for template literal context
|
|
593
|
+
// (e.g., \` for backticks, \${ for interpolations). Babel validates that
|
|
594
|
+
// the raw value is valid template literal content.
|
|
595
|
+
//
|
|
596
|
+
// We fix any unescaped backticks or ${ sequences that would make the
|
|
597
|
+
// template literal invalid. "Unescaped" means preceded by an even number
|
|
598
|
+
// of backslashes (0, 2, …), since pairs of backslashes form escape
|
|
599
|
+
// sequences for backslash itself, leaving the next character unescaped.
|
|
600
|
+
const content = attrValue.content
|
|
601
|
+
.replace(/\\*`/g, (match) => {
|
|
602
|
+
const bs = match.length - 1
|
|
603
|
+
return bs % 2 === 0 ? match.slice(0, bs) + '\\`' : match
|
|
604
|
+
})
|
|
605
|
+
.replace(/\\*\$\{/g, (match) => {
|
|
606
|
+
const bs = match.length - 2
|
|
607
|
+
return bs % 2 === 0 ? match.slice(0, bs) + '\\${' : match
|
|
608
|
+
})
|
|
609
|
+
|
|
242
610
|
const attributeDefinition = t.jsxAttribute(
|
|
243
611
|
t.jsxIdentifier(attrName),
|
|
244
|
-
t.jsxExpressionContainer(
|
|
245
|
-
types.templateLiteral([types.templateElement({ raw: attrValue.content })], [])
|
|
246
|
-
)
|
|
612
|
+
t.jsxExpressionContainer(types.templateLiteral([types.templateElement({ raw: content })], []))
|
|
247
613
|
)
|
|
248
614
|
jsxNode.openingElement.attributes.push(attributeDefinition)
|
|
249
615
|
}
|
|
250
616
|
|
|
617
|
+
// A JSX attribute string is raw text: nothing in it is unescaped, yet Babel
|
|
618
|
+
// prints a backslash or a line break in it escaped, so `pattern="\d"` would reach
|
|
619
|
+
// the page as `\\d`. Such a value goes in an expression container instead, where
|
|
620
|
+
// the escapes are JavaScript's and are read back.
|
|
621
|
+
const RAW_JSX_ATTRIBUTE_UNSAFE = /[\\\n\r\u2028\u2029]/
|
|
622
|
+
|
|
251
623
|
/**
|
|
252
624
|
* node must be a AST node element of type JSXElement (babel-types) or
|
|
253
625
|
* equivalent
|
|
254
626
|
*/
|
|
255
627
|
const getProperAttributeValueAssignment = (value: string | unknown, t = types) => {
|
|
256
|
-
if (
|
|
257
|
-
return
|
|
628
|
+
if (typeof value === 'string') {
|
|
629
|
+
return RAW_JSX_ATTRIBUTE_UNSAFE.test(value)
|
|
630
|
+
? t.jsxExpressionContainer(t.stringLiteral(value))
|
|
631
|
+
: t.stringLiteral(StringUtils.encode(value))
|
|
258
632
|
}
|
|
259
633
|
|
|
260
|
-
if (
|
|
261
|
-
return
|
|
634
|
+
if (!value && value !== 0 && value !== false) {
|
|
635
|
+
return null
|
|
262
636
|
}
|
|
263
637
|
|
|
264
638
|
return t.jsxExpressionContainer(convertValueToLiteral(value))
|
|
@@ -300,7 +674,18 @@ export const objectToObjectExpression = (
|
|
|
300
674
|
const value = objectMap[key]
|
|
301
675
|
let computedLiteralValue = null
|
|
302
676
|
|
|
303
|
-
if (value
|
|
677
|
+
if (value === undefined) {
|
|
678
|
+
return acc
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
// Handle null values explicitly - they are valid in array mappers with different schemas
|
|
682
|
+
if (value === null) {
|
|
683
|
+
computedLiteralValue = t.nullLiteral()
|
|
684
|
+
}
|
|
685
|
+
// This is for function props that have successfully been parsed.
|
|
686
|
+
else if (typeof value === 'object' && 'functionExpressionParseResult' in value) {
|
|
687
|
+
computedLiteralValue = value.functionExpressionParseResult
|
|
688
|
+
} else if (value instanceof ParsedASTNode || value.constructor.name === 'ParsedASTNode') {
|
|
304
689
|
computedLiteralValue = (value as ParsedASTNode).ast
|
|
305
690
|
} else if (typeof value === 'boolean') {
|
|
306
691
|
computedLiteralValue = t.booleanLiteral(value)
|
|
@@ -361,7 +746,24 @@ export const convertValueToLiteral = (
|
|
|
361
746
|
return t.arrayExpression(value.map((val) => convertValueToLiteral(val)))
|
|
362
747
|
}
|
|
363
748
|
|
|
364
|
-
|
|
749
|
+
if (explicitType === 'array' && typeof value === 'object' && value !== null) {
|
|
750
|
+
const arr = Object.keys(value)
|
|
751
|
+
.sort((a, b) => Number(a) - Number(b))
|
|
752
|
+
.map((key) => convertValueToLiteral(value[key]))
|
|
753
|
+
return t.arrayExpression(arr)
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
if ((explicitType === 'array' || explicitType === 'object') && typeof value === 'string') {
|
|
757
|
+
try {
|
|
758
|
+
const parsed = JSON.parse(value)
|
|
759
|
+
return convertValueToLiteral(parsed, explicitType, t)
|
|
760
|
+
} catch {
|
|
761
|
+
// If parsing fails, fall through to treat as a regular string
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
const actualType = typeof value
|
|
766
|
+
const typeToCompare = explicitType && explicitType === actualType ? explicitType : actualType
|
|
365
767
|
switch (typeToCompare) {
|
|
366
768
|
case 'string':
|
|
367
769
|
return t.stringLiteral(value)
|
|
@@ -396,7 +798,7 @@ export const getTSAnnotationForType = (type: any, t = types) => {
|
|
|
396
798
|
case 'boolean':
|
|
397
799
|
return t.tsBooleanKeyword()
|
|
398
800
|
default:
|
|
399
|
-
return t.
|
|
801
|
+
return t.tsAnyKeyword()
|
|
400
802
|
}
|
|
401
803
|
}
|
|
402
804
|
|
|
@@ -419,6 +821,7 @@ export const createClassComponent = (
|
|
|
419
821
|
propDefinitions: Record<string, UIDLPropDefinition>,
|
|
420
822
|
stateDefinitions: Record<string, UIDLStateDefinition>,
|
|
421
823
|
jsxTagTree: types.JSXElement,
|
|
824
|
+
dynamicReferencePrefixMap?: { prop: string; state: string; local: string },
|
|
422
825
|
t = types
|
|
423
826
|
) => {
|
|
424
827
|
// TODO: Add event handlers as separate functions later
|
|
@@ -432,6 +835,20 @@ export const createClassComponent = (
|
|
|
432
835
|
if (Object.keys(stateDefinitions).length > 0) {
|
|
433
836
|
const stateDeclarationsAST = Object.keys(stateDefinitions).map((stateKey) => {
|
|
434
837
|
const stateDefinition = stateDefinitions[stateKey]
|
|
838
|
+
if (
|
|
839
|
+
stateDefinition.type === 'object' &&
|
|
840
|
+
dynamicReferencePrefixMap &&
|
|
841
|
+
isObjectStateWithEntries(stateDefinition)
|
|
842
|
+
) {
|
|
843
|
+
return t.objectProperty(
|
|
844
|
+
t.identifier(stateKey),
|
|
845
|
+
convertObjectStateDefaultToExpression(
|
|
846
|
+
stateDefinition.defaultValue as Record<string, unknown>,
|
|
847
|
+
dynamicReferencePrefixMap,
|
|
848
|
+
t
|
|
849
|
+
)
|
|
850
|
+
)
|
|
851
|
+
}
|
|
435
852
|
return t.objectProperty(
|
|
436
853
|
t.identifier(stateKey),
|
|
437
854
|
convertValueToLiteral(stateDefinition.defaultValue)
|
|
@@ -469,12 +886,14 @@ export const createPureComponent = (
|
|
|
469
886
|
stateDefinitions: Record<string, UIDLStateDefinition>,
|
|
470
887
|
jsxTagTree: types.JSXElement,
|
|
471
888
|
windowImports: Record<string, types.ExpressionStatement> = {},
|
|
889
|
+
dynamicReferencePrefixMap?: { prop: string; state: string; local: string },
|
|
472
890
|
t = types
|
|
473
891
|
): types.VariableDeclaration => {
|
|
474
892
|
const arrowFunctionBody = createReturnExpressionSyntax(
|
|
475
893
|
stateDefinitions,
|
|
476
894
|
jsxTagTree,
|
|
477
|
-
windowImports
|
|
895
|
+
windowImports,
|
|
896
|
+
dynamicReferencePrefixMap
|
|
478
897
|
)
|
|
479
898
|
const arrowFunction = t.arrowFunctionExpression([t.identifier('props')], arrowFunctionBody)
|
|
480
899
|
|
|
@@ -488,15 +907,16 @@ export const createReturnExpressionSyntax = (
|
|
|
488
907
|
stateDefinitions: Record<string, UIDLStateDefinition>,
|
|
489
908
|
jsxTagTree: types.JSXElement,
|
|
490
909
|
windowImports: Record<string, types.ExpressionStatement> = {},
|
|
910
|
+
dynamicReferencePrefixMap?: { prop: string; state: string; local: string },
|
|
491
911
|
t = types
|
|
492
912
|
) => {
|
|
493
913
|
const returnStatement = t.returnStatement(jsxTagTree)
|
|
494
914
|
|
|
495
915
|
const stateHooks = Object.keys(stateDefinitions).map((stateKey) =>
|
|
496
|
-
createStateHookAST(stateKey, stateDefinitions[stateKey])
|
|
916
|
+
createStateHookAST(stateKey, stateDefinitions[stateKey], dynamicReferencePrefixMap)
|
|
497
917
|
)
|
|
498
918
|
|
|
499
|
-
return t.blockStatement([...stateHooks, ...Object.values(windowImports), returnStatement]
|
|
919
|
+
return t.blockStatement([...stateHooks, ...Object.values(windowImports), returnStatement])
|
|
500
920
|
}
|
|
501
921
|
|
|
502
922
|
/**
|
|
@@ -505,33 +925,336 @@ export const createReturnExpressionSyntax = (
|
|
|
505
925
|
export const createStateHookAST = (
|
|
506
926
|
stateKey: string,
|
|
507
927
|
stateDefinition: UIDLStateDefinition,
|
|
928
|
+
dynamicReferencePrefixMap?: { prop: string; state: string; local: string },
|
|
508
929
|
t = types
|
|
509
930
|
) => {
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
931
|
+
let defaultValueArgument: types.Expression
|
|
932
|
+
|
|
933
|
+
if (
|
|
934
|
+
stateDefinition.type === 'object' &&
|
|
935
|
+
dynamicReferencePrefixMap &&
|
|
936
|
+
isObjectStateWithEntries(stateDefinition)
|
|
937
|
+
) {
|
|
938
|
+
defaultValueArgument = convertObjectStateDefaultToExpression(
|
|
939
|
+
stateDefinition.defaultValue as Record<string, unknown>,
|
|
940
|
+
dynamicReferencePrefixMap,
|
|
941
|
+
t
|
|
942
|
+
)
|
|
943
|
+
} else {
|
|
944
|
+
defaultValueArgument = convertValueToLiteral(stateDefinition.defaultValue, stateDefinition.type)
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// When the state has a dataSourceBinding, the initial value comes from props
|
|
948
|
+
// Generated: useState(props.stateKey !== undefined ? props.stateKey : defaultValue)
|
|
949
|
+
let useStateArgument: types.Expression = defaultValueArgument
|
|
950
|
+
if (stateDefinition.dataSourceBinding) {
|
|
951
|
+
const propAccess = t.memberExpression(t.identifier('props'), t.identifier(stateKey))
|
|
952
|
+
useStateArgument = t.conditionalExpression(
|
|
953
|
+
t.binaryExpression('!==', propAccess, t.identifier('undefined')),
|
|
954
|
+
propAccess,
|
|
955
|
+
defaultValueArgument
|
|
956
|
+
)
|
|
957
|
+
} else if (
|
|
958
|
+
stateDefinition.urlSearchParamBinding &&
|
|
959
|
+
typeof stateDefinition.urlSearchParamBinding.key === 'string' &&
|
|
960
|
+
stateDefinition.urlSearchParamBinding.key !== '' &&
|
|
961
|
+
// `hydrateAfterMount`: the state keeps its static default on the client's
|
|
962
|
+
// first render too, and the router read-back effect adopts the URL value
|
|
963
|
+
// once `router.isReady` — a real update, so the elements it gates
|
|
964
|
+
// re-render. Needed where the server markup and a URL-seeded client value
|
|
965
|
+
// would differ only in ATTRIBUTES of same-tag siblings (a pressed toggle):
|
|
966
|
+
// React 17 does not patch those on hydration. See the type's docs.
|
|
967
|
+
stateDefinition.urlSearchParamBinding.hydrateAfterMount !== true
|
|
968
|
+
) {
|
|
969
|
+
// URL-search-param binding: seed the initial state directly from
|
|
970
|
+
// `window.location.search`. We deliberately DO NOT use Next.js'
|
|
971
|
+
// `router.query` here because on statically-generated pages (getStaticProps
|
|
972
|
+
// / getStaticPaths) `router.query` is empty on the first render and only
|
|
973
|
+
// hydrates after `router.isReady` flips to true — by which point React's
|
|
974
|
+
// `useState` initializer has already captured the fallback default. That
|
|
975
|
+
// regression shipped as "detail panel does not auto-open on deep links to
|
|
976
|
+
// /admin/products?products_detail_panel_item_id=<id>". `window.location`
|
|
977
|
+
// is populated synchronously on both direct loads and client-side
|
|
978
|
+
// navigations, and the `typeof window` guard keeps SSR falling back to
|
|
979
|
+
// the declared static default cleanly.
|
|
980
|
+
//
|
|
981
|
+
// Emitted shape:
|
|
982
|
+
// useState(
|
|
983
|
+
// (typeof window !== "undefined"
|
|
984
|
+
// ? new URLSearchParams(window.location.search).get("<key>")
|
|
985
|
+
// : null) ?? <defaultValueLiteral>
|
|
986
|
+
// )
|
|
987
|
+
const paramKey = stateDefinition.urlSearchParamBinding.key
|
|
988
|
+
const urlSearchParamsExpr = t.newExpression(t.identifier('URLSearchParams'), [
|
|
989
|
+
t.memberExpression(
|
|
990
|
+
t.memberExpression(t.identifier('window'), t.identifier('location')),
|
|
991
|
+
t.identifier('search')
|
|
992
|
+
),
|
|
993
|
+
])
|
|
994
|
+
const readParamExpr = t.callExpression(
|
|
995
|
+
t.memberExpression(urlSearchParamsExpr, t.identifier('get')),
|
|
996
|
+
[t.stringLiteral(paramKey)]
|
|
997
|
+
)
|
|
998
|
+
const browserGuard = t.binaryExpression(
|
|
999
|
+
'!==',
|
|
1000
|
+
t.unaryExpression('typeof', t.identifier('window')),
|
|
1001
|
+
t.stringLiteral('undefined')
|
|
1002
|
+
)
|
|
1003
|
+
useStateArgument = t.logicalExpression(
|
|
1004
|
+
'??',
|
|
1005
|
+
t.conditionalExpression(browserGuard, readParamExpr, t.nullLiteral()),
|
|
1006
|
+
defaultValueArgument
|
|
1007
|
+
)
|
|
1008
|
+
}
|
|
514
1009
|
|
|
515
1010
|
return t.variableDeclaration('const', [
|
|
516
1011
|
t.variableDeclarator(
|
|
517
1012
|
t.arrayPattern([
|
|
518
|
-
|
|
1013
|
+
// The state NAME comes from the UIDL and may be a reserved word (a
|
|
1014
|
+
// character sheet has a column called `class`), which is fatal in
|
|
1015
|
+
// binding position. Reads go through the same sanitiser, so the
|
|
1016
|
+
// declaration and every reference stay in sync.
|
|
1017
|
+
t.identifier(JSIdentifiers.createSafeJSIdentifier(stateKey)),
|
|
519
1018
|
t.identifier(StringUtils.createStateStoringFunction(stateKey)),
|
|
520
1019
|
]),
|
|
521
|
-
t.callExpression(t.identifier('useState'), [
|
|
1020
|
+
t.callExpression(t.identifier('useState'), [useStateArgument])
|
|
522
1021
|
),
|
|
523
1022
|
])
|
|
524
1023
|
}
|
|
525
1024
|
|
|
1025
|
+
export const isObjectStateWithEntries = (stateDefinition: UIDLStateDefinition): boolean => {
|
|
1026
|
+
if (stateDefinition.type !== 'object') {
|
|
1027
|
+
return false
|
|
1028
|
+
}
|
|
1029
|
+
const defaultValue = stateDefinition.defaultValue
|
|
1030
|
+
if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
|
|
1031
|
+
return false
|
|
1032
|
+
}
|
|
1033
|
+
return Object.values(defaultValue).some((entry) => {
|
|
1034
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
1035
|
+
return false
|
|
1036
|
+
}
|
|
1037
|
+
const typed = entry as Record<string, unknown>
|
|
1038
|
+
return (typed.type === 'static' || typed.type === 'dynamic') && 'content' in typed
|
|
1039
|
+
})
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
export const convertObjectStateDefaultToExpression = (
|
|
1043
|
+
defaultValue: Record<string, unknown>,
|
|
1044
|
+
prefixMap: { prop: string; state: string; local: string },
|
|
1045
|
+
t = types
|
|
1046
|
+
): types.ObjectExpression => {
|
|
1047
|
+
const properties = Object.keys(defaultValue).map((key) => {
|
|
1048
|
+
const valueExpression = resolveObjectStateEntry(defaultValue[key], prefixMap, t)
|
|
1049
|
+
return t.objectProperty(t.stringLiteral(key), valueExpression)
|
|
1050
|
+
})
|
|
1051
|
+
|
|
1052
|
+
return t.objectExpression(properties)
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
const resolveObjectStateEntry = (
|
|
1056
|
+
entry: unknown,
|
|
1057
|
+
prefixMap: { prop: string; state: string; local: string },
|
|
1058
|
+
t = types
|
|
1059
|
+
): types.Expression => {
|
|
1060
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
1061
|
+
return convertValueToLiteral(entry) as types.Expression
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
const typed = entry as { type?: string; content?: unknown }
|
|
1065
|
+
|
|
1066
|
+
if (typed.type === 'static') {
|
|
1067
|
+
return convertValueToLiteral(typed.content) as types.Expression
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
if (typed.type === 'dynamic') {
|
|
1071
|
+
const content = typed.content as {
|
|
1072
|
+
referenceType: string
|
|
1073
|
+
id: string
|
|
1074
|
+
refPath?: string[]
|
|
1075
|
+
}
|
|
1076
|
+
const { referenceType, id, refPath } = content
|
|
1077
|
+
|
|
1078
|
+
if (referenceType === 'globalState') {
|
|
1079
|
+
const gsRefPath = refPath || []
|
|
1080
|
+
let expr: types.Identifier | types.OptionalMemberExpression = t.identifier(id)
|
|
1081
|
+
for (const segment of gsRefPath) {
|
|
1082
|
+
expr = t.optionalMemberExpression(expr, t.identifier(segment), false, true)
|
|
1083
|
+
}
|
|
1084
|
+
return expr
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
if (referenceType === 'global') {
|
|
1088
|
+
// Normalize Shape B ({ refPath: ['Current User', 'id'] }) to Shape A
|
|
1089
|
+
// ({ id: 'currentUser', refPath: ['id'] }) so downstream access is uniform.
|
|
1090
|
+
const resolvedId = resolveGlobalRefId(content)
|
|
1091
|
+
if (resolvedId) {
|
|
1092
|
+
const tail = !id && refPath && refPath.length > 0 ? refPath.slice(1) : refPath || []
|
|
1093
|
+
let expr: types.Identifier | types.OptionalMemberExpression = t.identifier(resolvedId)
|
|
1094
|
+
for (const segment of tail) {
|
|
1095
|
+
expr = t.optionalMemberExpression(expr, t.identifier(segment), false, true)
|
|
1096
|
+
}
|
|
1097
|
+
return expr
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
const idWithPath = UIDLUtils.generateIdWithRefPath(id, refPath)
|
|
1102
|
+
const prefix = prefixMap[referenceType as 'prop' | 'state' | 'local'] || ''
|
|
1103
|
+
|
|
1104
|
+
return prefix === ''
|
|
1105
|
+
? t.identifier(idWithPath)
|
|
1106
|
+
: t.memberExpression(t.identifier(prefix), t.identifier(idWithPath))
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
return convertValueToLiteral(entry) as types.Expression
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
// Mapping from the UIDL display name used in a global reference refPath
|
|
1113
|
+
// to the runtime variable name that holds the value. Kept here so both the
|
|
1114
|
+
// JSX emitter and the object-state global-reference collectors stay in sync.
|
|
1115
|
+
export const GLOBAL_REF_ID_MAP: Record<string, string> = {
|
|
1116
|
+
'E-commerce': 'ecommerce',
|
|
1117
|
+
Cart: 'cart',
|
|
1118
|
+
'Current User': 'currentUser',
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
export const resolveGlobalRefId = (
|
|
1122
|
+
content: { id?: string; refPath?: string[] } | undefined
|
|
1123
|
+
): string | undefined => {
|
|
1124
|
+
if (!content) {
|
|
1125
|
+
return undefined
|
|
1126
|
+
}
|
|
1127
|
+
if (content.id) {
|
|
1128
|
+
return content.id
|
|
1129
|
+
}
|
|
1130
|
+
if (!content.refPath || content.refPath.length === 0) {
|
|
1131
|
+
return undefined
|
|
1132
|
+
}
|
|
1133
|
+
return GLOBAL_REF_ID_MAP[content.refPath[0]]
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
export const collectGlobalReferencesFromObjectStates = (
|
|
1137
|
+
stateDefinitions: Record<string, UIDLStateDefinition>
|
|
1138
|
+
): string[] => {
|
|
1139
|
+
const globalRefs: string[] = []
|
|
1140
|
+
|
|
1141
|
+
Object.values(stateDefinitions).forEach((stateDef) => {
|
|
1142
|
+
if (stateDef.type !== 'object') {
|
|
1143
|
+
return
|
|
1144
|
+
}
|
|
1145
|
+
const defaultValue = stateDef.defaultValue
|
|
1146
|
+
if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
|
|
1147
|
+
return
|
|
1148
|
+
}
|
|
1149
|
+
|
|
1150
|
+
Object.values(defaultValue as Record<string, unknown>).forEach((entry) => {
|
|
1151
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
1152
|
+
return
|
|
1153
|
+
}
|
|
1154
|
+
const typed = entry as { type?: string; content?: unknown }
|
|
1155
|
+
if (typed.type === 'dynamic') {
|
|
1156
|
+
const content = typed.content as {
|
|
1157
|
+
referenceType?: string
|
|
1158
|
+
id?: string
|
|
1159
|
+
refPath?: string[]
|
|
1160
|
+
}
|
|
1161
|
+
if (content.referenceType === 'global') {
|
|
1162
|
+
const resolvedId = resolveGlobalRefId(content)
|
|
1163
|
+
if (resolvedId) {
|
|
1164
|
+
globalRefs.push(resolvedId)
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
})
|
|
1169
|
+
})
|
|
1170
|
+
|
|
1171
|
+
return globalRefs
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
export const collectGlobalStateReferencesFromObjectStates = (
|
|
1175
|
+
stateDefinitions: Record<string, UIDLStateDefinition>
|
|
1176
|
+
): Array<{ id: string }> => {
|
|
1177
|
+
const refs: Array<{ id: string }> = []
|
|
1178
|
+
|
|
1179
|
+
Object.values(stateDefinitions).forEach((stateDef) => {
|
|
1180
|
+
if (stateDef.type !== 'object') {
|
|
1181
|
+
return
|
|
1182
|
+
}
|
|
1183
|
+
const defaultValue = stateDef.defaultValue
|
|
1184
|
+
if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
|
|
1185
|
+
return
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
Object.values(defaultValue as Record<string, unknown>).forEach((entry) => {
|
|
1189
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
1190
|
+
return
|
|
1191
|
+
}
|
|
1192
|
+
const typed = entry as { type?: string; content?: unknown }
|
|
1193
|
+
if (typed.type === 'dynamic') {
|
|
1194
|
+
const content = typed.content as { referenceType?: string; id?: string }
|
|
1195
|
+
if (content.referenceType === 'globalState' && content.id) {
|
|
1196
|
+
refs.push({ id: content.id })
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
})
|
|
1200
|
+
})
|
|
1201
|
+
|
|
1202
|
+
return refs
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
/**
|
|
1206
|
+
* The mount-time side-effect import for a package that cannot be imported at
|
|
1207
|
+
* module scope because it touches `window` while it evaluates —
|
|
1208
|
+
* self-registering web components such as `<lottie-player>` and
|
|
1209
|
+
* `<model-viewer>`. Running it from an effect keeps it off the server render.
|
|
1210
|
+
*
|
|
1211
|
+
* useEffect(() => {
|
|
1212
|
+
* import('@google/model-viewer').catch((error) => {
|
|
1213
|
+
* console.warn('[teleport] Failed to load "@google/model-viewer"', error)
|
|
1214
|
+
* })
|
|
1215
|
+
* }, [])
|
|
1216
|
+
*
|
|
1217
|
+
* Two details of that shape are load-bearing:
|
|
1218
|
+
*
|
|
1219
|
+
* - The callback body is a BLOCK. A concise arrow body (`() => import(…)`)
|
|
1220
|
+
* also RETURNS the import's Promise, and React stores an effect's return
|
|
1221
|
+
* value as its cleanup function and calls it on unmount — so every mounted
|
|
1222
|
+
* copy of the component turned navigating away into
|
|
1223
|
+
* `TypeError: destroy is not a function`, thrown from React's commit phase
|
|
1224
|
+
* with no frame naming the component. Nothing is returned here.
|
|
1225
|
+
* - The rejection is handled. A chunk that fails to load (offline, a stale
|
|
1226
|
+
* deploy, a blocked CDN) would otherwise surface as an unhandled promise
|
|
1227
|
+
* rejection; the element simply stays unupgraded, which is a degraded page
|
|
1228
|
+
* rather than a broken one, and the warning is what makes that visible.
|
|
1229
|
+
*/
|
|
526
1230
|
export const generateDynamicWindowImport = (
|
|
527
1231
|
hookName = 'useEffect',
|
|
528
1232
|
dependency: string
|
|
529
1233
|
): types.ExpressionStatement => {
|
|
1234
|
+
const failureIdentifier = types.identifier('error')
|
|
1235
|
+
const importCall = types.callExpression(types.import(), [types.stringLiteral(dependency)])
|
|
1236
|
+
const guardedImport = types.callExpression(
|
|
1237
|
+
types.memberExpression(importCall, types.identifier('catch')),
|
|
1238
|
+
[
|
|
1239
|
+
types.arrowFunctionExpression(
|
|
1240
|
+
[failureIdentifier],
|
|
1241
|
+
types.blockStatement([
|
|
1242
|
+
types.expressionStatement(
|
|
1243
|
+
types.callExpression(
|
|
1244
|
+
types.memberExpression(types.identifier('console'), types.identifier('warn')),
|
|
1245
|
+
[types.stringLiteral(`[teleport] Failed to load "${dependency}"`), failureIdentifier]
|
|
1246
|
+
)
|
|
1247
|
+
),
|
|
1248
|
+
])
|
|
1249
|
+
),
|
|
1250
|
+
]
|
|
1251
|
+
)
|
|
1252
|
+
|
|
530
1253
|
return types.expressionStatement(
|
|
531
1254
|
types.callExpression(types.identifier(hookName), [
|
|
532
1255
|
types.arrowFunctionExpression(
|
|
533
1256
|
[],
|
|
534
|
-
types.
|
|
1257
|
+
types.blockStatement([types.expressionStatement(guardedImport)])
|
|
535
1258
|
),
|
|
536
1259
|
types.arrayExpression([]),
|
|
537
1260
|
])
|
|
@@ -543,9 +1266,7 @@ export const wrapObjectPropertiesWithExpression = (properties: types.ObjectPrope
|
|
|
543
1266
|
|
|
544
1267
|
export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
|
|
545
1268
|
const fetchUrl = computeFetchUrl(resource)
|
|
546
|
-
const authHeaderAST = computeAuthorizationHeaderAST(resource?.headers)
|
|
547
1269
|
const headersASTs = resource?.headers ? generateRESTHeadersAST(resource.headers) : []
|
|
548
|
-
|
|
549
1270
|
const queryParams = generateURLParamsAST(resource?.params)
|
|
550
1271
|
const fetchUrlQuasis = fetchUrl.quasis
|
|
551
1272
|
const queryParamsQuasis = queryParams?.quasis || [types.templateElement({ raw: '', cooked: '' })]
|
|
@@ -560,60 +1281,8 @@ export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
|
|
|
560
1281
|
queryParamsQuasis.pop()
|
|
561
1282
|
}
|
|
562
1283
|
|
|
563
|
-
const
|
|
564
|
-
|
|
565
|
-
).reduce((acc: Array<types.ObjectProperty | types.SpreadElement>, item) => {
|
|
566
|
-
const prop = resource.params[item]
|
|
567
|
-
if (prop.type === 'static') {
|
|
568
|
-
acc.push(types.objectProperty(types.stringLiteral(item), ASTUtils.resolveObjectValue(prop)))
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
if (prop.type === 'expr') {
|
|
572
|
-
acc.push(
|
|
573
|
-
types.objectProperty(
|
|
574
|
-
types.stringLiteral(item),
|
|
575
|
-
ASTUtils.getExpressionFromUIDLExpressionNode(prop)
|
|
576
|
-
)
|
|
577
|
-
)
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
if (prop.type === 'dynamic') {
|
|
581
|
-
acc.push(
|
|
582
|
-
types.spreadElement(
|
|
583
|
-
types.logicalExpression(
|
|
584
|
-
'&&',
|
|
585
|
-
types.memberExpression(
|
|
586
|
-
types.identifier('params'),
|
|
587
|
-
types.stringLiteral(prop.content.id),
|
|
588
|
-
true,
|
|
589
|
-
false
|
|
590
|
-
),
|
|
591
|
-
types.objectExpression([
|
|
592
|
-
types.objectProperty(
|
|
593
|
-
types.stringLiteral(item),
|
|
594
|
-
types.memberExpression(
|
|
595
|
-
types.identifier('params'),
|
|
596
|
-
types.stringLiteral(prop.content.id),
|
|
597
|
-
true,
|
|
598
|
-
false
|
|
599
|
-
)
|
|
600
|
-
),
|
|
601
|
-
])
|
|
602
|
-
)
|
|
603
|
-
)
|
|
604
|
-
)
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
return acc
|
|
608
|
-
}, [])
|
|
609
|
-
|
|
610
|
-
const paramsAST = types.variableDeclaration('const', [
|
|
611
|
-
types.variableDeclarator(
|
|
612
|
-
types.identifier('urlParams'),
|
|
613
|
-
types.objectExpression(paramsDeclerations)
|
|
614
|
-
),
|
|
615
|
-
])
|
|
616
|
-
|
|
1284
|
+
const urlParamsDecleration = generateParamsAST(resource?.params)
|
|
1285
|
+
const bodyParamsDecleration = generateParamsAST(resource?.body)
|
|
617
1286
|
const url = queryParams?.quasis
|
|
618
1287
|
? types.templateLiteral(
|
|
619
1288
|
[...fetchUrlQuasis, ...queryParamsQuasis],
|
|
@@ -628,31 +1297,113 @@ export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
|
|
|
628
1297
|
|
|
629
1298
|
let allHeaders: types.ObjectProperty[] = []
|
|
630
1299
|
|
|
631
|
-
if (
|
|
632
|
-
allHeaders.push(
|
|
1300
|
+
if (resource?.headers?.authToken) {
|
|
1301
|
+
allHeaders.push(computeAuthorizationHeaderAST(resource?.headers))
|
|
633
1302
|
}
|
|
634
1303
|
|
|
635
1304
|
if (headersASTs.length) {
|
|
636
1305
|
allHeaders = allHeaders.concat(headersASTs)
|
|
637
1306
|
}
|
|
638
1307
|
|
|
639
|
-
const
|
|
640
|
-
types.identifier('headers'),
|
|
641
|
-
types.objectExpression(allHeaders)
|
|
642
|
-
)
|
|
643
|
-
|
|
644
|
-
const fetchAST = types.variableDeclaration('const', [
|
|
1308
|
+
const fetchAST = types.variableDeclaration('let', [
|
|
645
1309
|
types.variableDeclarator(
|
|
646
1310
|
types.identifier('data'),
|
|
647
1311
|
types.awaitExpression(
|
|
648
1312
|
types.callExpression(types.identifier('fetch'), [
|
|
649
1313
|
url,
|
|
650
|
-
types.objectExpression([
|
|
1314
|
+
types.objectExpression([
|
|
1315
|
+
method,
|
|
1316
|
+
...(allHeaders.length > 0
|
|
1317
|
+
? [
|
|
1318
|
+
types.objectProperty(
|
|
1319
|
+
types.identifier('headers'),
|
|
1320
|
+
types.objectExpression(allHeaders)
|
|
1321
|
+
),
|
|
1322
|
+
]
|
|
1323
|
+
: []),
|
|
1324
|
+
...(bodyParamsDecleration.length > 0 && resource?.method === 'POST'
|
|
1325
|
+
? [
|
|
1326
|
+
types.objectProperty(
|
|
1327
|
+
types.identifier('body'),
|
|
1328
|
+
types.callExpression(
|
|
1329
|
+
types.memberExpression(
|
|
1330
|
+
types.identifier('JSON'),
|
|
1331
|
+
types.identifier('stringify')
|
|
1332
|
+
),
|
|
1333
|
+
[types.identifier('bodyParams')]
|
|
1334
|
+
)
|
|
1335
|
+
),
|
|
1336
|
+
]
|
|
1337
|
+
: []),
|
|
1338
|
+
]),
|
|
651
1339
|
])
|
|
652
1340
|
)
|
|
653
1341
|
),
|
|
654
1342
|
])
|
|
655
1343
|
|
|
1344
|
+
// Fallback in case i18n interferes with normal CMS flows
|
|
1345
|
+
// Only generate fallback if locale parameter exists
|
|
1346
|
+
const hasLocaleParam = resource?.params?.locale !== undefined
|
|
1347
|
+
let fallbackAST = null
|
|
1348
|
+
|
|
1349
|
+
if (hasLocaleParam) {
|
|
1350
|
+
const fallbackParams = JSON.parse(JSON.stringify(resource))
|
|
1351
|
+
delete fallbackParams?.params?.locale
|
|
1352
|
+
const fallbackUrlParamsDeclaration = generateParamsAST(fallbackParams?.params)
|
|
1353
|
+
const assignmentOfNewUrlParams = types.expressionStatement(
|
|
1354
|
+
types.assignmentExpression(
|
|
1355
|
+
'=',
|
|
1356
|
+
types.identifier('urlParams'),
|
|
1357
|
+
types.objectExpression([...fallbackUrlParamsDeclaration])
|
|
1358
|
+
)
|
|
1359
|
+
)
|
|
1360
|
+
|
|
1361
|
+
const assignmentExpressionAST = types.expressionStatement(
|
|
1362
|
+
types.assignmentExpression(
|
|
1363
|
+
'=',
|
|
1364
|
+
types.identifier('data'),
|
|
1365
|
+
types.awaitExpression(
|
|
1366
|
+
types.callExpression(types.identifier('fetch'), [
|
|
1367
|
+
url,
|
|
1368
|
+
types.objectExpression([
|
|
1369
|
+
method,
|
|
1370
|
+
...(allHeaders.length > 0
|
|
1371
|
+
? [
|
|
1372
|
+
types.objectProperty(
|
|
1373
|
+
types.identifier('headers'),
|
|
1374
|
+
types.objectExpression(allHeaders)
|
|
1375
|
+
),
|
|
1376
|
+
]
|
|
1377
|
+
: []),
|
|
1378
|
+
...(bodyParamsDecleration.length > 0 && resource?.method === 'POST'
|
|
1379
|
+
? [
|
|
1380
|
+
types.objectProperty(
|
|
1381
|
+
types.identifier('body'),
|
|
1382
|
+
types.callExpression(
|
|
1383
|
+
types.memberExpression(
|
|
1384
|
+
types.identifier('JSON'),
|
|
1385
|
+
types.identifier('stringify')
|
|
1386
|
+
),
|
|
1387
|
+
[types.identifier('bodyParams')]
|
|
1388
|
+
)
|
|
1389
|
+
),
|
|
1390
|
+
]
|
|
1391
|
+
: []),
|
|
1392
|
+
]),
|
|
1393
|
+
])
|
|
1394
|
+
)
|
|
1395
|
+
)
|
|
1396
|
+
)
|
|
1397
|
+
|
|
1398
|
+
fallbackAST = types.ifStatement(
|
|
1399
|
+
types.binaryExpression(
|
|
1400
|
+
'!==',
|
|
1401
|
+
types.memberExpression(types.identifier('data'), types.identifier('status')),
|
|
1402
|
+
types.numericLiteral(200)
|
|
1403
|
+
),
|
|
1404
|
+
types.blockStatement([assignmentOfNewUrlParams, assignmentExpressionAST])
|
|
1405
|
+
)
|
|
1406
|
+
}
|
|
656
1407
|
const responseType = resource?.response?.type ?? 'json'
|
|
657
1408
|
let responseJSONAST
|
|
658
1409
|
|
|
@@ -719,20 +1470,98 @@ export const generateRemoteResourceASTs = (resource: UIDLResourceItem) => {
|
|
|
719
1470
|
}
|
|
720
1471
|
}
|
|
721
1472
|
|
|
722
|
-
return [
|
|
1473
|
+
return [
|
|
1474
|
+
...(urlParamsDecleration.length > 0
|
|
1475
|
+
? [
|
|
1476
|
+
types.variableDeclaration('let', [
|
|
1477
|
+
types.variableDeclarator(
|
|
1478
|
+
types.identifier('urlParams'),
|
|
1479
|
+
types.objectExpression(urlParamsDecleration)
|
|
1480
|
+
),
|
|
1481
|
+
]),
|
|
1482
|
+
]
|
|
1483
|
+
: []),
|
|
1484
|
+
...(bodyParamsDecleration.length > 0
|
|
1485
|
+
? [
|
|
1486
|
+
types.variableDeclaration('const', [
|
|
1487
|
+
types.variableDeclarator(
|
|
1488
|
+
types.identifier('bodyParams'),
|
|
1489
|
+
types.objectExpression(bodyParamsDecleration)
|
|
1490
|
+
),
|
|
1491
|
+
]),
|
|
1492
|
+
]
|
|
1493
|
+
: []),
|
|
1494
|
+
fetchAST,
|
|
1495
|
+
...(fallbackAST ? [fallbackAST] : []),
|
|
1496
|
+
responseJSONAST,
|
|
1497
|
+
].filter(Boolean)
|
|
1498
|
+
}
|
|
1499
|
+
|
|
1500
|
+
const generateParamsAST = (
|
|
1501
|
+
props: Record<string, UIDLStaticValue | UIDLPropValue | UIDLStateValue | UIDLExpressionValue>
|
|
1502
|
+
): Array<types.ObjectProperty | types.SpreadElement> => {
|
|
1503
|
+
return Object.keys(props || {}).reduce(
|
|
1504
|
+
(acc: Array<types.ObjectProperty | types.SpreadElement>, item) => {
|
|
1505
|
+
const prop = props[item]
|
|
1506
|
+
if (prop.type === 'static') {
|
|
1507
|
+
acc.push(types.objectProperty(types.stringLiteral(item), resolveObjectValue(prop)))
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
if (prop.type === 'expr') {
|
|
1511
|
+
acc.push(
|
|
1512
|
+
types.objectProperty(types.stringLiteral(item), getExpressionFromUIDLExpressionNode(prop))
|
|
1513
|
+
)
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
if (prop.type === 'dynamic') {
|
|
1517
|
+
acc.push(
|
|
1518
|
+
types.spreadElement(
|
|
1519
|
+
types.logicalExpression(
|
|
1520
|
+
'&&',
|
|
1521
|
+
types.memberExpression(
|
|
1522
|
+
types.identifier('params'),
|
|
1523
|
+
types.stringLiteral(prop.content.id),
|
|
1524
|
+
true,
|
|
1525
|
+
false
|
|
1526
|
+
),
|
|
1527
|
+
types.objectExpression([
|
|
1528
|
+
types.objectProperty(
|
|
1529
|
+
types.stringLiteral(item),
|
|
1530
|
+
types.memberExpression(
|
|
1531
|
+
types.identifier('params'),
|
|
1532
|
+
types.stringLiteral(prop.content.id),
|
|
1533
|
+
true,
|
|
1534
|
+
false
|
|
1535
|
+
)
|
|
1536
|
+
),
|
|
1537
|
+
])
|
|
1538
|
+
)
|
|
1539
|
+
)
|
|
1540
|
+
)
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
return acc
|
|
1544
|
+
},
|
|
1545
|
+
[]
|
|
1546
|
+
)
|
|
723
1547
|
}
|
|
724
1548
|
|
|
725
1549
|
const generateRESTHeadersAST = (headers: UIDLResourceItem['headers']): types.ObjectProperty[] => {
|
|
726
|
-
return
|
|
727
|
-
.
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
1550
|
+
return (
|
|
1551
|
+
Object.keys(headers)
|
|
1552
|
+
// `authToken` is rendered as the `Authorization` header; `authScheme` is a
|
|
1553
|
+
// generator-only directive for that header's prefix — neither is emitted as
|
|
1554
|
+
// its own literal HTTP header.
|
|
1555
|
+
.filter((header) => header !== 'authToken' && header !== 'authScheme')
|
|
1556
|
+
.map((header) => {
|
|
1557
|
+
const headerResolved = resolveResourceValue(headers[header])
|
|
1558
|
+
const value =
|
|
1559
|
+
headers[header].type === 'static'
|
|
1560
|
+
? types.stringLiteral(String(headerResolved))
|
|
1561
|
+
: types.identifier(String(headerResolved))
|
|
1562
|
+
return types.objectProperty(types.stringLiteral(header), value)
|
|
1563
|
+
})
|
|
1564
|
+
)
|
|
736
1565
|
}
|
|
737
1566
|
|
|
738
1567
|
export const generateMemberExpressionASTFromBase = (
|
|
@@ -754,6 +1583,22 @@ export const generateMemberExpressionASTFromBase = (
|
|
|
754
1583
|
)
|
|
755
1584
|
}
|
|
756
1585
|
|
|
1586
|
+
export const parseValuePath = (valuePath: Array<string | number>): Array<string | number> => {
|
|
1587
|
+
return valuePath.map((segment) => {
|
|
1588
|
+
if (typeof segment === 'string') {
|
|
1589
|
+
const bracketMatch = segment.match(/^\[(\d+)\]$/)
|
|
1590
|
+
if (bracketMatch) {
|
|
1591
|
+
return parseInt(bracketMatch[1], 10)
|
|
1592
|
+
}
|
|
1593
|
+
const numericMatch = segment.match(/^\d+$/)
|
|
1594
|
+
if (numericMatch) {
|
|
1595
|
+
return parseInt(segment, 10)
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
return segment
|
|
1599
|
+
})
|
|
1600
|
+
}
|
|
1601
|
+
|
|
757
1602
|
export const generateMemberExpressionASTFromPath = (
|
|
758
1603
|
path: Array<string | number>
|
|
759
1604
|
): types.OptionalMemberExpression | types.Identifier => {
|
|
@@ -769,7 +1614,7 @@ export const generateMemberExpressionASTFromPath = (
|
|
|
769
1614
|
return types.optionalMemberExpression(
|
|
770
1615
|
generateMemberExpressionASTFromPath(pathClone),
|
|
771
1616
|
types.numericLiteral(currentPath),
|
|
772
|
-
|
|
1617
|
+
true,
|
|
773
1618
|
true
|
|
774
1619
|
)
|
|
775
1620
|
}
|
|
@@ -855,14 +1700,28 @@ const computeAuthorizationHeaderAST = (headers: UIDLResourceItem['headers']) =>
|
|
|
855
1700
|
|
|
856
1701
|
const authTokenType = headers.authToken?.type
|
|
857
1702
|
|
|
1703
|
+
// The auth scheme prefix defaults to `Bearer ` (back-compatible with every CMS
|
|
1704
|
+
// and data-source that stores a bare bearer token). A resource may override it
|
|
1705
|
+
// via a `headers.authScheme` static value — e.g. WordPress Basic / Application
|
|
1706
|
+
// Password auth sets `Basic ` so the rendered header is `Basic <base64>`
|
|
1707
|
+
// instead of the wrong `Bearer <base64>`. `authScheme` is consumed here and
|
|
1708
|
+
// filtered out of the emitted REST headers (see generateRESTHeadersAST).
|
|
1709
|
+
const authSchemeValue = headers.authScheme
|
|
1710
|
+
const schemePrefix =
|
|
1711
|
+
authSchemeValue &&
|
|
1712
|
+
authSchemeValue.type === 'static' &&
|
|
1713
|
+
typeof authSchemeValue.content === 'string'
|
|
1714
|
+
? authSchemeValue.content
|
|
1715
|
+
: 'Bearer '
|
|
1716
|
+
|
|
858
1717
|
return types.objectProperty(
|
|
859
1718
|
types.identifier('Authorization'),
|
|
860
1719
|
types.templateLiteral(
|
|
861
1720
|
[
|
|
862
1721
|
types.templateElement(
|
|
863
1722
|
{
|
|
864
|
-
cooked: authTokenType === 'static' ?
|
|
865
|
-
raw: authTokenType === 'static' ?
|
|
1723
|
+
cooked: authTokenType === 'static' ? `${schemePrefix}${authToken}` : schemePrefix,
|
|
1724
|
+
raw: authTokenType === 'static' ? `${schemePrefix}${authToken}` : schemePrefix,
|
|
866
1725
|
},
|
|
867
1726
|
false
|
|
868
1727
|
),
|
|
@@ -885,7 +1744,7 @@ const computeAuthorizationHeaderAST = (headers: UIDLResourceItem['headers']) =>
|
|
|
885
1744
|
)
|
|
886
1745
|
}
|
|
887
1746
|
|
|
888
|
-
const computeFetchUrl = (resource: UIDLResourceItem) => {
|
|
1747
|
+
export const computeFetchUrl = (resource: UIDLResourceItem) => {
|
|
889
1748
|
const { path } = resource
|
|
890
1749
|
const fetchBaseUrl = resolveResourceValue(path.baseUrl)
|
|
891
1750
|
const resourceRoute = resolveResourceValue(path.route)
|
|
@@ -894,7 +1753,42 @@ const computeFetchUrl = (resource: UIDLResourceItem) => {
|
|
|
894
1753
|
const routeType = path.route?.type
|
|
895
1754
|
|
|
896
1755
|
if (baseUrlType === 'static' && routeType === 'static') {
|
|
897
|
-
const
|
|
1756
|
+
const baseUrlStr = typeof fetchBaseUrl === 'string' ? fetchBaseUrl : String(fetchBaseUrl || '')
|
|
1757
|
+
const routeStr = typeof resourceRoute === 'string' ? resourceRoute : String(resourceRoute || '')
|
|
1758
|
+
const cleanBaseUrl = baseUrlStr.endsWith('/') ? baseUrlStr.slice(0, -1) : baseUrlStr
|
|
1759
|
+
const cleanRoute = routeStr.startsWith('/') ? routeStr.slice(1) : routeStr
|
|
1760
|
+
const stringsToJoin = [cleanBaseUrl, cleanRoute].filter((item) => item).join('/')
|
|
1761
|
+
|
|
1762
|
+
// If the URL is relative (starts with /), add a runtime base URL prefix
|
|
1763
|
+
// so fetch() works in server-side contexts (getStaticProps/getServerSideProps).
|
|
1764
|
+
// Non-NEXT_PUBLIC_ env vars are only available server-side in Next.js,
|
|
1765
|
+
// so NEXTAUTH_URL naturally resolves to undefined on the client (making baseUrl '').
|
|
1766
|
+
if (stringsToJoin.startsWith('/')) {
|
|
1767
|
+
const processEnv = types.memberExpression(
|
|
1768
|
+
types.identifier('process'),
|
|
1769
|
+
types.identifier('env')
|
|
1770
|
+
)
|
|
1771
|
+
const serverBaseUrlExpr = types.logicalExpression(
|
|
1772
|
+
'||',
|
|
1773
|
+
types.logicalExpression(
|
|
1774
|
+
'||',
|
|
1775
|
+
types.memberExpression(processEnv, types.identifier('NEXT_PUBLIC_SITE_URL')),
|
|
1776
|
+
types.memberExpression(
|
|
1777
|
+
types.memberExpression(types.identifier('process'), types.identifier('env')),
|
|
1778
|
+
types.identifier('NEXTAUTH_URL')
|
|
1779
|
+
)
|
|
1780
|
+
),
|
|
1781
|
+
types.stringLiteral('')
|
|
1782
|
+
)
|
|
1783
|
+
return types.templateLiteral(
|
|
1784
|
+
[
|
|
1785
|
+
types.templateElement({ cooked: '', raw: '' }, false),
|
|
1786
|
+
types.templateElement({ cooked: `${stringsToJoin}`, raw: `${stringsToJoin}` }, true),
|
|
1787
|
+
],
|
|
1788
|
+
[serverBaseUrlExpr]
|
|
1789
|
+
)
|
|
1790
|
+
}
|
|
1791
|
+
|
|
898
1792
|
return types.templateLiteral(
|
|
899
1793
|
[types.templateElement({ cooked: `${stringsToJoin}`, raw: `${stringsToJoin}` }, true)],
|
|
900
1794
|
[]
|
|
@@ -983,6 +1877,7 @@ export const resolveObjectValue = (
|
|
|
983
1877
|
| types.NumericLiteral
|
|
984
1878
|
| types.BooleanLiteral
|
|
985
1879
|
| types.ObjectExpression
|
|
1880
|
+
| types.ArrayExpression
|
|
986
1881
|
| types.Expression => {
|
|
987
1882
|
if (prop.type === 'static') {
|
|
988
1883
|
const value =
|
|
@@ -992,6 +1887,8 @@ export const resolveObjectValue = (
|
|
|
992
1887
|
? types.booleanLiteral(prop.content)
|
|
993
1888
|
: typeof prop.content === 'number'
|
|
994
1889
|
? types.numericLiteral(prop.content)
|
|
1890
|
+
: Array.isArray(prop.content)
|
|
1891
|
+
? types.arrayExpression(prop.content.map((element) => convertValueToLiteral(element)))
|
|
995
1892
|
: typeof prop.content === 'object'
|
|
996
1893
|
? objectToObjectExpression(prop.content as unknown as Record<string, unknown>)
|
|
997
1894
|
: types.identifier(String(prop.content))
|
|
@@ -1004,14 +1901,99 @@ export const resolveObjectValue = (
|
|
|
1004
1901
|
}
|
|
1005
1902
|
}
|
|
1006
1903
|
|
|
1904
|
+
/**
|
|
1905
|
+
* Detects if a value is a UIDL dynamic reference (state or prop)
|
|
1906
|
+
*/
|
|
1907
|
+
export const isUIDLDynamicReference = (value: unknown): boolean => {
|
|
1908
|
+
return (
|
|
1909
|
+
typeof value === 'object' &&
|
|
1910
|
+
value !== null &&
|
|
1911
|
+
'type' in value &&
|
|
1912
|
+
(value as Record<string, unknown>).type === 'dynamic' &&
|
|
1913
|
+
'content' in value &&
|
|
1914
|
+
typeof (value as Record<string, unknown>).content === 'object' &&
|
|
1915
|
+
(value as Record<string, unknown>).content !== null &&
|
|
1916
|
+
'referenceType' in ((value as Record<string, unknown>).content as Record<string, unknown>) &&
|
|
1917
|
+
'id' in ((value as Record<string, unknown>).content as Record<string, unknown>)
|
|
1918
|
+
)
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
/**
|
|
1922
|
+
* Converts a filter destination value to an AST expression.
|
|
1923
|
+
* Handles both static values and dynamic references (state/prop).
|
|
1924
|
+
*/
|
|
1925
|
+
export const convertFilterDestinationToExpression = (
|
|
1926
|
+
destination: unknown,
|
|
1927
|
+
options?: { dynamicReferencePrefixMap?: Record<string, string> }
|
|
1928
|
+
): types.Expression => {
|
|
1929
|
+
// Handle dynamic references (state or prop)
|
|
1930
|
+
if (isUIDLDynamicReference(destination)) {
|
|
1931
|
+
const content = (destination as Record<string, unknown>).content as {
|
|
1932
|
+
referenceType: string
|
|
1933
|
+
id: string
|
|
1934
|
+
}
|
|
1935
|
+
const { referenceType, id } = content
|
|
1936
|
+
|
|
1937
|
+
if (referenceType === 'state') {
|
|
1938
|
+
return types.identifier(id)
|
|
1939
|
+
}
|
|
1940
|
+
|
|
1941
|
+
if (referenceType === 'prop') {
|
|
1942
|
+
const prefix = options?.dynamicReferencePrefixMap?.prop || 'props'
|
|
1943
|
+
return types.memberExpression(types.identifier(prefix), types.identifier(id))
|
|
1944
|
+
}
|
|
1945
|
+
|
|
1946
|
+
// Fallback for other reference types
|
|
1947
|
+
return types.identifier(id)
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
// Handle static string values
|
|
1951
|
+
if (typeof destination === 'string') {
|
|
1952
|
+
return types.stringLiteral(destination)
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
// Handle other primitives
|
|
1956
|
+
if (typeof destination === 'number') {
|
|
1957
|
+
return types.numericLiteral(destination)
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
if (typeof destination === 'boolean') {
|
|
1961
|
+
return types.booleanLiteral(destination)
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
// Handle arrays
|
|
1965
|
+
if (Array.isArray(destination)) {
|
|
1966
|
+
return types.arrayExpression(
|
|
1967
|
+
destination.map((item) => convertFilterDestinationToExpression(item, options))
|
|
1968
|
+
)
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
// Fallback to empty string for undefined/null
|
|
1972
|
+
return types.stringLiteral('')
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1007
1975
|
export const getExpressionFromUIDLExpressionNode = (
|
|
1008
1976
|
node: UIDLExpressionValue
|
|
1009
1977
|
): types.Expression => {
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1978
|
+
let ast
|
|
1979
|
+
try {
|
|
1980
|
+
ast = parse(sanitizeExprContent(node.content), {
|
|
1981
|
+
sourceType: 'module' as const,
|
|
1982
|
+
})
|
|
1983
|
+
} catch (err) {
|
|
1984
|
+
// Malformed expression content in the UIDL (e.g. `?.subtitle` missing its
|
|
1985
|
+
// left-hand identifier). Don't abort the whole generation — warn and fall
|
|
1986
|
+
// back to `undefined`, which renders as nothing in JSX.
|
|
1987
|
+
// tslint:disable-next-line:no-console
|
|
1988
|
+
console.warn(
|
|
1989
|
+
`Failed to parse UIDL expression content ${JSON.stringify(node.content)}: ${
|
|
1990
|
+
(err as Error).message
|
|
1991
|
+
}. Falling back to 'undefined'.`
|
|
1992
|
+
)
|
|
1993
|
+
return types.identifier('undefined')
|
|
1994
|
+
}
|
|
1013
1995
|
|
|
1014
|
-
if (!('program' in ast)) {
|
|
1996
|
+
if (!ast || !('program' in ast)) {
|
|
1015
1997
|
throw new Error(
|
|
1016
1998
|
`The AST does not have a program node in the expression inside addDynamicExpressionAttributeToJSXTag`
|
|
1017
1999
|
)
|
|
@@ -1019,9 +2001,123 @@ export const getExpressionFromUIDLExpressionNode = (
|
|
|
1019
2001
|
|
|
1020
2002
|
const theStatementOnlyWihtoutTheProgram = ast.program.body[0]
|
|
1021
2003
|
|
|
1022
|
-
if (
|
|
2004
|
+
if (
|
|
2005
|
+
!theStatementOnlyWihtoutTheProgram ||
|
|
2006
|
+
theStatementOnlyWihtoutTheProgram.type !== 'ExpressionStatement'
|
|
2007
|
+
) {
|
|
1023
2008
|
throw new Error(`Expr dynamic attribute only support expressions statements at the moment.`)
|
|
1024
2009
|
}
|
|
1025
2010
|
|
|
1026
|
-
return theStatementOnlyWihtoutTheProgram.expression
|
|
2011
|
+
return makeMemberAccessOptional(theStatementOnlyWihtoutTheProgram.expression)
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
/**
|
|
2015
|
+
* Every member read in a UIDL expression becomes an optional-chain read:
|
|
2016
|
+
* `strengths[0].pillar` → `strengths?.[0]?.pillar`. A binding into a list
|
|
2017
|
+
* that is empty until a workflow fills it (the first render, a reset) must
|
|
2018
|
+
* read `undefined`, never throw — one such read took a whole page down at
|
|
2019
|
+
* server render ("Cannot read properties of undefined"). A call's callee
|
|
2020
|
+
* keeps its plain member (`JSON.stringify(x)`), and an assignment or update
|
|
2021
|
+
* target is left as written.
|
|
2022
|
+
*/
|
|
2023
|
+
export const makeMemberAccessOptional = <T extends types.Node>(node: T): T => {
|
|
2024
|
+
const SKIP_KEYS = new Set([
|
|
2025
|
+
'loc',
|
|
2026
|
+
'start',
|
|
2027
|
+
'end',
|
|
2028
|
+
'leadingComments',
|
|
2029
|
+
'trailingComments',
|
|
2030
|
+
'innerComments',
|
|
2031
|
+
'extra',
|
|
2032
|
+
])
|
|
2033
|
+
const isNode = (value: unknown): value is types.Node =>
|
|
2034
|
+
Boolean(value) &&
|
|
2035
|
+
typeof value === 'object' &&
|
|
2036
|
+
typeof (value as { type?: unknown }).type === 'string'
|
|
2037
|
+
|
|
2038
|
+
const visit = (current: types.Node, asCallee: boolean, asTarget: boolean): types.Node => {
|
|
2039
|
+
if (current.type === 'MemberExpression' && !asCallee && !asTarget) {
|
|
2040
|
+
const member = current as types.MemberExpression
|
|
2041
|
+
const object = visit(member.object, false, false) as types.Expression
|
|
2042
|
+
const property = member.computed
|
|
2043
|
+
? (visit(member.property, false, false) as types.Expression)
|
|
2044
|
+
: member.property
|
|
2045
|
+
return types.optionalMemberExpression(
|
|
2046
|
+
object,
|
|
2047
|
+
property as types.Expression,
|
|
2048
|
+
member.computed,
|
|
2049
|
+
true
|
|
2050
|
+
)
|
|
2051
|
+
}
|
|
2052
|
+
if (
|
|
2053
|
+
current.type === 'CallExpression' ||
|
|
2054
|
+
current.type === 'OptionalCallExpression' ||
|
|
2055
|
+
current.type === 'NewExpression'
|
|
2056
|
+
) {
|
|
2057
|
+
const call = current as types.CallExpression
|
|
2058
|
+
// The callee's own member stays plain; what it is read from is guarded.
|
|
2059
|
+
if (call.callee.type === 'MemberExpression') {
|
|
2060
|
+
const callee = call.callee as types.MemberExpression
|
|
2061
|
+
callee.object = visit(callee.object, false, false) as types.Expression
|
|
2062
|
+
if (callee.computed)
|
|
2063
|
+
callee.property = visit(callee.property, false, false) as types.Expression
|
|
2064
|
+
} else {
|
|
2065
|
+
call.callee = visit(call.callee, true, false) as types.Expression
|
|
2066
|
+
}
|
|
2067
|
+
call.arguments = call.arguments.map(
|
|
2068
|
+
(argument) => visit(argument, false, false) as typeof argument
|
|
2069
|
+
)
|
|
2070
|
+
return call
|
|
2071
|
+
}
|
|
2072
|
+
if (current.type === 'AssignmentExpression') {
|
|
2073
|
+
const assignment = current as types.AssignmentExpression
|
|
2074
|
+
assignment.right = visit(assignment.right, false, false) as types.Expression
|
|
2075
|
+
return assignment
|
|
2076
|
+
}
|
|
2077
|
+
if (
|
|
2078
|
+
current.type === 'UpdateExpression' ||
|
|
2079
|
+
(current.type === 'UnaryExpression' &&
|
|
2080
|
+
(current as types.UnaryExpression).operator === 'delete')
|
|
2081
|
+
) {
|
|
2082
|
+
return current
|
|
2083
|
+
}
|
|
2084
|
+
for (const key of Object.keys(current)) {
|
|
2085
|
+
if (SKIP_KEYS.has(key)) continue
|
|
2086
|
+
const value = (current as unknown as Record<string, unknown>)[key]
|
|
2087
|
+
if (Array.isArray(value)) {
|
|
2088
|
+
;(current as unknown as Record<string, unknown>)[key] = value.map((item) =>
|
|
2089
|
+
isNode(item) ? visit(item, false, false) : item
|
|
2090
|
+
)
|
|
2091
|
+
} else if (isNode(value)) {
|
|
2092
|
+
;(current as unknown as Record<string, unknown>)[key] = visit(value, false, false)
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
return current
|
|
2096
|
+
}
|
|
2097
|
+
return visit(node, false, false) as T
|
|
2098
|
+
}
|
|
2099
|
+
|
|
2100
|
+
export const isJSXElement = (value: types.JSXElement | HastNode): value is types.JSXElement =>
|
|
2101
|
+
value.type === 'JSXElement'
|
|
2102
|
+
|
|
2103
|
+
/**
|
|
2104
|
+
* Because of the restrictions of the AST Types we need to have a clear subset of binary operators we can use
|
|
2105
|
+
* @param operation - the operation defined in the UIDL for the current state branch
|
|
2106
|
+
*/
|
|
2107
|
+
export const convertToBinaryOperator = (operation: string): BinaryOperator => {
|
|
2108
|
+
const allowedOperations = ['===', '!==', '>=', '<=', '>', '<']
|
|
2109
|
+
if (allowedOperations.includes(operation)) {
|
|
2110
|
+
return operation as BinaryOperator
|
|
2111
|
+
} else {
|
|
2112
|
+
return '==='
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
|
|
2116
|
+
export const convertToUnaryOperator = (operation: string): UnaryOperation => {
|
|
2117
|
+
const allowedOperations = ['!']
|
|
2118
|
+
if (allowedOperations.includes(operation)) {
|
|
2119
|
+
return operation as UnaryOperation
|
|
2120
|
+
} else {
|
|
2121
|
+
return '!'
|
|
2122
|
+
}
|
|
1027
2123
|
}
|