@lingxiteam/ebe-utils 0.0.7 → 0.0.9

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/es/index.d.ts CHANGED
@@ -24,10 +24,13 @@ interface CodeServices {
24
24
  findApplication: (params: {
25
25
  appId: string;
26
26
  }) => Promise<any>;
27
- getWaterMarkByAppId: (params: {
27
+ translateToEnglish: (params: {
28
28
  appId: string;
29
+ chinese: string;
30
+ rule: string;
29
31
  }) => Promise<any>;
30
32
  }
33
+ export declare const getSafeTypeName: (name: any) => any;
31
34
  interface CodeOptions {
32
35
  appId: string;
33
36
  baseUrl: string;
@@ -37,10 +40,11 @@ interface CodeOptions {
37
40
  log: string;
38
41
  progress: number;
39
42
  }) => void;
43
+ needTranslatePagePathToEnglish?: boolean;
40
44
  }
41
45
  export declare const setWorkerJsUrl: (url: string) => void;
42
46
  export declare const init: () => Promise<void>;
43
- export declare const fetchData: ({ appId, services, platform, baseUrl, onProgress, }: CodeOptions) => Promise<{
47
+ export declare const fetchData: ({ appId, services, platform, baseUrl, onProgress, needTranslatePagePathToEnglish, }: CodeOptions) => Promise<{
44
48
  options: {
45
49
  platform: string;
46
50
  appId: string;
@@ -55,11 +59,11 @@ export declare const fetchData: ({ appId, services, platform, baseUrl, onProgres
55
59
  themeCss: any;
56
60
  models: Record<string, any>;
57
61
  appInfo: Record<string, any>;
58
- waterMark: any;
62
+ pagePathEnglishMapping: any;
59
63
  };
60
64
  cleanedTree: any;
61
65
  }>;
62
- export declare const codeCreate: ({ appId, services, platform, baseUrl, onProgress, }: CodeOptions) => Promise<{
66
+ export declare const codeCreate: ({ appId, services, platform, baseUrl, onProgress, needTranslatePagePathToEnglish, }: CodeOptions) => Promise<{
63
67
  success: boolean;
64
68
  msg?: undefined;
65
69
  } | {
package/es/index.js CHANGED
@@ -241,6 +241,9 @@ export var clearLXPagesDSL = function clearLXPagesDSL(pages) {
241
241
  return removeObjectByRules(page, lingxiDslRules);
242
242
  });
243
243
  };
244
+ export var getSafeTypeName = function getSafeTypeName(name) {
245
+ return name.replaceAll(' ', '').replaceAll('/', '').replaceAll('-', '').replaceAll('(', '').replaceAll(')', '');
246
+ };
244
247
  var workerJsUrl = '';
245
248
  export var setWorkerJsUrl = function setWorkerJsUrl(url) {
246
249
  workerJsUrl = url;
@@ -265,52 +268,52 @@ export var init = /*#__PURE__*/function () {
265
268
  };
266
269
  }();
267
270
  export var fetchData = /*#__PURE__*/function () {
268
- var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_ref4) {
269
- var appId, services, platform, baseUrl, onProgress, appInfo, attrSpecPage, resultObject, frontendHookList, themeCss, temCompAssetList, compAssetList, globalDataInfo, dataSourceList, globalDataMap, pageIdMapping, appPageList, lastPageId, data, pages, itemHash, itemLists, busiData, busiCompMapping, busiPages, pageDSLS, waterMark, options, cleanedTree;
270
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
271
- while (1) switch (_context2.prev = _context2.next) {
271
+ var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref4) {
272
+ var appId, services, platform, baseUrl, onProgress, needTranslatePagePathToEnglish, appInfo, attrSpecPage, resultObject, frontendHookList, themeCss, temCompAssetList, compAssetList, globalDataInfo, dataSourceList, globalDataMap, pageIdMapping, appPageList, lastPageId, data, pages, itemHash, itemLists, busiData, busiCompMapping, busiPages, getTranslateName, key, translateName, pagePathEnglishMapping, pagePathEnglishSet, getName, _key, _translateName, _pages$_key$pageConta, _pagePathEnglishMappi, safeTranslateName, pageDSLS, options, cleanedTree;
273
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
274
+ while (1) switch (_context3.prev = _context3.next) {
272
275
  case 0:
273
- appId = _ref4.appId, services = _ref4.services, platform = _ref4.platform, baseUrl = _ref4.baseUrl, onProgress = _ref4.onProgress;
274
- _context2.next = 3;
276
+ appId = _ref4.appId, services = _ref4.services, platform = _ref4.platform, baseUrl = _ref4.baseUrl, onProgress = _ref4.onProgress, needTranslatePagePathToEnglish = _ref4.needTranslatePagePathToEnglish;
277
+ _context3.next = 3;
275
278
  return services.findApplication({
276
279
  appId: appId
277
280
  });
278
281
  case 3:
279
- appInfo = _context2.sent;
282
+ appInfo = _context3.sent;
280
283
  onProgress({
281
284
  log: '获取应用信息',
282
285
  progress: 1
283
286
  });
284
287
  // 根据 appId 获取当前应用的全部页面
285
- _context2.next = 7;
288
+ _context3.next = 7;
286
289
  return services.qryAttrSpecPage({
287
290
  appId: appId,
288
291
  pageNum: 1,
289
292
  pageSize: 999999
290
293
  });
291
294
  case 7:
292
- attrSpecPage = _context2.sent;
295
+ attrSpecPage = _context3.sent;
293
296
  onProgress({
294
297
  log: '获取当前应用的全部页面',
295
298
  progress: 2
296
299
  });
297
300
  // 根据 appId 获取当前应用的全部页面
298
- _context2.next = 11;
301
+ _context3.next = 11;
299
302
  return services.qryPageInstListByAppId({
300
303
  appId: appId,
301
304
  terminalType: platform
302
305
  });
303
306
  case 11:
304
- resultObject = _context2.sent;
305
- _context2.next = 14;
307
+ resultObject = _context3.sent;
308
+ _context3.next = 14;
306
309
  return services.queryFrontendHookList({
307
310
  appId: appId
308
311
  });
309
312
  case 14:
310
- frontendHookList = _context2.sent;
313
+ frontendHookList = _context3.sent;
311
314
  themeCss = '';
312
- _context2.prev = 16;
313
- _context2.next = 19;
315
+ _context3.prev = 16;
316
+ _context3.next = 19;
314
317
  return Promise.race([new Promise(function (resolve, reject) {
315
318
  services.getThemeCss({
316
319
  appId: appId,
@@ -324,26 +327,26 @@ export var fetchData = /*#__PURE__*/function () {
324
327
  }, 5000);
325
328
  })]);
326
329
  case 19:
327
- themeCss = _context2.sent;
330
+ themeCss = _context3.sent;
328
331
  console.log('====获取主题成功', themeCss);
329
- _context2.next = 26;
332
+ _context3.next = 26;
330
333
  break;
331
334
  case 23:
332
- _context2.prev = 23;
333
- _context2.t0 = _context2["catch"](16);
334
- console.error('====获取主题失败', _context2.t0);
335
+ _context3.prev = 23;
336
+ _context3.t0 = _context3["catch"](16);
337
+ console.error('====获取主题失败', _context3.t0);
335
338
  case 26:
336
339
  // 根据 appId 获取当前应用的使用的自定义组件
337
340
  onProgress({
338
341
  log: '获取当前应用的使用的自定义组件',
339
342
  progress: 3
340
343
  });
341
- _context2.next = 29;
344
+ _context3.next = 29;
342
345
  return services.qryPageCompAssetList({
343
346
  appId: appId
344
347
  });
345
348
  case 29:
346
- temCompAssetList = _context2.sent;
349
+ temCompAssetList = _context3.sent;
347
350
  // 兼容下割接数据,数组前面的自定义组件是新的
348
351
  compAssetList = temCompAssetList.reduce(function (acc, current) {
349
352
  var codes = acc.map(function (item) {
@@ -358,13 +361,13 @@ export var fetchData = /*#__PURE__*/function () {
358
361
  log: '获取全局数据源',
359
362
  progress: 4
360
363
  });
361
- _context2.next = 34;
364
+ _context3.next = 34;
362
365
  return services.queryFrontendDatasourcePage({
363
366
  appId: appId,
364
367
  pageSize: 10000
365
368
  });
366
369
  case 34:
367
- globalDataInfo = _context2.sent;
370
+ globalDataInfo = _context3.sent;
368
371
  dataSourceList = (globalDataInfo === null || globalDataInfo === void 0 ? void 0 : globalDataInfo.list) || [];
369
372
  globalDataMap = {};
370
373
  dataSourceList.forEach(function (item) {
@@ -388,7 +391,7 @@ export var fetchData = /*#__PURE__*/function () {
388
391
  log: '获取所有页面dsl',
389
392
  progress: 5
390
393
  });
391
- _context2.next = 45;
394
+ _context3.next = 45;
392
395
  return Promise.all(appPageList.map(function (i) {
393
396
  lastPageId = i.pageId;
394
397
  return services.findPageInstByVersionId({
@@ -397,7 +400,7 @@ export var fetchData = /*#__PURE__*/function () {
397
400
  });
398
401
  }));
399
402
  case 45:
400
- data = _context2.sent;
403
+ data = _context3.sent;
401
404
  pages = getPageDsls(data); // busiCompId 过滤重复
402
405
  itemHash = {}; // 找到所有页面使用到的 业务组件
403
406
  findAllItem(pages, function (item) {
@@ -408,7 +411,7 @@ export var fetchData = /*#__PURE__*/function () {
408
411
  log: '获取所有业务组件dsl',
409
412
  progress: 6
410
413
  });
411
- _context2.next = 53;
414
+ _context3.next = 53;
412
415
  return Promise.all(itemLists.map(function (i) {
413
416
  return services.findBusiCompById({
414
417
  busiCompId: i,
@@ -417,27 +420,144 @@ export var fetchData = /*#__PURE__*/function () {
417
420
  });
418
421
  }));
419
422
  case 53:
420
- busiData = _context2.sent;
423
+ busiData = _context3.sent;
421
424
  busiCompMapping = {}; // 过滤为空
422
425
  busiPages = busiData.filter(Boolean).map(function (i, index) {
423
426
  var _i$busiCompVersion;
424
- var busiData = JSON.parse(i === null || i === void 0 || (_i$busiCompVersion = i.busiCompVersion) === null || _i$busiCompVersion === void 0 ? void 0 : _i$busiCompVersion.sourceCodeJson);
427
+ // 业务组件为空,返回一个 fallback
428
+ var busiData = JSON.parse((i === null || i === void 0 || (_i$busiCompVersion = i.busiCompVersion) === null || _i$busiCompVersion === void 0 ? void 0 : _i$busiCompVersion.sourceCodeJson) || '{"id":"100101","pageContainerType":"BusiComp","pageName":"错误组件","pagePath":"","objType":"app","busiCompCode":"Custom","callbacks":["onChange"],"compState":"","events":[],"actions":[],"pageDynamicFlag":true,"setEvents":[{"dataName":"event","dataId":"798407","path":[],"value":"useEffect","params":[],"children":[]}],"layout":"BaseLayout","searchParams":[{"name":"业务主键","code":"bizId"},{"name":"业务场景","code":"sceneCode"},{"name":"业务数据","code":"bizData"}],"catalogItemId":"-1","platformType":"LowCode","editorVersion":"3.6.1.04251034","createdEditorVersion":"0.2.1130.05051011","busiCompObjectRelDTOList":[],"platform":"pc","appId":"1064722784465846272","components":[{"id":"Icon_2609852","label":"图标","compName":"Icon","type":"Icon","compType":1,"compLib":"@/components","props":{"name":"图标","mode":"normal","rotate":0,"basicStatus":1,"icon":{"theme":"outlined","type":"smile","isIconFont":false},"popoverSetting":{"page":{"pagePath":"/ceshiqipao2781","pageId":"1049616591121936384","pageName":"测试气泡1206","options":[{"name":"业务主键","code":"bizId"},{"name":"业务场景","code":"sceneCode"},{"name":"业务数据","code":"bizData"}],"tipType":"1","trigger":"click"}}},"style":{},"isContainer":false,"isBusiObjContainer":false,"cmdgroup":["basic"],"platform":"pc","icon":"Icon","description":"","image":"","groupsName":"通用","isInlineBlock":true,"setEvents":[],"isLabelDropBoxChild":false,"components":[],"path":["965041"]}],"path":[]}');
425
429
  busiData.busiCompId = i === null || i === void 0 ? void 0 : i.busiCompId;
426
430
  busiCompMapping[itemLists[index]] = busiData.id;
427
431
  return busiData;
428
- }); // 合并页面,生成器那边支持页面类型和业务组件类型
429
- pageDSLS = [].concat(_toConsumableArray(pages), _toConsumableArray(busiPages));
432
+ });
433
+ /**
434
+ * 新增中文转英文功能
435
+ ● API:translateToEnglish GET 请求,参数:chinese
436
+ rule
437
+ ● 支持多种生成规则
438
+ ○ UPPER_CAMEL 驼峰首字母大写
439
+ ○ LOWER_CAMEL 驼峰首字母小写
440
+ ○ UPPER_UNDERSCORE 下划线大写
441
+ ○ LOWER_UNDERSCORE 下划线小写
442
+ */
443
+ // 获取翻译,尝试三次
444
+ getTranslateName = /*#__PURE__*/function () {
445
+ var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(appId, chinese, rule) {
446
+ var _services$translateTo;
447
+ var count,
448
+ translateName,
449
+ _args2 = arguments;
450
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
451
+ while (1) switch (_context2.prev = _context2.next) {
452
+ case 0:
453
+ count = _args2.length > 3 && _args2[3] !== undefined ? _args2[3] : 0;
454
+ _context2.next = 3;
455
+ return services === null || services === void 0 || (_services$translateTo = services.translateToEnglish) === null || _services$translateTo === void 0 ? void 0 : _services$translateTo.call(services, {
456
+ appId: appId,
457
+ chinese: chinese,
458
+ rule: rule
459
+ });
460
+ case 3:
461
+ translateName = _context2.sent;
462
+ if (!(translateName && typeof translateName === 'string')) {
463
+ _context2.next = 8;
464
+ break;
465
+ }
466
+ return _context2.abrupt("return", translateName);
467
+ case 8:
468
+ if (!(count < 3)) {
469
+ _context2.next = 15;
470
+ break;
471
+ }
472
+ console.error("\u7FFB\u8BD1\u9519\u8BEF\uFF1A".concat(chinese, "\uFF0C\u7B2C").concat(count + 1, "\u91CD\u65B0\u5C1D\u8BD5"));
473
+ _context2.next = 12;
474
+ return getTranslateName(appId, chinese, rule, count + 1);
475
+ case 12:
476
+ return _context2.abrupt("return", _context2.sent);
477
+ case 15:
478
+ console.error("\u7FFB\u8BD1\u9519\u8BEF\uFF1A\u5C1D\u8BD5\u65E0\u6548");
479
+ return _context2.abrupt("return", 'TranslateError');
480
+ case 17:
481
+ case "end":
482
+ return _context2.stop();
483
+ }
484
+ }, _callee2);
485
+ }));
486
+ return function getTranslateName(_x2, _x3, _x4) {
487
+ return _ref6.apply(this, arguments);
488
+ };
489
+ }(); // 翻译业务组件的名字
490
+ key = 0;
491
+ case 58:
492
+ if (!(key < busiPages.length)) {
493
+ _context3.next = 68;
494
+ break;
495
+ }
496
+ _context3.next = 61;
497
+ return getTranslateName(appId, getSafeTypeName(busiPages[key].pageName), 'UPPER_CAMEL');
498
+ case 61:
499
+ translateName = _context3.sent;
430
500
  onProgress({
431
- log: '查询水印配置信息',
432
- progress: 7
501
+ log: '翻译业务组件名称',
502
+ progress: 6 + key / busiPages.length
433
503
  });
434
- // 获取水印
435
- _context2.next = 60;
436
- return services.getWaterMarkByAppId({
437
- appId: appId
504
+ busiPages[key]._pageName = busiPages[key].pageName;
505
+ busiPages[key].pageName = translateName;
506
+ case 65:
507
+ key++;
508
+ _context3.next = 58;
509
+ break;
510
+ case 68:
511
+ pagePathEnglishMapping = {};
512
+ if (!needTranslatePagePathToEnglish) {
513
+ _context3.next = 83;
514
+ break;
515
+ }
516
+ pagePathEnglishSet = {};
517
+ getName = function getName(name, type) {
518
+ var _pagePathEnglishSet$t;
519
+ var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
520
+ var compName = "".concat(name).concat(index === 0 ? '' : index);
521
+ (_pagePathEnglishSet$t = pagePathEnglishSet[type]) !== null && _pagePathEnglishSet$t !== void 0 ? _pagePathEnglishSet$t : pagePathEnglishSet[type] = new Set();
522
+ // 名称重复,不同页面类型,名称允许重复
523
+ if (!pagePathEnglishSet[type].has(compName)) {
524
+ var saleName = "/".concat(getSafeTypeName(compName));
525
+ pagePathEnglishSet[type].add(saleName);
526
+ return saleName;
527
+ }
528
+ return getName("".concat(compName), type, index + 1);
529
+ }; // 翻译页面的名字
530
+ _key = 0;
531
+ case 73:
532
+ if (!(_key < pages.length)) {
533
+ _context3.next = 83;
534
+ break;
535
+ }
536
+ _context3.next = 76;
537
+ return getTranslateName(appId, getSafeTypeName(pages[_key].pageName), 'LOWER_CAMEL');
538
+ case 76:
539
+ _translateName = _context3.sent;
540
+ onProgress({
541
+ log: '翻译页面路径',
542
+ progress: 7 + _key / pages.length
438
543
  });
439
- case 60:
440
- waterMark = _context2.sent;
544
+ console.log(_translateName);
545
+ // 如果页面路径翻译失败,就不处理路径
546
+ // index 保留不处理
547
+ if (_translateName !== 'TranslateError' && pages[_key].pagePath !== '/index') {
548
+ (_pagePathEnglishMappi = pagePathEnglishMapping[_pages$_key$pageConta = pages[_key].pageContainerType]) !== null && _pagePathEnglishMappi !== void 0 ? _pagePathEnglishMappi : pagePathEnglishMapping[_pages$_key$pageConta] = {};
549
+ safeTranslateName = getName(_translateName, pages[_key].pageContainerType);
550
+ pagePathEnglishMapping[pages[_key].pageContainerType][pages[_key].pagePath] = safeTranslateName;
551
+ pages[_key]._pagePath = pages[_key].pagePath;
552
+ pages[_key].pagePath = safeTranslateName;
553
+ }
554
+ case 80:
555
+ _key++;
556
+ _context3.next = 73;
557
+ break;
558
+ case 83:
559
+ // 合并页面,生成器那边支持页面类型和业务组件类型
560
+ pageDSLS = [].concat(_toConsumableArray(pages), _toConsumableArray(busiPages));
441
561
  options = {
442
562
  platform: platform,
443
563
  appId: appId,
@@ -454,7 +574,8 @@ export var fetchData = /*#__PURE__*/function () {
454
574
  themeCss: themeCss,
455
575
  models: globalDataMap,
456
576
  appInfo: clearAppInfo(appInfo),
457
- waterMark: waterMark
577
+ // 英文路径的对应关系
578
+ pagePathEnglishMapping: pagePathEnglishMapping
458
579
  };
459
580
  onProgress({
460
581
  log: '清理无用数据',
@@ -462,43 +583,44 @@ export var fetchData = /*#__PURE__*/function () {
462
583
  });
463
584
  cleanedTree = cleanTree(pageDSLS, ['path']); // 清理字段'b'和字段'e'
464
585
  cleanedTree = clearLXPagesDSL(cleanedTree);
465
- return _context2.abrupt("return", {
586
+ return _context3.abrupt("return", {
466
587
  options: options,
467
588
  cleanedTree: cleanedTree
468
589
  });
469
- case 66:
590
+ case 89:
470
591
  case "end":
471
- return _context2.stop();
592
+ return _context3.stop();
472
593
  }
473
- }, _callee2, null, [[16, 23]]);
594
+ }, _callee3, null, [[16, 23]]);
474
595
  }));
475
596
  return function fetchData(_x) {
476
597
  return _ref5.apply(this, arguments);
477
598
  };
478
599
  }();
479
600
  export var codeCreate = /*#__PURE__*/function () {
480
- var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(_ref6) {
481
- var appId, services, platform, baseUrl, _onProgress, _yield$fetchData, cleanedTree, options, result;
482
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
483
- while (1) switch (_context3.prev = _context3.next) {
601
+ var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(_ref7) {
602
+ var appId, services, platform, baseUrl, _onProgress, _ref7$needTranslatePa, needTranslatePagePathToEnglish, _yield$fetchData, cleanedTree, options, result;
603
+ return _regeneratorRuntime().wrap(function _callee4$(_context4) {
604
+ while (1) switch (_context4.prev = _context4.next) {
484
605
  case 0:
485
- appId = _ref6.appId, services = _ref6.services, platform = _ref6.platform, baseUrl = _ref6.baseUrl, _onProgress = _ref6.onProgress;
486
- _context3.prev = 1;
487
- _context3.next = 4;
606
+ appId = _ref7.appId, services = _ref7.services, platform = _ref7.platform, baseUrl = _ref7.baseUrl, _onProgress = _ref7.onProgress, _ref7$needTranslatePa = _ref7.needTranslatePagePathToEnglish, needTranslatePagePathToEnglish = _ref7$needTranslatePa === void 0 ? false : _ref7$needTranslatePa;
607
+ _context4.prev = 1;
608
+ _context4.next = 4;
488
609
  return fetchData({
489
610
  appId: appId,
490
611
  services: services,
491
612
  platform: platform,
492
613
  baseUrl: baseUrl,
493
- onProgress: _onProgress
614
+ onProgress: _onProgress,
615
+ needTranslatePagePathToEnglish: needTranslatePagePathToEnglish
494
616
  });
495
617
  case 4:
496
- _yield$fetchData = _context3.sent;
618
+ _yield$fetchData = _context4.sent;
497
619
  cleanedTree = _yield$fetchData.cleanedTree;
498
620
  options = _yield$fetchData.options;
499
621
  console.log(cleanedTree);
500
622
  console.log(options);
501
- _context3.next = 11;
623
+ _context4.next = 11;
502
624
  return generateCode({
503
625
  solution: 'alita',
504
626
  // 出码方案
@@ -529,7 +651,7 @@ export var codeCreate = /*#__PURE__*/function () {
529
651
  workerJsUrl: workerJsUrl
530
652
  });
531
653
  case 11:
532
- result = _context3.sent;
654
+ result = _context4.sent;
533
655
  console.log(result);
534
656
  // 出码结果(默认是递归结构描述的,可以传 flattenResult: true 以生成扁平结构的结果)
535
657
  publishers.zip().publish({
@@ -537,23 +659,23 @@ export var codeCreate = /*#__PURE__*/function () {
537
659
  // 上一步生成的 project
538
660
  projectSlug: appId // 项目标识
539
661
  });
540
- return _context3.abrupt("return", {
662
+ return _context4.abrupt("return", {
541
663
  success: true
542
664
  });
543
665
  case 17:
544
- _context3.prev = 17;
545
- _context3.t0 = _context3["catch"](1);
546
- return _context3.abrupt("return", {
547
- msg: _context3.t0,
666
+ _context4.prev = 17;
667
+ _context4.t0 = _context4["catch"](1);
668
+ return _context4.abrupt("return", {
669
+ msg: _context4.t0,
548
670
  success: false
549
671
  });
550
672
  case 20:
551
673
  case "end":
552
- return _context3.stop();
674
+ return _context4.stop();
553
675
  }
554
- }, _callee3, null, [[1, 17]]);
676
+ }, _callee4, null, [[1, 17]]);
555
677
  }));
556
- return function codeCreate(_x2) {
557
- return _ref7.apply(this, arguments);
678
+ return function codeCreate(_x5) {
679
+ return _ref8.apply(this, arguments);
558
680
  };
559
681
  }();
@@ -0,0 +1,217 @@
1
+ import * as React from 'react';
2
+
3
+ export function isAtLeastReact17(version: string): boolean {
4
+ const major = version.match(/^([^.]+)/);
5
+ return major !== null && parseInt(major[0], 10) >= 17;
6
+ }
7
+ let eventId = 0;
8
+ // 简单实现
9
+ function captureException() {
10
+ return `${(eventId += 1)}`;
11
+ }
12
+ export const UNKNOWN_COMPONENT = 'unknown';
13
+
14
+ export type FallbackRenderProps = {
15
+ error: Error;
16
+ componentStack: string | null;
17
+ eventId: string | null;
18
+ resetError(): void;
19
+ id: string;
20
+ compName: string;
21
+ getLocale: (
22
+ key: string,
23
+ placeholder?: string,
24
+ kv?: Record<string, string>,
25
+ ) => string;
26
+ };
27
+
28
+ export type FallbackRender = (
29
+ errorData: FallbackRenderProps,
30
+ ) => React.ReactElement;
31
+
32
+ export type ErrorBoundaryProps = {
33
+ /**
34
+ * A fallback component that gets rendered when the error boundary encounters an error.
35
+ *
36
+ * Can either provide a React Component, or a function that returns React Component as
37
+ * a valid fallback prop. If a function is provided, the function will be called with
38
+ * the error, the component stack, and an function that resets the error boundary on error.
39
+ *
40
+ */
41
+ fallback?: React.ReactElement | FallbackRender;
42
+
43
+ /** Called when the error boundary encounters an error */
44
+ onError?(error: Error, componentStack: string, eventId: string): void;
45
+
46
+ /** Called on componentDidMount() */
47
+ onMount?(): void;
48
+
49
+ /** Called if resetError() is called from the fallback render props function */
50
+ onReset?(
51
+ error: Error | null,
52
+ componentStack: string | null,
53
+ eventId: string | null,
54
+ ): void;
55
+
56
+ /** Called on componentWillUnmount() */
57
+ onUnmount?(
58
+ error: Error | null,
59
+ componentStack: string | null,
60
+ eventId: string | null,
61
+ ): void;
62
+
63
+ /** Called before the error is captured by Sentry, allows for you to add tags or context using the scope */
64
+ beforeCapture?(
65
+ scope: any,
66
+ error: Error | null,
67
+ componentStack: string | null,
68
+ ): void;
69
+ children?: React.ReactNode | (() => React.ReactNode);
70
+
71
+ otherProps?: Record<string, any>;
72
+ };
73
+
74
+ type ErrorBoundaryState = {
75
+ componentStack: Required<React.ErrorInfo>['componentStack'] | null;
76
+ error: Error | null;
77
+ eventId: string | null;
78
+ };
79
+
80
+ const INITIAL_STATE = {
81
+ componentStack: null,
82
+ error: null,
83
+ eventId: null,
84
+ };
85
+
86
+ /**
87
+ * A ErrorBoundary component that logs errors to Sentry. Requires React >= 16.
88
+ * NOTE: If you are a Sentry user, and you are seeing this stack frame, it means the
89
+ * Sentry React SDK ErrorBoundary caught an error invoking your application code. This
90
+ * is expected behavior and NOT indicative of a bug with the Sentry React SDK.
91
+ */
92
+ export class ErrorBoundary extends React.Component<
93
+ ErrorBoundaryProps,
94
+ ErrorBoundaryState
95
+ > {
96
+ public state: ErrorBoundaryState = INITIAL_STATE;
97
+
98
+ static defaultProps = {
99
+ otherProps: {},
100
+ };
101
+
102
+ public componentDidMount(): void {
103
+ const { onMount } = this.props;
104
+ if (onMount) {
105
+ onMount();
106
+ }
107
+ }
108
+
109
+ public componentWillUnmount(): void {
110
+ const { error, componentStack, eventId } = this.state;
111
+ const { onUnmount } = this.props;
112
+ if (onUnmount) {
113
+ onUnmount(error, componentStack, eventId);
114
+ }
115
+ }
116
+
117
+ public resetErrorBoundary: () => void = () => {
118
+ const { onReset } = this.props;
119
+ const { error, componentStack, eventId } = this.state;
120
+ if (onReset) {
121
+ onReset(error, componentStack, eventId);
122
+ }
123
+ this.setState(INITIAL_STATE);
124
+ };
125
+
126
+ public componentDidCatch(
127
+ error: Error & { cause?: Error },
128
+ { componentStack }: React.ErrorInfo,
129
+ ): void {
130
+ const { beforeCapture, onError } = this.props;
131
+
132
+ // If on React version >= 17, create stack trace from componentStack param and links
133
+ // to to the original error using `error.cause` otherwise relies on error param for stacktrace.
134
+ // Linking errors requires the `LinkedErrors` integration be enabled.
135
+ if (isAtLeastReact17(React.version)) {
136
+ const errorBoundaryError = new Error(error.message);
137
+ errorBoundaryError.name = `React ErrorBoundary ${errorBoundaryError.name}`;
138
+ // @ts-ignore
139
+ errorBoundaryError.stack = componentStack;
140
+
141
+ // Using the `LinkedErrors` integration to link the errors together.
142
+ error.cause = errorBoundaryError;
143
+ }
144
+
145
+ if (beforeCapture) {
146
+ // @ts-ignore
147
+ beforeCapture(null, error, componentStack);
148
+ }
149
+ const eventId = captureException();
150
+ if (onError) {
151
+ // @ts-ignore
152
+ onError(error, componentStack, eventId);
153
+ }
154
+
155
+ // componentDidCatch is used over getDerivedStateFromError
156
+ // so that componentStack is accessible through state.
157
+ // @ts-ignore
158
+ this.setState({ error, componentStack, eventId });
159
+ }
160
+
161
+ public render(): React.ReactNode {
162
+ // @ts-ignore
163
+ const { fallback, children, otherProps } = this.props;
164
+ const { error, componentStack, eventId } = this.state;
165
+
166
+ if (error) {
167
+ let element: React.ReactElement | undefined;
168
+ if (typeof fallback === 'function') {
169
+ // @ts-ignore
170
+ element = fallback({
171
+ error,
172
+ componentStack,
173
+ resetError: this.resetErrorBoundary,
174
+ eventId,
175
+ ...otherProps,
176
+ });
177
+ } else {
178
+ element = fallback;
179
+ }
180
+
181
+ if (React.isValidElement(element)) {
182
+ return element;
183
+ }
184
+
185
+ if (fallback) {
186
+ console.warn('fallback did not produce a valid ReactElement');
187
+ }
188
+
189
+ // Fail gracefully if no fallback provided or is not valid
190
+ return null;
191
+ }
192
+
193
+ if (typeof children === 'function') {
194
+ return children();
195
+ }
196
+ return children;
197
+ }
198
+ }
199
+
200
+ /**
201
+ * 渲染错误边界处理
202
+ * @param WrappedComponent 组件监听
203
+ * @returns
204
+ */
205
+ export function catchErrorBoundary<T>(
206
+ WrappedComponent: React.ComponentClass<T> | React.FunctionComponent<T>,
207
+ fallback?: ErrorBoundaryProps['fallback'],
208
+ schema?: Record<string, any>,
209
+ ) {
210
+ return React.forwardRef<any, any>((props, ref) => {
211
+ return (
212
+ <ErrorBoundary fallback={fallback} otherProps={{ schema }}>
213
+ <WrappedComponent {...props} ref={ref} />
214
+ </ErrorBoundary>
215
+ );
216
+ });
217
+ }
@@ -0,0 +1,246 @@
1
+ import { ARRAY_OPERATE_TYPE } from '@/constants';
2
+ import useSetState from '@/hooks/useSetState';
3
+ import ArrayUtil from '@/utils/array';
4
+ import { fetchQueryObject, fetchQueryService } from '@/utils/dataSource';
5
+ import { cloneDeep, isPlainObject } from 'lodash';
6
+ import { useEffect, useRef, useState } from 'react';
7
+
8
+ export interface UpdateDataSourceOptions {
9
+ /**
10
+ * 数据源名称
11
+ */
12
+ name: string;
13
+
14
+ /**
15
+ * 更新数据源的路径
16
+ */
17
+ path: string;
18
+
19
+ /**
20
+ * 目标值
21
+ */
22
+ value?: any;
23
+
24
+ /**
25
+ * 需要过滤的变量
26
+ */
27
+ predicate?: (item: any, index: number) => boolean;
28
+
29
+ /**
30
+ * 操作类型 数组时需要
31
+ */
32
+ operateType?: 0 | 1 | 2 | 3;
33
+
34
+ /**
35
+ * 数组或者对象类型
36
+ */
37
+ type: 'object' | 'array';
38
+
39
+ /**
40
+ * 是否局部赋值
41
+ */
42
+ onlySetPatch: boolean;
43
+ }
44
+
45
+ export interface DataSourceOptions {
46
+ urlParam?: Record<string, any>;
47
+ routerData?: Record<string, any>;
48
+ state?: Record<string, any>;
49
+ lcdpApi?: any;
50
+ }
51
+
52
+ export interface BaseDataSourceType {
53
+ _others_: {
54
+ /**
55
+ * 用户信息
56
+ */
57
+ personInfo: Record<string, any>;
58
+ };
59
+ [key: string]: any;
60
+ }
61
+
62
+ const useBaseDataSource = <T extends BaseDataSourceType>(
63
+ options: DataSourceOptions,
64
+ ) => {
65
+ const { lcdpApi } = options;
66
+
67
+ // 是否正在加载数据,发起请求时会切换loading
68
+ const [loading, setLoading] = useState(false);
69
+ // 数据源是否准备完成
70
+ const [dataReadyComplete, setDataReadyComplete] = useState(false);
71
+ // 数据源
72
+ const [data, setData] = useSetState<T>();
73
+ // 保存数据源快照,只有服务和对象发起成功后才会保存,用来缓存服务数据
74
+ const dataSnapshotRef = useRef<Record<string, any>>({});
75
+
76
+ /**
77
+ * 保存快照
78
+ */
79
+ const setDataSnapshot = (snapshot: Record<string, any>) => {
80
+ Object.assign(dataSnapshotRef.current, snapshot);
81
+ };
82
+
83
+ /**
84
+ * 设置用户信息
85
+ */
86
+ useEffect(() => {
87
+ setData({
88
+ _others_: {
89
+ personInfo: lcdpApi.data?.user || {},
90
+ },
91
+ });
92
+ }, [lcdpApi.data?.user]);
93
+
94
+ /**
95
+ * 更新数据源
96
+ */
97
+ const updateData = async ({
98
+ name,
99
+ path,
100
+ value,
101
+ type,
102
+ operateType,
103
+ predicate = () => false,
104
+ onlySetPatch = true,
105
+ }: UpdateDataSourceOptions) => {
106
+ try {
107
+ // 对象类型 直接赋值
108
+ if (type === 'object') {
109
+ ArrayUtil.updateObject({
110
+ data,
111
+ path,
112
+ value,
113
+ isPatch: onlySetPatch,
114
+ });
115
+ } else if (type === 'array') {
116
+ if (operateType === ARRAY_OPERATE_TYPE.ADD) {
117
+ ArrayUtil.push(data, path, value);
118
+ } else if (operateType === ARRAY_OPERATE_TYPE.DELETE) {
119
+ ArrayUtil.remove(data, path, predicate);
120
+ } else if (operateType === ARRAY_OPERATE_TYPE.REPLACE) {
121
+ ArrayUtil.replace(data, path, value);
122
+ } else if (operateType === ARRAY_OPERATE_TYPE.UPDATE) {
123
+ ArrayUtil.update(
124
+ {
125
+ data,
126
+ path,
127
+ value,
128
+ isPatch: onlySetPatch,
129
+ },
130
+ predicate,
131
+ );
132
+ }
133
+ }
134
+ return setData({
135
+ [name]: cloneDeep(data![name]),
136
+ });
137
+ } catch (error) {
138
+ return Promise.reject(error as Error);
139
+ }
140
+ };
141
+
142
+ // 清空数据源
143
+ const cleanDataSource = (name: string, initialData: Record<string, any>) => {
144
+ const newData = initialData[name];
145
+ if (Array.isArray(newData)) {
146
+ return [];
147
+ }
148
+ if (isPlainObject(newData)) {
149
+ return {};
150
+ }
151
+ return undefined;
152
+ };
153
+
154
+ /**
155
+ * 重置数据源
156
+ */
157
+ const clearDataSource = (name: string, initialData: Record<string, any>) => {
158
+ /**
159
+ * 数据源名字不存在,无需重置数据源
160
+ */
161
+ if (!name) return Promise.resolve(null);
162
+ return setData({
163
+ [name]: cleanDataSource(name, initialData) as any,
164
+ });
165
+ };
166
+
167
+ /**
168
+ * 刷新自定义数据源
169
+ */
170
+ const reloadCustomDataSource = (name: string, params?: any) =>
171
+ setData({
172
+ [name]: params,
173
+ });
174
+
175
+ /**
176
+ * 刷新对象数据源
177
+ */
178
+ const reloadObjectDataSource = (
179
+ name: string,
180
+ url: string,
181
+ options: any,
182
+ params: any,
183
+ ) => {
184
+ setLoading(true);
185
+ return fetchQueryObject(url, {
186
+ ...options,
187
+ attrs: params,
188
+ })
189
+ .then((res) => {
190
+ setData({
191
+ [name]: res,
192
+ });
193
+ const snapShot = cloneDeep(res);
194
+ setDataSnapshot({
195
+ [name]: snapShot,
196
+ [`${name}Filter`]: params,
197
+ });
198
+ return res;
199
+ })
200
+ .catch(console.log)
201
+ .finally(() => {
202
+ setLoading(false);
203
+ });
204
+ };
205
+
206
+ /**
207
+ * 刷新服务数据源
208
+ */
209
+ const reloadServiceDataSource = (name: string, service: any, params: any) => {
210
+ setLoading(true);
211
+ return fetchQueryService(service, params)
212
+ .then((res) => {
213
+ setData({
214
+ [name]: res,
215
+ });
216
+ const snapShot = cloneDeep(res);
217
+ setDataSnapshot({
218
+ [name]: snapShot,
219
+ [`${name}Filter`]: params,
220
+ });
221
+ return res;
222
+ })
223
+ .catch(console.log)
224
+ .finally(() => {
225
+ setLoading(false);
226
+ });
227
+ };
228
+
229
+ return {
230
+ data,
231
+ updateData,
232
+ clearDataSource,
233
+ reloadCustomDataSource,
234
+ loading,
235
+ dataSnapshot: dataSnapshotRef.current,
236
+ reloadServiceDataSource,
237
+ reloadObjectDataSource,
238
+ dataReadyComplete,
239
+ setLoading,
240
+ setDataSnapshot,
241
+ setDataReadyComplete,
242
+ setData,
243
+ };
244
+ };
245
+
246
+ export default useBaseDataSource;
@@ -0,0 +1,73 @@
1
+ import { parse } from 'qs';
2
+ import { useMemo, useRef } from 'react';
3
+
4
+ /**
5
+ * 生成基础上下文
6
+ * @param baseContext
7
+ */
8
+ const useGenerateContext = (
9
+ props: Record<string, any>,
10
+ baseContext: Record<string, any> = {},
11
+ options: Record<string, any> = {},
12
+ ) => {
13
+ // 指令定时器存储
14
+ const actionTimerRef = useRef<Record<string, any>>({
15
+ timeout: {},
16
+ interval: {},
17
+ });
18
+
19
+ // 清除定时器
20
+ const clearActionTimer = (timerName: string) => {
21
+ const actionTimer = actionTimerRef.current;
22
+ if (actionTimer.interval?.[timerName]) {
23
+ clearInterval(actionTimer.interval[timerName]);
24
+ actionTimer.interval[timerName] = null;
25
+ }
26
+ if (actionTimer.timeout?.[timerName]) {
27
+ clearTimeout(actionTimer.timeout[timerName]);
28
+ actionTimer.timeout[timerName] = null;
29
+ }
30
+ };
31
+
32
+ // 增加指令定时器
33
+ const addActionTimer = (
34
+ type: 'interval' | 'timeout' = 'timeout',
35
+ timerName: string,
36
+ callback: () => void,
37
+ time: number = 0,
38
+ ) => {
39
+ const actionTimer = actionTimerRef.current;
40
+ clearActionTimer(type);
41
+ const delay = time > 0 ? +time : 0;
42
+ if (type === 'interval') {
43
+ actionTimer.interval[timerName] = setInterval(() => {
44
+ callback?.();
45
+ }, delay);
46
+ }
47
+ if (type === 'timeout') {
48
+ actionTimer.interval[timerName] = setTimeout(() => {
49
+ callback?.();
50
+ }, delay);
51
+ }
52
+ };
53
+
54
+ /**
55
+ * url参数
56
+ */
57
+ const urlParam = useMemo(() => {
58
+ const queryParams = parse((location?.search ?? '?')?.split('?')[1]);
59
+ return {
60
+ ...queryParams,
61
+ ...props.urlParam,
62
+ };
63
+ }, [props.urlParam]);
64
+
65
+ return {
66
+ ...baseContext,
67
+ urlParam,
68
+ clearActionTimer,
69
+ addActionTimer,
70
+ };
71
+ };
72
+
73
+ export default useGenerateContext;
@@ -0,0 +1,9 @@
1
+ import http from '@/utils/service/baseRequest';
2
+ import urlHelper from '@/utils/service/urlHelper';
3
+
4
+ export async function getWaterMarkByAppId(appId: string) {
5
+ return http.get(
6
+ urlHelper.url('app/appPage/getWaterMarkByAppId', { appId }, { appId }),
7
+ { appId },
8
+ );
9
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lingxiteam/ebe-utils",
3
- "version": "0.0.7",
3
+ "version": "0.0.9",
4
4
  "description": "",
5
5
  "keywords": [],
6
6
  "author": "",
@@ -17,7 +17,7 @@
17
17
  "@babel/parser": "^7.12.12",
18
18
  "@babel/traverse": "^7.12.12",
19
19
  "@babel/types": "^7.12.12",
20
- "@lingxiteam/ebe": "0.0.7",
20
+ "@lingxiteam/ebe": "0.0.9",
21
21
  "cac": "^6.7.14",
22
22
  "fs-extra": "9.x"
23
23
  },