@qxs-bns/utils 0.0.16 → 0.0.18

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.
Files changed (132) hide show
  1. package/es/index.js +11 -0
  2. package/es/index.js.map +1 -0
  3. package/es/src/argo-log.js +78 -0
  4. package/es/src/argo-log.js.map +1 -0
  5. package/es/src/date-transfer.js +34 -0
  6. package/es/src/date-transfer.js.map +1 -0
  7. package/es/src/device.js +23 -0
  8. package/es/src/device.js.map +1 -0
  9. package/es/src/file-operations.js +105 -0
  10. package/es/src/file-operations.js.map +1 -0
  11. package/es/src/json.js +67 -0
  12. package/es/src/json.js.map +1 -0
  13. package/es/src/oss-uploader.js +115 -0
  14. package/es/src/oss-uploader.js.map +1 -0
  15. package/es/src/storage.js +113 -0
  16. package/es/src/storage.js.map +1 -0
  17. package/es/src/types.js +38 -0
  18. package/es/src/types.js.map +1 -0
  19. package/es/src/use-api.js +65 -0
  20. package/es/src/use-api.js.map +1 -0
  21. package/es/src/watermark.js +209 -0
  22. package/es/src/watermark.js.map +1 -0
  23. package/lib/index.js +40 -1
  24. package/lib/index.js.map +1 -1
  25. package/lib/src/argo-log.js +79 -1
  26. package/lib/src/argo-log.js.map +1 -1
  27. package/lib/src/date-transfer.js +35 -1
  28. package/lib/src/date-transfer.js.map +1 -1
  29. package/lib/src/device.js +27 -1
  30. package/lib/src/device.js.map +1 -1
  31. package/lib/src/file-operations.js +107 -1
  32. package/lib/src/file-operations.js.map +1 -1
  33. package/lib/src/json.js +69 -1
  34. package/lib/src/json.js.map +1 -1
  35. package/lib/src/oss-uploader.js +119 -1
  36. package/lib/src/oss-uploader.js.map +1 -1
  37. package/lib/src/storage.js +114 -1
  38. package/lib/src/storage.js.map +1 -1
  39. package/lib/src/types.js +46 -1
  40. package/lib/src/types.js.map +1 -1
  41. package/lib/src/use-api.js +66 -1
  42. package/lib/src/use-api.js.map +1 -1
  43. package/lib/src/watermark.js +192 -13
  44. package/lib/src/watermark.js.map +1 -1
  45. package/package.json +26 -27
  46. package/{es → types}/index.d.ts +1 -0
  47. package/types/index.d.ts.map +1 -0
  48. package/{es → types}/src/argo-log.d.ts +1 -0
  49. package/types/src/argo-log.d.ts.map +1 -0
  50. package/types/src/date-transfer.d.ts +12 -0
  51. package/types/src/date-transfer.d.ts.map +1 -0
  52. package/types/src/device.d.ts +18 -0
  53. package/types/src/device.d.ts.map +1 -0
  54. package/{es → types}/src/file-operations.d.ts +1 -0
  55. package/types/src/file-operations.d.ts.map +1 -0
  56. package/{lib → types}/src/json.d.ts +1 -0
  57. package/types/src/json.d.ts.map +1 -0
  58. package/{es → types}/src/oss-uploader.d.ts +2 -2
  59. package/types/src/oss-uploader.d.ts.map +1 -0
  60. package/{es → types}/src/storage.d.ts +1 -0
  61. package/types/src/storage.d.ts.map +1 -0
  62. package/{lib → types}/src/types.d.ts +1 -0
  63. package/types/src/types.d.ts.map +1 -0
  64. package/{lib → types}/src/use-api.d.ts +3 -4
  65. package/types/src/use-api.d.ts.map +1 -0
  66. package/{es → types}/src/watermark.d.ts +1 -0
  67. package/types/src/watermark.d.ts.map +1 -0
  68. package/types/tsconfig.tsbuildinfo +1 -0
  69. package/README.md +0 -65
  70. package/es/_virtual/_commonjs-dynamic-modules.mjs +0 -7
  71. package/es/_virtual/_commonjs-dynamic-modules.mjs.map +0 -1
  72. package/es/_virtual/_commonjsHelpers.mjs +0 -7
  73. package/es/_virtual/_commonjsHelpers.mjs.map +0 -1
  74. package/es/_virtual/ali-oss/dist/aliyun-oss-sdk.mjs +0 -20195
  75. package/es/_virtual/ali-oss/dist/aliyun-oss-sdk.mjs.map +0 -1
  76. package/es/_virtual/aliyun-oss-sdk.mjs +0 -8
  77. package/es/_virtual/aliyun-oss-sdk.mjs.map +0 -1
  78. package/es/_virtual/aliyun-oss-sdk2.mjs +0 -5
  79. package/es/_virtual/aliyun-oss-sdk2.mjs.map +0 -1
  80. package/es/_virtual/ans-javascript-sdk/sdk/AnalysysAgent_JS_SDK.es6.min.mjs +0 -2142
  81. package/es/_virtual/ans-javascript-sdk/sdk/AnalysysAgent_JS_SDK.es6.min.mjs.map +0 -1
  82. package/es/_virtual/xlsx/xlsx.mjs +0 -24583
  83. package/es/_virtual/xlsx/xlsx.mjs.map +0 -1
  84. package/es/index.mjs +0 -35
  85. package/es/index.mjs.map +0 -1
  86. package/es/src/argo-log.mjs +0 -68
  87. package/es/src/argo-log.mjs.map +0 -1
  88. package/es/src/date-transfer.d.ts +0 -20
  89. package/es/src/date-transfer.mjs +0 -62
  90. package/es/src/date-transfer.mjs.map +0 -1
  91. package/es/src/device.d.ts +0 -4
  92. package/es/src/device.mjs +0 -24
  93. package/es/src/device.mjs.map +0 -1
  94. package/es/src/file-operations.mjs +0 -79
  95. package/es/src/file-operations.mjs.map +0 -1
  96. package/es/src/json.d.ts +0 -15
  97. package/es/src/json.mjs +0 -45
  98. package/es/src/json.mjs.map +0 -1
  99. package/es/src/oss-uploader.mjs +0 -89
  100. package/es/src/oss-uploader.mjs.map +0 -1
  101. package/es/src/storage.mjs +0 -81
  102. package/es/src/storage.mjs.map +0 -1
  103. package/es/src/types.d.ts +0 -26
  104. package/es/src/types.mjs +0 -37
  105. package/es/src/types.mjs.map +0 -1
  106. package/es/src/use-api.d.ts +0 -47
  107. package/es/src/use-api.mjs +0 -44
  108. package/es/src/use-api.mjs.map +0 -1
  109. package/es/src/watermark.mjs +0 -147
  110. package/es/src/watermark.mjs.map +0 -1
  111. package/lib/_virtual/_commonjs-dynamic-modules.js +0 -2
  112. package/lib/_virtual/_commonjs-dynamic-modules.js.map +0 -1
  113. package/lib/_virtual/_commonjsHelpers.js +0 -2
  114. package/lib/_virtual/_commonjsHelpers.js.map +0 -1
  115. package/lib/_virtual/ali-oss/dist/aliyun-oss-sdk.js +0 -85
  116. package/lib/_virtual/ali-oss/dist/aliyun-oss-sdk.js.map +0 -1
  117. package/lib/_virtual/aliyun-oss-sdk.js +0 -2
  118. package/lib/_virtual/aliyun-oss-sdk.js.map +0 -1
  119. package/lib/_virtual/aliyun-oss-sdk2.js +0 -2
  120. package/lib/_virtual/aliyun-oss-sdk2.js.map +0 -1
  121. package/lib/_virtual/ans-javascript-sdk/sdk/AnalysysAgent_JS_SDK.es6.min.js +0 -30
  122. package/lib/_virtual/ans-javascript-sdk/sdk/AnalysysAgent_JS_SDK.es6.min.js.map +0 -1
  123. package/lib/_virtual/xlsx/xlsx.js +0 -105
  124. package/lib/_virtual/xlsx/xlsx.js.map +0 -1
  125. package/lib/index.d.ts +0 -10
  126. package/lib/src/argo-log.d.ts +0 -32
  127. package/lib/src/date-transfer.d.ts +0 -20
  128. package/lib/src/device.d.ts +0 -4
  129. package/lib/src/file-operations.d.ts +0 -42
  130. package/lib/src/oss-uploader.d.ts +0 -43
  131. package/lib/src/storage.d.ts +0 -26
  132. package/lib/src/watermark.d.ts +0 -47
