@jolibox/implement 1.1.4-beta.10

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 (195) hide show
  1. package/.eslintrc.js +13 -0
  2. package/.rush/temp/package-deps_build.json +105 -0
  3. package/.rush/temp/shrinkwrap-deps.json +79 -0
  4. package/README.md +1 -0
  5. package/dist/common/api-factory/index.d.ts +21 -0
  6. package/dist/common/api-factory/validator/__tests__/validate/any.test.d.ts +1 -0
  7. package/dist/common/api-factory/validator/__tests__/validate/array.test.d.ts +1 -0
  8. package/dist/common/api-factory/validator/__tests__/validate/arraybuffer.test.d.ts +1 -0
  9. package/dist/common/api-factory/validator/__tests__/validate/boolean.test.d.ts +1 -0
  10. package/dist/common/api-factory/validator/__tests__/validate/enum.test.d.ts +1 -0
  11. package/dist/common/api-factory/validator/__tests__/validate/function.test.d.ts +1 -0
  12. package/dist/common/api-factory/validator/__tests__/validate/literal.test.d.ts +1 -0
  13. package/dist/common/api-factory/validator/__tests__/validate/nullish.test.d.ts +1 -0
  14. package/dist/common/api-factory/validator/__tests__/validate/number.test.d.ts +1 -0
  15. package/dist/common/api-factory/validator/__tests__/validate/object.test.d.ts +1 -0
  16. package/dist/common/api-factory/validator/__tests__/validate/or.test.d.ts +1 -0
  17. package/dist/common/api-factory/validator/__tests__/validate/record.test.d.ts +1 -0
  18. package/dist/common/api-factory/validator/__tests__/validate/string.test.d.ts +1 -0
  19. package/dist/common/api-factory/validator/__tests__/validate/symbol.test.d.ts +1 -0
  20. package/dist/common/api-factory/validator/__tests__/validate/tuple.test.d.ts +1 -0
  21. package/dist/common/api-factory/validator/__tests__/validate/type-asserts.test.d.ts +1 -0
  22. package/dist/common/api-factory/validator/__tests__/validate/utils.test.d.ts +1 -0
  23. package/dist/common/api-factory/validator/index.d.ts +29 -0
  24. package/dist/common/api-factory/validator/validate.d.ts +119 -0
  25. package/dist/common/can-i-use.d.ts +2 -0
  26. package/dist/common/context/index.d.ts +16 -0
  27. package/dist/common/context/types.d.ts +5 -0
  28. package/dist/common/context/url-parse.d.ts +22 -0
  29. package/dist/common/http/index.d.ts +13 -0
  30. package/dist/common/http/uuid.d.ts +2 -0
  31. package/dist/common/http/xua.d.ts +17 -0
  32. package/dist/common/report/base-tracker.d.ts +13 -0
  33. package/dist/common/report/create-trace.d.ts +7 -0
  34. package/dist/common/report/errors/error-types.d.ts +122 -0
  35. package/dist/common/report/errors/index.d.ts +13 -0
  36. package/dist/common/report/errors/report/index.d.ts +51 -0
  37. package/dist/common/report/errors/report/listeners.d.ts +1 -0
  38. package/dist/common/report/index.d.ts +3 -0
  39. package/dist/common/report/task-track/index.d.ts +25 -0
  40. package/dist/common/report/track.d.ts +3 -0
  41. package/dist/common/report/types.d.ts +75 -0
  42. package/dist/h5/ads/ads-action-detection.d.ts +6 -0
  43. package/dist/h5/ads/anti-cheating.d.ts +61 -0
  44. package/dist/h5/ads/index.d.ts +275 -0
  45. package/dist/h5/api/base.d.ts +13 -0
  46. package/dist/h5/api/get-system-info.d.ts +1 -0
  47. package/dist/h5/api/index.d.ts +4 -0
  48. package/dist/h5/api/lifecycle.d.ts +1 -0
  49. package/dist/h5/api/storage.d.ts +27 -0
  50. package/dist/h5/api/task.d.ts +1 -0
  51. package/dist/h5/bootstrap/index.d.ts +1 -0
  52. package/dist/h5/http/index.d.ts +33 -0
  53. package/dist/h5/http/utils/__tests__/uuid.test.d.ts +1 -0
  54. package/dist/h5/http/utils/__tests__/xua.test.d.ts +1 -0
  55. package/dist/h5/http/utils/index.d.ts +14 -0
  56. package/dist/h5/http/utils/session.d.ts +1 -0
  57. package/dist/h5/report/errors/index.d.ts +4 -0
  58. package/dist/h5/report/event-tracker.d.ts +8 -0
  59. package/dist/h5/report/index.d.ts +10 -0
  60. package/dist/h5/report/task-tracker.d.ts +18 -0
  61. package/dist/index.d.ts +3 -0
  62. package/dist/index.js +13 -0
  63. package/dist/index.native.d.ts +2 -0
  64. package/dist/index.native.js +3 -0
  65. package/dist/native/api/ads.d.ts +1 -0
  66. package/dist/native/api/base.d.ts +13 -0
  67. package/dist/native/api/get-system-info.d.ts +1 -0
  68. package/dist/native/api/index.d.ts +8 -0
  69. package/dist/native/api/keyboard.d.ts +9 -0
  70. package/dist/native/api/lifecycle.d.ts +1 -0
  71. package/dist/native/api/login.d.ts +1 -0
  72. package/dist/native/api/request.d.ts +1 -0
  73. package/dist/native/api/storage.d.ts +25 -0
  74. package/dist/native/api/task.d.ts +1 -0
  75. package/dist/native/bootstrap/bridge.d.ts +4 -0
  76. package/dist/native/bootstrap/index.d.ts +1 -0
  77. package/dist/native/js-bridge/const.d.ts +5 -0
  78. package/dist/native/js-bridge/index.d.ts +2 -0
  79. package/dist/native/js-bridge/invoke.d.ts +21 -0
  80. package/dist/native/js-bridge/js-bridge.d.ts +6 -0
  81. package/dist/native/js-bridge/report.d.ts +63 -0
  82. package/dist/native/js-bridge/subscribe.d.ts +8 -0
  83. package/dist/native/js-bridge/types.d.ts +14 -0
  84. package/dist/native/js-bridge/utils.d.ts +17 -0
  85. package/dist/native/js-core/index.d.ts +3 -0
  86. package/dist/native/js-core/jolibox-js-core.d.ts +45 -0
  87. package/dist/native/js-core/message-port.d.ts +12 -0
  88. package/dist/native/js-core/utils.d.ts +7 -0
  89. package/dist/native/network/create-fetch.d.ts +27 -0
  90. package/dist/native/network/index.d.ts +11 -0
  91. package/dist/native/network/report.d.ts +15 -0
  92. package/dist/native/network/types.d.ts +61 -0
  93. package/dist/native/network/utils.d.ts +9 -0
  94. package/dist/native/report/errors/index.d.ts +4 -0
  95. package/dist/native/report/index.d.ts +10 -0
  96. package/dist/native/report/task-tracker.d.ts +24 -0
  97. package/dist/utils/index.d.ts +0 -0
  98. package/esbuild.config.js +66 -0
  99. package/implement.build.log +9 -0
  100. package/package.json +30 -0
  101. package/src/common/api-factory/index.ts +188 -0
  102. package/src/common/api-factory/validator/__tests__/validate/any.test.ts +68 -0
  103. package/src/common/api-factory/validator/__tests__/validate/array.test.ts +402 -0
  104. package/src/common/api-factory/validator/__tests__/validate/arraybuffer.test.ts +48 -0
  105. package/src/common/api-factory/validator/__tests__/validate/boolean.test.ts +27 -0
  106. package/src/common/api-factory/validator/__tests__/validate/enum.test.ts +106 -0
  107. package/src/common/api-factory/validator/__tests__/validate/function.test.ts +54 -0
  108. package/src/common/api-factory/validator/__tests__/validate/literal.test.ts +130 -0
  109. package/src/common/api-factory/validator/__tests__/validate/nullish.test.ts +41 -0
  110. package/src/common/api-factory/validator/__tests__/validate/number.test.ts +147 -0
  111. package/src/common/api-factory/validator/__tests__/validate/object.test.ts +131 -0
  112. package/src/common/api-factory/validator/__tests__/validate/or.test.ts +96 -0
  113. package/src/common/api-factory/validator/__tests__/validate/record.test.ts +274 -0
  114. package/src/common/api-factory/validator/__tests__/validate/string.test.ts +187 -0
  115. package/src/common/api-factory/validator/__tests__/validate/symbol.test.ts +23 -0
  116. package/src/common/api-factory/validator/__tests__/validate/tuple.test.ts +86 -0
  117. package/src/common/api-factory/validator/__tests__/validate/type-asserts.test.ts +13 -0
  118. package/src/common/api-factory/validator/__tests__/validate/utils.test.ts +44 -0
  119. package/src/common/api-factory/validator/index.ts +107 -0
  120. package/src/common/api-factory/validator/validate.ts +641 -0
  121. package/src/common/can-i-use.ts +19 -0
  122. package/src/common/context/index.ts +85 -0
  123. package/src/common/context/types.ts +5 -0
  124. package/src/common/context/url-parse.ts +63 -0
  125. package/src/common/http/index.ts +29 -0
  126. package/src/common/http/uuid.ts +11 -0
  127. package/src/common/http/xua.ts +79 -0
  128. package/src/common/report/base-tracker.ts +134 -0
  129. package/src/common/report/create-trace.ts +17 -0
  130. package/src/common/report/errors/error-types.ts +206 -0
  131. package/src/common/report/errors/index.ts +20 -0
  132. package/src/common/report/errors/report/index.ts +63 -0
  133. package/src/common/report/errors/report/listeners.ts +80 -0
  134. package/src/common/report/index.ts +3 -0
  135. package/src/common/report/task-track/index.ts +102 -0
  136. package/src/common/report/track.ts +49 -0
  137. package/src/common/report/types.ts +90 -0
  138. package/src/h5/ads/ads-action-detection.ts +31 -0
  139. package/src/h5/ads/anti-cheating.ts +244 -0
  140. package/src/h5/ads/index.ts +658 -0
  141. package/src/h5/api/base.ts +9 -0
  142. package/src/h5/api/get-system-info.ts +59 -0
  143. package/src/h5/api/index.ts +4 -0
  144. package/src/h5/api/lifecycle.ts +95 -0
  145. package/src/h5/api/storage.ts +173 -0
  146. package/src/h5/api/task.ts +190 -0
  147. package/src/h5/bootstrap/index.ts +16 -0
  148. package/src/h5/http/index.ts +189 -0
  149. package/src/h5/http/utils/__tests__/uuid.test.ts +16 -0
  150. package/src/h5/http/utils/__tests__/xua.test.ts +27 -0
  151. package/src/h5/http/utils/index.ts +19 -0
  152. package/src/h5/http/utils/session.ts +10 -0
  153. package/src/h5/report/errors/index.ts +40 -0
  154. package/src/h5/report/event-tracker.ts +40 -0
  155. package/src/h5/report/index.ts +56 -0
  156. package/src/h5/report/task-tracker.ts +42 -0
  157. package/src/index.native.ts +7 -0
  158. package/src/index.ts +9 -0
  159. package/src/native/api/ads.ts +52 -0
  160. package/src/native/api/base.ts +8 -0
  161. package/src/native/api/get-system-info.ts +44 -0
  162. package/src/native/api/index.ts +8 -0
  163. package/src/native/api/keyboard.ts +75 -0
  164. package/src/native/api/lifecycle.ts +76 -0
  165. package/src/native/api/login.ts +73 -0
  166. package/src/native/api/request.ts +154 -0
  167. package/src/native/api/storage.ts +287 -0
  168. package/src/native/api/task.ts +227 -0
  169. package/src/native/bootstrap/bridge.ts +59 -0
  170. package/src/native/bootstrap/index.ts +59 -0
  171. package/src/native/js-bridge/const.ts +11 -0
  172. package/src/native/js-bridge/index.ts +2 -0
  173. package/src/native/js-bridge/invoke.ts +210 -0
  174. package/src/native/js-bridge/js-bridge.ts +23 -0
  175. package/src/native/js-bridge/report.ts +311 -0
  176. package/src/native/js-bridge/subscribe.ts +50 -0
  177. package/src/native/js-bridge/types.ts +26 -0
  178. package/src/native/js-bridge/utils.ts +116 -0
  179. package/src/native/js-core/index.ts +4 -0
  180. package/src/native/js-core/jolibox-js-core.ts +188 -0
  181. package/src/native/js-core/message-port.ts +52 -0
  182. package/src/native/js-core/utils.ts +9 -0
  183. package/src/native/network/create-fetch.ts +237 -0
  184. package/src/native/network/index.ts +15 -0
  185. package/src/native/network/report.ts +58 -0
  186. package/src/native/network/types.ts +77 -0
  187. package/src/native/network/utils.ts +90 -0
  188. package/src/native/report/errors/index.ts +27 -0
  189. package/src/native/report/index.ts +51 -0
  190. package/src/native/report/task-tracker.ts +72 -0
  191. package/src/native/types/global.d.ts +26 -0
  192. package/src/native/types/native-method-map.d.ts +282 -0
  193. package/src/native/types/native-method.d.ts +30 -0
  194. package/src/utils/index.ts +0 -0
  195. package/tsconfig.json +18 -0
