import { KV } from '@cloudbase/types' import { getSdkName } from '../constants' export function isArray(val: any): boolean { return Object.prototype.toString.call(val) === '[object Array]' } export function isString(val: any): boolean { return typeof val === 'string' } export function isUndefined(val: any): boolean { return typeof val === 'undefined' } export function isPalinObject(val: any): boolean { return Object.prototype.toString.call(val) === '[object Object]' } export function isNull(val: any): boolean { return Object.prototype.toString.call(val) === '[object Null]' } export function isInstanceOf(instance: any, construct: any): boolean { return instance instanceof construct } export function isFormData(val: any): boolean { return Object.prototype.toString.call(val) === '[object FormData]' } export function genSeqId(): string { return Math.random().toString(16) .slice(2) } export function generateRequestId() { let d = new Date().getTime() let d2 = (Date?.now && Date.now() * 1000) || 0 return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { let r = Math.random() * 16 if (d > 0) { r = (d + r) % 16 | 0 d = Math.floor(d / 16) } else { r = (d2 + r) % 16 | 0 d2 = Math.floor(d2 / 16) } return (c === 'x' ? r : (r & 0x7) | 0x8).toString(16) }) } export function formatUrl(PROTOCOL: string, url: string, query: KV = {}): string { const urlHasQuery = /\?/.test(url) let queryString = '' Object.keys(query).forEach((key) => { if (queryString === '') { !urlHasQuery && (url += '?') } else { queryString += '&' } queryString += `${key}=${encodeURIComponent(query[key])}` }) url += queryString if (/^http(s)?:\/\//.test(url)) { return url } return `${PROTOCOL}${url}` } export function toQueryString(query: KV = {}) { const queryString = [] Object.keys(query).forEach((key) => { queryString.push(`${key}=${encodeURIComponent(query[key])}`) }) return queryString.join('&') } export function getQuery(name: string, url?: string) { if (typeof window === 'undefined') { return false } // 参数:变量名,url为空则表从当前页面的url中取 const u = url || decodeURIComponent(window.location.search) const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`) const r = u.substr(u.indexOf('?') + 1).match(reg) return r !== null && r !== undefined ? r[2] : '' } export const getHash = function (name: string) { if (typeof window === 'undefined') { return '' } const matches = window.location.hash.match(new RegExp(`[#?&/]${name}=([^&#]*)`)) return matches ? matches[1] : '' } export function removeParam(key: string, sourceURL: string) { let rtn = sourceURL.split('?')[0] let param let params = [] const queryString = sourceURL.indexOf('?') !== -1 ? sourceURL.split('?')[1] : '' if (queryString !== '') { params = queryString.split('&') for (let i = params.length - 1; i >= 0; i -= 1) { /* eslint-disable-next-line */ param = params[i].split('=')[0] if (param === key) { params.splice(i, 1) } } rtn = `${rtn}?${params.join('&')}` } return rtn } export function createPromiseCallback() { let cb: any = {} if (!Promise) { cb = () => {} cb.promise = {} const throwPromiseNotDefined = () => { throw new Error('Your Node runtime does support ES6 Promises. ' + 'Set "global.Promise" to your preferred implementation of promises.',) } Object.defineProperty(cb.promise, 'then', { get: throwPromiseNotDefined }) Object.defineProperty(cb.promise, 'catch', { get: throwPromiseNotDefined }) return cb } const promise = new Promise((resolve, reject) => { cb = (err, data) => { if (err) return reject(err) return resolve(data) } }) cb.promise = promise return cb } export function execCallback(fn: Function | null | undefined, err: any, data = null) { if (fn && typeof fn === 'function') { return fn(err, data) } if (err) { throw err } return data } export function printWarn(error: string, msg: string) { console.warn(`[${getSdkName()}][${error}]:${msg}`) } export function printError(error: string, msg: string) { console.error({ code: error, msg: `[${getSdkName()}][${error}]:${msg}`, }) } export function printInfo(error: string, msg: string) { console.log(`[${getSdkName()}][${error}]:${msg}`) } export function throwError(error: string, msg: string) { // legacy v1 兼容路径(auth v1-compat 本地校验):message 保持已发布版本的 JSON-string 形状 // (v1 错误处理范式 JSON.parse(e.message) 不受影响),额外挂 code 属性供新范式直访 const err: any = new Error(JSON.stringify({ code: error, msg: `[${getSdkName()}][${error}]:${msg}`, }),) err.code = error throw err } // ========== Cloudbase Error Factory ========== export interface ICloudbaseErrorOptions { code: string msg: string requestId?: string [key: string]: any } export type CloudbaseErrorFactory = (opts: ICloudbaseErrorOptions) => Error /** * 浏览器形态默认错误类:对齐 v3 已发布行为(实测 @cloudbase/js-sdk@3.8.2 网关业务错误 * 抛 {code, message, requestId},`e.code` 直接可访问),同时保留 Error 特性 * (instanceof / stack,是 v3 裸对象的超集)。 * JSON.stringify(err) 的结果与 v3.8.2 裸对象逐字段一致。 */ export class CloudbaseError extends Error { public readonly code: string public readonly message: string public readonly requestId: string public constructor(opts: ICloudbaseErrorOptions) { super(opts.msg || opts.message || '') this.code = opts.code || '' this.requestId = opts.requestId || '' // Error 构造器创建的 message 自有属性是不可枚举的,直接赋值会保留该属性描述符, // 导致 JSON.stringify(err) 丢失 message(v3.8.2 裸对象里 message 是可枚举的) Object.defineProperty(this, 'message', { value: opts.msg || opts.message || '', enumerable: true, writable: true, configurable: true, }) } } const defaultErrorFactory: CloudbaseErrorFactory = opts => new CloudbaseError(opts) /** * 创建错误对象。无全局状态:factory 由调用方通过 config.errorFactory 传入(per-instance), * 未传入时使用默认工厂(浏览器形态)。 */ export function createCloudbaseError(opts: ICloudbaseErrorOptions, factory?: CloudbaseErrorFactory): Error { return (factory || defaultErrorFactory)(opts) } // ========== 统一 throw 开关 ========== /** * 解析是否抛错:只读 `config.throw`,默认 true。 * `throwOnCode` 仅在 init 时作为别名被 canonicalize 到 `throw`,内部不再保留。 * 该开关统一控制「服务端业务错误 + 本地校验」的抛/返回行为; * Supabase-like API(auth 新方法、storage.from())不受此开关影响。 */ export function resolveThrow(config?: { throw?: boolean } | any): boolean { if (config && typeof config.throw === 'boolean') { return config.throw } return true } /** * 按 `resolveThrow` 决定抛错或返回 `{ code, message }`。 * - throw=true:抛 `createCloudbaseError` * - throw=false:返回 `{ code, message, ...(requestId) }` */ export function maybeThrow( config: { throw?: boolean } | any, opts: { code: string; message: string; requestId?: string }, ): any { if (resolveThrow(config)) { throw createCloudbaseError({ ...opts, msg: opts.message }, config?.errorFactory) } return { code: opts.code, message: opts.message, ...(opts.requestId ? { requestId: opts.requestId } : {}) } } // ========== 网关响应归一化 ========== /** * 将网关响应的业务错误码/信息从 `data` 提升到顶层(若顶层缺失)。 * 网关(gateWay)返回 `{ requestId, data: {...}, statusCode, ... }`,业务错误码在 `data.code` / `data.message`; * 消费方(database / storage 经典)统一用顶层 `res.code` 判断。 * * 无副作用:需要提升时返回新对象,无需提升时原样返回入参。 */ export function promoteGatewayError(res: any): any { if (res && typeof res === 'object' && res.data && typeof res.data === 'object') { const { code, message } = res.data if ((!res.code && code) || (!res.message && message)) { return { ...res, ...(!res.code && code ? { code } : {}), ...(!res.message && message ? { message } : {}), } } } return res } export function errorToResult(e: any): { code: string; message: string; requestId?: string; [key: string]: any } { if (e instanceof Error && typeof e.message === 'string') { try { const parsed = JSON.parse(e.message) if (parsed && typeof parsed.code === 'string') { return { code: parsed.code, message: parsed.msg || parsed.message || '', requestId: parsed.requestId, } } } catch (_) {} } if (e && typeof e.code === 'string') { return { code: e.code, message: e.message || '', requestId: e.requestId } } return { code: 'UNKNOWN_ERROR', message: String(e?.message || e || '') } } interface IPrintGroupLogOptions { title: string subtitle: string | object content: { type: 'info' | 'warn' | 'error' body: string | Error }[] printTrace?: boolean collapsed?: boolean } export function printGroupLog(options: IPrintGroupLogOptions) { const { title, subtitle = '', content = [], printTrace = false, collapsed = false } = options if (collapsed) { (console.groupCollapsed || console.error)(title, subtitle) } else { (console.group || console.error)(title, subtitle) } for (const tip of content) { const { type, body } = tip switch (type) { case 'info': console.log(body) break case 'warn': console.warn(body) break case 'error': console.error(body) break } } if (printTrace) { (console.trace || console.log)('stack trace:') } console.groupEnd?.() } export const sleep = (ms = 0) => new Promise(r => setTimeout(r, ms)) export function transformPhone(phoneNumber: string) { return `+86${phoneNumber}` } export const parseQueryString = (queryString) => { queryString = queryString.replace(/^\?/, '') const params = {} const pairs = queryString.split('&') pairs.forEach((item) => { let [key, value] = item.split('=') key = decodeURIComponent(key) value = decodeURIComponent(value) if (key) { if (params[key]) { if (Array.isArray(params[key])) { params[key].push(value) } else { params[key] = [params[key], value] } } else { params[key] = value } } }) return params } // 解析URL参数 export function parseCaptcha(url) { let queryObj: any = {} const matched = url.match(/^(data:.*?)(\?[^#\s]*)?$/) if (matched) { // eslint-disable-next-line prefer-destructuring url = matched[1] const search = matched[2] if (search) { queryObj = parseQueryString(search) } } const { token, ...restQueryObj } = queryObj if (/^data:/.test(url) && !token) { return { error: 'invalid_argument', error_description: `invalid captcha data: ${url}`, } } if (!token) { return { error: 'unimplemented', error_description: 'need to impl captcha data', } } // 解析url得到的参数 return { state: restQueryObj.state, token, // 验证码token captchaData: url, // 验证码base64图片 } }