@bytedance/mona-client-web
Version:
web for mona
252 lines • 12.1 kB
JavaScript
// function queryStringify(params: Record<string, any>, inBody?: boolean) {
// const items: string[] = [];
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
// function itemStringify(obj: Record<string, any>, prefix: string) {
// const type = Object.prototype.toString.call(obj);
// if (type === '[object Array]') {
// obj.forEach((item: Record<string, any>, key: any) => {
// itemStringify(item, `${prefix}[${key}]`);
// });
// } else if (type === '[object Object]') {
// for (const key in obj) {
// itemStringify(obj[key], `${prefix}[${key}]`);
// }
// } else if (type === '[object Date]') {
// items.push(`${prefix}=${obj.toISOString()}`);
// } else if (type === '[object Null]') {
// items.push(`${prefix}=`);
// } else if (type !== '[object Undefined]') {
// items.push(`${prefix}=${encodeURIComponent(obj)}`);
// }
// }
// for (const k in params) {
// itemStringify(params[k], k);
// }
// const str = items.join('&');
// return str && !inBody ? `?${str}` : str;
// }
function canUseEval() {
try {
(function () { }).constructor('return window.fetch')();
}
catch (error) {
return false;
}
return true;
}
var useEval = canUseEval();
export var MyFetch = useEval ? (function () { }).constructor('return window.fetch')() : window.fetch;
function getTokenByCookie(name) {
var reg = new RegExp("^".concat(name, "="));
try {
var myCookie = (function () { }).constructor('return document.cookie')();
var arr = myCookie.split(';').map(function (i) { return i.trim(); });
var token = '';
for (var i = 0; i < arr.length; i++) {
if (reg.test(arr[i])) {
token = arr[i].replace("".concat(name, "="), '');
break;
}
}
return token || '';
}
catch (_a) { }
return '';
}
// const fromCompass =
// /compass\.jinritemai\.com/.test(location.href) || /ecom-compass-boe\.bytedance\.net/.test(location.href);
// const fromDmall = /dmall\.jinritemai\.com/.test(location.href) || /dmall-boe\.bytedance\.net/.test(location.href);
// const fromEcom = /\.jinritemai\.com/.test(location.href) || /\.bytedance\.net/.test(location.href);
export function getTokenInfoByDomain() {
return {
'x-open-client': 'doudian',
'x-open-microapp': getTokenByCookie('PHPSESSID') || getTokenByCookie('PHPSESSID_SS') || '',
};
}
function getLightAppToken(req) {
var headers = __assign({ 'Content-Type': 'application/json' }, getTokenInfoByDomain());
return MyFetch("https://lgw.jinritemai.com/open/tokenForApp?appId=".concat(req.appId), { method: 'GET', headers: headers });
}
function getAppIdByUrl() {
var _a, _b, _c, _d;
try {
// @ts-ignore 兜底
return (_d = (_c = (_b = (_a = (window.__mona_public_path__ || window.__webpack_public_path__)) === null || _a === void 0 ? void 0 : _a.split('cmp-ecom-open-pigeon-plugin/')) === null || _b === void 0 ? void 0 : _b[1]) === null || _c === void 0 ? void 0 : _c.split('/')) === null || _d === void 0 ? void 0 : _d[0];
}
catch (error) { }
}
export function getAppId() {
var _a;
var ee = new Error();
var pp = new Promise(function () { });
return (((_a = window.__MONA_LIGHT_APP_LIFE_CYCLE_LANUCH_QUERY) === null || _a === void 0 ? void 0 : _a.appId) ||
getAppIdByUrl() ||
(
// @ts-ignore 兜底
pp === null || pp === void 0 ? void 0 : pp.appId) ||
(
// @ts-ignore 兜底
ee === null || ee === void 0 ? void 0 : ee.appId) ||
'');
}
export var APP_ID = getAppId();
var Token = /** @class */ (function () {
function Token(appId) {
this._appId = appId || APP_ID || getAppId();
this._lightAppTokenKey = this._appId;
this._tokenMap = new Map();
}
Token.prototype.getToken = function () {
return __awaiter(this, void 0, void 0, function () {
var _a, _tokenMap, _lightAppTokenKey, val, currentTime;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
_a = this, _tokenMap = _a._tokenMap, _lightAppTokenKey = _a._lightAppTokenKey;
if (!_tokenMap.has(_lightAppTokenKey)) return [3 /*break*/, 3];
val = _tokenMap.get(_lightAppTokenKey);
currentTime = Math.ceil(Date.now() / 1000);
if (!(currentTime > val.expire)) return [3 /*break*/, 2];
return [4 /*yield*/, this.fetchToken()];
case 1: return [2 /*return*/, _b.sent()];
case 2: return [2 /*return*/, _tokenMap.get(_lightAppTokenKey).token];
case 3: return [4 /*yield*/, this.fetchToken()];
case 4: return [2 /*return*/, _b.sent()];
}
});
});
};
Token.prototype.fetchToken = function () {
return __awaiter(this, void 0, void 0, function () {
var _a, _appId, _tokenMap, _lightAppTokenKey, data, data, respData;
var _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
_a = this, _appId = _a._appId, _tokenMap = _a._tokenMap, _lightAppTokenKey = _a._lightAppTokenKey;
if (!this._pendingFetch) return [3 /*break*/, 2];
return [4 /*yield*/, this._pendingFetch];
case 1:
data = _d.sent();
if ((_b = data === null || data === void 0 ? void 0 : data.BizError) === null || _b === void 0 ? void 0 : _b.message) {
return [2 /*return*/, data.BizError];
}
return [2 /*return*/, data.token];
case 2:
_d.trys.push([2, , 5, 6]);
this._pendingFetch = getLightAppToken({ session: '', appId: _appId });
return [4 /*yield*/, this._pendingFetch];
case 3:
data = (_d.sent());
if (!data.ok) {
return [2 /*return*/, Promise.reject('token生成异常')];
}
return [4 /*yield*/, data.json()];
case 4:
respData = _d.sent();
console.log('respData', respData);
if ((_c = respData === null || respData === void 0 ? void 0 : respData.BizError) === null || _c === void 0 ? void 0 : _c.message) {
return [2 /*return*/, respData.BizError];
}
_tokenMap.set(_lightAppTokenKey, respData);
return [2 /*return*/, respData.token];
case 5:
this._pendingFetch = undefined;
return [7 /*endfinally*/];
case 6: return [2 /*return*/];
}
});
});
};
return Token;
}());
export { Token };
export var tokenIns = new Token('');
export function getLightToken() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
if (window.__MONA_LIGHT_APP_GET_TOEKN) {
// @ts-ignore
return window.__MONA_LIGHT_APP_GET_TOEKN.apply(window, args);
}
else {
return tokenIns.getToken();
}
}
// @ts-ignore
window.__MONA_LIGHT_USE_TEST = window.__MONA_LIGHT_USE_TEST || '0';
export function getLightHeaders() {
return __awaiter(this, void 0, void 0, function () {
var token;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, getLightToken()];
case 1:
token = (_a.sent()) || '';
if (typeof window.__LIGHT_APP_GET_TOKENS === 'function') {
return [2 /*return*/, __assign({ 'x-open-token': token, 'x-use-test': window.__MONA_LIGHT_USE_TEST }, (window.__LIGHT_APP_GET_TOKENS() || {}))];
}
else if (window.__MONA_LIGHT_APP_GET_COMPASS_TOKEN) {
return [2 /*return*/, {
'x-open-token': token,
'x-use-test': window.__MONA_LIGHT_USE_TEST,
'x-open-compass': (window === null || window === void 0 ? void 0 : window.__MONA_LIGHT_APP_GET_COMPASS_TOKEN) ? window.__MONA_LIGHT_APP_GET_COMPASS_TOKEN() : '',
}];
}
else {
return [2 /*return*/, __assign({ 'x-open-token': token, 'x-use-test': window.__MONA_LIGHT_USE_TEST }, getTokenInfoByDomain())];
}
return [2 /*return*/];
}
});
});
}
//# sourceMappingURL=light.js.map