Skip to content

Commit

Permalink
Merge pull request #1698 from alibaba/feat/0228
Browse files Browse the repository at this point in the history
feat: 出码引擎 1.0.8
  • Loading branch information
liujuping authored Mar 14, 2023
2 parents a09ef54 + a6ebd5b commit 41753de
Show file tree
Hide file tree
Showing 56 changed files with 412 additions and 171 deletions.
28 changes: 14 additions & 14 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ module.exports = {
'no-prototype-builtins': 1,
'no-useless-constructor': 1,
'no-empty-function': 1,
'@typescript-eslint/member-ordering': 0,
'lines-between-class-members': 0,
'no-await-in-loop': 0,
'no-plusplus': 0,
Expand All @@ -35,23 +34,24 @@ module.exports = {
'@typescript-eslint/indent': 0,
'import/no-cycle': 0,
'@typescript-eslint/no-shadow': 0,
"@typescript-eslint/method-signature-style": 0,
"@typescript-eslint/consistent-type-assertions": 0,
"@typescript-eslint/no-useless-constructor": 0,
'@typescript-eslint/method-signature-style': 0,
'@typescript-eslint/consistent-type-assertions': 0,
'@typescript-eslint/no-useless-constructor': 0,
'@typescript-eslint/dot-notation': 0, // for lint performance
'@typescript-eslint/restrict-plus-operands': 0, // for lint performance
'no-unexpected-multiline': 1,
'no-multiple-empty-lines': ['error', { "max": 1 }],
'no-multiple-empty-lines': ['error', { max: 1 }],
'lines-around-comment': ['error', {
"beforeBlockComment": true,
"afterBlockComment": false,
"afterLineComment": false,
"allowBlockStart": true,
beforeBlockComment: true,
afterBlockComment: false,
afterLineComment: false,
allowBlockStart: true,
}],
"no-unused-vars": ['error', { "destructuredArrayIgnorePattern": "^_" }],
"@typescript-eslint/member-ordering": [
"error",
{ "default": ["signature", "field", "constructor", "method"] }
'comma-dangle': ['error', 'always-multiline'],
'@typescript-eslint/member-ordering': [
'error',
{ default: ['signature', 'field', 'constructor', 'method'] }
],
}
'no-unused-vars': ['error', { "destructuredArrayIgnorePattern": "^_" }]
},
};
8 changes: 4 additions & 4 deletions modules/code-generator/example-schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
},
"lifeCycles": {
"componentDidMount": {
"type": "JSExpression",
"type": "JSFunction",
"value": "function() { console.log('componentDidMount'); }"
}
},
Expand All @@ -91,7 +91,7 @@
"isSync": true
},
"dataHandler": {
"type": "JSExpression",
"type": "JSFunction",
"value": "function (response) {\nif (!response.data.success){\n throw new Error(response.data.message);\n }\n return response.data.data;\n}"
}
},
Expand All @@ -105,13 +105,13 @@
"isSync": true
},
"dataHandler": {
"type": "JSExpression",
"type": "JSFunction",
"value": "function (response) {\nif (!response.data.success){\n throw new Error(response.data.message);\n }\n return response.data.data.result;\n}"
}
}
],
"dataHandler": {
"type": "JSExpression",
"type": "JSFunction",
"value": "function (dataMap) {\n console.info(\"All datasources loaded:\", dataMap);\n}"
}
},
Expand Down
8 changes: 4 additions & 4 deletions modules/code-generator/example-schema.json5
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
},
lifeCycles: {
componentDidMount: {
type: 'JSExpression',
type: 'JSFunction',
value: "function() { console.log('componentDidMount'); }",
},
},
Expand All @@ -91,7 +91,7 @@
isSync: true,
},
dataHandler: {
type: 'JSExpression',
type: 'JSFunction',
value: 'function (response) {\nif (!response.data.success){\n throw new Error(response.data.message);\n }\n return response.data.data;\n}',
},
},
Expand All @@ -105,13 +105,13 @@
isSync: true,
},
dataHandler: {
type: 'JSExpression',
type: 'JSFunction',
value: 'function (response) {\nif (!response.data.success){\n throw new Error(response.data.message);\n }\n return response.data.data.result;\n}',
},
},
],
dataHandler: {
type: 'JSExpression',
type: 'JSFunction',
value: 'function (dataMap) {\n console.info("All datasources loaded:", dataMap);\n}',
},
},
Expand Down
2 changes: 1 addition & 1 deletion modules/code-generator/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@alilc/lowcode-code-generator",
"version": "1.0.7",
"version": "1.0.8",
"description": "出码引擎 for LowCode Engine",
"license": "MIT",
"main": "lib/index.js",
Expand Down
21 changes: 21 additions & 0 deletions modules/code-generator/src/const/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,26 @@ export const CONTAINER_TYPE = {

export const SUPPORT_SCHEMA_VERSION_LIST = ['0.0.1', '1.0.0'];

// built-in slot names which have been handled in ProjectBuilder
export const BUILTIN_SLOT_NAMES = [
'pages',
'components',
'router',
'entry',
'appConfig',
'buildConfig',
'constants',
'utils',
'i18n',
'globalStyle',
'htmlEntry',
'packageJSON',
'demo',
];

export const isBuiltinSlotName = function (name: string) {
return BUILTIN_SLOT_NAMES.includes(name);
};

export * from './file';
export * from './generator';
5 changes: 2 additions & 3 deletions modules/code-generator/src/generator/ModuleBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,9 @@ export function createModuleBuilder(

if (options.postProcessors.length > 0) {
files = files.map((file) => {
let { content } = file;
const type = file.ext;
let { content, ext: type, name } = file;
options.postProcessors.forEach((processer) => {
content = processer(content, type);
content = processer(content, type, name);
});

return createResultFile(file.name, type, content);
Expand Down
30 changes: 29 additions & 1 deletion modules/code-generator/src/generator/ProjectBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { createResultDir, addDirectory, addFile } from '../utils/resultHelper';
import { createModuleBuilder } from './ModuleBuilder';
import { ProjectPreProcessor, ProjectPostProcessor, IContextData } from '../types/core';
import { CodeGeneratorError } from '../types/error';
import { isBuiltinSlotName } from '../const';

interface IModuleInfo {
moduleName?: string;
Expand All @@ -24,22 +25,31 @@ interface IModuleInfo {
}

export interface ProjectBuilderInitOptions {

/** 项目模板 */
template: IProjectTemplate;

/** 项目插件 */
plugins: IProjectPlugins;

/** 模块后置处理器 */
postProcessors: PostProcessor[];

/** Schema 解析器 */
schemaParser?: ISchemaParser;

/** 项目级别的前置处理器 */
projectPreProcessors?: ProjectPreProcessor[];

/** 项目级别的后置处理器 */
projectPostProcessors?: ProjectPostProcessor[];

/** 是否处于严格模式 */
inStrictMode?: boolean;

/** 一些额外的上下文数据 */
extraContextData?: Record<string, unknown>;

/**
* Hook which is used to customize original options, we can reorder/add/remove plugins/processors
* of the existing solution.
Expand Down Expand Up @@ -126,6 +136,7 @@ export class ProjectBuilder implements IProjectBuilder {
const builders = this.createModuleBuilders({
extraContextData: {
projectRemark: parseResult?.project?.projectRemark,
template: this.template,
},
});
// Generator Code module
Expand Down Expand Up @@ -263,7 +274,8 @@ export class ProjectBuilder implements IProjectBuilder {
});
}

// TODO: 更多 slots 的处理??是不是可以考虑把 template 中所有的 slots 都处理下?
// handle extra slots
await this.generateExtraSlots(builders, parseResult, buildResult);

// Post Process
const isSingleComponent = parseResult?.project?.projectRemark?.isSingleComponent;
Expand Down Expand Up @@ -320,6 +332,22 @@ export class ProjectBuilder implements IProjectBuilder {

return builders;
}

private async generateExtraSlots(
builders: Record<string, IModuleBuilder>,
parseResult: IParseResult,
buildResult: IModuleInfo[],
) {
for (const slotName in this.template.slots) {
if (!isBuiltinSlotName(slotName)) {
const { files } = await builders[slotName].generateModule(parseResult);
buildResult.push({
path: this.template.slots[slotName].path,
files,
});
}
}
}
}

export function createProjectBuilder(initOptions: ProjectBuilderInitOptions): IProjectBuilder {
Expand Down
3 changes: 2 additions & 1 deletion modules/code-generator/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/**
* 低代码引擎的出码模块,负责将编排产出的 Schema 转换成实际可执行的代码。
* 注意:为了保持 API 的稳定性, 这里所有导出的 API 均要显式命名方式导出
* 注意:为了保持 API 的稳定性这里所有导出的 API 均要显式命名方式导出
* (即用 export { xxx } from 'xx' 的方式,不要直接 export * from 'xxx')
* 而且所有导出的 API 务必在 tests/public 中编写单元测试
*/
Expand Down Expand Up @@ -51,6 +51,7 @@ export default {
},
plugins: {
common: {

/**
* 处理 ES Module
* @deprecated please use esModule
Expand Down
4 changes: 3 additions & 1 deletion modules/code-generator/src/plugins/common/esmodule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,7 @@ function buildPackageImport(
export interface PluginConfig {
fileType?: string; // 导出的文件类型
useAliasName?: boolean; // 是否使用 componentName 重命名组件 identifier
filter?: (deps: IDependency[]) => IDependency[]; // 支持过滤能力
}

const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?: PluginConfig) => {
Expand All @@ -460,7 +461,8 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?: Plu
const ir = next.ir as IWithDependency;

if (ir && ir.deps && ir.deps.length > 0) {
const packs = groupDepsByPack(ir.deps);
const deps = cfg.filter ? cfg.filter(ir.deps) : ir.deps;
const packs = groupDepsByPack(deps);

Object.keys(packs).forEach((pkg) => {
const chunks = buildPackageImport(pkg, packs[pkg], cfg.fileType, cfg.useAliasName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
IContainerInfo,
} from '../../../types';
import { debug } from '../../../utils/debug';
import { isJSExpressionFn } from '../../../utils/common';

export interface PluginConfig {
fileType: string;
Expand Down Expand Up @@ -49,6 +50,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
// 过滤掉非法数据(有些场景下会误传入空字符串或 null)
if (
!isJSFunction(lifeCycles[lifeCycleName]) &&
!isJSExpressionFn(lifeCycles[lifeCycleName]) &&
!isJSExpression(lifeCycles[lifeCycleName])
) {
return;
Expand Down
3 changes: 1 addition & 2 deletions modules/code-generator/src/plugins/component/rax/jsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,7 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>

// 注意:这里其实隐含了一个假设:schema 中的 componentName 应该是一个有效的 JS 标识符,而且是大写字母打头的
// FIXME: 为了快速修复临时加的逻辑,需要用 pre-process 的方式替代处理。
const mapComponentNameToAliasOrKeepIt = (componentName: string) =>
componentsNameAliasMap.get(componentName) || componentName;
const mapComponentNameToAliasOrKeepIt = (componentName: string) => componentsNameAliasMap.get(componentName) || componentName;

// 然后过滤掉所有的别名 chunks
next.chunks = next.chunks.filter((chunk) => !isImportAliasDefineChunk(chunk));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {

// 将模块名转换成 PascalCase 的格式,并添加特定后缀,防止命名冲突
const componentClassName = ensureValidClassName(
`${changeCase.pascalCase(ir.moduleName)}$$Page`,
`${changeCase.pascalCase(ir.moduleName)}$$${ir.containerType}`,
);

next.chunks.push({
Expand All @@ -43,6 +43,18 @@ const pluginFactory: BuilderComponentPluginFactory<unknown> = () => {
],
});

if (ir.containerType === 'Component') {
next.chunks.push({
type: ChunkType.STRING,
fileType: FileType.JSX,
name: CLASS_DEFINE_CHUNK_NAME.InsVar,
content: `static displayName = '${changeCase.pascalCase(ir.moduleName)}';`,
linkAfter: [
CLASS_DEFINE_CHUNK_NAME.Start,
],
});
}

next.chunks.push({
type: ChunkType.STRING,
fileType: FileType.JSX,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ import {
} from '../../../types';

export interface PluginConfig {
fileType: string;
fileType?: string;
implementType: 'inConstructor' | 'insMember' | 'hooks';
}

const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) => {
const cfg: PluginConfig = {
const cfg: PluginConfig & { fileType: string } = {
fileType: FileType.JSX,
implementType: 'inConstructor',
...config,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { generateCompositeType } from '../../../utils/compositeType';
import { parseExpressionConvertThis2Context } from '../../../utils/expressionParser';
import { isValidContainerType } from '../../../utils/schema';
import { REACT_CHUNK_NAME } from './const';
import { isJSExpressionFn } from '../../../utils/common';

export interface PluginConfig {
fileType?: string;
Expand All @@ -37,6 +38,7 @@ export interface PluginConfig {
* 数据源配置
*/
datasourceConfig?: {

/** 数据源引擎的版本 */
engineVersion?: string;

Expand Down Expand Up @@ -188,15 +190,15 @@ const pluginFactory: BuilderComponentPluginFactory<PluginConfig> = (config?) =>
export default pluginFactory;

function wrapAsFunction(value: IPublicTypeCompositeValue, scope: IScope): IPublicTypeCompositeValue {
if (isJSExpression(value) || isJSFunction(value)) {
if (isJSExpression(value) || isJSFunction(value) || isJSExpressionFn(value)) {
return {
type: 'JSExpression',
value: `function(){ return ((${value.value}))}`,
value: `function(){ return ((${value.value}))}.bind(this)`,
};
}

return {
type: 'JSExpression',
value: `function(){return((${generateCompositeType(value, scope)}))}`,
value: `function(){return((${generateCompositeType(value, scope)}))}.bind(this)`,
};
}
Loading

0 comments on commit 41753de

Please sign in to comment.