@cloudbase/lowcode-builder 1.0.38 → 1.0.40-alpha.0

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.
@@ -48,15 +48,15 @@ async function buildWedaApp({ cals, subAppCalsList = [], dependencies = [], appK
48
48
  weapps: apps,
49
49
  projDir: appBuildDir,
50
50
  appId: appKey,
51
- domain: domain,
51
+ domain,
52
52
  materials: dependencies,
53
53
  plugins,
54
54
  isProduction: mode === common_1.WebpackModeType.PRODUCTION,
55
55
  deployMode,
56
- extraData,
57
56
  isMixMode,
58
57
  options: {
59
58
  isCrossAccount: resourceAppId !== deployOptions.targetMpAppId,
59
+ mpAppId: deployOptions.mpAppId || '',
60
60
  resourceAppId,
61
61
  },
62
62
  buildTypeList,
@@ -86,11 +86,11 @@ async function buildWedaApp({ cals, subAppCalsList = [], dependencies = [], appK
86
86
  // 模板需要占位保证 mp 文件夹存在
87
87
  fs_extra_1.default.removeSync(path_1.default.resolve(outDir, 'miniprogram_npm'));
88
88
  }
89
- cb === null || cb === void 0 ? void 0 : cb(null, {
89
+ await (cb === null || cb === void 0 ? void 0 : cb(null, {
90
90
  ...result,
91
91
  outDir,
92
92
  timeElapsed: Date.now() - startTime,
93
- });
93
+ }));
94
94
  return outDir;
95
95
  }
96
96
  else {
@@ -109,10 +109,10 @@ async function buildWedaApp({ cals, subAppCalsList = [], dependencies = [], appK
109
109
  ignoreInstall,
110
110
  domain,
111
111
  });
112
- cb === null || cb === void 0 ? void 0 : cb(null, {
112
+ await (cb === null || cb === void 0 ? void 0 : cb(null, {
113
113
  outDir: h5BuildDir,
114
114
  timeElapsed: Date.now() - startTime,
115
- });
115
+ }));
116
116
  return h5BuildDir;
117
117
  }
118
118
  }
@@ -19,11 +19,20 @@ const types_1 = require("../../types");
19
19
  const mp_1 = require("../mp");
20
20
  const common_2 = require("../../utils/common");
21
21
  const config_1 = require("../config");
22
+ const fs_extra_1 = __importDefault(require("fs-extra"));
22
23
  async function buildH5App({ appKey, buildDir, dependencies, i18nConfig, extraData, cals, buildTypeList = [common_1.BuildType.WEB], subAppCalsList, mode, devTool, runtime = types_1.RUNTIME.NONE, deployMode = types_1.DEPLOY_MODE.PREVIEW, ignoreInstall = false, domain = '', }) {
23
- var _a, _b;
24
+ var _a, _b, _c;
24
25
  try {
25
26
  const { materialsDir } = runtime === types_1.RUNTIME.CI ? (0, util_1.getCompileDirs)(appKey) : (0, util_1.getCompileDirs)('app');
26
27
  const h5BuildDir = path_1.default.join(buildDir, 'h5');
28
+ if (buildTypeList.includes(common_1.BuildType.APP) ||
29
+ buildTypeList.includes(common_1.BuildType.XPAGE_PC) ||
30
+ buildTypeList.includes(common_1.BuildType.ADMIN_PORTAL)) {
31
+ if (!cals.extra) {
32
+ cals.extra = {};
33
+ }
34
+ cals.extra.historyType = types_1.HISTORY_TYPE.HASH;
35
+ }
27
36
  const mainAppSerializeData = (0, common_2.processCals2WeappsData)(cals, dependencies);
28
37
  const subAppSerializeDataList = (subAppCalsList === null || subAppCalsList === void 0 ? void 0 : subAppCalsList.map((item) => (0, common_2.processCals2WeappsData)(item, dependencies))) || [];
29
38
  const buildContext = {
@@ -43,7 +52,7 @@ async function buildH5App({ appKey, buildDir, dependencies, i18nConfig, extraDat
43
52
  // 处理应用数据
44
53
  const mainAppData = (0, weapps_core_1.deserialize)(mainAppSerializeData);
45
54
  if (!mainAppData.extra) {
46
- mainAppData.extra = { domain: domain };
55
+ mainAppData.extra = { domain };
47
56
  }
48
57
  if (!((_a = mainAppData.extra) === null || _a === void 0 ? void 0 : _a.domain)) {
49
58
  mainAppData.extra.domain = domain;
@@ -133,6 +142,10 @@ async function buildH5App({ appKey, buildDir, dependencies, i18nConfig, extraDat
133
142
  }
134
143
  });
135
144
  });
145
+ // 普通 web 模式,且非hash模式,根据页面生成多份入口
146
+ if (!((_c = cals.extra) === null || _c === void 0 ? void 0 : _c.historyType) || cals.extra.historyType === types_1.HISTORY_TYPE.BROWSER) {
147
+ await Promise.all((cals.items || []).map((page) => fs_extra_1.default.copy(path_1.default.resolve(h5BuildDir, webpack_2.OUTPUT_DIR, 'index.html'), path_1.default.resolve(h5BuildDir, webpack_2.OUTPUT_DIR, page.id, 'index.html'))));
148
+ }
136
149
  return h5BuildDir;
137
150
  }
138
151
  catch (e) {
@@ -2,7 +2,7 @@ import { IMaterialItem, IWeAppData, IPlugin } from '@cloudbase/lowcode-generator
2
2
  import { IBuildContext } from './BuildContext';
3
3
  import { DEPLOY_MODE } from '../../types';
4
4
  import { BuildType, IAppUsedComp, IUsedComps } from '../types/common';
5
- export declare function generateWxMp({ weapps, projDir, appId, domain, materials, plugins, isProduction, deployMode, extraData, isMixMode, options, buildTypeList, isBrowserMpBuilder, }: {
5
+ export declare function generateWxMp({ weapps, projDir, appId, domain, materials, plugins, isProduction, deployMode, isMixMode, options, buildTypeList, isBrowserMpBuilder, }: {
6
6
  weapps: IWeAppData[];
7
7
  projDir: string;
8
8
  appId: string;
@@ -11,9 +11,9 @@ export declare function generateWxMp({ weapps, projDir, appId, domain, materials
11
11
  plugins: IPlugin[];
12
12
  isProduction: boolean;
13
13
  deployMode: DEPLOY_MODE;
14
- extraData: any;
15
14
  isMixMode: boolean;
16
15
  options: {
16
+ mpAppId: string;
17
17
  resourceAppId?: string;
18
18
  isCrossAccount: boolean;
19
19
  };
@@ -54,7 +54,7 @@ const cals_1 = require("@cloudbase/cals");
54
54
  const templateDir = `${config_1.appTemplateDir}/mp/`;
55
55
  const em = chalk_1.default.blue.bold;
56
56
  const error = chalk_1.default.redBright;
57
- async function generateWxMp({ weapps, projDir, appId, domain, materials, plugins, isProduction, deployMode, extraData, isMixMode, options, buildTypeList, isBrowserMpBuilder = false, }) {
57
+ async function generateWxMp({ weapps, projDir, appId, domain, materials, plugins, isProduction, deployMode, isMixMode, options, buildTypeList, isBrowserMpBuilder = false, }) {
58
58
  var _a;
59
59
  const operationLabel = em('Wexin MiniProgram Generated');
60
60
  console.time(operationLabel);
@@ -72,7 +72,6 @@ async function generateWxMp({ weapps, projDir, appId, domain, materials, plugins
72
72
  domain,
73
73
  isBrowserMpBuilder,
74
74
  };
75
- const yyptConfig = await (0, util_3.getYyptConfigInfo)(extraData);
76
75
  const { allAppUsedComps } = handleUsedComponents({
77
76
  buildContext,
78
77
  weapps,
@@ -82,7 +81,7 @@ async function generateWxMp({ weapps, projDir, appId, domain, materials, plugins
82
81
  // 安装依赖库,生成 materials 目录
83
82
  await (0, materials_1.installMaterials)(projDir, allAppUsedComps, weapps, buildContext);
84
83
  const wxmlDataPrefix = (0, mp_1.getWxmlDataPrefix)(!isProduction);
85
- const { projConfig, appConfig, pageConfigs } = (0, mp_config_1.generateMpConfig)(weapps, buildContext);
84
+ const { projConfig, appConfig, pageConfigs } = (0, mp_config_1.generateMpConfig)(weapps, buildContext, { mpAppId: options.mpAppId });
86
85
  // #1 generate project files
87
86
  if (!mainAppData.mpPkgUrl) {
88
87
  const projectFileData = {
@@ -135,7 +134,8 @@ async function generateWxMp({ weapps, projDir, appId, domain, materials, plugins
135
134
  };
136
135
  }
137
136
  if (mainAppData.mpPkgUrl) {
138
- // 合并 project 和 app json
137
+ // 合并 project 和 app json,复写 appId
138
+ projectConfigJson.appId = projConfig.appId;
139
139
  if (!projectConfigJson.setting) {
140
140
  projectConfigJson.setting = {};
141
141
  }
@@ -315,7 +315,7 @@ async function generatePkg(weapp, appRoot, ctx, pageConfigs) {
315
315
  pageUUID: rootPath ? `${rootPath}/${page.id}` : page.id,
316
316
  pageName: page.id,
317
317
  pageSource: page.data.src || '',
318
- eventHanlders: (0, util_2.createEventHanlders)(page.componentInstances, 'this', ctx),
318
+ eventHanlders: (0, util_2.createEventHanlders)(page.componentInstances, 'this', ctx, page),
319
319
  dataBinds: (0, util_2.createDataBinds)(page.componentInstances, ctx),
320
320
  pageAttributes: {
321
321
  ...(((_a = page.data) === null || _a === void 0 ? void 0 : _a.appShareMessage) ? { appShareMessage: page.data.appShareMessage.value } : {}),
@@ -553,3 +553,18 @@ function cleanMaterils(materialsDir, usedComps) {
553
553
  });
554
554
  }
555
555
  }
556
+ function postprocessDeployExtraJson(projectPath, deployOptions) {
557
+ let { targetMpAppId, mpAppId } = deployOptions;
558
+ if (targetMpAppId !== mpAppId) {
559
+ let projectJson = fs.readJsonSync(path_1.default.resolve(projectPath, 'project.config.json'));
560
+ const miniprogramRoot = (projectJson === null || projectJson === void 0 ? void 0 : projectJson.miniprogramRoot) || './';
561
+ const extPaht = path_1.default.resolve(projectPath, miniprogramRoot, 'ext.json');
562
+ const extJson = {
563
+ ...(fs.existsSync(extPaht) ? fs.readJsonSync(extPaht) : {}),
564
+ extEnable: true,
565
+ extAppid: targetMpAppId,
566
+ directCommit: true,
567
+ };
568
+ fs.writeFileSync(extPaht, JSON.stringify(extJson, null, 2));
569
+ }
570
+ }
@@ -6,7 +6,9 @@ import { IBuildContext } from './BuildContext';
6
6
  * @param kboneConfig https://wechat-miniprogram.github.io/kbone/docs/config/
7
7
  * @param appConfigs app config from prop edit panel
8
8
  */
9
- export declare function generateMpConfig(weapps: IWeAppData[], ctx: IBuildContext): {
9
+ export declare function generateMpConfig(weapps: IWeAppData[], ctx: IBuildContext, options: {
10
+ mpAppId?: string;
11
+ }): {
10
12
  appConfig: any;
11
13
  projConfig: any;
12
14
  pageConfigs: {}[];
@@ -40,7 +40,7 @@ const chalk_1 = __importDefault(require("chalk"));
40
40
  * @param kboneConfig https://wechat-miniprogram.github.io/kbone/docs/config/
41
41
  * @param appConfigs app config from prop edit panel
42
42
  */
43
- function generateMpConfig(weapps, ctx) {
43
+ function generateMpConfig(weapps, ctx, options) {
44
44
  var _a;
45
45
  const appConfig = {
46
46
  useExtendedLib: { weui: true },
@@ -116,6 +116,9 @@ function generateMpConfig(weapps, ctx) {
116
116
  });
117
117
  }
118
118
  });
119
+ if (options.mpAppId) {
120
+ projConfig.appId = options.mpAppId;
121
+ }
119
122
  // merge(pageConfigs, extractAllPagesConfig())
120
123
  return { appConfig, projConfig, pageConfigs };
121
124
  }
@@ -1,4 +1,4 @@
1
- import { IDynamicValue, IWeAppComponentInstance, ICompositedComponent } from '@cloudbase/lowcode-generator/lib/weapps-core';
1
+ import { IDynamicValue, IWeAppComponentInstance, ICompositedComponent, IWeAppPage } from '@cloudbase/lowcode-generator/lib/weapps-core';
2
2
  import { IBuildContext } from './BuildContext';
3
3
  export declare function extractWidgetProps(props: Required<IWeAppComponentInstance>['xProps'], compInfo: ICompositedComponent): any;
4
4
  export declare function generatedDynamicData(data: {
@@ -7,13 +7,12 @@ export declare function generatedDynamicData(data: {
7
7
  staticProps: {};
8
8
  boundProps: {};
9
9
  };
10
- export declare function generateDataBind(bind: IDynamicValue): string;
11
10
  export declare function createWidgetProps(widgets: {
12
11
  [key: string]: IWeAppComponentInstance;
13
12
  }, ctx: IBuildContext): {};
14
13
  export declare function createEventHanlders(widgets: {
15
14
  [key: string]: IWeAppComponentInstance;
16
- }, componentApi: string, ctx: IBuildContext): {};
15
+ }, componentApi: string, ctx: IBuildContext, page?: IWeAppPage): {};
17
16
  export declare function createDataBinds(widgets: {
18
17
  [key: string]: IWeAppComponentInstance;
19
18
  }, ctx: IBuildContext): {};
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createDataBinds = exports.createEventHanlders = exports.createWidgetProps = exports.generateDataBind = exports.generatedDynamicData = exports.extractWidgetProps = void 0;
3
+ exports.createDataBinds = exports.createEventHanlders = exports.createWidgetProps = exports.generatedDynamicData = exports.extractWidgetProps = void 0;
4
4
  const weapps_core_1 = require("@cloudbase/lowcode-generator/lib/weapps-core");
5
+ const lowcode_generator_1 = require("@cloudbase/lowcode-generator");
5
6
  const weapp_1 = require("@cloudbase/lowcode-generator/lib/generator/util/weapp");
6
7
  const wxml_1 = require("./wxml");
7
8
  const mp_1 = require("@cloudbase/lowcode-generator/lib/generator/config/mp");
@@ -47,20 +48,27 @@ function generatedDynamicData(data, compInfo) {
47
48
  }
48
49
  }
49
50
  else {
50
- boundProps[key] = generateDataBind(data[key]);
51
+ setDataBind(boundProps, key, data[key]);
51
52
  }
52
53
  }
53
54
  return { staticProps, boundProps };
54
55
  }
55
56
  exports.generatedDynamicData = generatedDynamicData;
56
57
  // For JS
57
- function generateDataBind(bind) {
58
+ function generateDataBindMeta(bind) {
58
59
  let expr = '';
60
+ let imports = 'const $for = forItems;'; // 基础 alias
59
61
  const { type, value } = bind;
60
62
  if (type === weapps_core_1.PropBindType.forItem) {
61
- expr = `forItems.${value}`;
63
+ expr = `$for.${value}`;
62
64
  }
63
65
  else if (type === weapps_core_1.PropBindType.expression) {
66
+ try {
67
+ imports += (0, lowcode_generator_1.generateExpressionAlias)(value);
68
+ }
69
+ catch (e) {
70
+ console.error('parse expression error', value, e);
71
+ }
64
72
  expr = value;
65
73
  }
66
74
  else if (type === weapps_core_1.PropBindType.prop) {
@@ -98,9 +106,8 @@ function generateDataBind(bind) {
98
106
  }
99
107
  }
100
108
  }
101
- return expr;
109
+ return { imports, expression: expr };
102
110
  }
103
- exports.generateDataBind = generateDataBind;
104
111
  function createWidgetProps(widgets, ctx) {
105
112
  const widgetProps = {};
106
113
  (0, weapp_1.walkThroughWidgets)(widgets, (id, widget, parentId) => {
@@ -130,8 +137,9 @@ function createWidgetProps(widgets, ctx) {
130
137
  return widgetProps;
131
138
  }
132
139
  exports.createWidgetProps = createWidgetProps;
133
- function createEventHanlders(widgets, componentApi, ctx) {
134
- const eventHanlders = {};
140
+ function createEventHanlders(widgets, componentApi, ctx, page) {
141
+ let eventHandlers = {};
142
+ const { listeners: pageListeners = [], id: pageId = '' } = page || {};
135
143
  (0, weapp_1.walkThroughWidgets)(widgets, (id, widget, parentId) => {
136
144
  var _a, _b, _c;
137
145
  const { xComponent } = widget;
@@ -168,39 +176,11 @@ function createEventHanlders(widgets, componentApi, ctx) {
168
176
  });
169
177
  });
170
178
  }
171
- listeners.forEach((l) => {
172
- var _a, _b, _c;
173
- const handlerName = (0, wxml_1.getMpEventHanlderName)(id, l.trigger, l);
174
- eventHanlders[handlerName] = eventHanlders[handlerName] || [];
175
- const params = generatedDynamicData(l.data);
176
- let handler = l.handler ? l.handler.name : l.jsCode;
177
- switch (l.type) {
178
- case weapps_core_1.ActionType.Platform: {
179
- handler = `function({data}){ return app.${(_a = l.handler) === null || _a === void 0 ? void 0 : _a.name}(data)}`;
180
- break;
181
- }
182
- case weapps_core_1.ActionType.DataSource: {
183
- handler = `function({data}){ return app.cloud.callDataSource(data)}`;
184
- break;
185
- }
186
- case weapps_core_1.ActionType.PropEvent: {
187
- handler = `function({event, data = {}}){ return ${componentApi}.props.events.${(_b = l.handler) === null || _b === void 0 ? void 0 : _b.name}({...event.detail, ...data}) }`;
188
- break;
189
- }
190
- }
191
- eventHanlders[handlerName].push({
192
- key: l.key || '',
193
- handler: handler,
194
- handlerModule: (_c = l.handler) === null || _c === void 0 ? void 0 : _c.moduleName,
195
- data: params.staticProps,
196
- boundData: params.boundProps,
197
- type: l.type,
198
- });
199
- });
179
+ eventHandlers = Object.assign(eventHandlers, getListenersHandlers(listeners, id, componentApi));
200
180
  // 如果是数据容器,则生成一个onDataChange事件处理
201
181
  if ((_c = compProto === null || compProto === void 0 ? void 0 : compProto.compConfig) === null || _c === void 0 ? void 0 : _c.isDataContainer) {
202
182
  const customName = (0, wxml_1.getMpEventHanlderName)(id, 'onDataChange', {});
203
- eventHanlders[customName] = [
183
+ eventHandlers[customName] = [
204
184
  {
205
185
  key: '',
206
186
  handler: `({event})=>{
@@ -213,9 +193,52 @@ function createEventHanlders(widgets, componentApi, ctx) {
213
193
  ];
214
194
  }
215
195
  });
216
- return eventHanlders;
196
+ // 增加页面事件节点 handlers
197
+ eventHandlers = Object.assign(eventHandlers, getListenersHandlers(pageListeners, pageId, componentApi));
198
+ return eventHandlers;
217
199
  }
218
200
  exports.createEventHanlders = createEventHanlders;
201
+ /**
202
+ * 根据 listeners 创建 handlers
203
+ * @param listeners {IEventListener[]}
204
+ * @param id {string}
205
+ * @param componentApi {string}
206
+ */
207
+ function getListenersHandlers(listeners, id, componentApi) {
208
+ if (!id)
209
+ return {};
210
+ const eventHandlers = {};
211
+ listeners.forEach((l) => {
212
+ var _a, _b, _c;
213
+ const handlerName = (0, wxml_1.getMpEventHanlderName)(id, l.trigger, l);
214
+ eventHandlers[handlerName] = eventHandlers[handlerName] || [];
215
+ const params = generatedDynamicData(l.data);
216
+ let handler = l.handler ? l.handler.name : l.jsCode;
217
+ switch (l.type) {
218
+ case weapps_core_1.ActionType.Platform: {
219
+ handler = `function({data}){ return app.${(_a = l.handler) === null || _a === void 0 ? void 0 : _a.name}(data)}`;
220
+ break;
221
+ }
222
+ case weapps_core_1.ActionType.DataSource: {
223
+ handler = `function({data}){ return app.cloud.callDataSource(data)}`;
224
+ break;
225
+ }
226
+ case weapps_core_1.ActionType.PropEvent: {
227
+ handler = `function({event, data = {}}){ return ${componentApi}.props.events.${(_b = l.handler) === null || _b === void 0 ? void 0 : _b.name}({...event.detail, ...data}) }`;
228
+ break;
229
+ }
230
+ }
231
+ eventHandlers[handlerName].push({
232
+ key: l.key || '',
233
+ handler: handler,
234
+ handlerModule: (_c = l.handler) === null || _c === void 0 ? void 0 : _c.moduleName,
235
+ data: params.staticProps,
236
+ boundData: params.boundProps,
237
+ type: l.type,
238
+ });
239
+ });
240
+ return eventHandlers;
241
+ }
219
242
  function createDataBinds(widgets, ctx) {
220
243
  const dataBinds = {};
221
244
  (0, weapp_1.walkThroughWidgets)(widgets, (id, widget, parentId) => {
@@ -255,10 +278,10 @@ function createDataBinds(widgets, ctx) {
255
278
  }
256
279
  exports.createDataBinds = createDataBinds;
257
280
  function setDataBind(target, prop, val) {
258
- if (val && val.type && val.type !== 'static') {
259
- const jsExpr = generateDataBind(val);
260
- if (jsExpr) {
261
- target[prop] = jsExpr;
281
+ if ((val === null || val === void 0 ? void 0 : val.type) && val.type !== 'static') {
282
+ const meta = generateDataBindMeta(val);
283
+ if (meta.expression) {
284
+ target[prop] = meta;
262
285
  }
263
286
  // Do not generate propBind since it's bound directly in wxml except for _waFor
264
287
  // const propsKeepPropBindInJs = ['_waFor', '_waIf']
@@ -2,6 +2,7 @@ import { IMaterialItem, IWebRuntimeAppData } from '@cloudbase/lowcode-generator/
2
2
  import { BuildType, WebpackModeType } from '../types/common';
3
3
  import { RUNTIME } from '../../types';
4
4
  export declare const PERSISTENT_DEPENDIENCES_MAP: {};
5
+ export declare const OUTPUT_DIR = "preview";
5
6
  export interface IMpConfig {
6
7
  origin: string;
7
8
  entry: string;
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.downloadAssets = exports.generateWebpackWebDevServerFile = exports.getMaterialNodeModulesPathList = exports.installDependencies = exports.downloadDependencies = exports.downloadAndInstallDependencies = exports.getAllPageMpEntryPath = exports.getWebpackMpBuildParams = exports.getWebpackWebBuildParams = exports.getMpAllRouterConfig = exports.getPageName = exports.getHomePageInstance = exports.getMainAppDataByList = exports.generateMpJsonConfigFile = exports.generateKboneAppConfig = exports.generateKbonePageConfig = exports.downloadAndWriteTabBarIcon = exports.generateKboneTabBarConfig = exports.generateAppConfig = exports.generateWebpackWebBuildParamsFile = exports.fixAppJson = exports.PERSISTENT_DEPENDIENCES_MAP = void 0;
6
+ exports.downloadAssets = exports.generateWebpackWebDevServerFile = exports.getMaterialNodeModulesPathList = exports.installDependencies = exports.downloadDependencies = exports.downloadAndInstallDependencies = exports.getAllPageMpEntryPath = exports.getWebpackMpBuildParams = exports.getWebpackWebBuildParams = exports.getMpAllRouterConfig = exports.getPageName = exports.getHomePageInstance = exports.getMainAppDataByList = exports.generateMpJsonConfigFile = exports.generateKboneAppConfig = exports.generateKbonePageConfig = exports.downloadAndWriteTabBarIcon = exports.generateKboneTabBarConfig = exports.generateAppConfig = exports.generateWebpackWebBuildParamsFile = exports.fixAppJson = exports.OUTPUT_DIR = exports.PERSISTENT_DEPENDIENCES_MAP = void 0;
7
7
  const path_1 = __importDefault(require("path"));
8
8
  const fs_extra_1 = __importDefault(require("fs-extra"));
9
9
  const lodash_1 = require("lodash");
@@ -18,6 +18,7 @@ const common_2 = require("../util/common");
18
18
  const types_1 = require("../../types");
19
19
  const generateFiles_1 = require("../util/generateFiles");
20
20
  exports.PERSISTENT_DEPENDIENCES_MAP = {};
21
+ exports.OUTPUT_DIR = 'preview';
21
22
  async function fixAppJson(appBuildDir) {
22
23
  const appJsonPath = path_1.default.resolve(appBuildDir, 'dist/mp/app.json');
23
24
  if (!fs_extra_1.default.existsSync(appJsonPath)) {
@@ -273,7 +274,7 @@ function getWebpackWebBuildParams(appId, appBuildDir, publicPath = '/', mode = c
273
274
  watch: false,
274
275
  entry: path_1.default.resolve(appBuildDir, 'src/index.jsx'),
275
276
  output: {
276
- path: path_1.default.resolve(appBuildDir, './preview'),
277
+ path: path_1.default.resolve(appBuildDir, exports.OUTPUT_DIR),
277
278
  filename: '[name].[contenthash].bundle.js',
278
279
  chunkFilename: '[name].[contenthash].chunk.js',
279
280
  publicPath: buildTypeList.includes(common_1.BuildType.APP) || buildTypeList.includes(common_1.BuildType.ADMIN_PORTAL) ? '' : publicPath,
@@ -294,8 +295,6 @@ function getWebpackWebBuildParams(appId, appBuildDir, publicPath = '/', mode = c
294
295
  resolveModules: [path_1.default.resolve(appBuildDir), 'node_modules'],
295
296
  definePlugin: {
296
297
  'process.env.buildType': `"${buildTypeList[0]}"`,
297
- 'process.env.isApp': buildTypeList.includes(common_1.BuildType.APP),
298
- 'process.env.isAdminPortal': (0, common_1.buildAsAdminPortalByBuildType)(buildTypeList),
299
298
  ...extraDefine,
300
299
  },
301
300
  devtool: ['app-nvzcvt10', 'app-msa2ihs9'].includes(appId)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudbase/lowcode-builder",
3
- "version": "1.0.38",
3
+ "version": "1.0.40-alpha.0",
4
4
  "description": "云开发 Tencent CloudBase Framework Low Code Plugin,将低码配置生成完整项目并一键部署云开发资源。",
5
5
  "author": "yhsunshining@gmail.com",
6
6
  "homepage": "https://github.com/TencentCloudBase/cloudbase-framework#readme",
@@ -39,7 +39,7 @@
39
39
  },
40
40
  "dependencies": {
41
41
  "@cloudbase/cals": "^0.4.9",
42
- "@cloudbase/lowcode-generator": "^1.0.17",
42
+ "@cloudbase/lowcode-generator": "^1.0.18",
43
43
  "axios": "^0.21.0",
44
44
  "browserfs": "^1.4.3",
45
45
  "browserify-zlib": "^0.2.0",
@@ -461,7 +461,7 @@
461
461
  ></script>
462
462
  <script
463
463
  crossorigin
464
- src="https://qbase.cdn-go.cn/lcap/lcap-resource-cdngo/-/0.1.4/_files/static/weda-render/main.8a81937eced4c70f449b.bundle.js"
464
+ src="https://qbase.cdn-go.cn/lcap/lcap-resource-cdngo/-/0.1.4/_files/static/weda-render/main.f25263146cb3af601abf.bundle.js"
465
465
  ></script>
466
466
  </body>
467
467
  </html>
@@ -28,53 +28,58 @@ export function createComputed(funcs, bindContext = null) {
28
28
  return computed
29
29
  }
30
30
 
31
+ /**
32
+ *
33
+ * @param evtListeners
34
+ * @param context
35
+ */
31
36
  export function createEventHandlers(evtListeners, context) {
32
- const evtHandlers = {}
37
+ const evtHandlers = {};
33
38
  for (const name in evtListeners) {
34
- const listeners = evtListeners[name]
35
- evtHandlers[name] = function (event) {
36
- const self = this
37
- const owner = this.getWeAppInst()
38
- const target = getWidget(owner.widgets, event.target.id)
39
- const currentTarget = getWidget(owner.widgets, event.currentTarget.id)
40
- event.target = target
41
- event.currentTarget = currentTarget
42
- const [prefix = ''] = name.split('$')
39
+ const listeners = evtListeners[name];
40
+ evtHandlers[name] = function (event = {}) {
41
+ const self = this;
42
+ const owner = this.getWeAppInst();
43
+ const target = !!event?.target?.id ? getWidget(owner.widgets, event.target.id) : undefined;
44
+ const currentTarget = !!event?.currentTarget?.id ? getWidget(owner.widgets, event.currentTarget.id) : undefined;
45
+ event.target = target;
46
+ event.currentTarget = currentTarget;
47
+ const [prefix = ''] = name.split('$');
43
48
  // The page event handler
44
- const { lists = [], itemsById = {} } = findForItemsOfWidget(currentTarget) || {}
49
+ const { lists = [], itemsById = {} } = !!currentTarget && findForItemsOfWidget(currentTarget) || {};
45
50
  listeners.forEach(async l => {
46
- let { data = {}, boundData = {} } = l
47
- data = { ...data }
51
+ let { data = {}, boundData = {} } = l;
52
+ data = { ...data };
48
53
  try {
49
54
  for (const k in boundData) {
50
- set(data, k, boundData[k].call(owner, owner, lists, itemsById, event, context))
55
+ set(data, k, boundData[k].call(owner, owner, lists, itemsById, event, context));
51
56
  }
52
- let res = await l.handler.call(owner, { event, lists, forItems: itemsById, data })
53
- let eventName = prefix && l.key ? `${prefix}$${l.key}_success` : ''
57
+ let res = await l.handler.call(owner, { event, lists, forItems: itemsById, data });
58
+ let eventName = prefix && l.key ? `${prefix}$${l.key}_success` : '';
54
59
  self[eventName] && self[eventName]({
55
60
  ...event,
56
61
  detail: res
57
- })
62
+ });
58
63
  } catch (e) {
59
- let eventName = l.key ? `${prefix}$${l.key}_fail` : ''
64
+ let eventName = l.key ? `${prefix}$${l.key}_fail` : '';
60
65
  if (self[eventName]) {
61
- console.error(`事件响应失败`, e)
66
+ console.error(`事件响应失败`, e);
62
67
  await self[eventName]({
63
68
  ...event,
64
69
  detail: e
65
- })
70
+ });
66
71
  } else {
67
72
  app.showToast({
68
73
  icon: 'error',
69
74
  title: `事件响应失败`
70
- })
71
- throw e
75
+ });
76
+ throw e;
72
77
  }
73
-
74
78
  }
75
79
  })
76
80
  }
77
81
  }
82
+
78
83
  return evtHandlers
79
84
  }
80
85
 
@@ -232,6 +237,7 @@ export function findLoginPage() {
232
237
  }
233
238
 
234
239
  let _AUTH_CONFIG_CACHE = null;
240
+
235
241
  export async function getAuthConfig() {
236
242
  const { app } = getApp();
237
243
  if (_AUTH_CONFIG_CACHE) {
@@ -261,6 +267,7 @@ export async function getAuthConfig() {
261
267
  }
262
268
 
263
269
  let _AUTH_CACHE_MAP = {}
270
+
264
271
  async function getAccessPermission(app, appId, pageId) {
265
272
  const cacheKey = `${appId}-${pageId}`
266
273
  if (_AUTH_CACHE_MAP[cacheKey] !== undefined) {
@@ -361,6 +368,7 @@ export function redirectToLogin(currentPage) {
361
368
 
362
369
  let loading = {};
363
370
  export let enumOptions = observable({});
371
+
364
372
  export function formatEnum(path, optionname) {
365
373
  // 判断是单选还是多选
366
374
  let isSingle = Array.isArray(path);
@@ -378,6 +386,7 @@ export function formatEnum(path, optionname) {
378
386
  // 对多选或者单选有不同处理
379
387
  return !isSingle ? value : multiTmp?.join(',');
380
388
  }
389
+
381
390
  function getEnumOptions(optionName) {
382
391
  if (enumOptions[optionName]) {
383
392
  return enumOptions[optionName];
@@ -390,6 +399,7 @@ function getEnumOptions(optionName) {
390
399
  }
391
400
  return '';
392
401
  }
402
+
393
403
  async function getGeneralOptions(optionName) {
394
404
  const { app } = getApp();
395
405
  return app.cloud.callWedaApi({
@@ -401,3 +411,10 @@ async function getGeneralOptions(optionName) {
401
411
  },
402
412
  });
403
413
  }
414
+
415
+ export function getMpEventHandlerName(widgetId, evtName, modifier = {}) {
416
+ // Only builtin events have will bubble
417
+ return `on${widgetId}$${evtName.replace(/\./g, '_')}${modifier.isCapturePhase ? '$cap' : ''}${
418
+ modifier.noPropagation ? '$cat' : ''
419
+ }`;
420
+ }
@@ -5,6 +5,7 @@ import mergeRenderer from './merge-renderer';
5
5
  import { createDataset, EXTRA_API, createStateDataSourceVar, generateParamsParser, setConfig } from '../datasources/index';
6
6
  import { runWatchers } from './watch'
7
7
  import lodashGet from 'lodash.get';
8
+ import { getMpEventHandlerName } from "./util";
8
9
 
9
10
  export function createPage(
10
11
  id,
@@ -20,26 +21,18 @@ export function createPage(
20
21
  handler,
21
22
  pageContext = {},
22
23
  context,
23
- pageAttributes
24
+ pageAttributes,
24
25
  ) {
25
26
  const evtHandlers = createEventHandlers(evtListeners, context);
26
27
 
27
- function extractLifecyles() {
28
+ function extractLifecycles() {
28
29
  const result = {};
29
30
  Object.keys(lifecycle).map(name => {
30
31
  result[name] = function () {
31
32
  return lifecycle[name].apply(this.getWeAppInst(), arguments)
32
33
  }
33
34
  })
34
- // const nameMaps = [
35
- // ['onReady', 'onPageReady'],
36
- // ];
37
- // nameMaps.forEach(e => {
38
- // if (!result[e[0]] && result[e[1]]) {
39
- // result[e[0]] = result[e[1]];
40
- // delete result[e[1]];
41
- // }
42
- // });
35
+
43
36
  result['onShareAppMessage'] = (res) => {
44
37
  if (res?.from === 'button' && res?.target?.dataset?.weda_share_info) {
45
38
  return res?.target?.dataset?.weda_share_info;
@@ -114,7 +107,7 @@ export function createPage(
114
107
  methods: {
115
108
  _pageActive: true,
116
109
  /** page lifecycles **/
117
- ...extractLifecyles(),
110
+ ...extractLifecycles(),
118
111
  ...evtHandlers,
119
112
  ...mergeRenderer,
120
113
  onLoad(options) {
@@ -129,20 +122,26 @@ export function createPage(
129
122
 
130
123
  const hook = lifecycle.onLoad || lifecycle.onPageLoad;
131
124
  hook && hook.call($page, query);
125
+
126
+ this.invokeEventHandler(id, 'load', {detail: {query}});
132
127
  },
133
128
  onReady() {
134
- const $page = this.getWeAppInst()
129
+ const $page = this.getWeAppInst();
135
130
 
136
- this._disposers.push(...runWatchers(index, this))
131
+ this._disposers.push(...runWatchers(index, this));
132
+
133
+ const hook = lifecycle.onReady || lifecycle.onPageReady;
134
+ hook && hook.call($page);
137
135
 
138
- const hook = lifecycle.onReady || lifecycle.onPageReady
139
- hook && hook.call($page)
136
+ this.invokeEventHandler(id, 'ready');
140
137
  },
141
138
  onUnload() {
142
139
  const $page = this.getWeAppInst()
143
140
 
144
141
  const hook = lifecycle.onUnload || lifecycle.onPageUnload;
145
142
  hook && hook.call($page);
143
+
144
+ this.invokeEventHandler(id, 'unload');
146
145
  },
147
146
  async onShow() {
148
147
  const $page = this.getWeAppInst()
@@ -159,14 +158,22 @@ export function createPage(
159
158
  weDaHasLogin: true,
160
159
  });
161
160
  }
161
+
162
+ this.invokeEventHandler(id, 'show');
162
163
  },
163
164
  onHide() {
164
165
  const $page = this.getWeAppInst()
165
166
  const hook = lifecycle.onHide || lifecycle.onPageHide;
166
167
  hook && hook.call($page);
167
168
  this._pageActive = false;
168
- },
169
169
 
170
+ // 触发页面节点事件
171
+ this.invokeEventHandler(id, 'hide');
172
+ },
173
+ invokeEventHandler(id, triggerName, params = {}) {
174
+ const keyName = getMpEventHandlerName(id, triggerName);
175
+ typeof evtHandlers?.[keyName] === 'function' && evtHandlers[keyName].call(this, params);
176
+ },
170
177
  getWeAppInst() {
171
178
  let $page = this.$WEAPPS_PAGE
172
179
  if ($page) { return $page }
@@ -11,6 +11,7 @@ import * as constObj from '../libCommonRes/const'
11
11
  import * as toolsObj from '../libCommonRes/tools'
12
12
 
13
13
  const libCode = '<%= materialName %>'
14
+ const $app = new Proxy({}, { get: function(obj, prop){ return app[prop] }});
14
15
  const context = observable({});
15
16
 
16
17
  const widgetProps = <%= stringifyObj(widgetProps, {depth: null}) %>
@@ -21,8 +22,8 @@ const evtListeners = {<% Object.entries(eventHandlers).map(([handlerName, listen
21
22
  key: '<%= l.key %>',
22
23
  handler: <% if (l.type == 'rematch') {%> _handler<%= l.handler %> <%} else if (l.type === 'inline') {%> function({event, lists, forItems, $context}, $comp){ <%= l.handler %> } <%} else {%> <%= l.handler %> <%} %>,
23
24
  data: <%= stringifyObj(l.data, {depth: null}) %>,
24
- boundData: {<% Object.entries(l.boundData).map(([prop, expr])=>{%>'<%= prop %>':($comp, lists, forItems, event, $context) => {const $for=forItems;return (
25
- <%= expr === '' ? 'undefined': expr %>
25
+ boundData: {<% Object.entries(l.boundData).map(([prop, bindMeta])=>{%>'<%= prop %>':($comp, lists, forItems, event, $context) => {<%= bindMeta.imports %> return (
26
+ <%= bindMeta.expression === '' ? 'undefined': bindMeta.expression %>
26
27
  )},
27
28
  <%}) %>}
28
29
  },<%})%>
@@ -50,9 +51,9 @@ const handler = {<% handlers.forEach(h => {%>
50
51
  }
51
52
 
52
53
  const dataBinds = {<% Object.entries(dataBinds).map(([id, widgetBinds])=>{%>
53
- <%= id %>: { <% Object.entries(widgetBinds).map(([prop, expr]) => { %>
54
- "<%= prop %>": function ($comp, lists, forItems, event, $context) {const $for=forItems; return (
55
- <%= expr === '' ? 'undefined': expr %>
54
+ <%= id %>: { <% Object.entries(widgetBinds).map(([prop, bindMeta]) => { %>
55
+ "<%= prop %>": function ($comp, lists, forItems, event, $context) {<%= bindMeta.imports %> return (
56
+ <%= bindMeta.expression === '' ? 'undefined': bindMeta.expression %>
56
57
  ); },<% }) %>
57
58
  },<%}) %>
58
59
  }
@@ -3,7 +3,7 @@
3
3
  "version": "1.0.8",
4
4
  "scripts": {},
5
5
  "dependencies": {
6
- "@cloudbase/weda-client": "0.2.22",
6
+ "@cloudbase/weda-client": "0.2.22-alpha.2",
7
7
  "@cloudbase/weda-cloud-sdk": "1.0.19",
8
8
  "@cloudbase/oauth": "0.1.1-alpha.5",
9
9
  "mobx": "^5.15.4",
@@ -19,20 +19,20 @@ const evtListeners = {<% Object.entries(eventHanlders).map(([handlerName, listen
19
19
  key: '<%= l.key %>',
20
20
  handler: <% if (l.type === 'rematch') {%> handlers.<%= l.handler %> <%} else if (l.type == 'material') {%> function(...args) { return require('../../materials/<%= l.handlerModule %>/actions/<%= l.handler %>/index').default(...args) } <%} else if (l.type == 'inline') {%> function({event, lists, forItems, $context}, $page){const $for = forItems; return <%= l.handler %> } <%} else {%> <%= l.handler %> <%} %>,
21
21
  data: <%= stringifyObj(l.data, {depth: null}) %>,
22
- boundData: {<% Object.entries(l.boundData).map(([prop, expr])=>{%>'<%= prop %>':($page, lists, forItems, event, $context) => {const $for = forItems; return (
23
- <%= expr === '' ? 'undefined': expr %>
22
+ boundData: {<% Object.entries(l.boundData).map(([prop, bindMeta])=>{%>'<%= prop %>':($page, lists, forItems, event, $context) => {<%= bindMeta.imports %> return (
23
+ <%= bindMeta.expression === '' ? 'undefined': bindMeta.expression %>
24
24
  )},
25
25
  <%}) %>}
26
26
  },<%})%>
27
27
  ],<%})%>
28
28
  }
29
+
29
30
  const dataBinds = {<% Object.entries(dataBinds).map(([id, widgetBinds])=>{%>
30
- <%= id %>: { <% Object.entries(widgetBinds).map(([prop, expr]) => { %>
31
- "<%= prop %>": function ($page, lists, forItems, event, $context) {const $for = forItems; return (
32
- <%= expr === '' ? 'undefined': expr %>
31
+ <%= id %>: { <% Object.entries(widgetBinds).map(([prop, bindMeta]) => { %>
32
+ "<%= prop %>": function ($page, lists, forItems, event, $context) {<%= bindMeta.imports %> return (
33
+ <%= bindMeta.expression === '' ? 'undefined': bindMeta.expression %>
33
34
  ); },<% }) %>
34
35
  },<%}) %>
35
36
  }
36
37
 
37
-
38
- createPage('<%= pageName %>', '<%= pageUUID %>', widgetProps, {}, lifecyle, state, computed, evtListeners, dataBinds, app, handlers, $page, context, <%= pageAttributes?JSON.stringify(pageAttributes):'{}' %>)
38
+ createPage('<%= pageName %>', '<%= pageUUID %>', widgetProps, {}, lifecyle, state, computed, evtListeners, dataBinds, app, handlers, $page, context, <%= pageAttributes?JSON.stringify(pageAttributes):'{}'%>);