@teleporthq/teleport-plugin-common 0.45.3-alpha.0 → 0.45.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/builders/html-builders.ts +9 -2
- package/__tests__/builders/style-builders.ts +135 -1
- 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/chart-data-guard.ts +101 -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 +635 -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 +80 -33
- 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 +10 -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 +1443 -45
- 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 +80 -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 +883 -72
- 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 +163 -11
- package/dist/cjs/utils/ast-utils.d.ts.map +1 -1
- package/dist/cjs/utils/ast-utils.js +1013 -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/nested-selector-commas.d.ts +2 -0
- package/dist/cjs/utils/nested-selector-commas.d.ts.map +1 -0
- package/dist/cjs/utils/nested-selector-commas.js +81 -0
- package/dist/cjs/utils/nested-selector-commas.js.map +1 -0
- 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 +78 -32
- 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 +1442 -47
- 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 +80 -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 +875 -70
- 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 +163 -11
- package/dist/esm/utils/ast-utils.d.ts.map +1 -1
- package/dist/esm/utils/ast-utils.js +989 -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/nested-selector-commas.d.ts +2 -0
- package/dist/esm/utils/nested-selector-commas.d.ts.map +1 -0
- package/dist/esm/utils/nested-selector-commas.js +77 -0
- package/dist/esm/utils/nested-selector-commas.js.map +1 -0
- 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 +121 -43
- package/src/index.ts +22 -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 +2135 -62
- package/src/node-handlers/node-to-jsx/types.ts +75 -32
- package/src/node-handlers/node-to-jsx/utils.ts +1173 -84
- package/src/utils/ast-utils.ts +1316 -127
- package/src/utils/hast-utils.ts +37 -9
- package/src/utils/nested-selector-commas.ts +88 -0
- 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
|
@@ -35,23 +35,72 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
35
35
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
36
36
|
};
|
|
37
37
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
38
|
-
exports.getExpressionFromUIDLExpressionNode = exports.resolveObjectValue = exports.generateURLParamsAST = exports.generateMemberExpressionASTFromPath = exports.generateMemberExpressionASTFromBase = exports.generateRemoteResourceASTs = exports.wrapObjectPropertiesWithExpression = exports.generateDynamicWindowImport = exports.createStateHookAST = exports.createReturnExpressionSyntax = exports.createPureComponent = exports.createClassComponent = exports.removeAttributeByName = exports.findAttributeByName = exports.getTSAnnotationForType = exports.addPropertyToASTObject = exports.convertValueToLiteral = exports.objectToObjectExpression = exports.renameJSXTag = exports.addSpreadAttributeToJSXTag = exports.addChildJSXText = exports.addChildJSXTag = exports.addRawAttributeToJSXTag = exports.addAttributeToJSXTag = exports.stringAsTemplateLiteral = exports.addMultipleDynamicAttributesToJSXTag = exports.addDynamicExpressionAttributeToJSXTag = exports.addDynamicAttributeToJSXTag = exports.addClassStringOnJSXTag = void 0;
|
|
38
|
+
exports.makeMemberAccessOptional = exports.getExpressionFromUIDLExpressionNode = exports.convertFilterDestinationToExpression = exports.isUIDLDynamicReference = exports.resolveObjectValue = exports.computeFetchUrl = exports.generateURLParamsAST = exports.generateMemberExpressionASTFromPath = exports.parseValuePath = exports.generateMemberExpressionASTFromBase = exports.generateRemoteResourceASTs = exports.wrapObjectPropertiesWithExpression = exports.generateDynamicWindowImport = exports.collectGlobalStateReferencesFromObjectStates = exports.collectGlobalReferencesFromObjectStates = exports.resolveGlobalRefId = exports.GLOBAL_REF_ID_MAP = exports.convertObjectStateDefaultToExpression = exports.isObjectStateWithEntries = exports.createStateHookAST = exports.createReturnExpressionSyntax = exports.createPureComponent = exports.createClassComponent = exports.removeAttributeByName = exports.findAttributeByName = exports.getTSAnnotationForType = exports.addPropertyToASTObject = exports.convertValueToLiteral = exports.passesCollectionTest = exports.isCollectionOperation = exports.coerceToDeclaredType = exports.objectToObjectExpression = exports.renameJSXTag = exports.addSpreadAttributeToJSXTag = exports.addChildJSXText = exports.addChildJSXTag = exports.addRawAttributeToJSXTag = exports.addAttributeToJSXTag = exports.parseStringWithTemplateExpressions = exports.parseJSExpressionAsAST = exports.containsTemplateExpression = exports.stringAsTemplateLiteral = exports.addMultipleDynamicAttributesToJSXTag = exports.addDynamicExpressionAttributeToJSXTag = exports.sanitizeExprContent = exports.addDynamicAttributeToJSXTag = exports.addClassStringOnJSXTag = exports.convertToReactAttributeName = exports.resolveAttributeNameForTag = exports.isCustomElementTagName = void 0;
|
|
39
|
+
exports.convertToUnaryOperator = exports.convertToBinaryOperator = exports.isJSXElement = void 0;
|
|
39
40
|
var types = __importStar(require("@babel/types"));
|
|
40
41
|
var core_1 = require("@babel/core");
|
|
41
42
|
var parsed_ast_1 = __importDefault(require("./parsed-ast"));
|
|
42
43
|
var teleport_shared_1 = require("@teleporthq/teleport-shared");
|
|
43
44
|
var preset_react_1 = __importDefault(require("@babel/preset-react"));
|
|
44
|
-
var
|
|
45
|
+
var template_expression_balance_1 = require("./template-expression-balance");
|
|
45
46
|
/**
|
|
46
|
-
*
|
|
47
|
+
* Converts HTML attribute names to React/JSX camelCase format
|
|
48
|
+
* Preserves data-* and aria-* attributes as-is
|
|
49
|
+
*/
|
|
50
|
+
/**
|
|
51
|
+
* React sets attributes on CUSTOM ELEMENTS (dash-named tags) verbatim, so
|
|
52
|
+
* camelCasing them is not just unnecessary — it breaks the element:
|
|
53
|
+
* `camera-controls` camelCased to `cameraControls` reaches the DOM as the
|
|
54
|
+
* meaningless `cameracontrols`. Web-component tags keep their attribute
|
|
55
|
+
* spelling untouched.
|
|
56
|
+
*/
|
|
57
|
+
var isCustomElementTagName = function (jsxNode) {
|
|
58
|
+
var name = jsxNode.openingElement.name;
|
|
59
|
+
return name.type === 'JSXIdentifier' && name.name.includes('-');
|
|
60
|
+
};
|
|
61
|
+
exports.isCustomElementTagName = isCustomElementTagName;
|
|
62
|
+
var resolveAttributeNameForTag = function (jsxNode, attrName) {
|
|
63
|
+
return (0, exports.isCustomElementTagName)(jsxNode) ? attrName : (0, exports.convertToReactAttributeName)(attrName);
|
|
64
|
+
};
|
|
65
|
+
exports.resolveAttributeNameForTag = resolveAttributeNameForTag;
|
|
66
|
+
var convertToReactAttributeName = function (attrName) {
|
|
67
|
+
if (attrName.startsWith('data-') || attrName.startsWith('aria-')) {
|
|
68
|
+
return attrName;
|
|
69
|
+
}
|
|
70
|
+
var htmlToReact = {
|
|
71
|
+
colspan: 'colSpan',
|
|
72
|
+
rowspan: 'rowSpan',
|
|
73
|
+
maxlength: 'maxLength',
|
|
74
|
+
minlength: 'minLength',
|
|
75
|
+
readonly: 'readOnly',
|
|
76
|
+
autocomplete: 'autoComplete',
|
|
77
|
+
autofocus: 'autoFocus',
|
|
78
|
+
tabindex: 'tabIndex',
|
|
79
|
+
contenteditable: 'contentEditable',
|
|
80
|
+
spellcheck: 'spellCheck',
|
|
81
|
+
};
|
|
82
|
+
if (htmlToReact[attrName]) {
|
|
83
|
+
return htmlToReact[attrName];
|
|
84
|
+
}
|
|
85
|
+
return attrName.replace(/-([a-z])/g, function (_, letter) { return letter.toUpperCase(); });
|
|
86
|
+
};
|
|
87
|
+
exports.convertToReactAttributeName = convertToReactAttributeName;
|
|
88
|
+
/**
|
|
89
|
+
* Adds a CSS class definition string to an existing string of classes
|
|
47
90
|
*/
|
|
48
91
|
var addClassStringOnJSXTag = function (jsxNode, classString, classAttributeName, dynamicValues) {
|
|
49
92
|
if (dynamicValues === void 0) { dynamicValues = []; }
|
|
93
|
+
if (classString === '' && dynamicValues.length === 0) {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
50
96
|
var classAttribute = getClassAttribute(jsxNode, { createIfNotFound: true, classAttributeName: classAttributeName });
|
|
51
97
|
if (dynamicValues.length === 0) {
|
|
52
98
|
if (classAttribute.value && classAttribute.value.type === 'StringLiteral') {
|
|
53
99
|
var classArray = classAttribute.value.value.split(' ');
|
|
54
|
-
|
|
100
|
+
if (classString) {
|
|
101
|
+
classArray.push(classString);
|
|
102
|
+
}
|
|
103
|
+
classArray.filter(function (item) { return item; });
|
|
55
104
|
classAttribute.value.value = classArray.join(' ').trim();
|
|
56
105
|
}
|
|
57
106
|
else {
|
|
@@ -102,10 +151,16 @@ var getClassAttribute = function (jsxNode, _a, t) {
|
|
|
102
151
|
var addDynamicAttributeToJSXTag = function (jsxASTNode, name, value, prefix, t) {
|
|
103
152
|
if (prefix === void 0) { prefix = ''; }
|
|
104
153
|
if (t === void 0) { t = types; }
|
|
154
|
+
var reactName = (0, exports.resolveAttributeNameForTag)(jsxASTNode, name);
|
|
155
|
+
// Same rule as `createDynamicValueExpression`: with no prefix the value IS the
|
|
156
|
+
// binding (React hooks state), so it must match the sanitised name
|
|
157
|
+
// `createStateHookAST` declared — `value={class}` does not parse. With a
|
|
158
|
+
// prefix it is `props.class` / `this.class`, where the UIDL spelling is legal
|
|
159
|
+
// AND load-bearing, so it is left alone.
|
|
105
160
|
var content = prefix === ''
|
|
106
|
-
? t.identifier(value)
|
|
161
|
+
? t.identifier(teleport_shared_1.JSIdentifiers.createSafeJSIdentifierPath(value))
|
|
107
162
|
: t.memberExpression(t.identifier(prefix), t.identifier(value));
|
|
108
|
-
jsxASTNode.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier(
|
|
163
|
+
jsxASTNode.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier(reactName), t.jsxExpressionContainer(content)));
|
|
109
164
|
};
|
|
110
165
|
exports.addDynamicAttributeToJSXTag = addDynamicAttributeToJSXTag;
|
|
111
166
|
/**
|
|
@@ -114,13 +169,48 @@ exports.addDynamicAttributeToJSXTag = addDynamicAttributeToJSXTag;
|
|
|
114
169
|
* the corresponding value from the contexts for now
|
|
115
170
|
* and in the future with other sources.
|
|
116
171
|
*/
|
|
172
|
+
/**
|
|
173
|
+
* UIDL `expr` values are opaque JavaScript expressions, but authoring tools
|
|
174
|
+
* (notably Teleport-GUI while the differentiator-navlink contract is mid-
|
|
175
|
+
* migration) occasionally emit malformed template literals with empty
|
|
176
|
+
* substitutions like `` `/profile/${}` ``. Babel rejects these and the whole
|
|
177
|
+
* generation run fails.
|
|
178
|
+
*
|
|
179
|
+
* We only repair a narrow set of known-safe patterns to avoid silently
|
|
180
|
+
* masking real UIDL bugs:
|
|
181
|
+
* 1. `/profile/${}` → `/profile/${currentUser?.id}` (My Profile navlink
|
|
182
|
+
* per the dual-mode profile page contract).
|
|
183
|
+
* 2. any remaining empty `${}` → `${''}` — at least the output parses and
|
|
184
|
+
* the placeholder is visibly empty at runtime.
|
|
185
|
+
* Each repair logs a warning so the upstream UIDL bug remains visible.
|
|
186
|
+
*/
|
|
187
|
+
var sanitizeExprContent = function (content, attrKey) {
|
|
188
|
+
if (typeof content !== 'string' || !content.includes('${}')) {
|
|
189
|
+
return content;
|
|
190
|
+
}
|
|
191
|
+
var repaired = content;
|
|
192
|
+
// My Profile navlink: the differentiator is always the session user's id.
|
|
193
|
+
repaired = repaired.replace(/`([^`]*\/profile\/)\$\{\}([^`]*)`/g, '`$1' + '$' + '{' + 'currentUser?.id}' + '$2`');
|
|
194
|
+
// Generic fallback: any other empty `${}` becomes an empty string literal so
|
|
195
|
+
// downstream Babel parsing succeeds. This is intentionally lossy — the goal
|
|
196
|
+
// is not to guess the original intent, just to keep the build from crashing.
|
|
197
|
+
if (repaired.includes('${}')) {
|
|
198
|
+
repaired = repaired.replace(/\$\{\}/g, '$' + '{' + "'" + "'" + '}');
|
|
199
|
+
}
|
|
200
|
+
if (repaired !== content) {
|
|
201
|
+
// tslint:disable-next-line:no-console
|
|
202
|
+
console.warn("[teleport] Repaired malformed empty template substitution in expr".concat(attrKey ? " attribute \"".concat(attrKey, "\"") : '', ": ").concat(content, " \u2192 ").concat(repaired));
|
|
203
|
+
}
|
|
204
|
+
return repaired;
|
|
205
|
+
};
|
|
206
|
+
exports.sanitizeExprContent = sanitizeExprContent;
|
|
117
207
|
var addDynamicExpressionAttributeToJSXTag = function (jsxASTNode, dynamicRef, attrKey, t) {
|
|
118
208
|
if (t === void 0) { t = types; }
|
|
119
209
|
var dynamicContent = dynamicRef.content;
|
|
120
210
|
if (dynamicRef.type !== 'expr') {
|
|
121
211
|
throw new Error("This method only works with dynamic nodes that have code expressions");
|
|
122
212
|
}
|
|
123
|
-
var code = dynamicContent;
|
|
213
|
+
var code = (0, exports.sanitizeExprContent)(dynamicContent, attrKey);
|
|
124
214
|
var options = {
|
|
125
215
|
sourceType: 'module',
|
|
126
216
|
};
|
|
@@ -132,7 +222,18 @@ var addDynamicExpressionAttributeToJSXTag = function (jsxASTNode, dynamicRef, at
|
|
|
132
222
|
if (theStatementOnlyWihtoutTheProgram.type !== 'ExpressionStatement') {
|
|
133
223
|
throw new Error("Expr dynamic attribute only support expressions statements at the moment.");
|
|
134
224
|
}
|
|
135
|
-
|
|
225
|
+
var expression = theStatementOnlyWihtoutTheProgram.expression;
|
|
226
|
+
// When an expression accesses `.value` on a simple identifier (e.g. `galleryImage?.value`),
|
|
227
|
+
// wrap it with a typeof check so that if the item is already a string we use it directly:
|
|
228
|
+
// `typeof galleryImage === 'string' ? galleryImage : galleryImage?.value`
|
|
229
|
+
if ((expression.type === 'OptionalMemberExpression' || expression.type === 'MemberExpression') &&
|
|
230
|
+
expression.object.type === 'Identifier' &&
|
|
231
|
+
expression.property.type === 'Identifier' &&
|
|
232
|
+
expression.property.name === 'value') {
|
|
233
|
+
var varName = expression.object.name;
|
|
234
|
+
expression = t.conditionalExpression(t.binaryExpression('===', t.unaryExpression('typeof', t.identifier(varName)), t.stringLiteral('string')), t.identifier(varName), expression);
|
|
235
|
+
}
|
|
236
|
+
jsxASTNode.openingElement.attributes.push(t.jsxAttribute(t.jsxIdentifier((0, exports.convertToReactAttributeName)(attrKey)), t.jsxExpressionContainer(expression)));
|
|
136
237
|
};
|
|
137
238
|
exports.addDynamicExpressionAttributeToJSXTag = addDynamicExpressionAttributeToJSXTag;
|
|
138
239
|
/*
|
|
@@ -176,36 +277,253 @@ var stringAsTemplateLiteral = function (str) {
|
|
|
176
277
|
return container.expression;
|
|
177
278
|
};
|
|
178
279
|
exports.stringAsTemplateLiteral = stringAsTemplateLiteral;
|
|
280
|
+
/**
|
|
281
|
+
* Checks if a string contains {{ expression }} template patterns
|
|
282
|
+
*/
|
|
283
|
+
var containsTemplateExpression = function (str) {
|
|
284
|
+
return /\{\{.+?\}\}/.test(str);
|
|
285
|
+
};
|
|
286
|
+
exports.containsTemplateExpression = containsTemplateExpression;
|
|
287
|
+
/**
|
|
288
|
+
* Parses a JavaScript expression string into an AST Expression node.
|
|
289
|
+
* e.g. "item.type || 'coin'" → LogicalExpression AST
|
|
290
|
+
*/
|
|
291
|
+
var parseJSExpressionAsAST = function (expr) {
|
|
292
|
+
var ast = (0, core_1.parse)("(".concat(expr, ")"), {
|
|
293
|
+
sourceType: 'module',
|
|
294
|
+
});
|
|
295
|
+
if (!ast || !('program' in ast)) {
|
|
296
|
+
throw new Error("Failed to parse expression: ".concat(expr));
|
|
297
|
+
}
|
|
298
|
+
return ast.program.body[0].expression;
|
|
299
|
+
};
|
|
300
|
+
exports.parseJSExpressionAsAST = parseJSExpressionAsAST;
|
|
301
|
+
/**
|
|
302
|
+
* Parses a string containing {{ expr }} template patterns into a TemplateLiteral AST node.
|
|
303
|
+
* e.g. "translate({{ enemy.x || '0' }}px)" → `translate(${enemy.x || '0'}px)`
|
|
304
|
+
*/
|
|
305
|
+
var parseStringWithTemplateExpressions = function (str) {
|
|
306
|
+
// Step 1: Normalize state references: state.xxx → xxx
|
|
307
|
+
var normalized = str.replace(/state\.(\w+)/g, '$1');
|
|
308
|
+
// Step 2: Convert well-formed {{ expr }} to ${expr}
|
|
309
|
+
//
|
|
310
|
+
// The expression is BALANCED on the way in. A binding that lost a closing
|
|
311
|
+
// paren upstream (`-(cameraX || ''`) produces source Babel cannot parse, and
|
|
312
|
+
// no amount of patching the static text around it can help — the repair has
|
|
313
|
+
// to happen inside the interpolation, which is the only place the bracket is
|
|
314
|
+
// actually missing.
|
|
315
|
+
var templateStr = normalized.replace(/\{\{\s*(.+?)\s*\}\}/g, function (_, expr) { return '${' + (0, template_expression_balance_1.balanceExpression)(expr.trim()) + '}'; });
|
|
316
|
+
// Step 3: Handle unclosed {{ expr (no closing }})
|
|
317
|
+
// After step 2, any remaining {{ was not well-formed
|
|
318
|
+
if (/\{\{/.test(templateStr)) {
|
|
319
|
+
templateStr = templateStr.replace(/\{\{\s*(.+?)$/gm, function (_, expr) { return '${' + (0, template_expression_balance_1.balanceExpression)(expr.trim()) + '}'; });
|
|
320
|
+
}
|
|
321
|
+
// Step 4: Detect and fix incomplete CSS function calls
|
|
322
|
+
// If the original string contained a CSS function like translateX(...) or translate(...)
|
|
323
|
+
// but the template expression consumed the closing, we need to re-close it.
|
|
324
|
+
//
|
|
325
|
+
// Counted over the STATIC text only. Including the parentheses inside `${…}`
|
|
326
|
+
// made an imbalance in the expression look like an unclosed CSS function, so
|
|
327
|
+
// this step appended a unit and a `)` to the end of a string whose real fault
|
|
328
|
+
// was several characters earlier and inside the interpolation.
|
|
329
|
+
var missingStaticCloses = (0, template_expression_balance_1.countUnclosedStaticParens)(templateStr);
|
|
330
|
+
if (missingStaticCloses > 0) {
|
|
331
|
+
// Determine the CSS unit by:
|
|
332
|
+
// 1. Looking for existing units already in the string (e.g. "translate(${x}px, ${y" → px)
|
|
333
|
+
// 2. Inferring from the CSS function name
|
|
334
|
+
var existingUnit = templateStr.match(/(px|deg|em|rem|%|vh|vw)[),\s]/);
|
|
335
|
+
var unit = 'px'; // default
|
|
336
|
+
if (existingUnit) {
|
|
337
|
+
unit = existingUnit[1];
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
// Infer unit from the CSS function name
|
|
341
|
+
var fnMatch = templateStr.match(/\b(rotate|skew|skewX|skewY)\s*\(/);
|
|
342
|
+
if (fnMatch) {
|
|
343
|
+
unit = 'deg';
|
|
344
|
+
}
|
|
345
|
+
var noUnitFns = /\b(scale|scaleX|scaleY|scale3d|opacity)\s*\(/;
|
|
346
|
+
if (noUnitFns.test(templateStr)) {
|
|
347
|
+
unit = '';
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
templateStr += unit + ')'.repeat(missingStaticCloses);
|
|
351
|
+
}
|
|
352
|
+
// Step 5: Parse — and NEVER let a single malformed binding abort the build.
|
|
353
|
+
//
|
|
354
|
+
// The inline-style caller has no error handling of its own, so an
|
|
355
|
+
// unparseable template used to escape as a raw Babel SyntaxError and take the
|
|
356
|
+
// whole project generation down with it. A UIDL can always carry a binding
|
|
357
|
+
// this module cannot rescue (hand-edited, produced by an older pipeline, or
|
|
358
|
+
// broken in a way `balanceExpression` refuses to guess at), and the right
|
|
359
|
+
// answer is to degrade that ONE value: emit the original text as a plain
|
|
360
|
+
// string so the property still renders and the other 99 pages still build.
|
|
361
|
+
try {
|
|
362
|
+
var ast = (0, core_1.parse)('const x = `' + templateStr + '`', {
|
|
363
|
+
sourceType: 'module',
|
|
364
|
+
});
|
|
365
|
+
if (ast && 'program' in ast) {
|
|
366
|
+
var decl = ast.program.body[0];
|
|
367
|
+
return decl.declarations[0].init;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
catch (_a) {
|
|
371
|
+
// Fall through to the static fallback below.
|
|
372
|
+
}
|
|
373
|
+
return staticTemplateLiteral(stripTemplateExpressions(str));
|
|
374
|
+
};
|
|
375
|
+
exports.parseStringWithTemplateExpressions = parseStringWithTemplateExpressions;
|
|
376
|
+
/**
|
|
377
|
+
* Drop every `{{ … }}` binding from a string, keeping any `'literal'` fallback
|
|
378
|
+
* it declared. `translateX({{ -(x || 0) }}px)` → `translateX(px)` is useless as
|
|
379
|
+
* a style value, but `{{ name || 'Guest' }}` → `Guest` keeps the text the
|
|
380
|
+
* author intended. Used only when the expression could not be parsed at all.
|
|
381
|
+
*/
|
|
382
|
+
var stripTemplateExpressions = function (value) {
|
|
383
|
+
return value.replace(/\{\{\s*([\s\S]*?)\s*\}\}/g, function (_, expr) {
|
|
384
|
+
var literalFallback = /\|\|\s*(['"])([\s\S]*?)\1\s*$/.exec(expr);
|
|
385
|
+
return literalFallback ? literalFallback[2] : '';
|
|
386
|
+
});
|
|
387
|
+
};
|
|
388
|
+
/** A TemplateLiteral with no interpolations, holding `value` verbatim. */
|
|
389
|
+
var staticTemplateLiteral = function (value) {
|
|
390
|
+
return types.templateLiteral([types.templateElement({ raw: value.replace(/[\\`]/g, '\\$&'), cooked: value }, true)], []);
|
|
391
|
+
};
|
|
392
|
+
var REACT_BOOLEAN_DOM_PROPS = new Set([
|
|
393
|
+
'disabled',
|
|
394
|
+
'required',
|
|
395
|
+
'readOnly',
|
|
396
|
+
'checked',
|
|
397
|
+
'multiple',
|
|
398
|
+
'hidden',
|
|
399
|
+
'autoFocus',
|
|
400
|
+
'muted',
|
|
401
|
+
'loop',
|
|
402
|
+
'playsInline',
|
|
403
|
+
'autoPlay',
|
|
404
|
+
'controls',
|
|
405
|
+
'async',
|
|
406
|
+
'defer',
|
|
407
|
+
'inert',
|
|
408
|
+
'scoped',
|
|
409
|
+
'reversed',
|
|
410
|
+
'allowFullScreen',
|
|
411
|
+
'defaultChecked',
|
|
412
|
+
'selected',
|
|
413
|
+
'formNoValidate',
|
|
414
|
+
'noValidate',
|
|
415
|
+
]);
|
|
179
416
|
var addAttributeToJSXTag = function (jsxNode, attrName, attrValue, t) {
|
|
417
|
+
var _a, _b;
|
|
180
418
|
if (t === void 0) { t = types; }
|
|
181
|
-
var
|
|
419
|
+
var reactAttrName = (0, exports.resolveAttributeNameForTag)(jsxNode, attrName);
|
|
420
|
+
var nameOfAttribute = t.jsxIdentifier(reactAttrName);
|
|
182
421
|
var attributeDefinition;
|
|
183
|
-
|
|
184
|
-
|
|
422
|
+
var normalizedValue = attrValue;
|
|
423
|
+
if (typeof attrValue === 'string' &&
|
|
424
|
+
(attrValue === 'true' || attrValue === 'false') &&
|
|
425
|
+
REACT_BOOLEAN_DOM_PROPS.has(reactAttrName)) {
|
|
426
|
+
normalizedValue = attrValue === 'true';
|
|
427
|
+
}
|
|
428
|
+
if (typeof normalizedValue === 'boolean') {
|
|
429
|
+
attributeDefinition = t.jsxAttribute(nameOfAttribute, normalizedValue === true
|
|
430
|
+
? undefined
|
|
431
|
+
: t.jsxExpressionContainer(t.booleanLiteral(normalizedValue)));
|
|
432
|
+
}
|
|
433
|
+
else if (t.isNode(attrValue) && t.isJSXElement(attrValue)) {
|
|
434
|
+
attributeDefinition = t.jsxAttribute(nameOfAttribute, t.jsxExpressionContainer(attrValue));
|
|
185
435
|
}
|
|
186
436
|
else {
|
|
187
|
-
attributeDefinition = t.jsxAttribute(nameOfAttribute, getProperAttributeValueAssignment(
|
|
437
|
+
attributeDefinition = t.jsxAttribute(nameOfAttribute, getProperAttributeValueAssignment(normalizedValue));
|
|
438
|
+
}
|
|
439
|
+
var attribute = jsxNode.openingElement.attributes.find(function (attr) {
|
|
440
|
+
if (attr.type === 'JSXAttribute') {
|
|
441
|
+
return attr.name.name === reactAttrName;
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
if (attribute && attribute.value && attribute.value.type === 'StringLiteral') {
|
|
445
|
+
attribute.value.value = "".concat(attribute.value.value, " ").concat(attrValue);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
// An object-valued attribute (e.g. `style={{ ... }}`) can be contributed by
|
|
449
|
+
// more than one independent code path — e.g. a ctx-scoped dynamic style value
|
|
450
|
+
// resolved at JSX-build time, and a `dynamicStyleBindings` inline style added
|
|
451
|
+
// later by a style plugin. Pushing a second `style` JSXAttribute would silently
|
|
452
|
+
// drop one of the two (JS keeps only the last of duplicate object keys once
|
|
453
|
+
// transpiled), so merge into the existing ObjectExpression instead, replacing
|
|
454
|
+
// any property with a matching key so the newer value wins.
|
|
455
|
+
if (attribute &&
|
|
456
|
+
((_a = attribute.value) === null || _a === void 0 ? void 0 : _a.type) === 'JSXExpressionContainer' &&
|
|
457
|
+
attribute.value.expression.type === 'ObjectExpression' &&
|
|
458
|
+
((_b = attributeDefinition.value) === null || _b === void 0 ? void 0 : _b.type) === 'JSXExpressionContainer' &&
|
|
459
|
+
attributeDefinition.value.expression.type === 'ObjectExpression') {
|
|
460
|
+
var existingProps_1 = attribute.value.expression.properties;
|
|
461
|
+
attributeDefinition.value.expression.properties.forEach(function (newProp) {
|
|
462
|
+
if (newProp.type !== 'ObjectProperty' || newProp.key.type === 'PrivateName') {
|
|
463
|
+
existingProps_1.push(newProp);
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
var newKeyName = newProp.key.type === 'Identifier' ? newProp.key.name : String(newProp.key.value);
|
|
467
|
+
var existingIndex = existingProps_1.findIndex(function (prop) {
|
|
468
|
+
if (prop.type !== 'ObjectProperty' || prop.key.type === 'PrivateName') {
|
|
469
|
+
return false;
|
|
470
|
+
}
|
|
471
|
+
var existingKeyName = prop.key.type === 'Identifier' ? prop.key.name : String(prop.key.value);
|
|
472
|
+
return existingKeyName === newKeyName;
|
|
473
|
+
});
|
|
474
|
+
if (existingIndex >= 0) {
|
|
475
|
+
existingProps_1[existingIndex] = newProp;
|
|
476
|
+
}
|
|
477
|
+
else {
|
|
478
|
+
existingProps_1.push(newProp);
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
return;
|
|
188
482
|
}
|
|
189
483
|
jsxNode.openingElement.attributes.push(attributeDefinition);
|
|
190
484
|
};
|
|
191
485
|
exports.addAttributeToJSXTag = addAttributeToJSXTag;
|
|
192
486
|
var addRawAttributeToJSXTag = function (jsxNode, attrName, attrValue, t) {
|
|
193
487
|
if (t === void 0) { t = types; }
|
|
194
|
-
|
|
488
|
+
// The content is expected to be pre-escaped for template literal context
|
|
489
|
+
// (e.g., \` for backticks, \${ for interpolations). Babel validates that
|
|
490
|
+
// the raw value is valid template literal content.
|
|
491
|
+
//
|
|
492
|
+
// We fix any unescaped backticks or ${ sequences that would make the
|
|
493
|
+
// template literal invalid. "Unescaped" means preceded by an even number
|
|
494
|
+
// of backslashes (0, 2, …), since pairs of backslashes form escape
|
|
495
|
+
// sequences for backslash itself, leaving the next character unescaped.
|
|
496
|
+
var content = attrValue.content
|
|
497
|
+
.replace(/\\*`/g, function (match) {
|
|
498
|
+
var bs = match.length - 1;
|
|
499
|
+
return bs % 2 === 0 ? match.slice(0, bs) + '\\`' : match;
|
|
500
|
+
})
|
|
501
|
+
.replace(/\\*\$\{/g, function (match) {
|
|
502
|
+
var bs = match.length - 2;
|
|
503
|
+
return bs % 2 === 0 ? match.slice(0, bs) + '\\${' : match;
|
|
504
|
+
});
|
|
505
|
+
var attributeDefinition = t.jsxAttribute(t.jsxIdentifier(attrName), t.jsxExpressionContainer(types.templateLiteral([types.templateElement({ raw: content })], [])));
|
|
195
506
|
jsxNode.openingElement.attributes.push(attributeDefinition);
|
|
196
507
|
};
|
|
197
508
|
exports.addRawAttributeToJSXTag = addRawAttributeToJSXTag;
|
|
509
|
+
// A JSX attribute string is raw text: nothing in it is unescaped, yet Babel
|
|
510
|
+
// prints a backslash or a line break in it escaped, so `pattern="\d"` would reach
|
|
511
|
+
// the page as `\\d`. Such a value goes in an expression container instead, where
|
|
512
|
+
// the escapes are JavaScript's and are read back.
|
|
513
|
+
var RAW_JSX_ATTRIBUTE_UNSAFE = /[\\\n\r\u2028\u2029]/;
|
|
198
514
|
/**
|
|
199
515
|
* node must be a AST node element of type JSXElement (babel-types) or
|
|
200
516
|
* equivalent
|
|
201
517
|
*/
|
|
202
518
|
var getProperAttributeValueAssignment = function (value, t) {
|
|
203
519
|
if (t === void 0) { t = types; }
|
|
204
|
-
if (!value) {
|
|
205
|
-
return null;
|
|
206
|
-
}
|
|
207
520
|
if (typeof value === 'string') {
|
|
208
|
-
return
|
|
521
|
+
return RAW_JSX_ATTRIBUTE_UNSAFE.test(value)
|
|
522
|
+
? t.jsxExpressionContainer(t.stringLiteral(value))
|
|
523
|
+
: t.stringLiteral(teleport_shared_1.StringUtils.encode(value));
|
|
524
|
+
}
|
|
525
|
+
if (!value && value !== 0 && value !== false) {
|
|
526
|
+
return null;
|
|
209
527
|
}
|
|
210
528
|
return t.jsxExpressionContainer((0, exports.convertValueToLiteral)(value));
|
|
211
529
|
};
|
|
@@ -238,7 +556,18 @@ var objectToObjectExpression = function (objectMap, t) {
|
|
|
238
556
|
var keyIdentifier = t.stringLiteral(key);
|
|
239
557
|
var value = objectMap[key];
|
|
240
558
|
var computedLiteralValue = null;
|
|
241
|
-
if (value
|
|
559
|
+
if (value === undefined) {
|
|
560
|
+
return acc;
|
|
561
|
+
}
|
|
562
|
+
// Handle null values explicitly - they are valid in array mappers with different schemas
|
|
563
|
+
if (value === null) {
|
|
564
|
+
computedLiteralValue = t.nullLiteral();
|
|
565
|
+
}
|
|
566
|
+
// This is for function props that have successfully been parsed.
|
|
567
|
+
else if (typeof value === 'object' && 'functionExpressionParseResult' in value) {
|
|
568
|
+
computedLiteralValue = value.functionExpressionParseResult;
|
|
569
|
+
}
|
|
570
|
+
else if (value instanceof parsed_ast_1.default || value.constructor.name === 'ParsedASTNode') {
|
|
242
571
|
computedLiteralValue = value.ast;
|
|
243
572
|
}
|
|
244
573
|
else if (typeof value === 'boolean') {
|
|
@@ -278,6 +607,86 @@ var objectToObjectExpression = function (objectMap, t) {
|
|
|
278
607
|
return objectExpression;
|
|
279
608
|
};
|
|
280
609
|
exports.objectToObjectExpression = objectToObjectExpression;
|
|
610
|
+
/**
|
|
611
|
+
* A value stored as text, read as the type it is declared with: a number prop
|
|
612
|
+
* or a condition comparing one meets "2" as the number 2, and a boolean one
|
|
613
|
+
* meets "true"/"false" as true/false, the way the editor's canvas compares
|
|
614
|
+
* them. A prop default and a condition's operand both arrive as text from
|
|
615
|
+
* writers that keep every input's value as typed.
|
|
616
|
+
*/
|
|
617
|
+
var coerceToDeclaredType = function (value, declaredType) {
|
|
618
|
+
if (typeof value !== 'string') {
|
|
619
|
+
return value;
|
|
620
|
+
}
|
|
621
|
+
if (declaredType === 'number' && value.trim() !== '' && !isNaN(Number(value))) {
|
|
622
|
+
return Number(value);
|
|
623
|
+
}
|
|
624
|
+
if (declaredType === 'boolean' && (value === 'true' || value === 'false')) {
|
|
625
|
+
return value === 'true';
|
|
626
|
+
}
|
|
627
|
+
return value;
|
|
628
|
+
};
|
|
629
|
+
exports.coerceToDeclaredType = coerceToDeclaredType;
|
|
630
|
+
var COLLECTION_OPERATIONS = [
|
|
631
|
+
'isEmpty',
|
|
632
|
+
'isNotEmpty',
|
|
633
|
+
'lengthEquals',
|
|
634
|
+
'lengthGreaterThan',
|
|
635
|
+
'lengthLessThan',
|
|
636
|
+
'contains',
|
|
637
|
+
'notContains',
|
|
638
|
+
'hasKey',
|
|
639
|
+
'notHasKey',
|
|
640
|
+
];
|
|
641
|
+
/** The operations that read a value as a collection rather than compare it. */
|
|
642
|
+
var isCollectionOperation = function (operation) {
|
|
643
|
+
return COLLECTION_OPERATIONS.includes(operation);
|
|
644
|
+
};
|
|
645
|
+
exports.isCollectionOperation = isCollectionOperation;
|
|
646
|
+
/**
|
|
647
|
+
* A collection operation answered on a value known at build time, with the
|
|
648
|
+
* meaning `createBinaryExpression` (node-to-jsx) gives it at runtime: the
|
|
649
|
+
* length of `value || []` (its key count, `value || {}`, for an object),
|
|
650
|
+
* `.includes(operand)`, `.some((item) => item[field] === operand)`,
|
|
651
|
+
* `hasOwnProperty`.
|
|
652
|
+
*/
|
|
653
|
+
var passesCollectionTest = function (operation, value, operand, options) {
|
|
654
|
+
if (options === void 0) { options = {}; }
|
|
655
|
+
var containsField = options.containsField, valueType = options.valueType;
|
|
656
|
+
var collection = (value || (valueType === 'object' ? {} : []));
|
|
657
|
+
var length = valueType === 'object' ? Object.keys(collection).length : collection.length;
|
|
658
|
+
var contains = function () {
|
|
659
|
+
if (containsField) {
|
|
660
|
+
return (typeof collection.some === 'function' &&
|
|
661
|
+
collection.some(function (item) { return (item === null || item === void 0 ? void 0 : item[containsField]) === operand; }));
|
|
662
|
+
}
|
|
663
|
+
return typeof collection.includes === 'function' && collection.includes(operand);
|
|
664
|
+
};
|
|
665
|
+
var hasKey = function () {
|
|
666
|
+
return Object.prototype.hasOwnProperty.call(value || {}, operand);
|
|
667
|
+
};
|
|
668
|
+
switch (operation) {
|
|
669
|
+
case 'isEmpty':
|
|
670
|
+
return length === 0;
|
|
671
|
+
case 'isNotEmpty':
|
|
672
|
+
return length > 0;
|
|
673
|
+
case 'lengthEquals':
|
|
674
|
+
return length === operand;
|
|
675
|
+
case 'lengthGreaterThan':
|
|
676
|
+
return length > operand;
|
|
677
|
+
case 'lengthLessThan':
|
|
678
|
+
return length < operand;
|
|
679
|
+
case 'contains':
|
|
680
|
+
return contains();
|
|
681
|
+
case 'notContains':
|
|
682
|
+
return !contains();
|
|
683
|
+
case 'hasKey':
|
|
684
|
+
return hasKey();
|
|
685
|
+
default:
|
|
686
|
+
return !hasKey();
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
exports.passesCollectionTest = passesCollectionTest;
|
|
281
690
|
var convertValueToLiteral = function (
|
|
282
691
|
// tslint:disable-next-line no-any
|
|
283
692
|
value, explicitType, t) {
|
|
@@ -289,7 +698,23 @@ value, explicitType, t) {
|
|
|
289
698
|
if (Array.isArray(value)) {
|
|
290
699
|
return t.arrayExpression(value.map(function (val) { return (0, exports.convertValueToLiteral)(val); }));
|
|
291
700
|
}
|
|
292
|
-
|
|
701
|
+
if (explicitType === 'array' && typeof value === 'object' && value !== null) {
|
|
702
|
+
var arr = Object.keys(value)
|
|
703
|
+
.sort(function (a, b) { return Number(a) - Number(b); })
|
|
704
|
+
.map(function (key) { return (0, exports.convertValueToLiteral)(value[key]); });
|
|
705
|
+
return t.arrayExpression(arr);
|
|
706
|
+
}
|
|
707
|
+
if ((explicitType === 'array' || explicitType === 'object') && typeof value === 'string') {
|
|
708
|
+
try {
|
|
709
|
+
var parsed = JSON.parse(value);
|
|
710
|
+
return (0, exports.convertValueToLiteral)(parsed, explicitType, t);
|
|
711
|
+
}
|
|
712
|
+
catch (_a) {
|
|
713
|
+
// If parsing fails, fall through to treat as a regular string
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
var actualType = typeof value;
|
|
717
|
+
var typeToCompare = explicitType && explicitType === actualType ? explicitType : actualType;
|
|
293
718
|
switch (typeToCompare) {
|
|
294
719
|
case 'string':
|
|
295
720
|
return t.stringLiteral(value);
|
|
@@ -322,7 +747,7 @@ var getTSAnnotationForType = function (type, t) {
|
|
|
322
747
|
case 'boolean':
|
|
323
748
|
return t.tsBooleanKeyword();
|
|
324
749
|
default:
|
|
325
|
-
return t.
|
|
750
|
+
return t.tsAnyKeyword();
|
|
326
751
|
}
|
|
327
752
|
};
|
|
328
753
|
exports.getTSAnnotationForType = getTSAnnotationForType;
|
|
@@ -337,7 +762,7 @@ var removeAttributeByName = function (jsxTag, attrName) {
|
|
|
337
762
|
});
|
|
338
763
|
};
|
|
339
764
|
exports.removeAttributeByName = removeAttributeByName;
|
|
340
|
-
var createClassComponent = function (name, propDefinitions, stateDefinitions, jsxTagTree, t) {
|
|
765
|
+
var createClassComponent = function (name, propDefinitions, stateDefinitions, jsxTagTree, dynamicReferencePrefixMap, t) {
|
|
341
766
|
if (t === void 0) { t = types; }
|
|
342
767
|
// TODO: Add event handlers as separate functions later
|
|
343
768
|
var classMethodsAndProperties = [];
|
|
@@ -348,6 +773,11 @@ var createClassComponent = function (name, propDefinitions, stateDefinitions, js
|
|
|
348
773
|
if (Object.keys(stateDefinitions).length > 0) {
|
|
349
774
|
var stateDeclarationsAST = Object.keys(stateDefinitions).map(function (stateKey) {
|
|
350
775
|
var stateDefinition = stateDefinitions[stateKey];
|
|
776
|
+
if (stateDefinition.type === 'object' &&
|
|
777
|
+
dynamicReferencePrefixMap &&
|
|
778
|
+
(0, exports.isObjectStateWithEntries)(stateDefinition)) {
|
|
779
|
+
return t.objectProperty(t.identifier(stateKey), (0, exports.convertObjectStateDefaultToExpression)(stateDefinition.defaultValue, dynamicReferencePrefixMap, t));
|
|
780
|
+
}
|
|
351
781
|
return t.objectProperty(t.identifier(stateKey), (0, exports.convertValueToLiteral)(stateDefinition.defaultValue));
|
|
352
782
|
});
|
|
353
783
|
classMethodsAndProperties.push(t.classProperty(t.identifier('state'), t.objectExpression(stateDeclarationsAST)));
|
|
@@ -360,44 +790,277 @@ var createClassComponent = function (name, propDefinitions, stateDefinitions, js
|
|
|
360
790
|
return classDeclaration;
|
|
361
791
|
};
|
|
362
792
|
exports.createClassComponent = createClassComponent;
|
|
363
|
-
var createPureComponent = function (name, stateDefinitions, jsxTagTree, windowImports, t) {
|
|
793
|
+
var createPureComponent = function (name, stateDefinitions, jsxTagTree, windowImports, dynamicReferencePrefixMap, t) {
|
|
364
794
|
if (windowImports === void 0) { windowImports = {}; }
|
|
365
795
|
if (t === void 0) { t = types; }
|
|
366
|
-
var arrowFunctionBody = (0, exports.createReturnExpressionSyntax)(stateDefinitions, jsxTagTree, windowImports);
|
|
796
|
+
var arrowFunctionBody = (0, exports.createReturnExpressionSyntax)(stateDefinitions, jsxTagTree, windowImports, dynamicReferencePrefixMap);
|
|
367
797
|
var arrowFunction = t.arrowFunctionExpression([t.identifier('props')], arrowFunctionBody);
|
|
368
798
|
var declarator = t.variableDeclarator(t.identifier(name), arrowFunction);
|
|
369
799
|
var component = t.variableDeclaration('const', [declarator]);
|
|
370
800
|
return component;
|
|
371
801
|
};
|
|
372
802
|
exports.createPureComponent = createPureComponent;
|
|
373
|
-
var createReturnExpressionSyntax = function (stateDefinitions, jsxTagTree, windowImports, t) {
|
|
803
|
+
var createReturnExpressionSyntax = function (stateDefinitions, jsxTagTree, windowImports, dynamicReferencePrefixMap, t) {
|
|
374
804
|
if (windowImports === void 0) { windowImports = {}; }
|
|
375
805
|
if (t === void 0) { t = types; }
|
|
376
806
|
var returnStatement = t.returnStatement(jsxTagTree);
|
|
377
807
|
var stateHooks = Object.keys(stateDefinitions).map(function (stateKey) {
|
|
378
|
-
return (0, exports.createStateHookAST)(stateKey, stateDefinitions[stateKey]);
|
|
808
|
+
return (0, exports.createStateHookAST)(stateKey, stateDefinitions[stateKey], dynamicReferencePrefixMap);
|
|
379
809
|
});
|
|
380
|
-
return t.blockStatement(__spreadArray(__spreadArray(__spreadArray([], stateHooks, true), Object.values(windowImports), true), [returnStatement], false)
|
|
810
|
+
return t.blockStatement(__spreadArray(__spreadArray(__spreadArray([], stateHooks, true), Object.values(windowImports), true), [returnStatement], false));
|
|
381
811
|
};
|
|
382
812
|
exports.createReturnExpressionSyntax = createReturnExpressionSyntax;
|
|
383
813
|
/**
|
|
384
814
|
* Creates an AST line for defining a single state hook
|
|
385
815
|
*/
|
|
386
|
-
var createStateHookAST = function (stateKey, stateDefinition, t) {
|
|
816
|
+
var createStateHookAST = function (stateKey, stateDefinition, dynamicReferencePrefixMap, t) {
|
|
387
817
|
if (t === void 0) { t = types; }
|
|
388
|
-
var defaultValueArgument
|
|
818
|
+
var defaultValueArgument;
|
|
819
|
+
if (stateDefinition.type === 'object' &&
|
|
820
|
+
dynamicReferencePrefixMap &&
|
|
821
|
+
(0, exports.isObjectStateWithEntries)(stateDefinition)) {
|
|
822
|
+
defaultValueArgument = (0, exports.convertObjectStateDefaultToExpression)(stateDefinition.defaultValue, dynamicReferencePrefixMap, t);
|
|
823
|
+
}
|
|
824
|
+
else {
|
|
825
|
+
defaultValueArgument = (0, exports.convertValueToLiteral)(stateDefinition.defaultValue, stateDefinition.type);
|
|
826
|
+
}
|
|
827
|
+
// When the state has a dataSourceBinding, the initial value comes from props
|
|
828
|
+
// Generated: useState(props.stateKey !== undefined ? props.stateKey : defaultValue)
|
|
829
|
+
var useStateArgument = defaultValueArgument;
|
|
830
|
+
if (stateDefinition.dataSourceBinding) {
|
|
831
|
+
var propAccess = t.memberExpression(t.identifier('props'), t.identifier(stateKey));
|
|
832
|
+
useStateArgument = t.conditionalExpression(t.binaryExpression('!==', propAccess, t.identifier('undefined')), propAccess, defaultValueArgument);
|
|
833
|
+
}
|
|
834
|
+
else if (stateDefinition.urlSearchParamBinding &&
|
|
835
|
+
typeof stateDefinition.urlSearchParamBinding.key === 'string' &&
|
|
836
|
+
stateDefinition.urlSearchParamBinding.key !== '' &&
|
|
837
|
+
// `hydrateAfterMount`: the state keeps its static default on the client's
|
|
838
|
+
// first render too, and the router read-back effect adopts the URL value
|
|
839
|
+
// once `router.isReady` — a real update, so the elements it gates
|
|
840
|
+
// re-render. Needed where the server markup and a URL-seeded client value
|
|
841
|
+
// would differ only in ATTRIBUTES of same-tag siblings (a pressed toggle):
|
|
842
|
+
// React 17 does not patch those on hydration. See the type's docs.
|
|
843
|
+
stateDefinition.urlSearchParamBinding.hydrateAfterMount !== true) {
|
|
844
|
+
// URL-search-param binding: seed the initial state directly from
|
|
845
|
+
// `window.location.search`. We deliberately DO NOT use Next.js'
|
|
846
|
+
// `router.query` here because on statically-generated pages (getStaticProps
|
|
847
|
+
// / getStaticPaths) `router.query` is empty on the first render and only
|
|
848
|
+
// hydrates after `router.isReady` flips to true — by which point React's
|
|
849
|
+
// `useState` initializer has already captured the fallback default. That
|
|
850
|
+
// regression shipped as "detail panel does not auto-open on deep links to
|
|
851
|
+
// /admin/products?products_detail_panel_item_id=<id>". `window.location`
|
|
852
|
+
// is populated synchronously on both direct loads and client-side
|
|
853
|
+
// navigations, and the `typeof window` guard keeps SSR falling back to
|
|
854
|
+
// the declared static default cleanly.
|
|
855
|
+
//
|
|
856
|
+
// Emitted shape:
|
|
857
|
+
// useState(
|
|
858
|
+
// (typeof window !== "undefined"
|
|
859
|
+
// ? new URLSearchParams(window.location.search).get("<key>")
|
|
860
|
+
// : null) ?? <defaultValueLiteral>
|
|
861
|
+
// )
|
|
862
|
+
var paramKey = stateDefinition.urlSearchParamBinding.key;
|
|
863
|
+
var urlSearchParamsExpr = t.newExpression(t.identifier('URLSearchParams'), [
|
|
864
|
+
t.memberExpression(t.memberExpression(t.identifier('window'), t.identifier('location')), t.identifier('search')),
|
|
865
|
+
]);
|
|
866
|
+
var readParamExpr = t.callExpression(t.memberExpression(urlSearchParamsExpr, t.identifier('get')), [t.stringLiteral(paramKey)]);
|
|
867
|
+
var browserGuard = t.binaryExpression('!==', t.unaryExpression('typeof', t.identifier('window')), t.stringLiteral('undefined'));
|
|
868
|
+
useStateArgument = t.logicalExpression('??', t.conditionalExpression(browserGuard, readParamExpr, t.nullLiteral()), defaultValueArgument);
|
|
869
|
+
}
|
|
389
870
|
return t.variableDeclaration('const', [
|
|
390
871
|
t.variableDeclarator(t.arrayPattern([
|
|
391
|
-
|
|
872
|
+
// The state NAME comes from the UIDL and may be a reserved word (a
|
|
873
|
+
// character sheet has a column called `class`), which is fatal in
|
|
874
|
+
// binding position. Reads go through the same sanitiser, so the
|
|
875
|
+
// declaration and every reference stay in sync.
|
|
876
|
+
t.identifier(teleport_shared_1.JSIdentifiers.createSafeJSIdentifier(stateKey)),
|
|
392
877
|
t.identifier(teleport_shared_1.StringUtils.createStateStoringFunction(stateKey)),
|
|
393
|
-
]), t.callExpression(t.identifier('useState'), [
|
|
878
|
+
]), t.callExpression(t.identifier('useState'), [useStateArgument])),
|
|
394
879
|
]);
|
|
395
880
|
};
|
|
396
881
|
exports.createStateHookAST = createStateHookAST;
|
|
882
|
+
var isObjectStateWithEntries = function (stateDefinition) {
|
|
883
|
+
if (stateDefinition.type !== 'object') {
|
|
884
|
+
return false;
|
|
885
|
+
}
|
|
886
|
+
var defaultValue = stateDefinition.defaultValue;
|
|
887
|
+
if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
|
|
888
|
+
return false;
|
|
889
|
+
}
|
|
890
|
+
return Object.values(defaultValue).some(function (entry) {
|
|
891
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
892
|
+
return false;
|
|
893
|
+
}
|
|
894
|
+
var typed = entry;
|
|
895
|
+
return (typed.type === 'static' || typed.type === 'dynamic') && 'content' in typed;
|
|
896
|
+
});
|
|
897
|
+
};
|
|
898
|
+
exports.isObjectStateWithEntries = isObjectStateWithEntries;
|
|
899
|
+
var convertObjectStateDefaultToExpression = function (defaultValue, prefixMap, t) {
|
|
900
|
+
if (t === void 0) { t = types; }
|
|
901
|
+
var properties = Object.keys(defaultValue).map(function (key) {
|
|
902
|
+
var valueExpression = resolveObjectStateEntry(defaultValue[key], prefixMap, t);
|
|
903
|
+
return t.objectProperty(t.stringLiteral(key), valueExpression);
|
|
904
|
+
});
|
|
905
|
+
return t.objectExpression(properties);
|
|
906
|
+
};
|
|
907
|
+
exports.convertObjectStateDefaultToExpression = convertObjectStateDefaultToExpression;
|
|
908
|
+
var resolveObjectStateEntry = function (entry, prefixMap, t) {
|
|
909
|
+
if (t === void 0) { t = types; }
|
|
910
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
911
|
+
return (0, exports.convertValueToLiteral)(entry);
|
|
912
|
+
}
|
|
913
|
+
var typed = entry;
|
|
914
|
+
if (typed.type === 'static') {
|
|
915
|
+
return (0, exports.convertValueToLiteral)(typed.content);
|
|
916
|
+
}
|
|
917
|
+
if (typed.type === 'dynamic') {
|
|
918
|
+
var content = typed.content;
|
|
919
|
+
var referenceType = content.referenceType, id = content.id, refPath = content.refPath;
|
|
920
|
+
if (referenceType === 'globalState') {
|
|
921
|
+
var gsRefPath = refPath || [];
|
|
922
|
+
var expr = t.identifier(id);
|
|
923
|
+
for (var _i = 0, gsRefPath_1 = gsRefPath; _i < gsRefPath_1.length; _i++) {
|
|
924
|
+
var segment = gsRefPath_1[_i];
|
|
925
|
+
expr = t.optionalMemberExpression(expr, t.identifier(segment), false, true);
|
|
926
|
+
}
|
|
927
|
+
return expr;
|
|
928
|
+
}
|
|
929
|
+
if (referenceType === 'global') {
|
|
930
|
+
// Normalize Shape B ({ refPath: ['Current User', 'id'] }) to Shape A
|
|
931
|
+
// ({ id: 'currentUser', refPath: ['id'] }) so downstream access is uniform.
|
|
932
|
+
var resolvedId = (0, exports.resolveGlobalRefId)(content);
|
|
933
|
+
if (resolvedId) {
|
|
934
|
+
var tail = !id && refPath && refPath.length > 0 ? refPath.slice(1) : refPath || [];
|
|
935
|
+
var expr = t.identifier(resolvedId);
|
|
936
|
+
for (var _a = 0, tail_1 = tail; _a < tail_1.length; _a++) {
|
|
937
|
+
var segment = tail_1[_a];
|
|
938
|
+
expr = t.optionalMemberExpression(expr, t.identifier(segment), false, true);
|
|
939
|
+
}
|
|
940
|
+
return expr;
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
var idWithPath = teleport_shared_1.UIDLUtils.generateIdWithRefPath(id, refPath);
|
|
944
|
+
var prefix = prefixMap[referenceType] || '';
|
|
945
|
+
return prefix === ''
|
|
946
|
+
? t.identifier(idWithPath)
|
|
947
|
+
: t.memberExpression(t.identifier(prefix), t.identifier(idWithPath));
|
|
948
|
+
}
|
|
949
|
+
return (0, exports.convertValueToLiteral)(entry);
|
|
950
|
+
};
|
|
951
|
+
// Mapping from the UIDL display name used in a global reference refPath
|
|
952
|
+
// to the runtime variable name that holds the value. Kept here so both the
|
|
953
|
+
// JSX emitter and the object-state global-reference collectors stay in sync.
|
|
954
|
+
exports.GLOBAL_REF_ID_MAP = {
|
|
955
|
+
'E-commerce': 'ecommerce',
|
|
956
|
+
Cart: 'cart',
|
|
957
|
+
'Current User': 'currentUser',
|
|
958
|
+
Company: 'company',
|
|
959
|
+
};
|
|
960
|
+
var resolveGlobalRefId = function (content) {
|
|
961
|
+
if (!content) {
|
|
962
|
+
return undefined;
|
|
963
|
+
}
|
|
964
|
+
if (content.id) {
|
|
965
|
+
return content.id;
|
|
966
|
+
}
|
|
967
|
+
if (!content.refPath || content.refPath.length === 0) {
|
|
968
|
+
return undefined;
|
|
969
|
+
}
|
|
970
|
+
return exports.GLOBAL_REF_ID_MAP[content.refPath[0]];
|
|
971
|
+
};
|
|
972
|
+
exports.resolveGlobalRefId = resolveGlobalRefId;
|
|
973
|
+
var collectGlobalReferencesFromObjectStates = function (stateDefinitions) {
|
|
974
|
+
var globalRefs = [];
|
|
975
|
+
Object.values(stateDefinitions).forEach(function (stateDef) {
|
|
976
|
+
if (stateDef.type !== 'object') {
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
var defaultValue = stateDef.defaultValue;
|
|
980
|
+
if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
|
|
981
|
+
return;
|
|
982
|
+
}
|
|
983
|
+
Object.values(defaultValue).forEach(function (entry) {
|
|
984
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
var typed = entry;
|
|
988
|
+
if (typed.type === 'dynamic') {
|
|
989
|
+
var content = typed.content;
|
|
990
|
+
if (content.referenceType === 'global') {
|
|
991
|
+
var resolvedId = (0, exports.resolveGlobalRefId)(content);
|
|
992
|
+
if (resolvedId) {
|
|
993
|
+
globalRefs.push(resolvedId);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
});
|
|
998
|
+
});
|
|
999
|
+
return globalRefs;
|
|
1000
|
+
};
|
|
1001
|
+
exports.collectGlobalReferencesFromObjectStates = collectGlobalReferencesFromObjectStates;
|
|
1002
|
+
var collectGlobalStateReferencesFromObjectStates = function (stateDefinitions) {
|
|
1003
|
+
var refs = [];
|
|
1004
|
+
Object.values(stateDefinitions).forEach(function (stateDef) {
|
|
1005
|
+
if (stateDef.type !== 'object') {
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
var defaultValue = stateDef.defaultValue;
|
|
1009
|
+
if (typeof defaultValue !== 'object' || defaultValue === null || Array.isArray(defaultValue)) {
|
|
1010
|
+
return;
|
|
1011
|
+
}
|
|
1012
|
+
Object.values(defaultValue).forEach(function (entry) {
|
|
1013
|
+
if (typeof entry !== 'object' || entry === null) {
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
1016
|
+
var typed = entry;
|
|
1017
|
+
if (typed.type === 'dynamic') {
|
|
1018
|
+
var content = typed.content;
|
|
1019
|
+
if (content.referenceType === 'globalState' && content.id) {
|
|
1020
|
+
refs.push({ id: content.id });
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
});
|
|
1024
|
+
});
|
|
1025
|
+
return refs;
|
|
1026
|
+
};
|
|
1027
|
+
exports.collectGlobalStateReferencesFromObjectStates = collectGlobalStateReferencesFromObjectStates;
|
|
1028
|
+
/**
|
|
1029
|
+
* The mount-time side-effect import for a package that cannot be imported at
|
|
1030
|
+
* module scope because it touches `window` while it evaluates —
|
|
1031
|
+
* self-registering web components such as `<lottie-player>` and
|
|
1032
|
+
* `<model-viewer>`. Running it from an effect keeps it off the server render.
|
|
1033
|
+
*
|
|
1034
|
+
* useEffect(() => {
|
|
1035
|
+
* import('@google/model-viewer').catch((error) => {
|
|
1036
|
+
* console.warn('[teleport] Failed to load "@google/model-viewer"', error)
|
|
1037
|
+
* })
|
|
1038
|
+
* }, [])
|
|
1039
|
+
*
|
|
1040
|
+
* Two details of that shape are load-bearing:
|
|
1041
|
+
*
|
|
1042
|
+
* - The callback body is a BLOCK. A concise arrow body (`() => import(…)`)
|
|
1043
|
+
* also RETURNS the import's Promise, and React stores an effect's return
|
|
1044
|
+
* value as its cleanup function and calls it on unmount — so every mounted
|
|
1045
|
+
* copy of the component turned navigating away into
|
|
1046
|
+
* `TypeError: destroy is not a function`, thrown from React's commit phase
|
|
1047
|
+
* with no frame naming the component. Nothing is returned here.
|
|
1048
|
+
* - The rejection is handled. A chunk that fails to load (offline, a stale
|
|
1049
|
+
* deploy, a blocked CDN) would otherwise surface as an unhandled promise
|
|
1050
|
+
* rejection; the element simply stays unupgraded, which is a degraded page
|
|
1051
|
+
* rather than a broken one, and the warning is what makes that visible.
|
|
1052
|
+
*/
|
|
397
1053
|
var generateDynamicWindowImport = function (hookName, dependency) {
|
|
398
1054
|
if (hookName === void 0) { hookName = 'useEffect'; }
|
|
1055
|
+
var failureIdentifier = types.identifier('error');
|
|
1056
|
+
var importCall = types.callExpression(types.import(), [types.stringLiteral(dependency)]);
|
|
1057
|
+
var guardedImport = types.callExpression(types.memberExpression(importCall, types.identifier('catch')), [
|
|
1058
|
+
types.arrowFunctionExpression([failureIdentifier], types.blockStatement([
|
|
1059
|
+
types.expressionStatement(types.callExpression(types.memberExpression(types.identifier('console'), types.identifier('warn')), [types.stringLiteral("[teleport] Failed to load \"".concat(dependency, "\"")), failureIdentifier])),
|
|
1060
|
+
])),
|
|
1061
|
+
]);
|
|
399
1062
|
return types.expressionStatement(types.callExpression(types.identifier(hookName), [
|
|
400
|
-
types.arrowFunctionExpression([], types.
|
|
1063
|
+
types.arrowFunctionExpression([], types.blockStatement([types.expressionStatement(guardedImport)])),
|
|
401
1064
|
types.arrayExpression([]),
|
|
402
1065
|
]));
|
|
403
1066
|
};
|
|
@@ -407,9 +1070,8 @@ var wrapObjectPropertiesWithExpression = function (properties) {
|
|
|
407
1070
|
};
|
|
408
1071
|
exports.wrapObjectPropertiesWithExpression = wrapObjectPropertiesWithExpression;
|
|
409
1072
|
var generateRemoteResourceASTs = function (resource) {
|
|
410
|
-
var _a, _b;
|
|
411
|
-
var fetchUrl = computeFetchUrl(resource);
|
|
412
|
-
var authHeaderAST = computeAuthorizationHeaderAST(resource === null || resource === void 0 ? void 0 : resource.headers);
|
|
1073
|
+
var _a, _b, _c, _d, _e;
|
|
1074
|
+
var fetchUrl = (0, exports.computeFetchUrl)(resource);
|
|
413
1075
|
var headersASTs = (resource === null || resource === void 0 ? void 0 : resource.headers) ? generateRESTHeadersAST(resource.headers) : [];
|
|
414
1076
|
var queryParams = (0, exports.generateURLParamsAST)(resource === null || resource === void 0 ? void 0 : resource.params);
|
|
415
1077
|
var fetchUrlQuasis = fetchUrl.quasis;
|
|
@@ -421,43 +1083,61 @@ var generateRemoteResourceASTs = function (resource) {
|
|
|
421
1083
|
fetchUrlQuasis[fetchUrlQuasis.length - 1].value.cooked + '?';
|
|
422
1084
|
queryParamsQuasis.pop();
|
|
423
1085
|
}
|
|
424
|
-
var
|
|
425
|
-
|
|
426
|
-
if (prop.type === 'static') {
|
|
427
|
-
acc.push(types.objectProperty(types.stringLiteral(item), __1.ASTUtils.resolveObjectValue(prop)));
|
|
428
|
-
}
|
|
429
|
-
if (prop.type === 'expr') {
|
|
430
|
-
acc.push(types.objectProperty(types.stringLiteral(item), __1.ASTUtils.getExpressionFromUIDLExpressionNode(prop)));
|
|
431
|
-
}
|
|
432
|
-
if (prop.type === 'dynamic') {
|
|
433
|
-
acc.push(types.spreadElement(types.logicalExpression('&&', types.memberExpression(types.identifier('params'), types.stringLiteral(prop.content.id), true, false), types.objectExpression([
|
|
434
|
-
types.objectProperty(types.stringLiteral(item), types.memberExpression(types.identifier('params'), types.stringLiteral(prop.content.id), true, false)),
|
|
435
|
-
]))));
|
|
436
|
-
}
|
|
437
|
-
return acc;
|
|
438
|
-
}, []);
|
|
439
|
-
var paramsAST = types.variableDeclaration('const', [
|
|
440
|
-
types.variableDeclarator(types.identifier('urlParams'), types.objectExpression(paramsDeclerations)),
|
|
441
|
-
]);
|
|
1086
|
+
var urlParamsDecleration = generateParamsAST(resource === null || resource === void 0 ? void 0 : resource.params);
|
|
1087
|
+
var bodyParamsDecleration = generateParamsAST(resource === null || resource === void 0 ? void 0 : resource.body);
|
|
442
1088
|
var url = (queryParams === null || queryParams === void 0 ? void 0 : queryParams.quasis)
|
|
443
1089
|
? types.templateLiteral(__spreadArray(__spreadArray([], fetchUrlQuasis, true), queryParamsQuasis, true), __spreadArray([], fetchUrl.expressions.concat(queryParams.expressions), true))
|
|
444
1090
|
: fetchUrl;
|
|
445
1091
|
var method = types.objectProperty(types.identifier('method'), types.stringLiteral(resource.method));
|
|
446
1092
|
var allHeaders = [];
|
|
447
|
-
if (
|
|
448
|
-
allHeaders.push(
|
|
1093
|
+
if ((_a = resource === null || resource === void 0 ? void 0 : resource.headers) === null || _a === void 0 ? void 0 : _a.authToken) {
|
|
1094
|
+
allHeaders.push(computeAuthorizationHeaderAST(resource === null || resource === void 0 ? void 0 : resource.headers));
|
|
449
1095
|
}
|
|
450
1096
|
if (headersASTs.length) {
|
|
451
1097
|
allHeaders = allHeaders.concat(headersASTs);
|
|
452
1098
|
}
|
|
453
|
-
var
|
|
454
|
-
var fetchAST = types.variableDeclaration('const', [
|
|
1099
|
+
var fetchAST = types.variableDeclaration('let', [
|
|
455
1100
|
types.variableDeclarator(types.identifier('data'), types.awaitExpression(types.callExpression(types.identifier('fetch'), [
|
|
456
1101
|
url,
|
|
457
|
-
types.objectExpression([
|
|
1102
|
+
types.objectExpression(__spreadArray(__spreadArray([
|
|
1103
|
+
method
|
|
1104
|
+
], (allHeaders.length > 0
|
|
1105
|
+
? [
|
|
1106
|
+
types.objectProperty(types.identifier('headers'), types.objectExpression(allHeaders)),
|
|
1107
|
+
]
|
|
1108
|
+
: []), true), (bodyParamsDecleration.length > 0 && (resource === null || resource === void 0 ? void 0 : resource.method) === 'POST'
|
|
1109
|
+
? [
|
|
1110
|
+
types.objectProperty(types.identifier('body'), types.callExpression(types.memberExpression(types.identifier('JSON'), types.identifier('stringify')), [types.identifier('bodyParams')])),
|
|
1111
|
+
]
|
|
1112
|
+
: []), true)),
|
|
458
1113
|
]))),
|
|
459
1114
|
]);
|
|
460
|
-
|
|
1115
|
+
// Fallback in case i18n interferes with normal CMS flows
|
|
1116
|
+
// Only generate fallback if locale parameter exists
|
|
1117
|
+
var hasLocaleParam = ((_b = resource === null || resource === void 0 ? void 0 : resource.params) === null || _b === void 0 ? void 0 : _b.locale) !== undefined;
|
|
1118
|
+
var fallbackAST = null;
|
|
1119
|
+
if (hasLocaleParam) {
|
|
1120
|
+
var fallbackParams = JSON.parse(JSON.stringify(resource));
|
|
1121
|
+
(_c = fallbackParams === null || fallbackParams === void 0 ? void 0 : fallbackParams.params) === null || _c === void 0 ? true : delete _c.locale;
|
|
1122
|
+
var fallbackUrlParamsDeclaration = generateParamsAST(fallbackParams === null || fallbackParams === void 0 ? void 0 : fallbackParams.params);
|
|
1123
|
+
var assignmentOfNewUrlParams = types.expressionStatement(types.assignmentExpression('=', types.identifier('urlParams'), types.objectExpression(__spreadArray([], fallbackUrlParamsDeclaration, true))));
|
|
1124
|
+
var assignmentExpressionAST = types.expressionStatement(types.assignmentExpression('=', types.identifier('data'), types.awaitExpression(types.callExpression(types.identifier('fetch'), [
|
|
1125
|
+
url,
|
|
1126
|
+
types.objectExpression(__spreadArray(__spreadArray([
|
|
1127
|
+
method
|
|
1128
|
+
], (allHeaders.length > 0
|
|
1129
|
+
? [
|
|
1130
|
+
types.objectProperty(types.identifier('headers'), types.objectExpression(allHeaders)),
|
|
1131
|
+
]
|
|
1132
|
+
: []), true), (bodyParamsDecleration.length > 0 && (resource === null || resource === void 0 ? void 0 : resource.method) === 'POST'
|
|
1133
|
+
? [
|
|
1134
|
+
types.objectProperty(types.identifier('body'), types.callExpression(types.memberExpression(types.identifier('JSON'), types.identifier('stringify')), [types.identifier('bodyParams')])),
|
|
1135
|
+
]
|
|
1136
|
+
: []), true)),
|
|
1137
|
+
]))));
|
|
1138
|
+
fallbackAST = types.ifStatement(types.binaryExpression('!==', types.memberExpression(types.identifier('data'), types.identifier('status')), types.numericLiteral(200)), types.blockStatement([assignmentOfNewUrlParams, assignmentExpressionAST]));
|
|
1139
|
+
}
|
|
1140
|
+
var responseType = (_e = (_d = resource === null || resource === void 0 ? void 0 : resource.response) === null || _d === void 0 ? void 0 : _d.type) !== null && _e !== void 0 ? _e : 'json';
|
|
461
1141
|
var responseJSONAST;
|
|
462
1142
|
/**
|
|
463
1143
|
* Responce types can be of json, text and we might be reading just headers
|
|
@@ -497,19 +1177,55 @@ var generateRemoteResourceASTs = function (resource) {
|
|
|
497
1177
|
]);
|
|
498
1178
|
}
|
|
499
1179
|
}
|
|
500
|
-
return [
|
|
1180
|
+
return __spreadArray(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], (urlParamsDecleration.length > 0
|
|
1181
|
+
? [
|
|
1182
|
+
types.variableDeclaration('let', [
|
|
1183
|
+
types.variableDeclarator(types.identifier('urlParams'), types.objectExpression(urlParamsDecleration)),
|
|
1184
|
+
]),
|
|
1185
|
+
]
|
|
1186
|
+
: []), true), (bodyParamsDecleration.length > 0
|
|
1187
|
+
? [
|
|
1188
|
+
types.variableDeclaration('const', [
|
|
1189
|
+
types.variableDeclarator(types.identifier('bodyParams'), types.objectExpression(bodyParamsDecleration)),
|
|
1190
|
+
]),
|
|
1191
|
+
]
|
|
1192
|
+
: []), true), [
|
|
1193
|
+
fetchAST
|
|
1194
|
+
], false), (fallbackAST ? [fallbackAST] : []), true), [
|
|
1195
|
+
responseJSONAST,
|
|
1196
|
+
], false).filter(Boolean);
|
|
501
1197
|
};
|
|
502
1198
|
exports.generateRemoteResourceASTs = generateRemoteResourceASTs;
|
|
1199
|
+
var generateParamsAST = function (props) {
|
|
1200
|
+
return Object.keys(props || {}).reduce(function (acc, item) {
|
|
1201
|
+
var prop = props[item];
|
|
1202
|
+
if (prop.type === 'static') {
|
|
1203
|
+
acc.push(types.objectProperty(types.stringLiteral(item), (0, exports.resolveObjectValue)(prop)));
|
|
1204
|
+
}
|
|
1205
|
+
if (prop.type === 'expr') {
|
|
1206
|
+
acc.push(types.objectProperty(types.stringLiteral(item), (0, exports.getExpressionFromUIDLExpressionNode)(prop)));
|
|
1207
|
+
}
|
|
1208
|
+
if (prop.type === 'dynamic') {
|
|
1209
|
+
acc.push(types.spreadElement(types.logicalExpression('&&', types.memberExpression(types.identifier('params'), types.stringLiteral(prop.content.id), true, false), types.objectExpression([
|
|
1210
|
+
types.objectProperty(types.stringLiteral(item), types.memberExpression(types.identifier('params'), types.stringLiteral(prop.content.id), true, false)),
|
|
1211
|
+
]))));
|
|
1212
|
+
}
|
|
1213
|
+
return acc;
|
|
1214
|
+
}, []);
|
|
1215
|
+
};
|
|
503
1216
|
var generateRESTHeadersAST = function (headers) {
|
|
504
|
-
return Object.keys(headers)
|
|
505
|
-
|
|
1217
|
+
return (Object.keys(headers)
|
|
1218
|
+
// `authToken` is rendered as the `Authorization` header; `authScheme` is a
|
|
1219
|
+
// generator-only directive for that header's prefix — neither is emitted as
|
|
1220
|
+
// its own literal HTTP header.
|
|
1221
|
+
.filter(function (header) { return header !== 'authToken' && header !== 'authScheme'; })
|
|
506
1222
|
.map(function (header) {
|
|
507
1223
|
var headerResolved = resolveResourceValue(headers[header]);
|
|
508
1224
|
var value = headers[header].type === 'static'
|
|
509
1225
|
? types.stringLiteral(String(headerResolved))
|
|
510
1226
|
: types.identifier(String(headerResolved));
|
|
511
1227
|
return types.objectProperty(types.stringLiteral(header), value);
|
|
512
|
-
});
|
|
1228
|
+
}));
|
|
513
1229
|
};
|
|
514
1230
|
var generateMemberExpressionASTFromBase = function (base, path) {
|
|
515
1231
|
if (path.length === 1) {
|
|
@@ -520,6 +1236,22 @@ var generateMemberExpressionASTFromBase = function (base, path) {
|
|
|
520
1236
|
return types.optionalMemberExpression((0, exports.generateMemberExpressionASTFromBase)(base, pathClone), types.identifier(path[path.length - 1]), false, true);
|
|
521
1237
|
};
|
|
522
1238
|
exports.generateMemberExpressionASTFromBase = generateMemberExpressionASTFromBase;
|
|
1239
|
+
var parseValuePath = function (valuePath) {
|
|
1240
|
+
return valuePath.map(function (segment) {
|
|
1241
|
+
if (typeof segment === 'string') {
|
|
1242
|
+
var bracketMatch = segment.match(/^\[(\d+)\]$/);
|
|
1243
|
+
if (bracketMatch) {
|
|
1244
|
+
return parseInt(bracketMatch[1], 10);
|
|
1245
|
+
}
|
|
1246
|
+
var numericMatch = segment.match(/^\d+$/);
|
|
1247
|
+
if (numericMatch) {
|
|
1248
|
+
return parseInt(segment, 10);
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
return segment;
|
|
1252
|
+
});
|
|
1253
|
+
};
|
|
1254
|
+
exports.parseValuePath = parseValuePath;
|
|
523
1255
|
var generateMemberExpressionASTFromPath = function (path) {
|
|
524
1256
|
var pathClone = __spreadArray([], path, true);
|
|
525
1257
|
if (path.length === 1) {
|
|
@@ -528,7 +1260,7 @@ var generateMemberExpressionASTFromPath = function (path) {
|
|
|
528
1260
|
pathClone.pop();
|
|
529
1261
|
var currentPath = path[path.length - 1];
|
|
530
1262
|
if (typeof currentPath === 'number') {
|
|
531
|
-
return types.optionalMemberExpression((0, exports.generateMemberExpressionASTFromPath)(pathClone), types.numericLiteral(currentPath),
|
|
1263
|
+
return types.optionalMemberExpression((0, exports.generateMemberExpressionASTFromPath)(pathClone), types.numericLiteral(currentPath), true, true);
|
|
532
1264
|
}
|
|
533
1265
|
var containsSpecial = currentPath.indexOf('.') !== -1 || currentPath.indexOf('-') !== -1;
|
|
534
1266
|
return types.optionalMemberExpression((0, exports.generateMemberExpressionASTFromPath)(pathClone), containsSpecial ? types.stringLiteral(currentPath) : types.identifier(currentPath), containsSpecial, true);
|
|
@@ -584,10 +1316,22 @@ var computeAuthorizationHeaderAST = function (headers) {
|
|
|
584
1316
|
return null;
|
|
585
1317
|
}
|
|
586
1318
|
var authTokenType = (_a = headers.authToken) === null || _a === void 0 ? void 0 : _a.type;
|
|
1319
|
+
// The auth scheme prefix defaults to `Bearer ` (back-compatible with every CMS
|
|
1320
|
+
// and data-source that stores a bare bearer token). A resource may override it
|
|
1321
|
+
// via a `headers.authScheme` static value — e.g. WordPress Basic / Application
|
|
1322
|
+
// Password auth sets `Basic ` so the rendered header is `Basic <base64>`
|
|
1323
|
+
// instead of the wrong `Bearer <base64>`. `authScheme` is consumed here and
|
|
1324
|
+
// filtered out of the emitted REST headers (see generateRESTHeadersAST).
|
|
1325
|
+
var authSchemeValue = headers.authScheme;
|
|
1326
|
+
var schemePrefix = authSchemeValue &&
|
|
1327
|
+
authSchemeValue.type === 'static' &&
|
|
1328
|
+
typeof authSchemeValue.content === 'string'
|
|
1329
|
+
? authSchemeValue.content
|
|
1330
|
+
: 'Bearer ';
|
|
587
1331
|
return types.objectProperty(types.identifier('Authorization'), types.templateLiteral(__spreadArray([
|
|
588
1332
|
types.templateElement({
|
|
589
|
-
cooked: authTokenType === 'static' ? "
|
|
590
|
-
raw: authTokenType === 'static' ? "
|
|
1333
|
+
cooked: authTokenType === 'static' ? "".concat(schemePrefix).concat(authToken) : schemePrefix,
|
|
1334
|
+
raw: authTokenType === 'static' ? "".concat(schemePrefix).concat(authToken) : schemePrefix,
|
|
591
1335
|
}, false)
|
|
592
1336
|
], (authTokenType === 'static'
|
|
593
1337
|
? []
|
|
@@ -606,7 +1350,23 @@ var computeFetchUrl = function (resource) {
|
|
|
606
1350
|
var baseUrlType = (_a = path.baseUrl) === null || _a === void 0 ? void 0 : _a.type;
|
|
607
1351
|
var routeType = (_b = path.route) === null || _b === void 0 ? void 0 : _b.type;
|
|
608
1352
|
if (baseUrlType === 'static' && routeType === 'static') {
|
|
609
|
-
var
|
|
1353
|
+
var baseUrlStr = typeof fetchBaseUrl === 'string' ? fetchBaseUrl : String(fetchBaseUrl || '');
|
|
1354
|
+
var routeStr = typeof resourceRoute === 'string' ? resourceRoute : String(resourceRoute || '');
|
|
1355
|
+
var cleanBaseUrl = baseUrlStr.endsWith('/') ? baseUrlStr.slice(0, -1) : baseUrlStr;
|
|
1356
|
+
var cleanRoute = routeStr.startsWith('/') ? routeStr.slice(1) : routeStr;
|
|
1357
|
+
var stringsToJoin = [cleanBaseUrl, cleanRoute].filter(function (item) { return item; }).join('/');
|
|
1358
|
+
// If the URL is relative (starts with /), add a runtime base URL prefix
|
|
1359
|
+
// so fetch() works in server-side contexts (getStaticProps/getServerSideProps).
|
|
1360
|
+
// Non-NEXT_PUBLIC_ env vars are only available server-side in Next.js,
|
|
1361
|
+
// so NEXTAUTH_URL naturally resolves to undefined on the client (making baseUrl '').
|
|
1362
|
+
if (stringsToJoin.startsWith('/')) {
|
|
1363
|
+
var processEnv = types.memberExpression(types.identifier('process'), types.identifier('env'));
|
|
1364
|
+
var serverBaseUrlExpr = types.logicalExpression('||', types.logicalExpression('||', types.memberExpression(processEnv, types.identifier('NEXT_PUBLIC_SITE_URL')), types.memberExpression(types.memberExpression(types.identifier('process'), types.identifier('env')), types.identifier('NEXTAUTH_URL'))), types.stringLiteral(''));
|
|
1365
|
+
return types.templateLiteral([
|
|
1366
|
+
types.templateElement({ cooked: '', raw: '' }, false),
|
|
1367
|
+
types.templateElement({ cooked: "".concat(stringsToJoin), raw: "".concat(stringsToJoin) }, true),
|
|
1368
|
+
], [serverBaseUrlExpr]);
|
|
1369
|
+
}
|
|
610
1370
|
return types.templateLiteral([types.templateElement({ cooked: "".concat(stringsToJoin), raw: "".concat(stringsToJoin) }, true)], []);
|
|
611
1371
|
}
|
|
612
1372
|
if (!routeType) {
|
|
@@ -643,6 +1403,7 @@ var computeFetchUrl = function (resource) {
|
|
|
643
1403
|
types.identifier(String(fetchBaseUrl))
|
|
644
1404
|
], (routeType === 'static' ? [] : [types.identifier(String(resourceRoute))]), true));
|
|
645
1405
|
};
|
|
1406
|
+
exports.computeFetchUrl = computeFetchUrl;
|
|
646
1407
|
var resolveResourceValue = function (value) {
|
|
647
1408
|
if (!value) {
|
|
648
1409
|
return '';
|
|
@@ -660,9 +1421,11 @@ var resolveObjectValue = function (prop) {
|
|
|
660
1421
|
? types.booleanLiteral(prop.content)
|
|
661
1422
|
: typeof prop.content === 'number'
|
|
662
1423
|
? types.numericLiteral(prop.content)
|
|
663
|
-
:
|
|
664
|
-
? (0, exports.
|
|
665
|
-
:
|
|
1424
|
+
: Array.isArray(prop.content)
|
|
1425
|
+
? types.arrayExpression(prop.content.map(function (element) { return (0, exports.convertValueToLiteral)(element); }))
|
|
1426
|
+
: typeof prop.content === 'object'
|
|
1427
|
+
? (0, exports.objectToObjectExpression)(prop.content)
|
|
1428
|
+
: types.identifier(String(prop.content));
|
|
666
1429
|
return value;
|
|
667
1430
|
}
|
|
668
1431
|
if (prop.type === 'expr') {
|
|
@@ -670,18 +1433,193 @@ var resolveObjectValue = function (prop) {
|
|
|
670
1433
|
}
|
|
671
1434
|
};
|
|
672
1435
|
exports.resolveObjectValue = resolveObjectValue;
|
|
1436
|
+
/**
|
|
1437
|
+
* Detects if a value is a UIDL dynamic reference (state or prop)
|
|
1438
|
+
*/
|
|
1439
|
+
var isUIDLDynamicReference = function (value) {
|
|
1440
|
+
return (typeof value === 'object' &&
|
|
1441
|
+
value !== null &&
|
|
1442
|
+
'type' in value &&
|
|
1443
|
+
value.type === 'dynamic' &&
|
|
1444
|
+
'content' in value &&
|
|
1445
|
+
typeof value.content === 'object' &&
|
|
1446
|
+
value.content !== null &&
|
|
1447
|
+
'referenceType' in value.content &&
|
|
1448
|
+
'id' in value.content);
|
|
1449
|
+
};
|
|
1450
|
+
exports.isUIDLDynamicReference = isUIDLDynamicReference;
|
|
1451
|
+
/**
|
|
1452
|
+
* Converts a filter destination value to an AST expression.
|
|
1453
|
+
* Handles both static values and dynamic references (state/prop).
|
|
1454
|
+
*/
|
|
1455
|
+
var convertFilterDestinationToExpression = function (destination, options) {
|
|
1456
|
+
var _a;
|
|
1457
|
+
// Handle dynamic references (state or prop)
|
|
1458
|
+
if ((0, exports.isUIDLDynamicReference)(destination)) {
|
|
1459
|
+
var content = destination.content;
|
|
1460
|
+
var referenceType = content.referenceType, id = content.id;
|
|
1461
|
+
if (referenceType === 'state') {
|
|
1462
|
+
return types.identifier(id);
|
|
1463
|
+
}
|
|
1464
|
+
if (referenceType === 'prop') {
|
|
1465
|
+
var prefix = ((_a = options === null || options === void 0 ? void 0 : options.dynamicReferencePrefixMap) === null || _a === void 0 ? void 0 : _a.prop) || 'props';
|
|
1466
|
+
return types.memberExpression(types.identifier(prefix), types.identifier(id));
|
|
1467
|
+
}
|
|
1468
|
+
// Fallback for other reference types
|
|
1469
|
+
return types.identifier(id);
|
|
1470
|
+
}
|
|
1471
|
+
// Handle static string values
|
|
1472
|
+
if (typeof destination === 'string') {
|
|
1473
|
+
return types.stringLiteral(destination);
|
|
1474
|
+
}
|
|
1475
|
+
// Handle other primitives
|
|
1476
|
+
if (typeof destination === 'number') {
|
|
1477
|
+
return types.numericLiteral(destination);
|
|
1478
|
+
}
|
|
1479
|
+
if (typeof destination === 'boolean') {
|
|
1480
|
+
return types.booleanLiteral(destination);
|
|
1481
|
+
}
|
|
1482
|
+
// Handle arrays
|
|
1483
|
+
if (Array.isArray(destination)) {
|
|
1484
|
+
return types.arrayExpression(destination.map(function (item) { return (0, exports.convertFilterDestinationToExpression)(item, options); }));
|
|
1485
|
+
}
|
|
1486
|
+
// Fallback to empty string for undefined/null
|
|
1487
|
+
return types.stringLiteral('');
|
|
1488
|
+
};
|
|
1489
|
+
exports.convertFilterDestinationToExpression = convertFilterDestinationToExpression;
|
|
673
1490
|
var getExpressionFromUIDLExpressionNode = function (node) {
|
|
674
|
-
var ast
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
1491
|
+
var ast;
|
|
1492
|
+
try {
|
|
1493
|
+
ast = (0, core_1.parse)((0, exports.sanitizeExprContent)(node.content), {
|
|
1494
|
+
sourceType: 'module',
|
|
1495
|
+
});
|
|
1496
|
+
}
|
|
1497
|
+
catch (err) {
|
|
1498
|
+
// Malformed expression content in the UIDL (e.g. `?.subtitle` missing its
|
|
1499
|
+
// left-hand identifier). Don't abort the whole generation — warn and fall
|
|
1500
|
+
// back to `undefined`, which renders as nothing in JSX.
|
|
1501
|
+
// tslint:disable-next-line:no-console
|
|
1502
|
+
console.warn("Failed to parse UIDL expression content ".concat(JSON.stringify(node.content), ": ").concat(err.message, ". Falling back to 'undefined'."));
|
|
1503
|
+
return types.identifier('undefined');
|
|
1504
|
+
}
|
|
1505
|
+
if (!ast || !('program' in ast)) {
|
|
678
1506
|
throw new Error("The AST does not have a program node in the expression inside addDynamicExpressionAttributeToJSXTag");
|
|
679
1507
|
}
|
|
680
1508
|
var theStatementOnlyWihtoutTheProgram = ast.program.body[0];
|
|
681
|
-
if (theStatementOnlyWihtoutTheProgram
|
|
1509
|
+
if (!theStatementOnlyWihtoutTheProgram ||
|
|
1510
|
+
theStatementOnlyWihtoutTheProgram.type !== 'ExpressionStatement') {
|
|
682
1511
|
throw new Error("Expr dynamic attribute only support expressions statements at the moment.");
|
|
683
1512
|
}
|
|
684
|
-
return theStatementOnlyWihtoutTheProgram.expression;
|
|
1513
|
+
return (0, exports.makeMemberAccessOptional)(theStatementOnlyWihtoutTheProgram.expression);
|
|
685
1514
|
};
|
|
686
1515
|
exports.getExpressionFromUIDLExpressionNode = getExpressionFromUIDLExpressionNode;
|
|
1516
|
+
/**
|
|
1517
|
+
* Every member read in a UIDL expression becomes an optional-chain read:
|
|
1518
|
+
* `strengths[0].pillar` → `strengths?.[0]?.pillar`. A binding into a list
|
|
1519
|
+
* that is empty until a workflow fills it (the first render, a reset) must
|
|
1520
|
+
* read `undefined`, never throw — one such read took a whole page down at
|
|
1521
|
+
* server render ("Cannot read properties of undefined"). A call's callee
|
|
1522
|
+
* keeps its plain member (`JSON.stringify(x)`), and an assignment or update
|
|
1523
|
+
* target is left as written.
|
|
1524
|
+
*/
|
|
1525
|
+
var makeMemberAccessOptional = function (node) {
|
|
1526
|
+
var SKIP_KEYS = new Set([
|
|
1527
|
+
'loc',
|
|
1528
|
+
'start',
|
|
1529
|
+
'end',
|
|
1530
|
+
'leadingComments',
|
|
1531
|
+
'trailingComments',
|
|
1532
|
+
'innerComments',
|
|
1533
|
+
'extra',
|
|
1534
|
+
]);
|
|
1535
|
+
var isNode = function (value) {
|
|
1536
|
+
return Boolean(value) &&
|
|
1537
|
+
typeof value === 'object' &&
|
|
1538
|
+
typeof value.type === 'string';
|
|
1539
|
+
};
|
|
1540
|
+
var visit = function (current, asCallee, asTarget) {
|
|
1541
|
+
if (current.type === 'MemberExpression' && !asCallee && !asTarget) {
|
|
1542
|
+
var member = current;
|
|
1543
|
+
var object = visit(member.object, false, false);
|
|
1544
|
+
var property = member.computed
|
|
1545
|
+
? visit(member.property, false, false)
|
|
1546
|
+
: member.property;
|
|
1547
|
+
return types.optionalMemberExpression(object, property, member.computed, true);
|
|
1548
|
+
}
|
|
1549
|
+
if (current.type === 'CallExpression' ||
|
|
1550
|
+
current.type === 'OptionalCallExpression' ||
|
|
1551
|
+
current.type === 'NewExpression') {
|
|
1552
|
+
var call = current;
|
|
1553
|
+
// The callee's own member stays plain; what it is read from is guarded.
|
|
1554
|
+
if (call.callee.type === 'MemberExpression') {
|
|
1555
|
+
var callee = call.callee;
|
|
1556
|
+
callee.object = visit(callee.object, false, false);
|
|
1557
|
+
if (callee.computed)
|
|
1558
|
+
callee.property = visit(callee.property, false, false);
|
|
1559
|
+
}
|
|
1560
|
+
else {
|
|
1561
|
+
call.callee = visit(call.callee, true, false);
|
|
1562
|
+
}
|
|
1563
|
+
call.arguments = call.arguments.map(function (argument) { return visit(argument, false, false); });
|
|
1564
|
+
return call;
|
|
1565
|
+
}
|
|
1566
|
+
if (current.type === 'AssignmentExpression') {
|
|
1567
|
+
var assignment = current;
|
|
1568
|
+
assignment.right = visit(assignment.right, false, false);
|
|
1569
|
+
return assignment;
|
|
1570
|
+
}
|
|
1571
|
+
if (current.type === 'UpdateExpression' ||
|
|
1572
|
+
(current.type === 'UnaryExpression' &&
|
|
1573
|
+
current.operator === 'delete')) {
|
|
1574
|
+
return current;
|
|
1575
|
+
}
|
|
1576
|
+
for (var _i = 0, _a = Object.keys(current); _i < _a.length; _i++) {
|
|
1577
|
+
var key = _a[_i];
|
|
1578
|
+
if (SKIP_KEYS.has(key))
|
|
1579
|
+
continue;
|
|
1580
|
+
var value = current[key];
|
|
1581
|
+
if (Array.isArray(value)) {
|
|
1582
|
+
;
|
|
1583
|
+
current[key] = value.map(function (item) {
|
|
1584
|
+
return isNode(item) ? visit(item, false, false) : item;
|
|
1585
|
+
});
|
|
1586
|
+
}
|
|
1587
|
+
else if (isNode(value)) {
|
|
1588
|
+
;
|
|
1589
|
+
current[key] = visit(value, false, false);
|
|
1590
|
+
}
|
|
1591
|
+
}
|
|
1592
|
+
return current;
|
|
1593
|
+
};
|
|
1594
|
+
return visit(node, false, false);
|
|
1595
|
+
};
|
|
1596
|
+
exports.makeMemberAccessOptional = makeMemberAccessOptional;
|
|
1597
|
+
var isJSXElement = function (value) {
|
|
1598
|
+
return value.type === 'JSXElement';
|
|
1599
|
+
};
|
|
1600
|
+
exports.isJSXElement = isJSXElement;
|
|
1601
|
+
/**
|
|
1602
|
+
* Because of the restrictions of the AST Types we need to have a clear subset of binary operators we can use
|
|
1603
|
+
* @param operation - the operation defined in the UIDL for the current state branch
|
|
1604
|
+
*/
|
|
1605
|
+
var convertToBinaryOperator = function (operation) {
|
|
1606
|
+
var allowedOperations = ['===', '!==', '>=', '<=', '>', '<'];
|
|
1607
|
+
if (allowedOperations.includes(operation)) {
|
|
1608
|
+
return operation;
|
|
1609
|
+
}
|
|
1610
|
+
else {
|
|
1611
|
+
return '===';
|
|
1612
|
+
}
|
|
1613
|
+
};
|
|
1614
|
+
exports.convertToBinaryOperator = convertToBinaryOperator;
|
|
1615
|
+
var convertToUnaryOperator = function (operation) {
|
|
1616
|
+
var allowedOperations = ['!'];
|
|
1617
|
+
if (allowedOperations.includes(operation)) {
|
|
1618
|
+
return operation;
|
|
1619
|
+
}
|
|
1620
|
+
else {
|
|
1621
|
+
return '!';
|
|
1622
|
+
}
|
|
1623
|
+
};
|
|
1624
|
+
exports.convertToUnaryOperator = convertToUnaryOperator;
|
|
687
1625
|
//# sourceMappingURL=ast-utils.js.map
|