@tuya-sat/micro-script 3.0.25 → 3.0.27-beta.1

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.
@@ -0,0 +1,2 @@
1
+ declare const _default: () => Promise<void>;
2
+ export default _default;
@@ -0,0 +1,202 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ const fs_extra_1 = __importDefault(require("fs-extra"));
39
+ const path_1 = __importDefault(require("path"));
40
+ const paths_1 = __importDefault(require("../config/paths"));
41
+ const ts = __importStar(require("typescript"));
42
+ const express_1 = require("express");
43
+ const prettier_1 = __importDefault(require("prettier"));
44
+ const isMonorepo = () => {
45
+ return (fs_extra_1.default.existsSync(path_1.default.join(process.cwd(), 'apps')) &&
46
+ fs_extra_1.default.existsSync(path_1.default.join(process.cwd(), 'packages')));
47
+ };
48
+ const isMainApp = () => {
49
+ const { debuggerConfig: { isMainApp }, } = require(paths_1.default.microConfig);
50
+ return isMainApp;
51
+ };
52
+ const createPropertyAssignment = (key, value) => {
53
+ return ts.factory.createPropertyAssignment(ts.factory.createStringLiteral(key), ts.factory.createStringLiteral(value));
54
+ };
55
+ exports.default = () => __awaiter(void 0, void 0, void 0, function* () {
56
+ var _a, _b, _c, _d;
57
+ if (isMainApp()) {
58
+ }
59
+ else if (isMonorepo()) {
60
+ }
61
+ else {
62
+ const sourceCode = fs_extra_1.default
63
+ .readFileSync(path_1.default.join(__dirname, './template.ts'))
64
+ .toString();
65
+ const ast = ts.createSourceFile('apis.ts', sourceCode, ts.ScriptTarget.ES2020, true);
66
+ const apiNode = (_d = (_c = (_b = (_a = ast.statements.find((s) => {
67
+ var _a, _b, _c;
68
+ return s.kind === ts.SyntaxKind.VariableStatement &&
69
+ ((_c = (_b = (_a = s === null || s === void 0 ? void 0 : s.declarationList) === null || _a === void 0 ? void 0 : _a.declarations) === null || _b === void 0 ? void 0 : _b[0].name) === null || _c === void 0 ? void 0 : _c.escapedText) ===
70
+ 'apis';
71
+ })) === null || _a === void 0 ? void 0 : _a.declarationList) === null || _b === void 0 ? void 0 : _b.declarations) === null || _c === void 0 ? void 0 : _c[0].initializer) === null || _d === void 0 ? void 0 : _d.properties;
72
+ const mf = fs_extra_1.default.readJSONSync(path_1.default.join(process.cwd(), 'manifest.json'));
73
+ const apis = mf.apis || [];
74
+ apis.forEach((api) => {
75
+ const paths = api.path.split('/').map((item) => {
76
+ return item
77
+ .replace('.', '')
78
+ .replace('-', '_')
79
+ .replace('{', '')
80
+ .replace('}', '')
81
+ .toUpperCase();
82
+ });
83
+ const apiName = `${api.method.toUpperCase()}${paths.join('_')}`;
84
+ const regex = /{(\w+)}/g;
85
+ const matches = [];
86
+ let match;
87
+ while ((match = regex.exec(api.path))) {
88
+ matches.push(match[1]);
89
+ }
90
+ const createParameterDeclarations = () => {
91
+ console.log('createParameterDeclarations', matches);
92
+ return [
93
+ ts.factory.createParameterDeclaration(undefined, undefined, undefined, ts.factory.createObjectBindingPattern([
94
+ ...[
95
+ matches.length > 0
96
+ ? ts.factory.createBindingElement(undefined, undefined, 'params')
97
+ : undefined,
98
+ ].filter(Boolean),
99
+ ts.factory.createBindingElement(undefined, undefined, 'query'),
100
+ ts.factory.createBindingElement(undefined, undefined, 'headers'),
101
+ ts.factory.createBindingElement(undefined, undefined, 'data'),
102
+ ]), undefined, ts.factory.createTypeLiteralNode([
103
+ ...[
104
+ matches.length > 0
105
+ ? ts.factory.createPropertySignature(undefined, 'params', undefined, ts.factory.createTypeLiteralNode(matches.map((match) => {
106
+ return ts.factory.createPropertySignature([], match, undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword));
107
+ })))
108
+ : undefined,
109
+ ].filter(Boolean),
110
+ ts.factory.createPropertySignature(undefined, 'query', ts.factory.createToken(ts.SyntaxKind.QuestionToken), ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)),
111
+ ts.factory.createPropertySignature(undefined, 'headers', ts.factory.createToken(ts.SyntaxKind.QuestionToken), ts.factory.createTypeLiteralNode([
112
+ ts.factory.createIndexSignature(undefined, undefined, [
113
+ ts.factory.createParameterDeclaration(undefined, undefined, undefined, 'key', undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), undefined),
114
+ ], ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)),
115
+ ])),
116
+ ts.factory.createPropertySignature(undefined, 'data', ts.factory.createToken(ts.SyntaxKind.QuestionToken), ts.factory.createTypeLiteralNode([
117
+ ts.factory.createIndexSignature(undefined, undefined, [
118
+ ts.factory.createParameterDeclaration(undefined, undefined, undefined, 'key', undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), undefined),
119
+ ], ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)),
120
+ ])),
121
+ ])),
122
+ ];
123
+ };
124
+ const reqNodes = () => {
125
+ let reqUrl = '/' +
126
+ `/open-api${api.path}`
127
+ .replace(regex, '')
128
+ .split('/')
129
+ .filter(Boolean)
130
+ .join('/') +
131
+ '/';
132
+ console.log('reqUrl', reqUrl);
133
+ const urlNode = () => {
134
+ if (matches.length > 0 && express_1.query) {
135
+ return ts.factory.createTemplateExpression(ts.factory.createTemplateHead(reqUrl), (() => {
136
+ if (matches.length == 1) {
137
+ return [
138
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + matches[0]), ts.factory.createTemplateMiddle('?')),
139
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('query'), ts.factory.createTemplateMiddle('')),
140
+ ];
141
+ }
142
+ else {
143
+ return [
144
+ ...matches.slice(0, -1).map((match) => {
145
+ return ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + match), ts.factory.createTemplateMiddle('/'));
146
+ }),
147
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + matches[matches.length - 1]), ts.factory.createTemplateMiddle('?')),
148
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('query'), ts.factory.createTemplateTail('')),
149
+ ];
150
+ }
151
+ })());
152
+ }
153
+ if (matches.length > 0) {
154
+ return ts.factory.createTemplateExpression(ts.factory.createTemplateHead(reqUrl + '?'), (() => {
155
+ if (matches.length === 1) {
156
+ return [
157
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + matches[0]), ts.factory.createTemplateMiddle('/')),
158
+ ];
159
+ }
160
+ else {
161
+ return [
162
+ ...matches.slice(0, -1).map((match) => {
163
+ return ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + match), ts.factory.createTemplateMiddle('/'));
164
+ }),
165
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + matches[matches.length - 1]), ts.factory.createTemplateTail('')),
166
+ ];
167
+ }
168
+ })());
169
+ }
170
+ if (express_1.query) {
171
+ return ts.factory.createTemplateExpression(ts.factory.createTemplateHead(reqUrl + '?'), [
172
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('query'), ts.factory.createTemplateTail('')),
173
+ ]);
174
+ }
175
+ return ts.factory.createStringLiteral(`/open-api${api.path}`);
176
+ };
177
+ return [
178
+ ts.factory.createObjectLiteralExpression(ts.factory.createNodeArray([
179
+ ts.factory.createPropertyAssignment(ts.factory.createStringLiteral('url'), urlNode()),
180
+ createPropertyAssignment('method', `${api.method}`),
181
+ ts.factory.createPropertyAssignment('headers', ts.factory.createIdentifier('headers')),
182
+ ts.factory.createPropertyAssignment('data', ts.factory.createIdentifier('data')),
183
+ ])),
184
+ ];
185
+ };
186
+ apiNode.push(ts.factory.createPropertyAssignment(apiName, ts.factory.createArrowFunction(undefined, undefined, createParameterDeclarations(), undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createBlock([
187
+ ts.factory.createReturnStatement(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('api'), 'request'), undefined, reqNodes()), 'then'), undefined, [
188
+ ts.factory.createArrowFunction(undefined, undefined, [
189
+ ts.factory.createParameterDeclaration(undefined, undefined, undefined, 'res', undefined, ts.factory.createTypeReferenceNode('any')),
190
+ ], undefined, undefined, ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('res'), ts.factory.createIdentifier('data'))),
191
+ ])),
192
+ ]))));
193
+ });
194
+ const printer = ts.createPrinter({
195
+ newLine: ts.NewLineKind.LineFeed,
196
+ });
197
+ const output = printer.printNode(ts.EmitHint.Unspecified, ast, ast);
198
+ const apiPath = path_1.default.join(process.cwd(), 'node_modules', '.micro', 'api.ts');
199
+ console.log('apiPath', apiPath);
200
+ fs_extra_1.default.writeFileSync(apiPath, prettier_1.default.format(output), { encoding: 'utf-8' });
201
+ }
202
+ });
@@ -0,0 +1,30 @@
1
+ import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios';
2
+ import { message } from 'antd';
3
+
4
+ const api = axios.create();
5
+
6
+ api.interceptors.request.use(
7
+ (config: AxiosRequestConfig) => {
8
+ config.headers = {
9
+ ...config.headers,
10
+ 'Content-Type': 'application/json;charset=utf-8',
11
+ };
12
+ return config;
13
+ },
14
+ (error: Error) => Promise.reject(error)
15
+ );
16
+
17
+ api.interceptors.response.use(
18
+ (response: AxiosResponse<any>) => {
19
+ const res = response.data;
20
+ if (!res.success) {
21
+ message.error(res.msg);
22
+ return Promise.reject(res);
23
+ }
24
+ return res;
25
+ },
26
+ (error: Error) => Promise.reject(error)
27
+ );
28
+
29
+ //根据 manifest apis生产微应用可以直接使用的
30
+ export const apis = {};
package/dist/bin/cli.js CHANGED
@@ -1,5 +1,4 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
2
  const PORXY_SIGN = "--proxy";
