@hlw-uni/mp-core 1.0.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.
package/dist/index.mjs ADDED
@@ -0,0 +1,309 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+ import { ref } from "vue";
8
+ const cosAdapter = {
9
+ name: "cos",
10
+ buildFormData(ctx) {
11
+ const c = ctx.credentials ?? {};
12
+ return {
13
+ "q-ak": c["ak"] ?? "",
14
+ policy: c["policy"] ?? "",
15
+ "q-key-time": c["key-time"] ?? "",
16
+ "q-signature": c["signature"] ?? "",
17
+ "Content-Disposition": `inline;filename=${encodeURIComponent(ctx.fileName)}`,
18
+ success_action_status: 200,
19
+ ...ctx.extraData ?? {}
20
+ };
21
+ }
22
+ };
23
+ const ossAdapter = {
24
+ name: "oss",
25
+ buildFormData(ctx) {
26
+ const c = ctx.credentials ?? {};
27
+ return {
28
+ policy: c["policy"] ?? "",
29
+ signature: c["signature"] ?? "",
30
+ OSSAccessKeyId: c["accessKeyId"] ?? "",
31
+ success_action_status: 200,
32
+ "Content-Disposition": `inline;filename=${encodeURIComponent(ctx.fileName)}`,
33
+ ...ctx.extraData ?? {}
34
+ };
35
+ }
36
+ };
37
+ const qiniuAdapter = {
38
+ name: "qiniu",
39
+ buildFormData(ctx) {
40
+ const c = ctx.credentials ?? {};
41
+ return {
42
+ token: c["token"] ?? "",
43
+ key: c["key"] ?? ctx.fileName,
44
+ ...ctx.extraData ?? {}
45
+ };
46
+ }
47
+ };
48
+ const alistAdapter = {
49
+ name: "alist",
50
+ buildFormData(ctx) {
51
+ const c = ctx.credentials ?? {};
52
+ return {
53
+ "file-path": c["file-path"] ?? ctx.fileName,
54
+ authorization: c["token"] ?? "",
55
+ ...ctx.extraData ?? {}
56
+ };
57
+ }
58
+ };
59
+ const adapters = {
60
+ cos: cosAdapter,
61
+ oss: ossAdapter,
62
+ qiniu: qiniuAdapter,
63
+ alist: alistAdapter
64
+ };
65
+ function getAdapter(name) {
66
+ const adapter = adapters[name];
67
+ if (!adapter)
68
+ throw new Error(`[hlw] Unknown upload adapter: ${name}`);
69
+ return adapter;
70
+ }
71
+ var define_import_meta_env_default = {};
72
+ class HttpClient {
73
+ constructor(options = {}) {
74
+ __publicField(this, "_reqInterceptors", []);
75
+ __publicField(this, "_resInterceptors", []);
76
+ __publicField(this, "_errInterceptors", []);
77
+ __publicField(this, "_baseURL");
78
+ __publicField(this, "_defaultHeaders");
79
+ this._baseURL = options.baseURL ?? "";
80
+ this._defaultHeaders = {
81
+ "Content-Type": "application/json",
82
+ ...options.headers
83
+ };
84
+ }
85
+ /** 添加请求拦截器,返回取消函数 */
86
+ onRequest(fn) {
87
+ this._reqInterceptors.push(fn);
88
+ return () => {
89
+ const idx = this._reqInterceptors.indexOf(fn);
90
+ if (idx > -1)
91
+ this._reqInterceptors.splice(idx, 1);
92
+ };
93
+ }
94
+ /** 添加响应拦截器 */
95
+ onResponse(fn) {
96
+ this._resInterceptors.push(fn);
97
+ return () => {
98
+ const idx = this._resInterceptors.indexOf(fn);
99
+ if (idx > -1)
100
+ this._resInterceptors.splice(idx, 1);
101
+ };
102
+ }
103
+ /** 添加错误拦截器 */
104
+ onError(fn) {
105
+ this._errInterceptors.push(fn);
106
+ return () => {
107
+ const idx = this._errInterceptors.indexOf(fn);
108
+ if (idx > -1)
109
+ this._errInterceptors.splice(idx, 1);
110
+ };
111
+ }
112
+ /**
113
+ * 全局请求
114
+ */
115
+ async request(config) {
116
+ let cfg = {
117
+ method: "GET",
118
+ ...config,
119
+ headers: { ...this._defaultHeaders, ...config.headers }
120
+ };
121
+ for (const fn of this._reqInterceptors) {
122
+ cfg = await fn(cfg);
123
+ }
124
+ const fullUrl = this._buildUrl(cfg.url);
125
+ const res = await this._doRequest(fullUrl, cfg);
126
+ for (const fn of this._resInterceptors) {
127
+ const modified = await fn(res);
128
+ if (modified !== void 0)
129
+ return modified;
130
+ }
131
+ return res;
132
+ }
133
+ /**
134
+ * 组件内请求,返回带状态的 composable
135
+ */
136
+ useRequest() {
137
+ const loading = ref(false);
138
+ const data = ref(null);
139
+ const error = ref(null);
140
+ async function run(cfg) {
141
+ loading.value = true;
142
+ error.value = null;
143
+ try {
144
+ const res = await this.request(cfg);
145
+ data.value = res.data;
146
+ return res;
147
+ } catch (e) {
148
+ error.value = e;
149
+ await this._applyErrorInterceptors(e);
150
+ throw e;
151
+ } finally {
152
+ loading.value = false;
153
+ }
154
+ }
155
+ const get = (url, d) => run({ url, method: "GET", data: d });
156
+ const post = (url, d) => run({ url, method: "POST", data: d });
157
+ const put = (url, d) => run({ url, method: "PUT", data: d });
158
+ const del = (url, d) => run({ url, method: "DELETE", data: d });
159
+ return { loading, data, error, run: run.bind(this), get, post, put, del };
160
+ }
161
+ /**
162
+ * 上传文件(策略模式)
163
+ */
164
+ upload(config) {
165
+ const adapter = getAdapter(config.type);
166
+ const fileName = config.fileName ?? config.filePath.split("/").pop() ?? "file";
167
+ let server = config.server;
168
+ if (config.type === "local" && config.url)
169
+ server = config.url;
170
+ const formData = adapter.buildFormData({
171
+ filePath: config.filePath,
172
+ fileName,
173
+ credentials: config.credentials
174
+ });
175
+ return new Promise((resolve, reject) => {
176
+ uni.uploadFile({
177
+ url: server,
178
+ filePath: config.filePath,
179
+ name: "file",
180
+ formData,
181
+ header: config.header,
182
+ success: (res) => {
183
+ if (res.statusCode === 200) {
184
+ try {
185
+ const body = JSON.parse(res.data);
186
+ resolve({ code: body.code ?? 1, msg: body.message ?? "上传成功", data: body.data ?? "" });
187
+ } catch {
188
+ resolve({ code: 1, msg: "上传成功", data: res.data });
189
+ }
190
+ } else {
191
+ reject(new Error("上传失败"));
192
+ }
193
+ },
194
+ fail: (err) => reject(new Error(err.errMsg || "上传失败"))
195
+ });
196
+ });
197
+ }
198
+ _buildUrl(url) {
199
+ if (/^https?:\/\//.test(url))
200
+ return url;
201
+ const sep = url.includes("?") ? "&" : "?";
202
+ return `${this._baseURL}${url}${sep}_t=${Date.now()}`;
203
+ }
204
+ async _doRequest(url, cfg) {
205
+ return new Promise((resolve, reject) => {
206
+ uni.request({
207
+ url,
208
+ method: cfg.method,
209
+ data: cfg.data,
210
+ header: cfg.headers,
211
+ success: (res) => {
212
+ var _a;
213
+ if (res.statusCode >= 200 && res.statusCode < 300) {
214
+ resolve(res.data);
215
+ } else {
216
+ const msg = ((_a = res.data) == null ? void 0 : _a.message) ?? `请求失败: ${res.statusCode}`;
217
+ reject(new Error(msg));
218
+ }
219
+ },
220
+ fail: (err) => reject(new Error(err.errMsg || "网络请求失败"))
221
+ });
222
+ });
223
+ }
224
+ async _applyErrorInterceptors(err) {
225
+ for (const fn of this._errInterceptors) {
226
+ await fn(err);
227
+ }
228
+ }
229
+ }
230
+ new HttpClient({
231
+ baseURL: define_import_meta_env_default.VITE_API_BASE_URL ?? ""
232
+ });
233
+ const _info = ref(null);
234
+ function collect() {
235
+ var _a;
236
+ const sys = uni.getSystemInfoSync();
237
+ let appid = "";
238
+ try {
239
+ const accountInfo = uni.getAccountInfoSync();
240
+ appid = ((_a = accountInfo == null ? void 0 : accountInfo.miniProgram) == null ? void 0 : _a.appId) || "";
241
+ } catch {
242
+ appid = sys.appId || "";
243
+ }
244
+ let appName = "";
245
+ let appVersion = "";
246
+ let appVersionCode = "";
247
+ let hostName = "";
248
+ let hostVersion = "";
249
+ let hostLanguage = "";
250
+ let hostTheme = "";
251
+ try {
252
+ const appInfo = uni.getAppBaseInfo();
253
+ appName = appInfo.appName || "";
254
+ appVersion = appInfo.appVersion || "";
255
+ appVersionCode = appInfo.appVersionCode || "";
256
+ hostName = appInfo.hostName || "";
257
+ hostVersion = appInfo.hostVersion || "";
258
+ hostLanguage = appInfo.hostLanguage || "";
259
+ hostTheme = appInfo.hostTheme || "";
260
+ } catch {
261
+ appVersion = sys.appVersion || "";
262
+ }
263
+ const deviceBrand = sys.deviceBrand || "";
264
+ const deviceModel = sys.deviceModel || "";
265
+ const deviceId = sys.deviceId || "";
266
+ const deviceType = sys.deviceType || "";
267
+ const deviceOrientation = sys.deviceOrientation || "portrait";
268
+ const system = sys.system || "";
269
+ return {
270
+ appid,
271
+ app_name: appName,
272
+ app_version: appVersion,
273
+ app_version_code: appVersionCode,
274
+ app_channel: sys.appChannel || "",
275
+ device_brand: deviceBrand,
276
+ device_model: deviceModel,
277
+ device_id: deviceId,
278
+ device_type: deviceType,
279
+ device_orientation: deviceOrientation,
280
+ brand: sys.brand || "",
281
+ model: sys.model || "",
282
+ system,
283
+ os: system.split(" ")[0] || "",
284
+ pixel_ratio: sys.pixelRatio || 0,
285
+ screen_width: sys.screenWidth || 0,
286
+ screen_height: sys.screenHeight || 0,
287
+ window_width: sys.windowWidth || 0,
288
+ window_height: sys.windowHeight || 0,
289
+ status_bar_height: sys.statusBarHeight || 0,
290
+ sdk_version: sys.SDKVersion || "",
291
+ host_name: hostName,
292
+ host_version: hostVersion,
293
+ host_language: hostLanguage,
294
+ host_theme: hostTheme,
295
+ platform: sys.platform || "",
296
+ language: sys.language || "",
297
+ version: sys.version || ""
298
+ };
299
+ }
300
+ function ensure() {
301
+ if (!_info.value) {
302
+ _info.value = collect();
303
+ }
304
+ }
305
+ function useDevice() {
306
+ ensure();
307
+ return _info;
308
+ }
309
+ useDevice();
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@hlw-uni/mp-core",
3
+ "version": "1.0.0",
4
+ "description": "UniApp 运行时核心包 — composables、Pinia stores、工具函数、UI 组件",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.mjs",
11
+ "require": "./dist/index.js",
12
+ "types": "./dist/index.d.ts"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "vite build",
20
+ "dev": "vite build --watch"
21
+ },
22
+ "peerDependencies": {
23
+ "pinia": ">=2.1.0",
24
+ "vue": ">=3.4.0"
25
+ },
26
+ "devDependencies": {
27
+ "@dcloudio/types": "^3.4.8",
28
+ "@types/md5": "^2.3.6",
29
+ "@types/node": "^20.11.0",
30
+ "pinia": "^2.1.7",
31
+ "typescript": "^4.9.4",
32
+ "vite": "5.2.8",
33
+ "vite-plugin-dts": "^4.5.4",
34
+ "@vitejs/plugin-vue": "^5.1.0"
35
+ },
36
+ "dependencies": {
37
+ "md5": "^2.3.0"
38
+ }
39
+ }