@@ -0,0 +1,76 @@
1
+ import { BaseError, createCommands, wrapUserFunction, hostEmitter } from '@jolibox/common';
2
+ import { createAPI, createSyncAPI, registerCanIUse, t } from './base';
3
+ import { reportError } from '@/common/report/errors/report';
4
+ import { applyNative, onNative } from '../bootstrap/bridge';
5
+ import { nativeTaskEmitter } from '../report';
6
+
7
+ const EXIT_GAME = 'exitGame';
8
+ const ON_READY = 'onReady';
9
+ const ON_SHOW = 'onJoliboxShow';
10
+ const ON_HIDE = 'onJoliboxHide';
11
+
12
+ const commands = createCommands();
13
+
14
+ const safeCallbackWrapper = wrapUserFunction(reportError as (err: Error | BaseError) => void);
15
+ const exitGame = createAPI(EXIT_GAME, {
16
+ paramsSchema: t.tuple(t.function()),
17
+ implement: async (onBeforeExit: () => void) => {
18
+ const safeCallback = safeCallbackWrapper(onBeforeExit);
19
+ // 集中上报
20
+ safeCallback.call(this);
21
+ await applyNative('exitAppAsync');
22
+ }
23
+ });
24
+
25
+ const onShow = createSyncAPI(ON_SHOW, {
26
+ paramsSchema: t.tuple(t.function()),
27
+ implement(callback) {
28
+ const safeCallback = safeCallbackWrapper(callback);
29
+ onNative('onJoliboxEnterForeground', () => {
30
+ safeCallback.call(this);
31
+ nativeTaskEmitter.emit('visible', true);
32
+ });
33
+ }
34
+ });
35
+
36
+ const onHide = createSyncAPI(ON_HIDE, {
37
+ paramsSchema: t.tuple(t.function()),
38
+ implement(callback) {
39
+ const safeCallback = safeCallbackWrapper(callback);
40
+ onNative('onJoliboxEnterBackground', () => {
41
+ safeCallback.call(this);
42
+ nativeTaskEmitter.emit('visible', false);
43
+ });
44
+ }
45
+ });
46
+
47
+ const onReadyHandler = createSyncAPI(ON_READY, {
48
+ paramsSchema: t.tuple(t.function()),
49
+ implement(callback) {
50
+ const safeCallback = safeCallbackWrapper(callback);
51
+ hostEmitter.on('LifecycleEvent.onReady', (info) => {
52
+ safeCallback(info);
53
+ });
54
+ }
55
+ });
56
+
57
+ commands.registerCommand('LifecycleSDK.exit', exitGame);
58
+ commands.registerCommand('LifecycleSDK.onReady', onReadyHandler);
59
+ commands.registerCommand('LifecycleSDK.onJoliboxShow', onShow);
60
+ commands.registerCommand('LifecycleSDK.onJoliboxHide', onHide);
61
+
62
+ registerCanIUse('lifeCycle.exit', {
63
+ version: '1.0.0' // mock
64
+ });
65
+
66
+ registerCanIUse('lifeCycle.onReady', {
67
+ version: '1.0.0' // mock
68
+ });
69
+
70
+ registerCanIUse('lifeCycle.onJoliboxShow', {
71
+ version: '1.0.0' // mock
72
+ });
73
+
74
+ registerCanIUse('lifeCycle.onJoliboxHide', {
75
+ version: '1.0.0' // mock
76
+ });
@@ -0,0 +1,73 @@
1
+ import { context } from '@/common/context';
2
+ import { applyNative, invokeNative, onNative } from '../bootstrap/bridge';
3
+ import { createAPI, t, registerCanIUse } from './base';
4
+ import { APIError, createCommands, Deferred, hostEmitter } from '@jolibox/common';
5
+ import { createAPIError } from '@/common/report/errors';
6
+
7
+ registerCanIUse('login', {
8
+ version: '1.0.0',
9
+ properties: {
10
+ force: '1.0.0'
11
+ },
12
+ success: {
13
+ errMsg: '1.0.0',
14
+ code: '1.0.0',
15
+ token: '1.0.0',
16
+ isLogin: '1.0.0'
17
+ }
18
+ });
19
+ registerCanIUse('checkSession', {
20
+ version: '1.0.0',
21
+ success: {
22
+ errMsg: '1.0.0'
23
+ }
24
+ });
25
+
26
+ const login = createAPI('login', {
27
+ async implement() {
28
+ const {
29
+ data: { isLogin }
30
+ } = await applyNative('checkLoginAsync');
31
+ if (isLogin) {
32
+ return { isLogin: true, token: context.hostUserInfo?.token };
33
+ }
34
+ onNative('onLoginStateChange', ({ isLogin, token, uuid }) => {
35
+ if (uuid == loginUUID) {
36
+ resolve({ isLogin, token });
37
+ }
38
+ });
39
+ const res = invokeNative('loginSync');
40
+
41
+ const {
42
+ data: { uuid: loginUUID }
43
+ } = res;
44
+ if (!loginUUID) {
45
+ throw createAPIError({
46
+ code: -1,
47
+ msg: 'login failed'
48
+ });
49
+ }
50
+ const { promise, resolve } = new Deferred<{ isLogin: boolean; token?: string }>();
51
+
52
+ const loginRes = await promise;
53
+ context.onEnvConfigChanged({ hostUserInfo: loginRes });
54
+ hostEmitter.emit('onLoginComplete', loginRes);
55
+
56
+ return loginRes;
57
+ }
58
+ });
59
+
60
+ const checkSession = createAPI('checkSession', {
61
+ async implement() {
62
+ const {
63
+ data: { isLogin }
64
+ } = await applyNative('checkLoginAsync');
65
+ return {
66
+ isLogin
67
+ };
68
+ }
69
+ });
70
+
71
+ const commands = createCommands();
72
+ commands.registerCommand('API.login', login);
73
+ commands.registerCommand('API.checkSession', checkSession);
@@ -0,0 +1,154 @@
1
+ import { createAPIError } from '@/common/report/errors';
2
+ import { createFetch } from '../network/create-fetch';
3
+ import { createAPI, registerCanIUse, t } from './base';
4
+ import { dirtyURL, normalizeHeader, normalizeMethod, normalizeTimeout } from '../network/utils';
5
+ import { BaseError, createCommands, Deferred, wrapUserFunction } from '@jolibox/common';
6
+ import { AnyFunction, ResponseType } from '@jolibox/types';
7
+ import { reportError } from '@/common/report/errors/report';
8
+ import { FetchOptions } from '../network/types';
9
+
10
+ const LIMIT = 15;
11
+
12
+ const publicFetch = createFetch('createRequestTaskSync', 'operateRequestTaskSync', {
13
+ type: 'public'
14
+ });
15
+
16
+ /** current active count */
17
+ let activeCount = 0;
18
+
19
+ const deferQueue: AnyFunction[] = [];
20
+
21
+ const safeCallbackWrapper = wrapUserFunction(reportError as (err: Error | BaseError) => void);
22
+
23
+ const remove = <T>(array: T[], predicate: (item: T) => boolean) => {
24
+ const removedElements = array.filter(predicate);
25
+
26
+ const remainingElements = array.filter((item) => !predicate(item));
27
+ array.length = 0;
28
+ array.push(...remainingElements);
29
+
30
+ return removedElements;
31
+ };
32
+
33
+ const request = (_params: unknown) => {
34
+ const deferred = new Deferred<{
35
+ code: ResponseType;
36
+ data?: string | JSON | ArrayBuffer | undefined;
37
+ message: string;
38
+ }>();
39
+
40
+ let teardown = () => {
41
+ // noop
42
+ };
43
+
44
+ const _request = createAPI('request', {
45
+ paramsSchema: t.tuple(
46
+ t.object({
47
+ url: t.string(),
48
+ method: t.string(),
49
+ header: t.object(),
50
+ data: t.object().optional(),
51
+ query: t.object().optional(),
52
+ dataType: t.string().default('json'),
53
+ responseType: t.string().default('text'),
54
+ enableCache: t.boolean().default(false),
55
+ appendHostCookie: t.boolean().default(true),
56
+ timeout: t.number().default(30000),
57
+ success: t.function(),
58
+ fail: t.function()
59
+ })
60
+ ),
61
+ implement(params) {
62
+ const action = async () => {
63
+ const failCallback = safeCallbackWrapper(params.fail);
64
+ try {
65
+ activeCount += 1;
66
+
67
+ // 在 action 执行前, 如果用户就调用了 abort 的话就会命中该逻辑
68
+ if (deferred.state !== 'pending') {
69
+ return;
70
+ }
71
+ const { data, dataType, responseType, enableCache, appendHostCookie } = params;
72
+
73
+ const header = normalizeHeader(params.header);
74
+ const method = normalizeMethod(params.method);
75
+ const timeout = normalizeTimeout(params.timeout);
76
+ const url = dirtyURL(params.url, method, data);
77
+ const successCallback = safeCallbackWrapper(params.success);
78
+
79
+ const _params = Object.assign({}, params, {
80
+ method,
81
+ header,
82
+ data: method === 'GET' || method === 'HEAD' ? undefined : data, // GET HEAD 请求不需要 data 参数
83
+ enableCache,
84
+ query: params.query ?? ({} as Record<string, string>),
85
+ dataType,
86
+ responseType,
87
+ appendHostCookie
88
+ }) as FetchOptions;
89
+
90
+ if (timeout) _params['timeout'] = timeout;
91
+
92
+ const task = publicFetch<string | ArrayBuffer | JSON>(url, _params);
93
+
94
+ {
95
+ const { response } = await task;
96
+ const { code, data, message } = response;
97
+
98
+ deferred.resolve({
99
+ code: (code ?? 'SUCCESS') as ResponseType,
100
+ data,
101
+ message: message ?? 'request:ok'
102
+ });
103
+
104
+ successCallback({
105
+ code: 'SUCCESS',
106
+ message: 'request:ok',
107
+ data
108
+ });
109
+ }
110
+ } catch (err) {
111
+ deferred.reject(err as Error);
112
+ failCallback({
113
+ code: 'FAILURE',
114
+ message: 'httpRequst: failed'
115
+ });
116
+ } finally {
117
+ activeCount -= 1;
118
+ deferQueue.shift()?.();
119
+ }
120
+ };
121
+
122
+ if (activeCount >= LIMIT) {
123
+ teardown = () => {
124
+ remove(deferQueue, (i) => i === action);
125
+ };
126
+ deferQueue.push(action);
127
+ } else {
128
+ void action();
129
+ }
130
+
131
+ return deferred.promise;
132
+ }
133
+ });
134
+
135
+ _request(_params);
136
+
137
+ return {
138
+ /**
139
+ * 1. requesting...
140
+ * 2. not in deferred
141
+ */
142
+ abort() {
143
+ deferred.reject(createAPIError({ code: -1, msg: 'request:fail abort' }));
144
+ teardown();
145
+ }
146
+ };
147
+ };
148
+
149
+ const commands = createCommands();
150
+
151
+ commands.registerCommand('HttpSDK.request', request);
152
+ registerCanIUse('request', {
153
+ version: '1.0.0'
154
+ });
@@ -0,0 +1,287 @@
1
+ import { createAPI, createSyncAPI, registerCanIUse, t } from './base';
2
+ import { applyNative, invokeNative } from '../bootstrap/bridge';
3
+ import { createCommands } from '@jolibox/common';
4
+ import { innerFetch as fetch } from '../network';
5
+ import { context } from '@/common/context';
6
+ import { API_CODE, StandardResponse, StorageResponse } from '@jolibox/types';
7
+
8
+ const commands = createCommands();
9
+
10
+ const getStorage = createAPI('getLocalStorage', {
11
+ paramsSchema: t.tuple(t.string()),
12
+ async implement(key) {
13
+ const { response } = await fetch<
14
+ StorageResponse<{
15
+ key: string;
16
+ value: string | null;
17
+ }>
18
+ >(`/api/games/user-storage/${context.mpId}`, {
19
+ method: 'GET',
20
+ responseType: 'json',
21
+ appendHostCookie: true,
22
+ query: {
23
+ key
24
+ }
25
+ });
26
+ const {
27
+ data: { code, message, data: originData }
28
+ } = await response;
29
+
30
+ if (code === 'SUCCESS') {
31
+ return {
32
+ code: code as API_CODE,
33
+ message,
34
+ data: originData?.value
35
+ };
36
+ }
37
+
38
+ try {
39
+ const {
40
+ data: { data, dataType }
41
+ } = await applyNative('getLocalStorageAsync', { key });
42
+ const parsedData = parse(data, dataType);
43
+ return {
44
+ code,
45
+ message: `${message}. fallback to native`,
46
+ data: parsedData
47
+ };
48
+ } catch (error) {
49
+ return {
50
+ code: 'INTERNAL_ERROR',
51
+ message: '[Jolibox SDK] get local storage failed',
52
+ data: null
53
+ };
54
+ }
55
+ }
56
+ });
57
+
58
+ commands.registerCommand('StorageSDK.getItem', getStorage);
59
+
60
+ registerCanIUse('storage.getItem', {
61
+ version: '1.0.0',
62
+ properties: {
63
+ key: '1.0.0',
64
+ value: '1.0.0'
65
+ }
66
+ });
67
+
68
+ const setStorage = createAPI('setStorage', {
69
+ paramsSchema: t.tuple(t.string(), t.or(t.string(), t.boolean(), t.number())),
70
+ async implement(key, value) {
71
+ const gameId = context.mpId;
72
+ const valueToStore = typeof value == 'string' ? value : String(value);
73
+ const { response } = await fetch<StorageResponse<void>>(`/api/games/user-storage/${gameId}`, {
74
+ method: 'POST',
75
+ responseType: 'json',
76
+ appendHostCookie: true,
77
+ data: {
78
+ key,
79
+ value: valueToStore
80
+ }
81
+ });
82
+
83
+ const {
84
+ data: { code, message }
85
+ } = response;
86
+ const dataType = getType(value);
87
+ const data = stringify(value, dataType);
88
+ // 同步备份
89
+ await applyNative('setLocalStorageAsync', {
90
+ key,
91
+ data,
92
+ dataType
93
+ });
94
+
95
+ if (code == 'SUCCESS') {
96
+ return {
97
+ code,
98
+ message
99
+ };
100
+ } else {
101
+ return {
102
+ code,
103
+ message: `${message}. fallback to native`
104
+ } as StandardResponse<void>;
105
+ }
106
+ }
107
+ });
108
+
109
+ commands.registerCommand('StorageSDK.setItem', setStorage);
110
+
111
+ registerCanIUse('storage.setItem', {
112
+ version: '1.0.0',
113
+ properties: {
114
+ key: '1.0.0',
115
+ value: '1.0.0'
116
+ }
117
+ });
118
+
119
+ /**
120
+ * 移除指定key
121
+ */
122
+ export const removeStorage = createAPI('removeStorage', {
123
+ paramsSchema: t.tuple(t.string()),
124
+ async implement(key) {
125
+ const gameId = context.mpId;
126
+ const { response } = await fetch<StorageResponse<void>>(`/api/games/user-storage/${gameId}/remove`, {
127
+ method: 'POST',
128
+ responseType: 'json',
129
+ appendHostCookie: true,
130
+ data: {
131
+ key
132
+ }
133
+ });
134
+
135
+ const {
136
+ data: { code, message }
137
+ } = response;
138
+ await applyNative('removeLocalStorageAsync', { key });
139
+ if (code === 'SUCCESS') {
140
+ return {
141
+ code,
142
+ message
143
+ };
144
+ } else {
145
+ return {
146
+ code,
147
+ message: '[Jolibox SDK] remove item succ'
148
+ } as StandardResponse<void>;
149
+ }
150
+ }
151
+ });
152
+
153
+ commands.registerCommand('StorageSDK.removeItem', removeStorage);
154
+
155
+ registerCanIUse('storage.removeItem', {
156
+ version: '1.0.0',
157
+ properties: {
158
+ key: '1.0.0'
159
+ }
160
+ });
161
+
162
+ /**
163
+ * 清理本地数据缓存
164
+ */
165
+ const clearStorage = createAPI('clearStorage', {
166
+ async implement() {
167
+ const gameId = context.mpId;
168
+ const { response } = await fetch<StorageResponse<void>>(`/api/games/user-storage/${gameId}/clear`, {
169
+ method: 'POST',
170
+ appendHostCookie: true
171
+ });
172
+ applyNative('clearLocalStorageAsync');
173
+ const {
174
+ data: { code, message }
175
+ } = response;
176
+ if (code === 'SUCCESS') {
177
+ return {
178
+ code,
179
+ message
180
+ };
181
+ }
182
+
183
+ return {
184
+ code,
185
+ message: `${message}.fallback to native`
186
+ } as StandardResponse<void>;
187
+ }
188
+ });
189
+
190
+ commands.registerCommand('StorageSDK.clear', clearStorage);
191
+
192
+ registerCanIUse('storage.clear', {
193
+ version: '1.0.0'
194
+ });
195
+
196
+ /**
197
+ * 异步获取当前storage的相关信息
198
+ */
199
+ export const getStorageInfo = createAPI('getStorageInfo', {
200
+ async implement() {
201
+ const { data } = await applyNative('getStorageInfoAsync');
202
+ return data;
203
+ }
204
+ });
205
+
206
+ registerCanIUse('getStorageInfo', {
207
+ version: '1.0.0',
208
+ success: {
209
+ keys: '1.0.0', // string[] 本地数据缓存中的所有键名列表,如本地数据则返回空数组
210
+ currentSize: '1.0.0', // number 当前占用的空间大小,以 KB 为单位
211
+ limitSize: '1.0.0' // number 存储空间上限,以 KB 为单位,一般来说会返回 10240
212
+ }
213
+ });
214
+
215
+ /**
216
+ * 同步获取当前storage的相关信息
217
+ */
218
+ export const getStorageInfoSync = createSyncAPI('getStorageInfoSync', {
219
+ implement() {
220
+ return invokeNative('getStorageInfoSync');
221
+ }
222
+ });
223
+
224
+ const DATA_TYPE = [
225
+ 'string',
226
+ 'number',
227
+ 'boolean',
228
+ 'object',
229
+ '' // 表示不支持的类型
230
+ ] as const;
231
+
232
+ type DataType = typeof DATA_TYPE[number];
233
+
234
+ function getType(data: unknown): DataType {
235
+ const type = Object.prototype.toString
236
+ .call(data)
237
+ .split(' ')[1]
238
+ .split(']')[0]
239
+ .toLocaleLowerCase() as DataType;
240
+
241
+ if (DATA_TYPE.includes(type)) {
242
+ return type;
243
+ }
244
+ return '';
245
+ }
246
+
247
+ /**
248
+ * 解析数据
249
+ */
250
+ function parse(str: string, type: string) {
251
+ try {
252
+ switch (type) {
253
+ case 'string':
254
+ return str;
255
+ case 'object':
256
+ return JSON.parse(str);
257
+ case 'number':
258
+ return parseFloat(str);
259
+ case 'boolean':
260
+ return str === 'true';
261
+ default:
262
+ return '';
263
+ }
264
+ } catch {
265
+ return '';
266
+ }
267
+ }
268
+
269
+ /**
270
+ * 序列化数据
271
+ */
272
+ function stringify(data: unknown, type: DataType) {
273
+ try {
274
+ switch (type) {
275
+ case 'string':
276
+ case 'number':
277
+ case 'boolean':
278
+ return `${data}`;
279
+ case 'object':
280
+ return JSON.stringify(data);
281
+ default:
282
+ return '';
283
+ }
284
+ } catch {
285
+ return '';
286
+ }
287
+ }