@@ -1,2 +1,115 @@
1
- "use strict";var h=Object.defineProperty;var l=(s,e,t)=>e in s?h(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var n=(s,e,t)=>l(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class m{constructor(e="qxs_"){n(this,"prefix");n(this,"local",{has:(e,t=!0)=>{const o=t?`${this.prefix}${e}`:e;return Object.prototype.hasOwnProperty.call(localStorage,o)},get:(e,t=!0)=>{const o=t?`${this.prefix}${e}`:e;return localStorage.getItem(o)},set:(e,t,o=!0)=>{const r=o?`${this.prefix}${e}`:e;localStorage.setItem(r,t)},remove:(e,t=!0)=>{const o=t?`${this.prefix}${e}`:e;localStorage.removeItem(o)},clear:()=>{localStorage.clear()}});n(this,"session",{has:(e,t=!0)=>{const o=t?`${this.prefix}${e}`:e;return Object.prototype.hasOwnProperty.call(sessionStorage,o)},get:(e,t=!0)=>{const o=t?`${this.prefix}${e}`:e;return sessionStorage.getItem(o)},set:(e,t,o=!0)=>{const r=o?`${this.prefix}${e}`:e;sessionStorage.setItem(r,t)},remove:(e,t=!0)=>{const o=t?`${this.prefix}${e}`:e;sessionStorage.removeItem(o)},clear:()=>{sessionStorage.clear()}});n(this,"cookie",{has:(e,t=!0)=>{const o=t?`${this.prefix}${e}`:e;return new RegExp(`(^|;)\\s*${o}=`).test(document.cookie)},get:(e,t=!0)=>{const o=t?`${this.prefix}${e}`:e,r=document.cookie.match(new RegExp(`(^|;)\\s*${o}=([^;]*)`));return r?decodeURIComponent(r[2]):null},set:(e,t,o=1,r="/",c=window.location.hostname,a=!0)=>{const p=a?`${this.prefix}${e}`:e,i=new Date;i.setTime(i.getTime()+o*24*60*60*1e3);const $=`;expires=${i.toUTCString()}`,x=`;path=${r}`,f=c?`;domain=${c}`:"";document.cookie=`${p}=${encodeURIComponent(t)}${$}${x}${f}`},remove:(e,t="/",o=window.location.hostname,r=!0)=>{const c=r?`${this.prefix}${e}`:e,a=`;expires=${new Date(0).toUTCString()}`,p=`;path=${t}`,i=o?`;domain=${o}`:"";document.cookie=`${c}=;${a}${p}${i}`},clear:()=>{const e=document.cookie.match(/[^ =;]+(?==)/g);e&&e.forEach(t=>{document.cookie=`${t}=;expires=${new Date(0).toUTCString()};path=/`})}});this.prefix=e}}exports.Storage=m;
1
+ 'use strict';
2
+
3
+ var __defProp = Object.defineProperty;
4
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true,
8
+ value
9
+ }) : obj[key] = value;
10
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
11
+ class Storage {
12
+ constructor() {
13
+ var _this = this;
14
+ let prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "qxs_";
15
+ __publicField(this, "prefix");
16
+ __publicField(this, "local", {
17
+ has: function (key) {
18
+ let usePrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
19
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
20
+ return Object.prototype.hasOwnProperty.call(localStorage, prefixedKey);
21
+ },
22
+ get: function (key) {
23
+ let usePrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
24
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
25
+ return localStorage.getItem(prefixedKey);
26
+ },
27
+ set: function (key, value) {
28
+ let usePrefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
29
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
30
+ localStorage.setItem(prefixedKey, value);
31
+ },
32
+ remove: function (key) {
33
+ let usePrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
34
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
35
+ localStorage.removeItem(prefixedKey);
36
+ },
37
+ clear: () => {
38
+ localStorage.clear();
39
+ }
40
+ });
41
+ __publicField(this, "session", {
42
+ has: function (key) {
43
+ let usePrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
44
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
45
+ return Object.prototype.hasOwnProperty.call(sessionStorage, prefixedKey);
46
+ },
47
+ get: function (key) {
48
+ let usePrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
49
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
50
+ return sessionStorage.getItem(prefixedKey);
51
+ },
52
+ set: function (key, value) {
53
+ let usePrefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
54
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
55
+ sessionStorage.setItem(prefixedKey, value);
56
+ },
57
+ remove: function (key) {
58
+ let usePrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
59
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
60
+ sessionStorage.removeItem(prefixedKey);
61
+ },
62
+ clear: () => {
63
+ sessionStorage.clear();
64
+ }
65
+ });
66
+ __publicField(this, "cookie", {
67
+ has: function (key) {
68
+ let usePrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
69
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
70
+ return new RegExp(`(^|;)\\s*${prefixedKey}=`).test(document.cookie);
71
+ },
72
+ get: function (key) {
73
+ let usePrefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
74
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
75
+ const match = document.cookie.match(new RegExp(`(^|;)\\s*${prefixedKey}=([^;]*)`));
76
+ return match ? decodeURIComponent(match[2]) : null;
77
+ },
78
+ set: function (key, value) {
79
+ let expires = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
80
+ let path = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "/";
81
+ let domain = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : window.location.hostname;
82
+ let usePrefix = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true;
83
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
84
+ const expiresDate = /* @__PURE__ */new Date();
85
+ expiresDate.setTime(expiresDate.getTime() + expires * 24 * 60 * 60 * 1e3);
86
+ const expiresStr = `;expires=${expiresDate.toUTCString()}`;
87
+ const pathStr = `;path=${path}`;
88
+ const domainStr = domain ? `;domain=${domain}` : "";
89
+ document.cookie = `${prefixedKey}=${encodeURIComponent(value)}${expiresStr}${pathStr}${domainStr}`;
90
+ },
91
+ remove: function (key) {
92
+ let path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "/";
93
+ let domain = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : window.location.hostname;
94
+ let usePrefix = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
95
+ const prefixedKey = usePrefix ? `${_this.prefix}${key}` : key;
96
+ const expiresStr = `;expires=${(/* @__PURE__ */new Date(0)).toUTCString()}`;
97
+ const pathStr = `;path=${path}`;
98
+ const domainStr = domain ? `;domain=${domain}` : "";
99
+ document.cookie = `${prefixedKey}=;${expiresStr}${pathStr}${domainStr}`;
100
+ },
101
+ clear: () => {
102
+ const keys = document.cookie.match(/[^ =;]+(?==)/g);
103
+ if (keys) {
104
+ keys.forEach(key => {
105
+ document.cookie = `${key}=;expires=${(/* @__PURE__ */new Date(0)).toUTCString()};path=/`;
106
+ });
107
+ }
108
+ }
109
+ });
110
+ this.prefix = prefix;
111
+ }
112
+ }
113
+
114
+ exports.Storage = Storage;
2
115
  //# sourceMappingURL=storage.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"storage.js","sources":["../../../../packages/utils/src/storage.ts"],"sourcesContent":["// 使用单例模式\nclass Storage {\n private readonly prefix: string\n\n constructor(prefix = 'qxs_') {\n this.prefix = prefix\n }\n\n local = {\n has: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n return Object.prototype.hasOwnProperty.call(localStorage, prefixedKey)\n },\n get: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n return localStorage.getItem(prefixedKey)\n },\n set: (key: string, value: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n localStorage.setItem(prefixedKey, value)\n },\n remove: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n localStorage.removeItem(prefixedKey)\n },\n clear: () => {\n localStorage.clear()\n },\n }\n\n session = {\n has: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n return Object.prototype.hasOwnProperty.call(sessionStorage, prefixedKey)\n },\n get: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n return sessionStorage.getItem(prefixedKey)\n },\n set: (key: string, value: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n sessionStorage.setItem(prefixedKey, value)\n },\n remove: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n sessionStorage.removeItem(prefixedKey)\n },\n clear: () => {\n sessionStorage.clear()\n },\n }\n\n cookie = {\n has: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n return new RegExp(`(^|;)\\\\s*${prefixedKey}=`).test(document.cookie)\n },\n get: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n const match = document.cookie.match(new RegExp(`(^|;)\\\\s*${prefixedKey}=([^;]*)`))\n return match ? decodeURIComponent(match[2]) : null\n },\n set: (key: string, value: string, expires = 1, path = '/', domain = window.location.hostname, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n const expiresDate = new Date()\n expiresDate.setTime(expiresDate.getTime() + expires * 24 * 60 * 60 * 1000)\n const expiresStr = `;expires=${expiresDate.toUTCString()}`\n const pathStr = `;path=${path}`\n const domainStr = domain ? `;domain=${domain}` : ''\n\n document.cookie = `${prefixedKey}=${encodeURIComponent(value)}${expiresStr}${pathStr}${domainStr}`\n },\n remove: (key: string, path = '/', domain = window.location.hostname, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n const expiresStr = `;expires=${new Date(0).toUTCString()}`\n const pathStr = `;path=${path}`\n const domainStr = domain ? `;domain=${domain}` : ''\n\n document.cookie = `${prefixedKey}=;${expiresStr}${pathStr}${domainStr}`\n },\n clear: () => {\n const keys = document.cookie.match(/[^ =;]+(?==)/g)\n if (keys) {\n keys.forEach((key) => {\n document.cookie = `${key}=;expires=${new Date(0).toUTCString()};path=/`\n })\n }\n },\n }\n}\n\n// 直接导出 Storage 类\nexport { Storage }\n"],"names":["Storage","prefix","__publicField","key","usePrefix","prefixedKey","value","match","expires","path","domain","expiresDate","expiresStr","pathStr","domainStr","keys"],"mappings":"oPACA,MAAMA,CAAQ,CAGZ,YAAYC,EAAS,OAAQ,CAFZC,EAAA,eAMjBA,EAAA,aAAQ,CAC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CAAW,KAAKO,CAAU,GAAGC,CAAO,GAAGC,CAAS,EACvE,EACA,MAAO,IAAM,CACX,MAAMC,EAAO,SAAS,OAAO,MAAM,eAAe,EAC9CA,GACGA,EAAA,QAASZ,GAAQ,CACX,SAAA,OAAS,GAAGA,CAAG,iBAAiB,KAAK,CAAC,EAAE,YAAA,CAAa,SAAA,CAC/D,CACH,CAEJ,GAnFE,KAAK,OAASF,CAAA,CAoFlB"}
