224 lines
12 KiB
JavaScript
224 lines
12 KiB
JavaScript
"use strict";
|
|
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
|
}) : (function(o, m, k, k2) {
|
|
if (k2 === undefined) k2 = k;
|
|
o[k2] = m[k];
|
|
}));
|
|
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
}) : function(o, v) {
|
|
o["default"] = v;
|
|
});
|
|
var __importStar = (this && this.__importStar) || function (mod) {
|
|
if (mod && mod.__esModule) return mod;
|
|
var result = {};
|
|
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
__setModuleDefault(result, mod);
|
|
return result;
|
|
};
|
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
};
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.getAmplifyJSClientGenerator = exports.createHookStatement = exports.buildBaseCollectionVariableStatement = exports.formatCode = exports.bindingPropertyUsesHook = exports.jsonToLiteral = exports.getDeclarationFilename = exports.buildSortFunction = exports.buildPrinter = exports.transpile = exports.defaultRenderConfig = void 0;
|
|
/*
|
|
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License").
|
|
You may not use this file except in compliance with the License.
|
|
You may obtain a copy of the License at
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
See the License for the specific language governing permissions and
|
|
limitations under the License.
|
|
*/
|
|
const codegen_ui_1 = require("@aws-amplify/codegen-ui");
|
|
const typescript_1 = __importStar(require("typescript"));
|
|
const vfs_1 = require("@typescript/vfs");
|
|
const path_1 = __importDefault(require("path"));
|
|
const react_render_config_1 = require("./react-render-config");
|
|
exports.defaultRenderConfig = {
|
|
script: react_render_config_1.ScriptKind.TSX,
|
|
target: react_render_config_1.ScriptTarget.ES2015,
|
|
module: react_render_config_1.ModuleKind.ESNext,
|
|
includeUseClientDirective: false,
|
|
};
|
|
const supportedTranspilationTargets = [
|
|
react_render_config_1.ScriptTarget.ES3,
|
|
react_render_config_1.ScriptTarget.ES5,
|
|
react_render_config_1.ScriptTarget.ES2015,
|
|
react_render_config_1.ScriptTarget.ES2016,
|
|
react_render_config_1.ScriptTarget.ES2017,
|
|
react_render_config_1.ScriptTarget.ES2018,
|
|
react_render_config_1.ScriptTarget.ES2019,
|
|
react_render_config_1.ScriptTarget.ES2020,
|
|
react_render_config_1.ScriptTarget.ES2021,
|
|
];
|
|
function transpile(code, renderConfig, shouldFormatCode = true) {
|
|
const { target, module, script, renderTypeDeclarations, inlineSourceMap } = renderConfig;
|
|
if (script === react_render_config_1.ScriptKind.JS || script === react_render_config_1.ScriptKind.JSX) {
|
|
const transpiledCode = (0, typescript_1.transpileModule)(code, {
|
|
compilerOptions: {
|
|
target,
|
|
module,
|
|
jsx: script === react_render_config_1.ScriptKind.JS ? typescript_1.default.JsxEmit.React : typescript_1.default.JsxEmit.Preserve,
|
|
esModuleInterop: true,
|
|
inlineSourceMap,
|
|
inlineSources: inlineSourceMap,
|
|
},
|
|
}).outputText;
|
|
const componentText = shouldFormatCode ? formatCode(transpiledCode) : transpiledCode;
|
|
/*
|
|
* createProgram is less performant than traspileModule and should only be used when necessary.
|
|
* createProgram is used here becuase transpileModule cannot produce type declarations.
|
|
* We execute in a virtual filesystem to ensure we have no dependencies on platform fs in this stage.
|
|
*/
|
|
if (renderTypeDeclarations) {
|
|
if (target && !new Set(supportedTranspilationTargets).has(target)) {
|
|
throw new codegen_ui_1.InvalidInputError(`ScriptTarget ${target} not supported with type declarations enabled, expected one of ${JSON.stringify(supportedTranspilationTargets)}`);
|
|
}
|
|
const compilerOptions = {
|
|
target,
|
|
module,
|
|
declaration: true,
|
|
emitDeclarationOnly: true,
|
|
skipLibCheck: true,
|
|
};
|
|
const fsMap = (0, vfs_1.createDefaultMapFromNodeModules)(compilerOptions, typescript_1.default);
|
|
fsMap.set('index.tsx', code);
|
|
const host = (0, vfs_1.createVirtualCompilerHost)((0, vfs_1.createSystem)(fsMap), compilerOptions, typescript_1.default);
|
|
(0, typescript_1.createProgram)({
|
|
rootNames: [...fsMap.keys()],
|
|
options: compilerOptions,
|
|
host: host.compilerHost,
|
|
}).emit();
|
|
const declaration = fsMap.get('index.d.ts');
|
|
if (!declaration) {
|
|
throw new codegen_ui_1.InternalError('Component declaration file not generated');
|
|
}
|
|
return { componentText, declaration };
|
|
}
|
|
return {
|
|
componentText,
|
|
};
|
|
}
|
|
return { componentText: formatCode(code) };
|
|
}
|
|
exports.transpile = transpile;
|
|
function buildPrinter(fileName, renderConfig) {
|
|
const { target, script } = renderConfig;
|
|
const file = (0, typescript_1.createSourceFile)(fileName, '', target || exports.defaultRenderConfig.target, false, script || exports.defaultRenderConfig.script);
|
|
const printer = (0, typescript_1.createPrinter)({
|
|
newLine: typescript_1.NewLineKind.LineFeed,
|
|
});
|
|
return { printer, file };
|
|
}
|
|
exports.buildPrinter = buildPrinter;
|
|
/**
|
|
* (s: SortPredicate<User>) => s.firstName('ASCENDING').lastName('DESCENDING')
|
|
*/
|
|
const buildSortFunction = (model, sort) => {
|
|
const ascendingSortDirection = typescript_1.factory.createPropertyAccessExpression(typescript_1.factory.createIdentifier('SortDirection'), typescript_1.factory.createIdentifier('ASCENDING'));
|
|
const descendingSortDirection = typescript_1.factory.createPropertyAccessExpression(typescript_1.factory.createIdentifier('SortDirection'), typescript_1.factory.createIdentifier('DESCENDING'));
|
|
let expr = typescript_1.factory.createIdentifier('s');
|
|
sort.forEach((sortPredicate) => {
|
|
expr = typescript_1.factory.createCallExpression(typescript_1.factory.createPropertyAccessExpression(expr, typescript_1.factory.createIdentifier(sortPredicate.field)), undefined, [sortPredicate.direction === 'ASC' ? ascendingSortDirection : descendingSortDirection]);
|
|
});
|
|
return typescript_1.factory.createArrowFunction(undefined, undefined, [
|
|
typescript_1.factory.createParameterDeclaration(undefined, undefined, undefined, typescript_1.factory.createIdentifier('s'), undefined, typescript_1.factory.createTypeReferenceNode(typescript_1.factory.createIdentifier('SortPredicate'), [
|
|
typescript_1.factory.createTypeReferenceNode(typescript_1.factory.createIdentifier(model), undefined),
|
|
]), undefined),
|
|
], undefined, typescript_1.factory.createToken(typescript_1.default.SyntaxKind.EqualsGreaterThanToken), expr);
|
|
};
|
|
exports.buildSortFunction = buildSortFunction;
|
|
function getDeclarationFilename(filename) {
|
|
return `${path_1.default.basename(filename, filename.includes('.tsx') ? '.tsx' : '.jsx')}.d.ts`;
|
|
}
|
|
exports.getDeclarationFilename = getDeclarationFilename;
|
|
// eslint-disable-next-line consistent-return
|
|
function jsonToLiteral(jsonObject, tryAndMarshallStringsToObjects) {
|
|
if (jsonObject === null) {
|
|
return typescript_1.factory.createNull();
|
|
}
|
|
// eslint-disable-next-line default-case
|
|
switch (typeof jsonObject) {
|
|
case 'string':
|
|
if (tryAndMarshallStringsToObjects) {
|
|
try {
|
|
const parsedObject = JSON.parse(jsonObject);
|
|
if (typeof parsedObject === 'object') {
|
|
return jsonToLiteral(parsedObject, tryAndMarshallStringsToObjects);
|
|
}
|
|
}
|
|
catch (e) { } // eslint-disable-line no-empty
|
|
}
|
|
return typescript_1.factory.createStringLiteral(jsonObject);
|
|
case 'number':
|
|
return typescript_1.factory.createNumericLiteral(jsonObject);
|
|
case 'boolean': {
|
|
if (jsonObject) {
|
|
return typescript_1.factory.createTrue();
|
|
}
|
|
return typescript_1.factory.createFalse();
|
|
}
|
|
case 'object': {
|
|
if (jsonObject instanceof Array) {
|
|
return typescript_1.factory.createArrayLiteralExpression(jsonObject.map((obj) => jsonToLiteral(obj, tryAndMarshallStringsToObjects)), false);
|
|
}
|
|
// else object
|
|
return typescript_1.factory.createObjectLiteralExpression(Object.entries(jsonObject).map(([key, value]) => typescript_1.factory.createPropertyAssignment(typescript_1.factory.createStringLiteral(key), jsonToLiteral(value, tryAndMarshallStringsToObjects))), false);
|
|
}
|
|
}
|
|
}
|
|
exports.jsonToLiteral = jsonToLiteral;
|
|
function bindingPropertyUsesHook(binding) {
|
|
return (0, codegen_ui_1.isDataPropertyBinding)(binding) && 'predicate' in binding.bindingProperties;
|
|
}
|
|
exports.bindingPropertyUsesHook = bindingPropertyUsesHook;
|
|
// optional import prettier
|
|
function formatCode(code) {
|
|
let prettier = null;
|
|
let parserTypescript = null;
|
|
try {
|
|
// eslint-disable-next-line global-require, import/no-extraneous-dependencies, @typescript-eslint/no-var-requires
|
|
prettier = require('prettier');
|
|
// eslint-disable-next-line global-require, import/no-extraneous-dependencies, @typescript-eslint/no-var-requires
|
|
parserTypescript = require('prettier/parser-typescript');
|
|
}
|
|
catch (_a) { } // eslint-disable-line no-empty
|
|
if (prettier && parserTypescript) {
|
|
return prettier.format(code, { parser: 'typescript', plugins: [parserTypescript] });
|
|
}
|
|
return code;
|
|
}
|
|
exports.formatCode = formatCode;
|
|
/*
|
|
base collection variable statement
|
|
const {identifier} = {propertyAccessExpression}.items
|
|
*/
|
|
const buildBaseCollectionVariableStatement = (identifier, expression) => {
|
|
return typescript_1.factory.createVariableStatement(undefined, typescript_1.factory.createVariableDeclarationList([
|
|
typescript_1.factory.createVariableDeclaration(identifier, undefined, undefined, typescript_1.factory.createPropertyAccessExpression(expression, typescript_1.factory.createIdentifier('items'))),
|
|
], typescript_1.default.NodeFlags.Const));
|
|
};
|
|
exports.buildBaseCollectionVariableStatement = buildBaseCollectionVariableStatement;
|
|
const createHookStatement = (variableName, methodName, props) => {
|
|
return typescript_1.factory.createVariableStatement(undefined, typescript_1.factory.createVariableDeclarationList([
|
|
typescript_1.factory.createVariableDeclaration(typescript_1.factory.createIdentifier(variableName), undefined, undefined, typescript_1.factory.createCallExpression(typescript_1.factory.createIdentifier(methodName), undefined, [props])),
|
|
], typescript_1.default.NodeFlags.Const));
|
|
};
|
|
exports.createHookStatement = createHookStatement;
|
|
// const client = generateClient();
|
|
const getAmplifyJSClientGenerator = () => {
|
|
return typescript_1.factory.createVariableStatement(undefined, typescript_1.factory.createVariableDeclarationList([
|
|
typescript_1.factory.createVariableDeclaration(typescript_1.factory.createIdentifier('client'), undefined, undefined, typescript_1.factory.createCallExpression(typescript_1.factory.createIdentifier('generateClient'), undefined, [])),
|
|
], typescript_1.default.NodeFlags.Const));
|
|
};
|
|
exports.getAmplifyJSClientGenerator = getAmplifyJSClientGenerator;
|
|
//# sourceMappingURL=react-studio-template-renderer-helper.js.map
|