@cpzxrobot/sdk 1.2.57 → 1.2.59

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.js CHANGED
@@ -22,9 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
25
  Object.defineProperty(exports, "__esModule", { value: true });
29
26
  exports.Cpzxrobot = void 0;
30
27
  exports.default = default_1;
@@ -32,7 +29,6 @@ const device_gateway_1 = require("./device_gateway");
32
29
  const user_gateway_1 = require("./user_gateway");
33
30
  const factory_gateway_1 = require("./factory_gateway");
34
31
  const transport_gateway_1 = require("./transport_gateway");
35
- const axios_1 = __importDefault(require("axios"));
36
32
  const assistant_gateway_1 = require("./assistant_gateway");
37
33
  const energy_gateway_1 = require("./energy_gateway");
38
34
  const camera_gateway_1 = require("./camera_gateway");
@@ -99,55 +95,72 @@ class Cpzxrobot {
99
95
  }
100
96
  initAxios(baseURL) {
101
97
  if (this.mode !== "miniapp_in_app") {
102
- var instance = axios_1.default.create({
103
- baseURL,
104
- });
105
- instance.interceptors.request.use((config) => {
106
- // 在发送请求之前在头部添加token
107
- config.headers.Authorization = this.token;
108
- // 解析和验证Token
109
- return config;
110
- }, function (error) {
111
- // 对请求错误做些什么
112
- return Promise.reject(error);
113
- });
114
- // @ts-ignore
115
- instance.getAndSave = (url, data, fileName) => {
116
- var args = Object.assign({ responseType: "blob" }, data);
117
- return instance.get(url, args).then((res) => {
118
- this.saveBlob(res.data, fileName || "file");
119
- });
98
+ const fetchWithAuth = async (input, init) => {
99
+ const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers);
100
+ headers.set('Authorization', this.token);
101
+ const response = await fetch(baseURL + input.toString(), Object.assign(Object.assign({}, init), { headers }));
102
+ if (!response.ok) {
103
+ throw new Error(`HTTP error! status: ${response.status}`);
104
+ }
105
+ return response;
120
106
  };
121
- // @ts-ignore
122
- instance.getAndPreview = instance.getAndSave;
123
- // @ts-ignore
124
- instance.upload = (url, option) => {
125
- return new Promise((resolve, reject) => {
126
- //add a file button to the body
127
- var button = document.createElement("input");
128
- button.type = "file";
129
- button.style.display = "none";
130
- document.body.appendChild(button);
131
- button.onclick = (e) => {
132
- var _a;
133
- var file = (_a = e.target.files) === null || _a === void 0 ? void 0 : _a[0];
134
- if (file) {
135
- const formData = new FormData();
136
- formData.append((option === null || option === void 0 ? void 0 : option["fileField"]) || "file", file);
137
- for (let key in option === null || option === void 0 ? void 0 : option["data"]) {
138
- formData.append(key, option["data"][key]);
107
+ const instance = {
108
+ get: async (url, config) => {
109
+ const response = await fetchWithAuth(url, {
110
+ method: 'GET',
111
+ headers: config === null || config === void 0 ? void 0 : config.headers
112
+ });
113
+ return { data: await response.json() };
114
+ },
115
+ post: async (url, data, config) => {
116
+ const response = await fetchWithAuth(url, {
117
+ method: 'POST',
118
+ headers: Object.assign({ 'Content-Type': 'application/json' }, config === null || config === void 0 ? void 0 : config.headers),
119
+ body: JSON.stringify(data)
120
+ });
121
+ return { data: await response.json() };
122
+ },
123
+ getAndSave: async (url, config, fileName) => {
124
+ const response = await fetchWithAuth(url, {
125
+ method: 'GET',
126
+ headers: config === null || config === void 0 ? void 0 : config.headers
127
+ });
128
+ const blob = await response.blob();
129
+ await this.saveBlob(blob, fileName || "file");
130
+ return { data: blob };
131
+ },
132
+ getAndPreview: async (url, config, fileName) => {
133
+ return instance.getAndSave(url, config, fileName);
134
+ },
135
+ upload: async (url, option) => {
136
+ return new Promise((resolve, reject) => {
137
+ const button = document.createElement("input");
138
+ button.type = "file";
139
+ button.style.display = "none";
140
+ document.body.appendChild(button);
141
+ button.onclick = async (e) => {
142
+ var _a;
143
+ const file = (_a = e.target.files) === null || _a === void 0 ? void 0 : _a[0];
144
+ if (file) {
145
+ const formData = new FormData();
146
+ formData.append((option === null || option === void 0 ? void 0 : option["fileField"]) || "file", file);
147
+ for (let key in option === null || option === void 0 ? void 0 : option["data"]) {
148
+ formData.append(key, option["data"][key]);
149
+ }
150
+ const response = await fetchWithAuth(url, {
151
+ method: 'POST',
152
+ body: formData
153
+ });
154
+ button.remove();
155
+ resolve({ data: await response.json() });
139
156
  }
140
- instance.post(url, formData).then((res) => {
157
+ else {
141
158
  button.remove();
142
- resolve(res);
143
- });
144
- }
145
- else {
146
- button.remove();
147
- resolve({ data: { Error: "没有选择文件" } });
148
- }
149
- };
150
- });
159
+ resolve({ data: { Error: "没有选择文件" } });
160
+ }
161
+ };
162
+ });
163
+ }
151
164
  };
152
165
  // @ts-ignore
153
166
  this.axios = instance;
@@ -393,19 +406,39 @@ class Cpzxrobot {
393
406
  openMiniApp(url) {
394
407
  this._jumpToMiniApp(url);
395
408
  }
396
- setAuth(auth, baseURL) {
409
+ setAuth(auth, args) {
410
+ var logger = (msg, level) => {
411
+ switch (level) {
412
+ case "debug":
413
+ if (args.verbose) {
414
+ console.debug(msg);
415
+ }
416
+ break;
417
+ case "info":
418
+ console.info(msg);
419
+ break;
420
+ case "warn":
421
+ console.warn(msg);
422
+ break;
423
+ case "error":
424
+ console.error(msg);
425
+ break;
426
+ }
427
+ };
397
428
  if (this.mode === "miniapp_in_app") {
398
429
  this.platformReady.then(() => {
399
- this.initAxios(baseURL);
400
- console.log("shzx is ready");
430
+ this.initAxios(args.baseURL);
431
+ logger("shzx is ready", "info");
401
432
  this.resolveReady(this.axios);
402
433
  });
403
434
  return;
404
435
  }
405
436
  else if (this.mode === "miniapp_in_web") {
437
+ logger("sdk under miniapp in web mode", "debug");
406
438
  //if localstorage has token, use it
407
439
  const token = localStorage.getItem("token");
408
440
  if (token) {
441
+ logger(`found token(${token}) in localstorage`, "debug");
409
442
  this.token = token;
410
443
  this.initAxios("https://www.cpzxrobot.com");
411
444
  this.axios.get("/api/v1/user/auth").then((res) => {
@@ -415,7 +448,8 @@ class Cpzxrobot {
415
448
  }
416
449
  this.resolveReady(this.axios);
417
450
  });
418
- if (!Cpzxrobot.factorySelectorLoaded) {
451
+ if (!Cpzxrobot.factorySelectorLoaded && !args.disableFactorySelector) {
452
+ logger("loading factory-selector module", "debug");
419
453
  Cpzxrobot.factorySelectorLoaded = true;
420
454
  //@ts-ignore
421
455
  Promise.resolve().then(() => __importStar(require('https://webc.cpzxrobot.com/webc/factory-selector.js'))).then(() => {
@@ -453,12 +487,14 @@ class Cpzxrobot {
453
487
  return;
454
488
  }
455
489
  else {
490
+ logger("no token found in localstorage", "debug");
456
491
  //if url has access_token and app_code, use it
457
492
  const url = new URL(window.location.href);
458
493
  const access_token = url.searchParams.get("access_token");
459
494
  const app_code = url.searchParams.get("app_code");
460
495
  if (access_token && app_code) {
461
- this.initAxios(baseURL);
496
+ logger(`found access_token(${access_token}) and app_code(${app_code}) in url`, "debug");
497
+ this.initAxios(args.baseURL);
462
498
  this.axios
463
499
  .post("/api/v1/user/auth", {
464
500
  appCode: app_code,
@@ -487,7 +523,8 @@ class Cpzxrobot {
487
523
  }
488
524
  }
489
525
  else {
490
- this.initAxios(baseURL);
526
+ logger(`sdk under ${this.mode} mode`, "debug");
527
+ this.initAxios(args.baseURL);
491
528
  this.auth = auth;
492
529
  if (this.auth.startsWith("Bearer ")) {
493
530
  this.token = auth;
@@ -538,14 +575,20 @@ function default_1(args = {
538
575
  id: 0,
539
576
  name: "",
540
577
  },
578
+ verbose: false,
541
579
  }) {
580
+ var _a;
542
581
  // @ts-ignore
543
582
  var instance = window.single_cpzxrobot_instance;
544
583
  if (!instance) {
545
584
  instance = new Cpzxrobot(args.appCode);
546
585
  // @ts-ignore
547
586
  window.single_cpzxrobot_instance = instance;
548
- instance.setAuth(args.devAuth, args.baseURL);
587
+ instance.setAuth(args.devAuth, {
588
+ baseURL: args.baseURL,
589
+ verbose: args.verbose,
590
+ disableFactorySelector: (_a = args.disableFactorySelector) !== null && _a !== void 0 ? _a : false,
591
+ });
549
592
  if (args.selectedFarm) {
550
593
  instance.user.selectedFarm = args.selectedFarm;
551
594
  }
package/index.ts CHANGED
@@ -6,7 +6,6 @@ import axios from "axios";
6
6
  import { AssistantGateway } from "./assistant_gateway";
7
7
  import { EnergyGateway } from "./energy_gateway";
8
8
  import { CameraGateway } from "./camera_gateway";
9
- import { type ElectricMeterRate } from "./energy_types/electric_meter_gateway";
10
9
  import { PigfarmGateway } from "./pigfarm_gateway";
11
10
  import { Device, Factory, MyAxiosInstance, Unit } from "./types";
12
11
  import { UnitGateway } from "./unit_gateway";
@@ -110,62 +109,79 @@ export class Cpzxrobot {
110
109
 
111
110
  initAxios(baseURL: string) {
112
111
  if (this.mode !== "miniapp_in_app") {
113
- var instance = axios.create({
114
- baseURL,
115
- })
116
- instance.interceptors.request.use(
117
- (config) => {
118
- // 在发送请求之前在头部添加token
119
- config.headers.Authorization = this.token;
120
- // 解析和验证Token
121
- return config;
122
- },
123
- function (error) {
124
- // 对请求错误做些什么
125
- return Promise.reject(error);
126
- }
127
- );
128
- // @ts-ignore
129
- instance.getAndSave = (url: string, data?: any, fileName?: string) => {
130
- var args = {
131
- responseType: "blob",
132
- ...data,
133
- };
134
- return instance.get(url, args).then((res) => {
135
- this.saveBlob(res.data, fileName || "file");
112
+ const fetchWithAuth = async (input: RequestInfo, init?: RequestInit) => {
113
+ const headers = new Headers(init?.headers);
114
+ headers.set('Authorization', this.token);
115
+ const response = await fetch(baseURL + input.toString(), {
116
+ ...init,
117
+ headers
136
118
  });
137
- }
138
- // @ts-ignore
139
- instance.getAndPreview = instance.getAndSave;
140
- // @ts-ignore
141
- instance.upload = (url: string, option?: {
142
- [key: string]: any;
143
- }) => {
144
- return new Promise<any>((resolve, reject) => {
145
- //add a file button to the body
146
- var button = document.createElement("input");
147
- button.type = "file";
148
- button.style.display = "none";
149
- document.body.appendChild(button);
150
- button.onclick = (e: Event) => {
151
- var file = (e.target as HTMLInputElement).files?.[0];
152
- if (file) {
153
- const formData = new FormData();
154
- formData.append(option?.["fileField"] || "file", file);
155
- for (let key in option?.["data"]) {
156
- formData.append(key, option!["data"][key]);
157
- }
158
- instance.post(url, formData).then((res) => {
119
+
120
+ if (!response.ok) {
121
+ throw new Error(`HTTP error! status: ${response.status}`);
122
+ }
123
+ return response;
124
+ };
125
+
126
+ const instance = {
127
+ get: async (url: string, config?: any) => {
128
+ const response = await fetchWithAuth(url, {
129
+ method: 'GET',
130
+ headers: config?.headers
131
+ });
132
+ return { data: await response.json() };
133
+ },
134
+ post: async (url: string, data?: any, config?: any) => {
135
+ const response = await fetchWithAuth(url, {
136
+ method: 'POST',
137
+ headers: {
138
+ 'Content-Type': 'application/json',
139
+ ...config?.headers
140
+ },
141
+ body: JSON.stringify(data)
142
+ });
143
+ return { data: await response.json() };
144
+ },
145
+ getAndSave: async (url: string, config?: any, fileName?: string) => {
146
+ const response = await fetchWithAuth(url, {
147
+ method: 'GET',
148
+ headers: config?.headers
149
+ });
150
+ const blob = await response.blob();
151
+ await this.saveBlob(blob, fileName || "file");
152
+ return { data: blob };
153
+ },
154
+ getAndPreview: async (url: string, config?: any, fileName?: string) => {
155
+ return instance.getAndSave(url, config, fileName);
156
+ },
157
+ upload: async (url: string, option?: any) => {
158
+ return new Promise<any>((resolve, reject) => {
159
+ const button = document.createElement("input");
160
+ button.type = "file";
161
+ button.style.display = "none";
162
+ document.body.appendChild(button);
163
+ button.onclick = async (e: Event) => {
164
+ const file = (e.target as HTMLInputElement).files?.[0];
165
+ if (file) {
166
+ const formData = new FormData();
167
+ formData.append(option?.["fileField"] || "file", file);
168
+ for (let key in option?.["data"]) {
169
+ formData.append(key, option!["data"][key]);
170
+ }
171
+ const response = await fetchWithAuth(url, {
172
+ method: 'POST',
173
+ body: formData
174
+ });
159
175
  button.remove();
160
- resolve(res);
161
- });
162
- } else {
163
- button.remove();
164
- resolve({ data: { Error: "没有选择文件" } })
165
- }
166
- };
167
- })
168
- }
176
+ resolve({ data: await response.json() });
177
+ } else {
178
+ button.remove();
179
+ resolve({ data: { Error: "没有选择文件" } });
180
+ }
181
+ };
182
+ });
183
+ }
184
+ };
169
185
  // @ts-ignore
170
186
  this.axios = instance;
171
187
  }
@@ -423,18 +439,42 @@ export class Cpzxrobot {
423
439
  this._jumpToMiniApp(url);
424
440
  }
425
441
 
426
- setAuth(auth: string, baseURL: string) {
442
+ setAuth(auth: string, args: {
443
+ baseURL: string;
444
+ verbose: boolean;
445
+ disableFactorySelector?: boolean;
446
+ }) {
447
+ var logger = (msg: string, level: "debug" | "info" | "warn" | "error") => {
448
+ switch (level) {
449
+ case "debug":
450
+ if (args.verbose) {
451
+ console.debug(msg);
452
+ }
453
+ break;
454
+ case "info":
455
+ console.info(msg);
456
+ break;
457
+ case "warn":
458
+ console.warn(msg);
459
+ break;
460
+ case "error":
461
+ console.error(msg);
462
+ break;
463
+ }
464
+ };
427
465
  if (this.mode === "miniapp_in_app") {
428
466
  this.platformReady.then(() => {
429
- this.initAxios(baseURL);
430
- console.log("shzx is ready");
467
+ this.initAxios(args.baseURL);
468
+ logger("shzx is ready", "info");
431
469
  this.resolveReady(this.axios);
432
470
  });
433
471
  return;
434
472
  } else if (this.mode === "miniapp_in_web") {
473
+ logger("sdk under miniapp in web mode", "debug");
435
474
  //if localstorage has token, use it
436
475
  const token = localStorage.getItem("token");
437
476
  if (token) {
477
+ logger(`found token(${token}) in localstorage`, "debug");
438
478
  this.token = token;
439
479
  this.initAxios("https://www.cpzxrobot.com");
440
480
  this.axios.get("/api/v1/user/auth").then((res) => {
@@ -444,7 +484,8 @@ export class Cpzxrobot {
444
484
  }
445
485
  this.resolveReady(this.axios);
446
486
  });
447
- if (!Cpzxrobot.factorySelectorLoaded) {
487
+ if (!Cpzxrobot.factorySelectorLoaded && !args.disableFactorySelector) {
488
+ logger("loading factory-selector module", "debug");
448
489
  Cpzxrobot.factorySelectorLoaded = true;
449
490
  //@ts-ignore
450
491
  import('https://webc.cpzxrobot.com/webc/factory-selector.js')
@@ -480,12 +521,14 @@ export class Cpzxrobot {
480
521
  }
481
522
  return;
482
523
  } else {
524
+ logger("no token found in localstorage", "debug");
483
525
  //if url has access_token and app_code, use it
484
526
  const url = new URL(window.location.href);
485
527
  const access_token = url.searchParams.get("access_token");
486
528
  const app_code = url.searchParams.get("app_code");
487
529
  if (access_token && app_code) {
488
- this.initAxios(baseURL);
530
+ logger(`found access_token(${access_token}) and app_code(${app_code}) in url`, "debug");
531
+ this.initAxios(args.baseURL);
489
532
  this.axios
490
533
  .post("/api/v1/user/auth", {
491
534
  appCode: app_code,
@@ -512,7 +555,8 @@ export class Cpzxrobot {
512
555
 
513
556
  }
514
557
  } else {
515
- this.initAxios(baseURL);
558
+ logger(`sdk under ${this.mode} mode`, "debug");
559
+ this.initAxios(args.baseURL);
516
560
  this.auth = auth;
517
561
  if (this.auth.startsWith("Bearer ")) {
518
562
  this.token = auth;
@@ -555,6 +599,8 @@ export default function (
555
599
  appCode: string;
556
600
  selectedFarm: Factory | null | undefined;
557
601
  selectedUnit: Unit | null | undefined;
602
+ verbose?: boolean;
603
+ disableFactorySelector?: boolean;
558
604
  } = {
559
605
  devAuth: "",
560
606
  appCode: "",
@@ -569,6 +615,7 @@ export default function (
569
615
  id: 0,
570
616
  name: "",
571
617
  },
618
+ verbose: false,
572
619
  }
573
620
  ): Cpzxrobot {
574
621
  // @ts-ignore
@@ -577,7 +624,11 @@ export default function (
577
624
  instance = new Cpzxrobot(args.appCode);
578
625
  // @ts-ignore
579
626
  window.single_cpzxrobot_instance = instance;
580
- instance.setAuth(args.devAuth, args.baseURL);
627
+ instance.setAuth(args.devAuth, {
628
+ baseURL: args.baseURL,
629
+ verbose: args.verbose,
630
+ disableFactorySelector: args.disableFactorySelector ?? false,
631
+ });
581
632
  if (args.selectedFarm) {
582
633
  instance.user.selectedFarm = args.selectedFarm;
583
634
  }
@@ -587,5 +638,3 @@ export default function (
587
638
  }
588
639
  return instance;
589
640
  }
590
-
591
- export { type ElectricMeterRate };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cpzxrobot/sdk",
3
- "version": "1.2.57",
3
+ "version": "1.2.59",
4
4
  "description": "提供给上海正芯数智APP第三方H5应用使用的SDK",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -12,9 +12,6 @@
12
12
  "devDependencies": {
13
13
  "typescript": "^5.5.3"
14
14
  },
15
- "dependencies": {
16
- "axios": "^1.7.2"
17
- },
18
15
  "types": "types.d.ts",
19
16
  "typings": "types.d.ts"
20
17
  }
package/types.d.ts CHANGED
@@ -18,6 +18,7 @@ import { RobotGateway } from "@cpzxrobot/sdk/robot_gateway";
18
18
  import { QuotationGateway } from "./quotation_gateway";
19
19
  import { AiGateway } from "./ai_gateway";
20
20
  import { EnergyGateway } from "./energy_gateway";
21
+ import { type ElectricMeterRate } from "./energy_types/electric_meter_gateway";
21
22
 
22
23
  type Device = {
23
24
  id: number;
@@ -372,6 +373,8 @@ declare module "@cpzxrobot/sdk" {
372
373
  appCode: string;
373
374
  selectedFarm: Factory | null | undefined;
374
375
  selectedUnit: Unit | null | undefined;
376
+ verbose?: boolean;
377
+ disableFactorySelector?: boolean;
375
378
  } = {
376
379
  devAuth: "",
377
380
  appCode: "",
@@ -386,6 +389,8 @@ declare module "@cpzxrobot/sdk" {
386
389
  id: 0,
387
390
  name: "",
388
391
  },
392
+ verbose: false,
393
+ disableFactorySelector: false,
389
394
  }
390
395
  ): Cpzxrobot;
391
396
  export {
@@ -410,5 +415,6 @@ declare module "@cpzxrobot/sdk" {
410
415
  DeviceV2,
411
416
  FieldDatas,
412
417
  SensorDatas,
418
+ ElectricMeterRate
413
419
  };
414
420
  }