4
3
  const IS_MAIN = "--main";
5
4
  const params = process.argv.slice(2);
@@ -17,10 +17,12 @@ const chalk_1 = __importDefault(require("chalk"));
17
17
  const ora_1 = __importDefault(require("ora"));
18
18
  const webpack_config_1 = __importDefault(require("../config/webpack.config"));
19
19
  const template_1 = __importDefault(require("../template"));
20
+ const apis_1 = __importDefault(require("../apis"));
20
21
  const BUILD_FAIL_TIP = '糟糕:打包失败了,下面是具体信息';
21
22
  const spinner = (0, ora_1.default)('building').start();
22
23
  const config = (0, webpack_config_1.default)();
23
24
  (() => __awaiter(void 0, void 0, void 0, function* () {
25
+ yield (0, apis_1.default)();
24
26
  yield (0, template_1.default)();
25
27
  (0, webpack_1.default)(config).run((err, stats) => {
26
28
  if (err) {
@@ -18,7 +18,9 @@ const mock_1 = __importDefault(require("../module/mock"));
18
18
  const bundleServer_1 = require("../module/bundleServer");
19
19
  const proxy_1 = __importDefault(require("../module/proxy"));
20
20
  const template_1 = __importDefault(require("../template"));
21
+ const apis_1 = __importDefault(require("../apis"));
21
22
  (() => __awaiter(void 0, void 0, void 0, function* () {
23
+ yield (0, apis_1.default)();
22
24
  yield (0, template_1.default)();
23
25
  let defaultPort = 9000;
24
26
  console.log(chalk_1.default.yellow('如果是pc端的微应用调试,请勿使用该命令,考虑使用`start --main`或`start --main --proxy`'));
@@ -18,7 +18,9 @@ const mainServer_1 = __importDefault(require("../module/mainServer"));
18
18
  const bundleServer_1 = require("../module/bundleServer");
19
19
  const kill_port_1 = __importDefault(require("kill-port"));
20
20
  const template_1 = __importDefault(require("../template"));
21
+ const apis_1 = __importDefault(require("../apis"));
21
22
  (() => __awaiter(void 0, void 0, void 0, function* () {
23
+ yield (0, apis_1.default)();
22
24
  yield (0, template_1.default)();
23
25
  let defaultPort = 9000;
24
26
  //检测端口占用情况
@@ -76,12 +76,18 @@ exports.default = () => __awaiter(void 0, void 0, void 0, function* () {
76
76
  fs.copyFileSync(path.join(__dirname, './micro-app/index.css'), path.join(microPath, 'index.css'));
77
77
  fs.copyFileSync(path.join(__dirname, './micro-app/public-path.js'), path.join(microPath, 'public-path.js'));
78
78
  fs.copyFileSync(path.join(__dirname, './micro-app/interfaces.ts'), path.join(microPath, 'interfaces.ts'));
79
+ fs.copyFileSync(path.join(__dirname, './micro-app/antdLang.ts'), path.join(microPath, 'antdLang.ts'));
79
80
  let content = fs.readFileSync(path.join(__dirname, './micro-app/index.tsx'), {
80
81
  encoding: 'utf8',
81
82
  });
82
83
  content = content.replace("import App from './App';", `import App from '../../src/App'`);
83
- content = content.replace("import './lang';", `import '../../src/lang';`);
84
84
  content = content.replace("import './styles/global.less';", `import '../../src/styles/global.less';`);
85
85
  fs.writeFileSync(microPath + '/index.tsx', content);
86
+ let langContent = fs.readFileSync(path.join(__dirname, './micro-app/lang.ts'), {
87
+ encoding: 'utf8',
88
+ });
89
+ langContent = langContent.replace("import en from './en';", `import en from '../../src/lang/en'`);
90
+ langContent = langContent.replace("import zh from './zh';", `import zh from '../../src/lang/zh'`);
91
+ fs.writeFileSync(microPath + '/lang.ts', langContent);
86
92
  }
87
93
  });
@@ -11,6 +11,7 @@ import './index.css';
11
11
  import './styles/global.less';
12
12
  export * from './interfaces';
13
13
  export * from './antdLang';
14
+ export * from 'api';
14
15
  export let microProps: IQiankunProps;
15
16
 
16
17
  function render(props: IQiankunProps) {
@@ -0,0 +1,16 @@
1
+ import i18n from 'i18next';
2
+ import { initReactI18next } from 'react-i18next';
3
+ import LanguageDetector from 'i18next-browser-languagedetector';
4
+ import en from './en';
5
+ import zh from './zh';
6
+
7
+ i18n
8
+ .use(LanguageDetector)
9
+ .use(initReactI18next)
10
+ .init({
11
+ resources: { en: { translation: en }, zh: { translation: zh } },
12
+ fallbackLng: 'en',
13
+ interpolation: {
14
+ escapeValue: false,
15
+ },
16
+ });
@@ -1,5 +1,5 @@
1
1
  export declare const promiser: () => {
2
2
  waiting: Promise<unknown>;
3
- resolve: undefined;
4
- reject: undefined;
3
+ resolve: any;
4
+ reject: any;
5
5
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuya-sat/micro-script",
3
- "version": "3.0.25",
3
+ "version": "3.0.27-beta.1",
4
4
  "bin": "./dist/bin/cli.js",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",
@@ -23,9 +23,9 @@
23
23
  "@babel/preset-typescript": "7.16.7",
24
24
  "@babel/traverse": "^7.20.13",
25
25
  "@pmmmwh/react-refresh-webpack-plugin": "0.5.4",
26
- "@tuya-sat/micro-dev-loader": "3.0.25",
27
- "@tuya-sat/micro-dev-proxy": "3.0.25",
28
- "@tuya-sat/micro-utils": "3.0.25",
26
+ "@tuya-sat/micro-dev-loader": "3.0.27-beta.1",
27
+ "@tuya-sat/micro-dev-proxy": "3.0.27-beta.1",
28
+ "@tuya-sat/micro-utils": "3.0.27-beta.1",
29
29
  "@types/kill-port": "^2.0.0",
30
30
  "babel-loader": "8.2.4",
31
31
  "babel-plugin-import": "1.13.3",
@@ -52,6 +52,7 @@
52
52
  "postcss": "8.4.12",
53
53
  "postcss-loader": "6.2.1",
54
54
  "postcss-preset-env": "7.4.3",
55
+ "prettier": "^2.8.8",
55
56
  "react-refresh": "0.11.0",
56
57
  "resolve-url-loader": "5.0.0",
57
58
  "sass": "1.49.9",
@@ -16,3 +16,8 @@ fs.copySync(
16
16
  path.join(process.cwd(), './src/template/main-app'),
17
17
  path.join(process.cwd(), 'dist/template/main-app')
18
18
  );
19
+
20
+ fs.copySync(
21
+ path.join(process.cwd(), './src/apis/template.ts'),
22
+ path.join(process.cwd(), 'dist/apis/template.ts')
23
+ );