UNPKG

t-comm

Version:

专业、稳定、纯粹的工具库

95 lines (91 loc) 3.16 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); /** * Cocos Network 子模块 - 默认实现集合 * * 把 `init.ts` 中的默认 storage / 默认 getLoginCode 抽出来, * 同时供 `cocos/env` 复用(环境切换的持久化也走同一份默认实现)。 * * - defaultStorage:基于 Cocos `sys.localStorage` → 浏览器 `localStorage` → 内存 * 的三级回退;get 自动 JSON 解析、set 自动 JSON 序列化、removeItem 删除。 * - defaultGetLoginCode:优先 `wx.login`,wx 不存在时返回空 code。 */ /** * 运行时获取 Cocos `sys.localStorage`(优先)或浏览器 `localStorage`。 * 两者 API 一致:getItem / setItem / removeItem。 * 避免编译期硬依赖 `cc` 模块。 */ function getDefaultLocalStorage() { var _a; var g = typeof globalThis !== 'undefined' ? globalThis : {}; // Cocos Creator 3.x 会把 sys 挂到全局(cc.sys / window.cc.sys) var cocosSys = ((_a = g.cc) === null || _a === void 0 ? void 0 : _a.sys) || g.sys; if (cocosSys === null || cocosSys === void 0 ? void 0 : cocosSys.localStorage) return cocosSys.localStorage; if (g.localStorage) return g.localStorage; return null; } /** 内存兜底(cocos sys.localStorage / 浏览器 localStorage 都不可用时使用) */ var memoryStore = {}; /** * 默认 storage:Cocos `sys.localStorage` → 浏览器 `localStorage` → 内存兜底。 * * - `get`:自动尝试 `JSON.parse`,失败则原样返回字符串 * - `set`:非字符串值自动 `JSON.stringify`;传 `null/undefined` 等价 `removeItem` * - `removeItem`:删除指定 key */ var defaultStorage = { get: function get(key) { var _a; var ls = getDefaultLocalStorage(); var raw = ls ? ls.getItem(key) : (_a = memoryStore[key]) !== null && _a !== void 0 ? _a : null; if (raw == null || raw === '') return null; try { return JSON.parse(raw); } catch (_b) { return raw; } }, set: function set(key, value) { if (value == null) { defaultStorage.removeItem(key); return; } var str = typeof value === 'string' ? value : JSON.stringify(value); var ls = getDefaultLocalStorage(); if (ls) { ls.setItem(key, str); return; } memoryStore[key] = str; }, removeItem: function removeItem(key) { var ls = getDefaultLocalStorage(); if (ls) { ls.removeItem(key); return; } delete memoryStore[key]; } }; /** 默认 getLoginCode:优先用 `wx.login`,`wx` 不存在则返回空 code */ var defaultGetLoginCode = function defaultGetLoginCode() { var g = typeof globalThis !== 'undefined' ? globalThis : {}; var wxObj = g.wx; if (!wxObj || typeof wxObj.login !== 'function') { return Promise.resolve({ code: '' }); } return new Promise(function (resolve, reject) { wxObj.login({ success: function success(r) { return resolve({ code: (r === null || r === void 0 ? void 0 : r.code) || '' }); }, fail: reject }); }); }; exports.defaultGetLoginCode = defaultGetLoginCode; exports.defaultStorage = defaultStorage;