1
+ {"version":3,"file":"storage.js","sources":["../../../../packages/utils/src/storage.ts"],"sourcesContent":["// 使用单例模式\nclass Storage {\n private readonly prefix: string\n\n constructor(prefix = 'qxs_') {\n this.prefix = prefix\n }\n\n local = {\n has: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n return Object.prototype.hasOwnProperty.call(localStorage, prefixedKey)\n },\n get: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n return localStorage.getItem(prefixedKey)\n },\n set: (key: string, value: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n localStorage.setItem(prefixedKey, value)\n },\n remove: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n localStorage.removeItem(prefixedKey)\n },\n clear: () => {\n localStorage.clear()\n },\n }\n\n session = {\n has: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n return Object.prototype.hasOwnProperty.call(sessionStorage, prefixedKey)\n },\n get: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n return sessionStorage.getItem(prefixedKey)\n },\n set: (key: string, value: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n sessionStorage.setItem(prefixedKey, value)\n },\n remove: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n sessionStorage.removeItem(prefixedKey)\n },\n clear: () => {\n sessionStorage.clear()\n },\n }\n\n cookie = {\n has: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n return new RegExp(`(^|;)\\\\s*${prefixedKey}=`).test(document.cookie)\n },\n get: (key: string, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n const match = document.cookie.match(new RegExp(`(^|;)\\\\s*${prefixedKey}=([^;]*)`))\n return match ? decodeURIComponent(match[2]) : null\n },\n set: (key: string, value: string, expires = 1, path = '/', domain = window.location.hostname, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n const expiresDate = new Date()\n expiresDate.setTime(expiresDate.getTime() + expires * 24 * 60 * 60 * 1000)\n const expiresStr = `;expires=${expiresDate.toUTCString()}`\n const pathStr = `;path=${path}`\n const domainStr = domain ? `;domain=${domain}` : ''\n\n document.cookie = `${prefixedKey}=${encodeURIComponent(value)}${expiresStr}${pathStr}${domainStr}`\n },\n remove: (key: string, path = '/', domain = window.location.hostname, usePrefix: boolean = true) => {\n const prefixedKey = usePrefix ? `${this.prefix}${key}` : key\n const expiresStr = `;expires=${new Date(0).toUTCString()}`\n const pathStr = `;path=${path}`\n const domainStr = domain ? `;domain=${domain}` : ''\n\n document.cookie = `${prefixedKey}=;${expiresStr}${pathStr}${domainStr}`\n },\n clear: () => {\n const keys = document.cookie.match(/[^ =;]+(?==)/g)\n if (keys) {\n keys.forEach((key) => {\n document.cookie = `${key}=;expires=${new Date(0).toUTCString()};path=/`\n })\n }\n },\n }\n}\n\n// 直接导出 Storage 类\nexport { Storage }\n"],"names":["Storage","constructor","_this","prefix","__publicField","has","key","usePrefix","arguments","length","undefined","prefixedKey","Object","prototype","hasOwnProperty","call","localStorage","get","getItem","set","value","setItem","remove","removeItem","clear","sessionStorage","RegExp","test","document","cookie","match","decodeURIComponent","expires","path","domain","window","location","hostname","expiresDate","Date","setTime","getTime","expiresStr","toU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A,GAAAA,GAAA;AACzD,QAAA,MAAMoC,aAAa,CAAY,SAAA,EAAA,gBAAA,IAAIH,KAAK,CAAC,CAAA,EAAEI,aAAa,CAAA,CAAA;AAClD,QAAA,MAAAC,OAAA,GAAU,CAASX,MAAAA,EAAAA,IAAI,CAAA,CAAA;QAC7B,MAAMY,SAAY,GAAAX,MAAA,GAAS,WAAWA,MAAM,CAAA,CAAK,GAAA,EAAA;QAExCN,QAAA,CAAAC,MAAA,GAAS,CAAGlB,EAAAA,WAAW,CAAK+B,EAAAA,EAAAA,UAAU,CAAGE,EAAAA,OAAO,CAAGC,EAAAA,SAAS,CAAA,CAAA;OACvE;MACArB,OAAOA,MAAM;QACX,MAAMuB,IAAO,GAAAnB,QAAA,CAASC,MAAO,CAAAC,KAAA,CAAM,eAAe,CAAA;AAClD,QAAA,IAAIiB,IAAM,EAAA;AACHA,UAAAA,IAAA,CAAAC,OAAA,CAAS1C,GAAQ,IAAA;AACXsB,YAAAA,QAAA,CAAAC,MAAA,GAAS,CAAGvB,EAAAA,GAAG,aAAA,oBAAiBiC,IAAK,CAAA,CAAC,CAAE,EAAAI,WAAA,EAAa,CAAA,OAAA,CAAA;AAChE,WAAC,CAAA;AACH;AACF;AACF,KAAA,CAAA;IAnFE,IAAA,CAAKxC,MAAS,GAAAA,MAAA;AAChB;AAmFF;;;;"}
package/lib/src/types.js CHANGED
@@ -1,2 +1,47 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=e=>e===void 0,i=e=>typeof e=="boolean",o=e=>typeof e=="number";function r(e){return typeof Element>"u"?!1:e instanceof Element}function s(e){return e===window}function l(e){return/^[\],:{}\s]*$/.test(e.replace(/\\["\\/bfnrtu]/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))&&u(e)}function u(e){try{return JSON.parse(e),!0}catch(n){return console.log("e: ",n),!1}}function c(e){return e.type.startsWith("image/")}function f(e){if(e===null||typeof e!="object")return!1;const n=Object.getPrototypeOf(e);return n===null||n===Object.prototype}exports.isBoolean=i;exports.isElement=r;exports.isImageByMimeType=c;exports.isJSONString=l;exports.isNumber=o;exports.isPlainObject=f;exports.isUndefined=t;exports.isWindow=s;
1
+ 'use strict';
2
+
3
+ const isUndefined = val => val === void 0;
4
+ const isBoolean = val => typeof val === "boolean";
5
+ const isNumber = val => typeof val === "number";
6
+ function isElement(e) {
7
+ if (typeof Element === "undefined") {
8
+ return false;
9
+ }
10
+ return e instanceof Element;
11
+ }
12
+ function isWindow(val) {
13
+ return val === window;
14
+ }
15
+ function isJSONString(str) {
16
+ const jsonStringRegex = /^[\],:{}\s]*$/.test(str.replace(/\\["\\/bfnrtu]/g, "@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]").replace(/(?:^|:|,)(?:\s*\[)+/g, ""));
17
+ return jsonStringRegex && isValidJSON(str);
18
+ }
19
+ function isValidJSON(str) {
20
+ try {
21
+ JSON.parse(str);
22
+ return true;
23
+ } catch (e) {
24
+ console.log("e: ", e);
25
+ return false;
26
+ }
27
+ }
28
+ function isImageByMimeType(file) {
29
+ return file.type.startsWith("image/");
30
+ }
31
+ function isPlainObject(value) {
32
+ if (value === null || typeof value !== "object") {
33
+ return false;
34
+ }
35
+ const proto = Object.getPrototypeOf(value);
36
+ return proto === null || proto === Object.prototype;
37
+ }
38
+
39
+ exports.isBoolean = isBoolean;
40
+ exports.isElement = isElement;
41
+ exports.isImageByMimeType = isImageByMimeType;
42
+ exports.isJSONString = isJSONString;
43
+ exports.isNumber = isNumber;
44
+ exports.isPlainObject = isPlainObject;
45
+ exports.isUndefined = isUndefined;
46
+ exports.isWindow = isWindow;
2
47
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sources":["../../../../packages/utils/src/types.ts"],"sourcesContent":["export const isUndefined = (val: any): val is undefined => val === undefined\nexport const isBoolean = (val: any): val is boolean => typeof val === 'boolean'\nexport const isNumber = (val: any): val is number => typeof val === 'number'\n\nexport function isElement(e: unknown): e is Element {\n if (typeof Element === 'undefined') {\n return false\n }\n return e instanceof Element\n}\n\nexport function isWindow(val: unknown): val is Window {\n return val === window\n}\n\n/**\n * 判断字符串是否为JSON字符串\n * @param str - 要判断的字符串\n * @returns 如果字符串是JSON字符串,则返回true,否则返回false\n */\nexport function isJSONString(str: string) {\n const jsonStringRegex = /^[\\],:{}\\s]*$/\n .test(str.replace(/\\\\[\"\\\\/bfnrtu]/g, '@')\n .replace(/\"[^\"\\\\\\n\\r]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?/g, ']')\n .replace(/(?:^|:|,)(?:\\s*\\[)+/g, ''))\n\n return jsonStringRegex && isValidJSON(str)\n}\n\n/**\n * 判断字符串是否为有效的JSON字符串\n * @param str - 要判断的字符串\n * @returns 如果字符串是有效的JSON字符串,则返回true,否则返回false\n */\nfunction isValidJSON(str: string) {\n try {\n JSON.parse(str)\n return true\n }\n catch (e) {\n console.log('e: ', e)\n return false\n }\n}\n\n/**\n * 通过 MIME 类型判断文件是否为图片\n * @param file - 要检查的文件对象\n * @returns {boolean} 如果文件是图片类型返回 true,否则返回 false\n * @example\n * const file = new File([''], 'test.png', { type: 'image/png' });\n * isImageByMimeType(file); // true\n */\nexport function isImageByMimeType(file: File) {\n return file.type.startsWith('image/')\n}\n\n/**\n * 判断一个值是否为普通对象\n * @param value - 要判断的值\n * @returns 如果值是普通对象,则返回 true,否则返回 false\n */\nexport function isPlainObject(value: unknown): value is Record<string, any> {\n if (value === null || typeof value !== 'object') {\n return false\n }\n\n // 获取原型\n const proto = Object.getPrototypeOf(value)\n\n // 如果没有原型(proto === null),说明是通过 Object.create(null) 创建的\n // 或者原型就是 Object.prototype,说明是普通对象\n return proto === null || proto === Object.prototype\n}\n"],"names":["isUndefined","val","isBoolean","isNumber","isElement","isWindow","isJSONString","str","isValidJSON","e","isImageByMimeType","file","isPlainObject","value","proto"],"mappings":"gFAAa,MAAAA,EAAeC,GAA+BA,IAAQ,OACtDC,EAAaD,GAA6B,OAAOA,GAAQ,UACzDE,EAAYF,GAA4B,OAAOA,GAAQ,SAE7D,SAASG,EAAU,EAA0B,CAC9C,OAAA,OAAO,QAAY,IACd,GAEF,aAAa,OACtB,CAEO,SAASC,EAASJ,EAA6B,CACpD,OAAOA,IAAQ,MACjB,CAOO,SAASK,EAAaC,EAAa,CAMjC,MALiB,gBACrB,KAAKA,EAAI,QAAQ,kBAAmB,GAAG,EACrC,QAAQ,mEAAoE,GAAG,EAC/E,QAAQ,uBAAwB,EAAE,CAAC,GAEdC,EAAYD,CAAG,CAC3C,CAOA,SAASC,EAAYD,EAAa,CAC5B,GAAA,CACF,YAAK,MAAMA,CAAG,EACP,SAEFE,EAAG,CACA,eAAA,IAAI,MAAOA,CAAC,EACb,EAAA,CAEX,CAUO,SAASC,EAAkBC,EAAY,CACrC,OAAAA,EAAK,KAAK,WAAW,QAAQ,CACtC,CAOO,SAASC,EAAcC,EAA8C,CAC1E,GAAIA,IAAU,MAAQ,OAAOA,GAAU,SAC9B,MAAA,GAIH,MAAAC,EAAQ,OAAO,eAAeD,CAAK,EAIlC,OAAAC,IAAU,MAAQA,IAAU,OAAO,SAC5C"}
1
+ {"version":3,"file":"types.js","sources":["../../../../packages/utils/src/types.ts"],"sourcesContent":["export const isUndefined = (val: any): val is undefined => val === undefined\nexport const isBoolean = (val: any): val is boolean => typeof val === 'boolean'\nexport const isNumber = (val: any): val is number => typeof val === 'number'\n\nexport function isElement(e: unknown): e is Element {\n if (typeof Element === 'undefined') {\n return false\n }\n return e instanceof Element\n}\n\nexport function isWindow(val: unknown): val is Window {\n return val === window\n}\n\n/**\n * 判断字符串是否为JSON字符串\n * @param str - 要判断的字符串\n * @returns 如果字符串是JSON字符串,则返回true,否则返回false\n */\nexport function isJSONString(str: string) {\n const jsonStringRegex = /^[\\],:{}\\s]*$/\n .test(str.replace(/\\\\[\"\\\\/bfnrtu]/g, '@')\n .replace(/\"[^\"\\\\\\n\\r]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?/g, ']')\n .replace(/(?:^|:|,)(?:\\s*\\[)+/g, ''))\n\n return jsonStringRegex && isValidJSON(str)\n}\n\n/**\n * 判断字符串是否为有效的JSON字符串\n * @param str - 要判断的字符串\n * @returns 如果字符串是有效的JSON字符串,则返回true,否则返回false\n */\nfunction isValidJSON(str: string) {\n try {\n JSON.parse(str)\n return true\n }\n catch (e) {\n console.log('e: ', e)\n return false\n }\n}\n\n/**\n * 通过 MIME 类型判断文件是否为图片\n * @param file - 要检查的文件对象\n * @returns {boolean} 如果文件是图片类型返回 true,否则返回 false\n * @example\n * const file = new File([''], 'test.png', { type: 'image/png' });\n * isImageByMimeType(file); // true\n */\nexport function isImageByMimeType(file: File) {\n return file.type.startsWith('image/')\n}\n\n/**\n * 判断一个值是否为普通对象\n * @param value - 要判断的值\n * @returns 如果值是普通对象,则返回 true,否则返回 false\n */\nexport function isPlainObject(value: unknown): value is Record<string, any> {\n if (value === null || typeof value !== 'object') {\n return false\n }\n\n // 获取原型\n const proto = Object.getPrototypeOf(value)\n\n // 如果没有原型(proto === null),说明是通过 Object.create(null) 创建的\n // 或者原型就是 Object.prototype,说明是普通对象\n return proto === null || proto === Object.prototype\n}\n"],"names":["isUndefined","val","isBoolean","isNumber","isElement","e","Element","isWindow","window","isJSONString","str","jsonStringRegex","test","replace","isValidJSON","JSON","parse","console","log","isImageByMimeType","file","type","startsWith","isPlainObject","value","proto","Object","getPrototypeOf","prototype"],"mappings":";;AAAa,MAAAA,WAAA,GAAeC,GAAA,IAA+BA,GAAQ,KAAA;AAC5D,MAAMC,SAAY,GAACD,GAA6B,IAAA,OAAOA,GAAQ,KAAA;AAC/D,MAAME,QAAW,GAACF,GAA4B,IAAA,OAAOA,GAAQ,KAAA;AAE7D,SAASG,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}):r[s]=e;var a=(r,s,e)=>l(r,typeof s!="symbol"?s+"":s,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./types.js"),i=class i{constructor(s,e){a(this,"useApi",async(s,e,u)=>{let d=null,o=null;try{const t={...s,...["GET"].includes(s.method.toUpperCase())?{params:e}:{data:e}};t.url=(t.proxyPrefix||"")+s.url,delete t.proxyPrefix;const n=await this.apiInstance(t);d=u?n.data:n.data.data}catch(t){if(this.axiosInstance.isAxiosError(t)){const{statusText:n="",status:h}=t.response||{};console.log(n?`${n}:${h}`:JSON.stringify(t))}else this.isAxiosResponse(t)?o=t.data:this.isErrorResponse(t)&&(o=t)}return{res:d,error:o}});if(this.apiInstance=s,this.axiosInstance=e,i.instance)return i.instance;i.instance=this}isBusinessError(s){return p.isPlainObject(s)&&typeof s.message=="string"&&typeof s.code=="number"&&s.code!==0}isAxiosResponse(s){return p.isPlainObject(s)&&s.data!==void 0&&this.isBusinessError(s.data)&&s.status!==void 0&&s.statusText!==void 0&&s.headers!==void 0&&s.config!==void 0&&s.request!==void 0}isErrorResponse(s){return"code"in s&&"data"in s&&"message"in s&&s.code!==0}};a(i,"instance");let c=i;exports.ApiService=c;
1
+ 'use strict';
2
+
3
+ var types = require('./types.js');
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {
7
+ enumerable: true,
8
+ configurable: true,
9
+ writable: true,
10
+ value
11
+ }) : obj[key] = value;
12
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
13
+ const _ApiService = class _ApiService {
14
+ constructor(apiInstance) {
15
+ this.apiInstance = apiInstance;
16
+ __publicField(this, "useApi", async (axiosConfig, params, isWholeResponse) => {
17
+ let res = null;
18
+ let error = null;
19
+ try {
20
+ const config = {
21
+ ...axiosConfig,
22
+ ...(["GET"].includes(axiosConfig.method.toUpperCase()) ? {
23
+ params
24
+ } : {
25
+ data: params
26
+ })
27
+ };
28
+ config.url = (config.proxyPrefix || "") + axiosConfig.url;
29
+ delete config.proxyPrefix;
30
+ const response = await this.apiInstance(config);
31
+ res = isWholeResponse ? response.data : response.data.data;
32
+ } catch (err) {
33
+ if (err.name !== "AxiosError") {
34
+ if (this.isAxiosResponse(err)) {
35
+ error = err.data;
36
+ } else if (this.isErrorResponse(err)) {
37
+ error = err;
38
+ }
39
+ } else {
40
+ console.error(err);
41
+ }
42
+ }
43
+ return {
44
+ res,
45
+ error
46
+ };
47
+ });
48
+ if (_ApiService.instance) {
49
+ return _ApiService.instance;
50
+ }
51
+ _ApiService.instance = this;
52
+ }
53
+ isBusinessError(obj) {
54
+ return types.isPlainObject(obj) && typeof obj.message === "string" && typeof obj.code === "number" && obj.code !== 0;
55
+ }
56
+ isAxiosResponse(value) {
57
+ return types.isPlainObject(value) && value.data !== void 0 && this.isBusinessError(value.data) && value.status !== void 0 && value.statusText !== void 0 && value.headers !== void 0 && value.config !== void 0 && value.request !== void 0;
58
+ }
59
+ isErrorResponse(value) {
60
+ return "code" in value && "data" in value && "message" in value && value.code !== 0;
61
+ }
62
+ };
63
+ __publicField(_ApiService, "instance");
64
+ let ApiService = _ApiService;
65
+
66
+ exports.ApiService = ApiService;
2
67
  //# sourceMappingURL=use-api.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-api.js","sources":["../../../../packages/utils/src/use-api.ts"],"sourcesContent":["import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosStatic } from 'axios'\nimport { isPlainObject } from './types'\n\nexport interface SuccessResponse<T> {\n code: number\n count: number\n data: T\n message: string\n}\n\nexport interface ErrorResponse {\n code: number\n data: null\n message: string\n}\n\nexport interface UseApiResponse<W extends boolean = false, T = unknown> {\n res: W extends true ? SuccessResponse<T> : T\n error: ErrorResponse | null\n}\n\nexport interface UrlObjectType {\n url: string\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'\n proxyPrefix?: string\n}\n\nexport type ApiTypeMap<U extends UrlObjectType> = {\n [K in U['url']]: {\n request: any\n response: any\n }\n}\n\ntype RequestPayload<T> = T extends { data: any } ? T['data'] : T\ntype RequestParams<T> = T extends { params: any } ? T['params'] : T\n\nexport class ApiService<\n T extends ApiTypeMap<U>,\n U extends UrlObjectType,\n> {\n private static instance: ApiService<any, any>\n\n constructor(\n private apiInstance: AxiosInstance,\n private axiosInstance: AxiosStatic,\n ) {\n if (ApiService.instance) {\n return ApiService.instance as ApiService<T, U>\n }\n ApiService.instance = this\n }\n\n private isBusinessError(obj: ErrorResponse): boolean {\n return isPlainObject(obj)\n && typeof obj.message === 'string'\n && typeof obj.code === 'number'\n && obj.code !== 0\n }\n\n private isAxiosResponse(value: any): value is AxiosResponse {\n return isPlainObject(value)\n && value.data !== undefined\n && this.isBusinessError(value.data)\n && value.status !== undefined\n && value.statusText !== undefined\n && value.headers !== undefined\n && value.config !== undefined\n && value.request !== undefined\n }\n\n private isErrorResponse(value: any): value is ErrorResponse {\n return 'code' in value && 'data' in value && 'message' in value && value.code !== 0\n }\n\n public useApi = async <\n K extends U,\n W extends boolean = false,\n >(\n axiosConfig: Omit<AxiosRequestConfig<RequestPayload<T[K['url']]['request']>>, 'params'> & K & {\n params?: RequestParams<T[K['url']]['request']>\n },\n params?: RequestParams<T[K['url']]['request']>,\n isWholeResponse?: W,\n ): Promise<UseApiResponse<W, T[K['url']]['response']>> => {\n let res: UseApiResponse<W, T[K['url']]['response']>['res'] | null = null\n let error: UseApiResponse['error'] = null\n\n try {\n const config = {\n ...axiosConfig,\n ...(['GET'].includes(axiosConfig.method.toUpperCase()) ? { params } : { data: params }),\n }\n\n config.url = (config.proxyPrefix || '') + axiosConfig.url\n delete config.proxyPrefix\n\n const response = await this.apiInstance<SuccessResponse<T[K['url']]['response']>>(config)\n res = isWholeResponse\n ? response.data\n : response.data.data\n }\n catch (err) {\n if (this.axiosInstance.isAxiosError(err)) {\n const { statusText = '', status } = err.response || {}\n console.log(statusText ? `${statusText}:${status}` : JSON.stringify(err))\n }\n else if (this.isAxiosResponse(err)) {\n error = err.data\n }\n else if (this.isErrorResponse(err)) {\n error = err\n }\n }\n\n return { res: res!, error }\n }\n}\n"],"names":["_ApiService","apiInstance","axiosInstance","__publicField","axiosConfig","params","isWholeResponse","res","error","config","response","err","statusText","status","obj","isPlainObject","value","ApiService"],"mappings":"kRAqCaA,EAAN,MAAMA,CAGX,CAGA,YACUC,EACAC,EACR,CA6BKC,EAAA,cAAS,MAIdC,EAGAC,EACAC,IACwD,CACxD,IAAIC,EAAgE,KAChEC,EAAiC,KAEjC,GAAA,CACF,MAAMC,EAAS,CACb,GAAGL,EACH,GAAI,CAAC,KAAK,EAAE,SAASA,EAAY,OAAO,YAAa,CAAA,EAAI,CAAE,OAAAC,GAAW,CAAE,KAAMA,CAAO,CACvF,EAEAI,EAAO,KAAOA,EAAO,aAAe,IAAML,EAAY,IACtD,OAAOK,EAAO,YAEd,MAAMC,EAAW,MAAM,KAAK,YAAsDD,CAAM,EACxFF,EAAMD,EACFI,EAAS,KACTA,EAAS,KAAK,WAEbC,EAAK,CACV,GAAI,KAAK,cAAc,aAAaA,CAAG,EAAG,CACxC,KAAM,CAAE,WAAAC,EAAa,GAAI,OAAAC,GAAWF,EAAI,UAAY,CAAC,EAC7C,QAAA,IAAIC,EAAa,GAAGA,CAAU,IAAIC,CAAM,GAAK,KAAK,UAAUF,CAAG,CAAC,CAEjE,MAAA,KAAK,gBAAgBA,CAAG,EAC/BH,EAAQG,EAAI,KAEL,KAAK,gBAAgBA,CAAG,IACvBH,EAAAG,EACV,CAGK,MAAA,CAAE,IAAAJ,EAAW,MAAAC,CAAM,CAC5B,GArEE,GAHQ,KAAA,YAAAP,EACA,KAAA,cAAAC,EAEJF,EAAW,SACb,OAAOA,EAAW,SAEpBA,EAAW,SAAW,IAAA,CAGhB,gBAAgBc,EAA6B,CACnD,OAAOC,EAAc,cAAAD,CAAG,GACnB,OAAOA,EAAI,SAAY,UACvB,OAAOA,EAAI,MAAS,UACpBA,EAAI,OAAS,CAAA,CAGZ,gBAAgBE,EAAoC,CACnD,OAAAD,EAAA,cAAcC,CAAK,GACrBA,EAAM,OAAS,QACf,KAAK,gBAAgBA,EAAM,IAAI,GAC/BA,EAAM,SAAW,QACjBA,EAAM,aAAe,QACrBA,EAAM,UAAY,QAClBA,EAAM,SAAW,QACjBA,EAAM,UAAY,MAAA,CAGjB,gBAAgBA,EAAoC,CAC1D,MAAO,SAAUA,GAAS,SAAUA,GAAS,YAAaA,GAASA,EAAM,OAAS,CAAA,CA6CtF,EA5EEb,EAJWH,EAII,YAJV,IAAMiB,EAANjB"}
1
+ {"version":3,"file":"use-api.js","sources":["../../../../packages/utils/src/use-api.ts"],"sourcesContent":["import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'\nimport { isPlainObject } from './types'\n\nexport interface SuccessResponse<T> {\n code: number\n count: number\n data: T\n message: string\n}\n\nexport interface ErrorResponse {\n code: number\n data: null\n message: string\n}\n\nexport interface UseApiResponse<W extends boolean = false, T = unknown> {\n res: W extends true ? SuccessResponse<T> : T\n error: ErrorResponse | null\n}\n\nexport interface UrlObjectType {\n url: string\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'\n proxyPrefix?: string\n}\n\nexport type ApiTypeMap<U extends UrlObjectType> = {\n [K in U['url']]: {\n request: any\n response: any\n }\n}\n\ntype RequestPayload<T> = T extends { data: any } ? T['data'] : T\ntype RequestParams<T> = T extends { params: any } ? T['params'] : T\n\nexport class ApiService<\n T extends ApiTypeMap<U>,\n U extends UrlObjectType,\n> {\n private static instance: ApiService<any, any>\n\n constructor(\n private apiInstance: AxiosInstance,\n ) {\n if (ApiService.instance) {\n return ApiService.instance as ApiService<T, U>\n }\n ApiService.instance = this\n }\n\n private isBusinessError(obj: ErrorResponse): boolean {\n return isPlainObject(obj)\n && typeof obj.message === 'string'\n && typeof obj.code === 'number'\n && obj.code !== 0\n }\n\n private isAxiosResponse(value: any): value is AxiosResponse {\n return isPlainObject(value)\n && value.data !== undefined\n && this.isBusinessError(value.data)\n && value.status !== undefined\n && value.statusText !== undefined\n && value.headers !== undefined\n && value.config !== undefined\n && value.request !== undefined\n }\n\n private isErrorResponse(value: any): value is ErrorResponse {\n return 'code' in value && 'data' in value && 'message' in value && value.code !== 0\n }\n\n public useApi = async <\n K extends U,\n W extends boolean = false,\n >(\n axiosConfig: Omit<AxiosRequestConfig<RequestPayload<T[K['url']]['request']>>, 'params'> & K & {\n params?: RequestParams<T[K['url']]['request']>\n },\n params?: RequestParams<T[K['url']]['request']>,\n isWholeResponse?: W,\n ): Promise<UseApiResponse<W, T[K['url']]['response']>> => {\n let res: UseApiResponse<W, T[K['url']]['response']>['res'] | null = null\n let error: UseApiResponse['error'] = null\n\n try {\n const config = {\n ...axiosConfig,\n ...(['GET'].includes(axiosConfig.method.toUpperCase()) ? { params } : { data: params }),\n }\n\n config.url = (config.proxyPrefix || '') + axiosConfig.url\n delete config.proxyPrefix\n\n const response = await this.apiInstance<SuccessResponse<T[K['url']]['response']>>(config)\n res = isWholeResponse\n ? response.data\n : response.data.data\n }\n catch (err: any) {\n if (err.name !== 'AxiosError') {\n if (this.isAxiosResponse(err)) {\n error = err.data\n }\n else if (this.isErrorResponse(err)) {\n error = err\n }\n }\n else {\n console.error(err)\n }\n }\n\n return { res: res!, error }\n }\n}\n"],"names":["_ApiService","constructor","apiInstance","__publicField","axiosConfig","params","isWholeResponse","res","error","config","includes","method","toUpperCase","data","url","proxyPrefix","response","err","name","isAxiosResponse","isErrorResponse","console","instance","isBusinessError","obj","isPlainObject","message","code","value","status","statusText","headers","request","ApiService"],"mappings":";;;;;;;;;;;;AAqCO,MAAMA,WAAA,GAAN,MAAMA,WAGX,CAAA;EAGAC,YACUC,WACR,EAAA;IADQ,IAAA,CAAAA,WAAA,GAAAA,WAAA;IA8BVC,aAAA,CAAA,IAAA,EAAO,QAAS,EAAA,OAIdC,WAGA,EAAAC,MAAA,EACAC,eACwD,KAAA;MACxD,IAAIC,GAA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AI,CAAAG,IAAA,KAAS,QACpB,IAAAH,GAAA,CAAIG,IAAS,KAAA,CAAA;AACpB;EAEQR,gBAAgBS,KAAoC,EAAA;IACnD,OAAAH,mBAAA,CAAcG,KAAK,CAAA,IACrBA,KAAM,CAAAf,IAAA,KAAS,UACf,IAAK,CAAAU,eAAA,CAAgBK,KAAM,CAAAf,IAAI,CAC/B,IAAAe,KAAA,CAAMC,WAAW,MACjB,IAAAD,KAAA,CAAME,UAAe,KAAA,MAAA,IACrBF,KAAM,CAAAG,OAAA,KAAY,UAClBH,KAAM,CAAAnB,MAAA,KAAW,MACjB,IAAAmB,KAAA,CAAMI,OAAY,KAAA,MAAA;AACzB;EAEQZ,gBAAgBQ,KAAoC,EAAA;AAC1D,IAAA,OAAO,UAAUA,KAAS,IAAA,MAAA,IAAUA,SAAS,SAAa,IAAAA,KAAA,IAASA,MAAMD,IAAS,KAAA,CAAA;AACpF;AA6CF,CAAA;AA5EExB,aAAA,CAJWH,WAII,EAAA,UAAA,CAAA;AAJV,IAAMiC,UAAN,GAAAjC;;;;"}
@@ -1,24 +1,119 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const $={id:"wm_div_id",prefix:"mask_div_id",text:"测试水印",x:0,y:0,rows:0,cols:0,width:0,height:0,x_space:100,y_space:40,font:"微软雅黑",color:"black",fontsize:"18px",alpha:.15,angle:15,parent_width:0,parent_height:0,parent_node:null,monitor:!0};function C(t,r,c){const u=document.createElement("canvas").getContext("2d");if(!u)return{width:100,height:100};u.font=`${c} ${r}`;const s=u.measureText(t.trim()),l=Number.parseFloat(c),p=s.actualBoundingBoxAscent!==void 0&&s.actualBoundingBoxDescent!==void 0?s.actualBoundingBoxAscent+s.actualBoundingBoxDescent:l;return{width:Math.ceil(s.width),height:Math.ceil(p)}}function M(){const t={...$};let r=!1;const c=new MutationObserver(k),w=new ResizeObserver(()=>{r||l(t)});function u(i,e){const h=i-t.x,n=e-t.y,o=t.x_space||20,d=t.y_space||20,m=Math.ceil(h/(t.width+o)),g=Math.ceil(n/(t.height+d));return{cols:m,rows:g,x_space:o,y_space:d}}function s(i,e,h){const n=document.createElement("div");return n.textContent=t.text,n.id=`${t.prefix}${h}`,n.style.cssText=`
2
- transform: rotate(-${t.angle}deg);
1
+ 'use strict';
2
+
3
+ const initialSettings = {
4
+ id: "wm_div_id",
5
+ prefix: "mask_div_id",
6
+ text: "\u6D4B\u8BD5\u6C34\u5370",
7
+ x: 0,
8
+ y: 0,
9
+ rows: 0,
10
+ cols: 0,
11
+ width: 0,
12
+ height: 0,
13
+ x_space: 100,
14
+ y_space: 40,
15
+ font: "\u5FAE\u8F6F\u96C5\u9ED1",
16
+ color: "black",
17
+ fontsize: "18px",
18
+ alpha: 0.15,
19
+ angle: 15,
20
+ parent_width: 0,
21
+ parent_height: 0,
22
+ parent_node: null,
23
+ monitor: true
24
+ };
25
+ function calculateTextDimensions(text, font, fontSize) {
26
+ const canvas = document.createElement("canvas");
27
+ const context = canvas.getContext("2d");
28
+ if (!context) {
29
+ return {
30
+ width: 100,
31
+ height: 100
32
+ };
33
+ }
34
+ context.font = `${fontSize} ${font}`;
35
+ const metrics = context.measureText(text.trim());
36
+ const fontSizeNum = Number.parseFloat(fontSize);
37
+ const height = metrics.actualBoundingBoxAscent !== void 0 && metrics.actualBoundingBoxDescent !== void 0 ? metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent : fontSizeNum;
38
+ return {
39
+ width: Math.ceil(metrics.width),
40
+ height: Math.ceil(height)
41
+ };
42
+ }
43
+ function watermark() {
44
+ const globalSetting = {
45
+ ...initialSettings
46
+ };
47
+ let forceRemove = false;
48
+ const watermarkDom = new MutationObserver(domChangeCallback);
49
+ const resizeObserver = new ResizeObserver(() => {
50
+ if (!forceRemove) {
51
+ loadMark(globalSetting);
52
+ }
53
+ });
54
+ function calculateWatermarkLayout(pageWidth, pageHeight) {
55
+ const availableWidth = pageWidth - globalSetting.x;
56
+ const availableHeight = pageHeight - globalSetting.y;
57
+ const x_space = globalSetting.x_space || 20;
58
+ const y_space = globalSetting.y_space || 20;
59
+ const cols = Math.ceil(availableWidth / (globalSetting.width + x_space));
60
+ const rows = Math.ceil(availableHeight / (globalSetting.height + y_space));
61
+ return {
62
+ cols,
63
+ rows,
64
+ x_space,
65
+ y_space
66
+ };
67
+ }
68
+ function createWatermarkElement(x, y, index) {
69
+ const maskDiv = document.createElement("div");
70
+ maskDiv.textContent = globalSetting.text;
71
+ maskDiv.id = `${globalSetting.prefix}${index}`;
72
+ maskDiv.style.cssText = `
73
+ transform: rotate(-${globalSetting.angle}deg);
3
74
  position: absolute;
4
- left: ${i}px;
5
- top: ${e}px;
75
+ left: ${x}px;
76
+ top: ${y}px;
6
77
  overflow: hidden;
7
78
  z-index: 9999999;
8
- opacity: ${t.alpha};
9
- font-size: ${t.fontsize};
10
- font-family: ${t.font};
11
- color: ${t.color};
79
+ opacity: ${globalSetting.alpha};
80
+ font-size: ${globalSetting.fontsize};
81
+ font-family: ${globalSetting.font};
82
+ color: ${globalSetting.color};
12
83
  text-align: center;
13
- width: ${t.width}px;
14
- height: ${t.height}px;
15
- line-height: ${t.height}px;
84
+ width: ${globalSetting.width}px;
85
+ height: ${globalSetting.height}px;
86
+ line-height: ${globalSetting.height}px;
16
87
  display: flex;
17
88
  align-items: center;
18
89
  justify-content: center;
19
90
  user-select: none;
20
91
  visibility: visible;
21
- `.replace(/\s+/g," ").trim(),n}function l(i){if(p(),Object.assign(t,i),t.width===0&&t.height===0||t.width===0||t.height===0){const a=C(t.text,t.font,t.fontsize),f=10;t.width===0&&(t.width=a.width+f),t.height===0&&(t.height=a.height+f)}const e=t.parent_node||document.body,h=Math.max(e.scrollWidth,e.clientWidth),n=Math.max(e.scrollHeight,e.clientHeight),o=document.createElement("div");o.id=t.id,e.closest("body")&&getComputedStyle(e).position==="static"&&(e.style.position="relative"),o.style.cssText=`
92
+ `.replace(/\s+/g, " ").trim();
93
+ return maskDiv;
94
+ }
95
+ function loadMark(settings) {
96
+ removeMark();
97
+ Object.assign(globalSetting, settings);
98
+ if (globalSetting.width === 0 && globalSetting.height === 0 || globalSetting.width === 0 || globalSetting.height === 0) {
99
+ const textDimensions = calculateTextDimensions(globalSetting.text, globalSetting.font, globalSetting.fontsize);
100
+ const padding = 10;
101
+ if (globalSetting.width === 0) {
102
+ globalSetting.width = textDimensions.width + padding;
103
+ }
104
+ if (globalSetting.height === 0) {
105
+ globalSetting.height = textDimensions.height + padding;
106
+ }
107
+ }
108
+ const parentElement = globalSetting.parent_node || document.body;
109
+ const pageWidth = Math.max(parentElement.scrollWidth, parentElement.clientWidth);
110
+ const pageHeight = Math.max(parentElement.scrollHeight, parentElement.clientHeight);
111
+ const watermarkContainer = document.createElement("div");
112
+ watermarkContainer.id = globalSetting.id;
113
+ if (parentElement.closest("body") && getComputedStyle(parentElement).position === "static") {
114
+ parentElement.style.position = "relative";
115
+ }
116
+ watermarkContainer.style.cssText = `
22
117
  pointer-events: none;
23
118
  display: block;
24
119
  position: absolute;
@@ -28,5 +123,89 @@
28
123
  height: 100%;
29
124
  z-index: 9999999;
30
125
  overflow: hidden;
31
- `.replace(/\s+/g," ").trim();const d=o.attachShadow?o.attachShadow({mode:"open"}):o;e.appendChild(o);const{cols:m,rows:g,x_space:v,y_space:y}=u(h,n);t.cols=m,t.rows=g,t.x_space=v,t.y_space=y;const b=document.createDocumentFragment();for(let a=0;a<g;a++){const f=t.y+(t.height+y)*a;for(let x=0;x<m;x++){const _=t.x+(t.width+v)*x;b.appendChild(s(_,f,a*m+x))}}if(d.appendChild(b),t.monitor){w.observe(e);const a={attributes:!0,childList:!0,subtree:!0,characterData:!0};c.observe(o,a),d!==o&&c.observe(d,a)}}function p(){var e;const i=document.getElementById(t.id);c.disconnect(),i&&((e=i.parentNode)==null||e.removeChild(i))}function k(i){if(r){r=!1;return}if(!document.getElementById(t.id)){l(t);return}i.some(n=>n.type==="childList"||n.type==="attributes"||n.type==="characterData")&&l(t)}return{addMark:l,removeMark:()=>{r=!0,p()}}}exports.watermark=M;
126
+ `.replace(/\s+/g, " ").trim();
127
+ const shadowRoot = watermarkContainer.attachShadow ? watermarkContainer.attachShadow({
128
+ mode: "open"
129
+ }) : watermarkContainer;
130
+ parentElement.appendChild(watermarkContainer);
131
+ const {
132
+ cols,
133
+ rows,
134
+ x_space,
135
+ y_space
136
+ } = calculateWatermarkLayout(pageWidth, pageHeight);
137
+ globalSetting.cols = cols;
138
+ globalSetting.rows = rows;
139
+ globalSetting.x_space = x_space;
140
+ globalSetting.y_space = y_space;
141
+ const fragment = document.createDocumentFragment();
142
+ for (let i = 0; i < rows; i++) {
143
+ const y = globalSetting.y + (globalSetting.height + y_space) * i;
144
+ for (let j = 0; j < cols; j++) {
145
+ const x = globalSetting.x + (globalSetting.width + x_space) * j;
146
+ fragment.appendChild(createWatermarkElement(x, y, i * cols + j));
147
+ }
148
+ }
149
+ shadowRoot.appendChild(fragment);
150
+ if (globalSetting.monitor) {
151
+ resizeObserver.observe(parentElement);
152
+ const config = {
153
+ attributes: true,
154
+ // 监听属性变化
155
+ childList: true,
156
+ // 监听子元素变化
157
+ subtree: true,
158
+ // 监听子树变化
159
+ characterData: true
160
+ // 监听文本内容变化
161
+ };
162
+ watermarkDom.observe(watermarkContainer, config);
163
+ if (shadowRoot !== watermarkContainer) {
164
+ watermarkDom.observe(shadowRoot, config);
165
+ }
166
+ }
167
+ }
168
+ function removeMark() {
169
+ const watermarkElement = document.getElementById(globalSetting.id);
170
+ watermarkDom.disconnect();
171
+ if (watermarkElement) {
172
+ watermarkElement.parentNode?.removeChild(watermarkElement);
173
+ }
174
+ }
175
+ function domChangeCallback(records) {
176
+ if (forceRemove) {
177
+ forceRemove = false;
178
+ return;
179
+ }
180
+ const watermarkElement = document.getElementById(globalSetting.id);
181
+ if (!watermarkElement) {
182
+ loadMark(globalSetting);
183
+ return;
184
+ }
185
+ const hasChanges = records.some(record => {
186
+ if (record.type === "childList") {
187
+ return true;
188
+ }
189
+ if (record.type === "attributes") {
190
+ return true;
191
+ }
192
+ if (record.type === "characterData") {
193
+ return true;
194
+ }
195
+ return false;
196
+ });
197
+ if (hasChanges) {
198
+ loadMark(globalSetting);
199
+ }
200
+ }
201
+ return {
202
+ addMark: loadMark,
203
+ removeMark: () => {
204
+ forceRemove = true;
205
+ removeMark();
206
+ }
207
+ };
208
+ }
209
+
210
+ exports.watermark = watermark;
32
211
  //# sourceMappingURL=watermark.js.map