重构项目文件夹目录

This commit is contained in:
2026-06-15 15:53:55 +08:00
parent 8093e07190
commit 7cbe5b3de5
1098 changed files with 34 additions and 4441 deletions
@@ -0,0 +1,110 @@
/**
* Purpose: inflightScopes supports action-guard.js by holding or executing the inflight scopes page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const inflightScopes = new Map()
/**
* Purpose: resolveScopeId supports action-guard.js by holding or executing the resolve scope id page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function resolveScopeId(scope) {
if (scope && typeof scope === 'string') {
return scope
}
if (scope && typeof scope.route === 'string' && scope.route) {
return scope.route
}
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : []
const current = pages[pages.length - 1]
if (current && current.route) {
return current.route
}
return 'global'
}
/**
* Purpose: getScopeMap supports action-guard.js by holding or executing the get scope map page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getScopeMap(scopeId) {
if (!inflightScopes.has(scopeId)) {
inflightScopes.set(scopeId, new Map())
}
return inflightScopes.get(scopeId)
}
/**
* Purpose: createGuardError supports action-guard.js by holding or executing the create guard error page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function createGuardError(message, scopeId, actionKey) {
const error = new Error(message || '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb')
error.isActionGuardError = true
error.scopeId = scopeId
error.actionKey = actionKey
return error
}
/**
* Purpose: run supports action-guard.js by holding or executing the run page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function run(scope, actionKey, task, options) {
const scopeId = resolveScopeId(scope)
const normalizedKey = String(actionKey || 'default')
const scopeMap = getScopeMap(scopeId)
if (scopeMap.get(normalizedKey)) {
return Promise.reject(createGuardError((options && options.message) || '', scopeId, normalizedKey))
}
scopeMap.set(normalizedKey, true)
try {
return await Promise.resolve().then(() => task())
} finally {
scopeMap.delete(normalizedKey)
if (!scopeMap.size) {
inflightScopes.delete(scopeId)
}
}
}
/**
* Purpose: isRunning supports action-guard.js by holding or executing the is running page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isRunning(scope, actionKey) {
const scopeId = resolveScopeId(scope)
const scopeMap = inflightScopes.get(scopeId)
if (!scopeMap) {
return false
}
return Boolean(scopeMap.get(String(actionKey || 'default')))
}
/**
* Purpose: clearScope supports action-guard.js by holding or executing the clear scope page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function clearScope(scope) {
inflightScopes.delete(resolveScopeId(scope))
}
/**
* Purpose: isGuardError supports action-guard.js by holding or executing the is guard error page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isGuardError(error) {
return Boolean(error && error.isActionGuardError)
}
module.exports = {
run,
isRunning,
clearScope,
isGuardError,
createGuardError
}
+147
View File
@@ -0,0 +1,147 @@
const { STORAGE_KEYS, getStorage, removeStorage, setStorage } = require('./storage')
/**
* Purpose: getAccessToken supports auth.js by holding or executing the get access token page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getAccessToken() {
return getStorage(STORAGE_KEYS.ACCESS_TOKEN, '')
}
/**
* Purpose: getRefreshToken supports auth.js by holding or executing the get refresh token page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getRefreshToken() {
return getStorage(STORAGE_KEYS.REFRESH_TOKEN, '')
}
/**
* Purpose: getStoredUserInfo supports auth.js by holding or executing the get stored user info page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getStoredUserInfo() {
return getStorage(STORAGE_KEYS.USER_INFO, null)
}
/**
* Purpose: getStoredPermissions supports auth.js by holding or executing the get stored permissions page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getStoredPermissions() {
return getStorage(STORAGE_KEYS.PERMISSIONS, [])
}
/**
* Purpose: getCurrentShop supports auth.js by holding or executing the get current shop page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getCurrentShop() {
return getStorage(STORAGE_KEYS.CURRENT_SHOP, null)
}
/**
* Purpose: isLoggedIn supports auth.js by holding or executing the is logged in page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isLoggedIn() {
return Boolean(getAccessToken())
}
/**
* Purpose: setSession supports auth.js by holding or executing the set session page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function setSession(payload) {
if (!payload || !payload.accessToken || !payload.refreshToken) {
return
}
setStorage(STORAGE_KEYS.ACCESS_TOKEN, payload.accessToken)
setStorage(STORAGE_KEYS.REFRESH_TOKEN, payload.refreshToken)
if (payload.userInfo) {
setStorage(STORAGE_KEYS.USER_INFO, payload.userInfo)
if (payload.userInfo.shopId) {
setCurrentShop({
id: payload.userInfo.shopId,
shopName: payload.userInfo.shopName || ''
})
} else {
removeStorage(STORAGE_KEYS.CURRENT_SHOP)
}
}
}
/**
* Purpose: updateStoredUserInfo supports auth.js by holding or executing the update stored user info page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function updateStoredUserInfo(userInfo) {
if (!userInfo) {
removeStorage(STORAGE_KEYS.USER_INFO)
return
}
setStorage(STORAGE_KEYS.USER_INFO, userInfo)
}
/**
* Purpose: setPermissions supports auth.js by holding or executing the set permissions page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function setPermissions(permissions) {
setStorage(STORAGE_KEYS.PERMISSIONS, Array.isArray(permissions) ? permissions : [])
}
/**
* Purpose: clearPermissions supports auth.js by holding or executing the clear permissions page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function clearPermissions() {
removeStorage(STORAGE_KEYS.PERMISSIONS)
}
/**
* Purpose: setCurrentShop supports auth.js by holding or executing the set current shop page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function setCurrentShop(shop) {
if (!shop || !shop.id) {
removeStorage(STORAGE_KEYS.CURRENT_SHOP)
return
}
setStorage(STORAGE_KEYS.CURRENT_SHOP, {
id: shop.id,
shopName: shop.shopName || ''
})
}
/**
* Purpose: clearSession supports auth.js by holding or executing the clear session page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function clearSession() {
removeStorage(STORAGE_KEYS.ACCESS_TOKEN)
removeStorage(STORAGE_KEYS.REFRESH_TOKEN)
removeStorage(STORAGE_KEYS.USER_INFO)
removeStorage(STORAGE_KEYS.PERMISSIONS)
removeStorage(STORAGE_KEYS.CURRENT_SHOP)
}
module.exports = {
getAccessToken,
getRefreshToken,
getStoredUserInfo,
getStoredPermissions,
getCurrentShop,
isLoggedIn,
setSession,
updateStoredUserInfo,
setPermissions,
clearPermissions,
setCurrentShop,
clearSession
}
+119
View File
@@ -0,0 +1,119 @@
/**
* Purpose: CACHE_PREFIX supports cache.js by holding or executing the cache prefix page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const CACHE_PREFIX = 'adminMiniCache:'
/**
* Purpose: memoryCache supports cache.js by holding or executing the memory cache page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const memoryCache = {}
/**
* Purpose: inflightCache supports cache.js by holding or executing the inflight cache page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const inflightCache = {}
/**
* Purpose: buildKey supports cache.js by holding or executing the build key page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildKey(key) {
return `${CACHE_PREFIX}${key}`
}
/**
* Purpose: now supports cache.js by holding or executing the now page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function now() {
return Date.now()
}
/**
* Purpose: getCache supports cache.js by holding or executing the get cache page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getCache(key, defaultValue) {
if (!key) {
return defaultValue
}
const memoryEntry = memoryCache[key]
if (memoryEntry && (!memoryEntry.expireAt || memoryEntry.expireAt > now())) {
return memoryEntry.value
}
delete memoryCache[key]
try {
const storedEntry = wx.getStorageSync(buildKey(key))
if (storedEntry && (!storedEntry.expireAt || storedEntry.expireAt > now())) {
memoryCache[key] = storedEntry
return storedEntry.value
}
wx.removeStorageSync(buildKey(key))
} catch (error) {}
return defaultValue
}
/**
* Purpose: setCache supports cache.js by holding or executing the set cache page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function setCache(key, value, ttlMs) {
if (!key) {
return value
}
const entry = {
value,
expireAt: ttlMs && ttlMs > 0 ? now() + ttlMs : 0
}
memoryCache[key] = entry
try {
wx.setStorageSync(buildKey(key), entry)
} catch (error) {}
return value
}
/**
* Purpose: removeCache supports cache.js by holding or executing the remove cache page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function removeCache(key) {
if (!key) {
return
}
delete memoryCache[key]
try {
wx.removeStorageSync(buildKey(key))
} catch (error) {}
}
/**
* Purpose: remember supports cache.js by holding or executing the remember page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function remember(key, ttlMs, loader) {
const cached = getCache(key, undefined)
if (cached !== undefined) {
return Promise.resolve(cached)
}
if (inflightCache[key]) {
return inflightCache[key]
}
inflightCache[key] = Promise.resolve()
.then(() => loader())
.then(value => setCache(key, value, ttlMs))
.finally(() => {
delete inflightCache[key]
})
return inflightCache[key]
}
module.exports = {
getCache,
setCache,
removeCache,
remember
}
+163
View File
@@ -0,0 +1,163 @@
/**
* Purpose: safeRequire supports config.js by holding or executing the safe require page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function safeRequire(modulePath) {
try {
return require(modulePath)
} catch (error) {
return {}
}
}
/**
* Purpose: getEnvVersion supports config.js by holding or executing the get env version page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getEnvVersion() {
if (typeof wx === 'undefined') {
return 'develop'
}
try {
if (typeof wx.getAccountInfoSync === 'function') {
const accountInfo = wx.getAccountInfoSync()
const miniProgram = accountInfo && accountInfo.miniProgram
if (miniProgram && miniProgram.envVersion) {
return miniProgram.envVersion
}
}
} catch (error) {}
return 'develop'
}
/**
* Purpose: getRuntimePlatform supports config.js by holding or executing the get runtime platform page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getRuntimePlatform() {
if (typeof wx === 'undefined') {
return 'devtools'
}
try {
const systemInfo = wx.getSystemInfoSync()
if (systemInfo && systemInfo.platform) {
return systemInfo.platform
}
} catch (error) {}
return 'unknown'
}
/**
* Purpose: normalizeDomain supports config.js by holding or executing the normalize domain page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function normalizeDomain(value, fallbackValue) {
const target = String(value || fallbackValue || '').trim()
return target.replace(/\/+$/, '')
}
/**
* Purpose: ensureHttps supports config.js by holding or executing the ensure https page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function ensureHttps(value, envVersion) {
if (!value) {
throw new Error(`Missing API domain for ${envVersion}`)
}
if (envVersion !== 'develop' && !value.startsWith('https://')) {
throw new Error(`${envVersion} environment must use HTTPS`)
}
return value
}
/**
* Purpose: localOverride supports config.js by holding or executing the local override page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const localOverride = safeRequire('./config.local')
/**
* Purpose: ENV_VERSION supports config.js by holding or executing the env version page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const ENV_VERSION = getEnvVersion()
/**
* Purpose: RUNTIME_PLATFORM supports config.js by holding or executing the runtime platform page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const RUNTIME_PLATFORM = getRuntimePlatform()
/**
* Purpose: IS_DEVTOOLS supports config.js by holding or executing the is devtools page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const IS_DEVTOOLS = RUNTIME_PLATFORM === 'devtools'
/**
* Purpose: DEFAULT_DOMAINS supports config.js by holding or executing the default domains page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DEFAULT_DOMAINS = {
local: 'http://127.0.0.1:80',
tunnel: 'https://yunail.art',
'dev-remote': 'https://yunail.art',
trial: 'https://yunail.art',
release: 'https://yunail.art'
}
/**
* Purpose: DOMAIN_MAP supports config.js by holding or executing the domain map page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DOMAIN_MAP = {
...DEFAULT_DOMAINS,
...(localOverride.domains || {})
}
/**
* Purpose: DEFAULT_DEVELOP_TARGET supports config.js by holding or executing the default develop target page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DEFAULT_DEVELOP_TARGET = IS_DEVTOOLS ? 'local' : 'dev-remote'
/**
* Purpose: DEVELOP_TARGET supports config.js by holding or executing the develop target page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DEVELOP_TARGET = String(localOverride.developTarget || DEFAULT_DEVELOP_TARGET)
/**
* Purpose: API_DOMAIN supports config.js by holding or executing the api domain page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const API_DOMAIN = ensureHttps(
ENV_VERSION === 'develop'
? normalizeDomain(DOMAIN_MAP[DEVELOP_TARGET], DOMAIN_MAP['dev-remote'])
: normalizeDomain(DOMAIN_MAP[ENV_VERSION], DOMAIN_MAP.release),
ENV_VERSION
)
module.exports = {
ENV_VERSION,
RUNTIME_PLATFORM,
IS_DEVTOOLS,
DEVELOP_TARGET,
API_DOMAIN,
ADMIN_API_BASE_URL: `${API_DOMAIN}/admin/api`,
IS_DEV_ENV: ENV_VERSION === 'develop',
REQUEST_TIMEOUT: Number(localOverride.requestTimeout || 10000),
ENABLE_REQUEST_SIGNING: localOverride.enableRequestSigning !== false,
IDLE_TIMEOUT_MS: 30 * 60 * 1000,
IDLE_WARNING_MS: 2 * 60 * 1000,
CACHE_TTL: {
permissions: 2 * 60 * 1000,
dict: 5 * 60 * 1000,
workbench: 60 * 1000
},
TAB_PAGES: [
'/admin/pages/workbench/index',
'/admin/pages/orders/index',
'/admin/pages/manage/index',
'/admin/pages/profile/index'
]
}
@@ -0,0 +1,12 @@
module.exports = {
developTarget: 'local',
requestTimeout: 10000,
enableRequestSigning: true,
domains: {
local: 'http://127.0.0.1:80',
tunnel: 'https://yunail.art',
'dev-remote': 'https://yunail.art',
trial: 'https://yunail.art',
release: 'https://yunail.art'
}
}
+213
View File
@@ -0,0 +1,213 @@
/**
* Purpose: utf8ToBytes supports crypto.js by holding or executing the utf8 to bytes page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function utf8ToBytes(text) {
const encoded = unescape(encodeURIComponent(String(text || '')))
const bytes = []
for (let index = 0; index < encoded.length; index += 1) {
bytes.push(encoded.charCodeAt(index))
}
return bytes
}
/**
* Purpose: bytesToHex supports crypto.js by holding or executing the bytes to hex page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function bytesToHex(bytes) {
return (Array.isArray(bytes) ? bytes : []).map(item => item.toString(16).padStart(2, '0')).join('')
}
/**
* Purpose: rightRotate supports crypto.js by holding or executing the right rotate page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function rightRotate(value, amount) {
return (value >>> amount) | (value << (32 - amount))
}
/**
* Purpose: sha256Bytes supports crypto.js by holding or executing the sha256 bytes page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function sha256Bytes(messageBytes) {
const k = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]
const h = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
]
const bytes = Array.isArray(messageBytes) ? messageBytes.slice() : []
const bitLength = BigInt(bytes.length) * 8n
bytes.push(0x80)
while ((bytes.length % 64) !== 56) {
bytes.push(0)
}
for (let index = 7; index >= 0; index -= 1) {
bytes.push(Number((bitLength >> BigInt(index * 8)) & 0xffn))
}
const words = new Array(64)
for (let offset = 0; offset < bytes.length; offset += 64) {
for (let index = 0; index < 16; index += 1) {
const start = offset + index * 4
words[index] = (
(bytes[start] << 24) |
(bytes[start + 1] << 16) |
(bytes[start + 2] << 8) |
bytes[start + 3]
) >>> 0
}
for (let index = 16; index < 64; index += 1) {
const s0 = (rightRotate(words[index - 15], 7) ^ rightRotate(words[index - 15], 18) ^ (words[index - 15] >>> 3)) >>> 0
const s1 = (rightRotate(words[index - 2], 17) ^ rightRotate(words[index - 2], 19) ^ (words[index - 2] >>> 10)) >>> 0
words[index] = (words[index - 16] + s0 + words[index - 7] + s1) >>> 0
}
let a = h[0]
let b = h[1]
let c = h[2]
let d = h[3]
let e = h[4]
let f = h[5]
let g = h[6]
let innerH = h[7]
for (let index = 0; index < 64; index += 1) {
const s1 = (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) >>> 0
const choice = ((e & f) ^ ((~e) & g)) >>> 0
const temp1 = (innerH + s1 + choice + k[index] + words[index]) >>> 0
const s0 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) >>> 0
const majority = ((a & b) ^ (a & c) ^ (b & c)) >>> 0
const temp2 = (s0 + majority) >>> 0
innerH = g
g = f
f = e
e = (d + temp1) >>> 0
d = c
c = b
b = a
a = (temp1 + temp2) >>> 0
}
h[0] = (h[0] + a) >>> 0
h[1] = (h[1] + b) >>> 0
h[2] = (h[2] + c) >>> 0
h[3] = (h[3] + d) >>> 0
h[4] = (h[4] + e) >>> 0
h[5] = (h[5] + f) >>> 0
h[6] = (h[6] + g) >>> 0
h[7] = (h[7] + innerH) >>> 0
}
const output = []
h.forEach(value => {
output.push((value >>> 24) & 0xff)
output.push((value >>> 16) & 0xff)
output.push((value >>> 8) & 0xff)
output.push(value & 0xff)
})
return output
}
/**
* Purpose: sha256Hex supports crypto.js by holding or executing the sha256 hex page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function sha256Hex(text) {
return bytesToHex(sha256Bytes(utf8ToBytes(text)))
}
/**
* Purpose: hmacSha256Hex supports crypto.js by holding or executing the hmac sha256 hex page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function hmacSha256Hex(secret, message) {
let keyBytes = utf8ToBytes(secret)
if (keyBytes.length > 64) {
keyBytes = sha256Bytes(keyBytes)
}
while (keyBytes.length < 64) {
keyBytes.push(0)
}
const outer = []
const inner = []
for (let index = 0; index < 64; index += 1) {
outer[index] = keyBytes[index] ^ 0x5c
inner[index] = keyBytes[index] ^ 0x36
}
const innerDigest = sha256Bytes(inner.concat(utf8ToBytes(message)))
return bytesToHex(sha256Bytes(outer.concat(innerDigest)))
}
/**
* Purpose: buildCanonicalParams supports crypto.js by holding or executing the build canonical params page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildCanonicalParams(input) {
const source = input || {}
const keys = Object.keys(source)
.filter(key => source[key] !== undefined && source[key] !== null && source[key] !== '')
.sort()
return keys.map(key => {
const rawValue = source[key]
const values = Array.isArray(rawValue) ? rawValue.slice() : [rawValue]
const normalized = values
.map(item => String(item))
.sort()
.join(',')
return `${key}=${normalized}`
}).join('&')
}
/**
* Purpose: buildJsonPayload supports crypto.js by holding or executing the build json payload page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildJsonPayload(data) {
if (data === undefined || data === null || data === '') {
return ''
}
if (typeof data === 'string') {
return data
}
return JSON.stringify(data)
}
/**
* Purpose: randomNonce supports crypto.js by holding or executing the random nonce page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function randomNonce() {
return `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
}
module.exports = {
sha256Hex,
hmacSha256Hex,
buildCanonicalParams,
buildJsonPayload,
randomNonce
}
+28
View File
@@ -0,0 +1,28 @@
const { STORAGE_KEYS, getStorage, setStorage } = require('./storage')
/**
* Purpose: createDeviceId supports device.js by holding or executing the create device id page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function createDeviceId() {
const randomText = Math.random().toString(36).slice(2, 10)
return `admin-mini-device-${Date.now()}-${randomText}`
}
/**
* Purpose: getDeviceId supports device.js by holding or executing the get device id page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getDeviceId() {
let value = getStorage(STORAGE_KEYS.DEVICE_ID, '')
if (value) {
return value
}
value = createDeviceId()
setStorage(STORAGE_KEYS.DEVICE_ID, value)
return value
}
module.exports = {
getDeviceId
}
@@ -0,0 +1,96 @@
/**
* Purpose: DRAFT_PREFIX supports form-draft.js by holding or executing the draft prefix page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DRAFT_PREFIX = 'adminMiniDraft:'
/**
* Purpose: buildDraftKey supports form-draft.js by holding or executing the build draft key page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildDraftKey(key) {
return `${DRAFT_PREFIX}${key}`
}
/**
* Purpose: getDraftValue supports form-draft.js by holding or executing the get draft value page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getDraftValue(key, defaultValue) {
if (!key) {
return defaultValue
}
try {
const record = wx.getStorageSync(buildDraftKey(key))
if (!record || typeof record !== 'object' || !Object.prototype.hasOwnProperty.call(record, 'value')) {
return defaultValue
}
return record.value
} catch (error) {
return defaultValue
}
}
/**
* Purpose: saveDraft supports form-draft.js by holding or executing the save draft page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function saveDraft(key, value) {
if (!key) {
return
}
try {
wx.setStorageSync(buildDraftKey(key), {
savedAt: Date.now(),
value
})
} catch (error) {}
}
/**
* Purpose: clearDraft supports form-draft.js by holding or executing the clear draft page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function clearDraft(key) {
if (!key) {
return
}
try {
wx.removeStorageSync(buildDraftKey(key))
} catch (error) {}
}
/**
* Purpose: scheduleDraftSave supports form-draft.js by holding or executing the schedule draft save page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function scheduleDraftSave(context, key, buildValue, delay) {
if (!context) {
return
}
if (context.__draftSaveTimer) {
clearTimeout(context.__draftSaveTimer)
}
context.__draftSaveTimer = setTimeout(() => {
saveDraft(key, buildValue())
}, delay || 300)
}
/**
* Purpose: clearDraftTimer supports form-draft.js by holding or executing the clear draft timer page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function clearDraftTimer(context) {
if (context && context.__draftSaveTimer) {
clearTimeout(context.__draftSaveTimer)
context.__draftSaveTimer = null
}
}
module.exports = {
getDraftValue,
saveDraft,
clearDraft,
scheduleDraftSave,
clearDraftTimer
}
+212
View File
@@ -0,0 +1,212 @@
/**
* Purpose: toIdString supports format.js by holding or executing the to id string page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function toIdString(value) {
return value === undefined || value === null ? '' : String(value)
}
/**
* Purpose: sameId supports format.js by holding or executing the same id page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function sameId(left, right) {
return toIdString(left) === toIdString(right)
}
/**
* Purpose: splitCsv supports format.js by holding or executing the split csv page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function splitCsv(value) {
return String(value || '')
.split(',')
.map(item => item.trim())
.filter(Boolean)
}
/**
* Purpose: formatPrice supports format.js by holding or executing the format price page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function formatPrice(value) {
return Number(value || 0).toFixed(2)
}
/**
* Purpose: formatDateTime supports format.js by holding or executing the format date time page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function formatDateTime(value) {
if (!value) {
return ''
}
return String(value).replace('T', ' ').slice(0, 16)
}
/**
* Purpose: formatDate supports format.js by holding or executing the format date page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function formatDate(value) {
return formatDateTime(value).slice(0, 10)
}
/**
* Purpose: maskPhone supports format.js by holding or executing the mask phone page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function maskPhone(phone) {
const value = String(phone || '')
if (value.length !== 11) {
return value
}
return `${value.slice(0, 3)}****${value.slice(7)}`
}
/**
* Purpose: truncateText supports format.js by holding or executing the truncate text page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function truncateText(value, limit) {
const text = String(value || '')
if (!limit || text.length <= limit) {
return text
}
return `${text.slice(0, limit)}...`
}
/**
* Purpose: buildShopName supports format.js by holding or executing the build shop name page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildShopName(record) {
if (!record) {
return '未绑定店铺'
}
if (Array.isArray(record.shopNames) && record.shopNames.length) {
return record.shopNames.join(' / ')
}
if (record.shopName) {
return record.shopName
}
return '未绑定店铺'
}
/**
* Purpose: getUserStatusText supports format.js by holding or executing the get user status text page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getUserStatusText(status) {
return Number(status) === 0 ? '已停用' : '正常'
}
/**
* Purpose: getUserTypeText supports format.js by holding or executing the get user type text page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getUserTypeText(type) {
const value = Number(type)
if (value === 4) {
return '平台管理员'
}
if (value === 2) {
return '店长'
}
if (value === 3) {
return '美甲师'
}
return '普通用户'
}
/**
* Purpose: getOrderStatusText supports format.js by holding or executing the get order status text page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getOrderStatusText(order) {
if (order && order.statusText) {
return order.statusText
}
const status = Number(order && order.status)
if (status === 1) {
return '待服务'
}
if (status === 2) {
return '已完成'
}
return '已取消'
}
/**
* Purpose: getCouponTypeText supports format.js by holding or executing the get coupon type text page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getCouponTypeText(type) {
return Number(type) === 1 ? '折扣券' : '满减券'
}
/**
* Purpose: getCouponValueText supports format.js by holding or executing the get coupon value text page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getCouponValueText(coupon) {
if (Number(coupon && coupon.couponType) === 1) {
return `${coupon && coupon.discountValue ? coupon.discountValue : '--'} 折`
}
return `满 ${formatPrice(coupon && coupon.minAmount)} 减 ${formatPrice(coupon && coupon.reduceAmount)}`
}
/**
* Purpose: parseDateTimeToPicker supports format.js by holding or executing the parse date time to picker page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function parseDateTimeToPicker(value) {
const text = formatDateTime(value)
if (!text) {
return {
date: '',
time: ''
}
}
const parts = text.split(' ')
return {
date: parts[0] || '',
time: (parts[1] || '').slice(0, 5)
}
}
/**
* Purpose: buildDateTime supports format.js by holding or executing the build date time page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildDateTime(date, time) {
if (!date || !time) {
return ''
}
return `${date} ${time}:00`
}
module.exports = {
toIdString,
sameId,
splitCsv,
formatPrice,
formatDateTime,
formatDate,
maskPhone,
truncateText,
buildShopName,
getUserStatusText,
getUserTypeText,
getOrderStatusText,
getCouponTypeText,
getCouponValueText,
parseDateTimeToPicker,
buildDateTime
}
@@ -0,0 +1,241 @@
/**
* Purpose: options supports idle-session.js by holding or executing the options page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let options = null
/**
* Purpose: timer supports idle-session.js by holding or executing the timer page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let timer = null
/**
* Purpose: warningShown supports idle-session.js by holding or executing the warning shown page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let warningShown = false
/**
* Purpose: loggingOut supports idle-session.js by holding or executing the logging out page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let loggingOut = false
/**
* Purpose: hiddenAt supports idle-session.js by holding or executing the hidden at page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let hiddenAt = 0
/**
* Purpose: lastActiveAt supports idle-session.js by holding or executing the last active at page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let lastActiveAt = Date.now()
/**
* Purpose: pagePatched supports idle-session.js by holding or executing the page patched page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let pagePatched = false
/**
* Purpose: shouldTrackMethod supports idle-session.js by holding or executing the should track method page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function shouldTrackMethod(name) {
return ![
'onHide',
'onUnload',
'onShareAppMessage',
'onShareTimeline'
].includes(name)
}
/**
* Purpose: ensurePagePatched supports idle-session.js by holding or executing the ensure page patched page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function ensurePagePatched() {
if (pagePatched || typeof Page !== 'function') {
return
}
const originalPage = Page
Page = function wrappedPage(definition) {
const nextDefinition = {}
Object.keys(definition || {}).forEach(key => {
const value = definition[key]
if (typeof value !== 'function') {
nextDefinition[key] = value
return
}
nextDefinition[key] = function wrappedHandler(...args) {
if (shouldTrackMethod(key)) {
markActive()
}
return value.apply(this, args)
}
})
return originalPage(nextDefinition)
}
pagePatched = true
}
/**
* Purpose: start supports idle-session.js by holding or executing the start page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function start() {
stop()
if (!options) {
return
}
timer = setInterval(check, 15000)
}
/**
* Purpose: stop supports idle-session.js by holding or executing the stop page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function stop() {
if (timer) {
clearInterval(timer)
timer = null
}
}
/**
* Purpose: isLoggedIn supports idle-session.js by holding or executing the is logged in page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isLoggedIn() {
return options && typeof options.isLoggedIn === 'function' ? Boolean(options.isLoggedIn()) : false
}
/**
* Purpose: markActive supports idle-session.js by holding or executing the mark active page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function markActive() {
if (!options || !isLoggedIn() || loggingOut) {
return
}
lastActiveAt = Date.now()
warningShown = false
}
/**
* Purpose: onAppShow supports idle-session.js by holding or executing the on app show page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function onAppShow() {
if (!options) {
return
}
if (hiddenAt > 0 && isLoggedIn()) {
const hiddenDuration = Date.now() - hiddenAt
if (hiddenDuration >= options.timeoutMs) {
forceLogout()
return
}
}
hiddenAt = 0
markActive()
start()
}
/**
* Purpose: onAppHide supports idle-session.js by holding or executing the on app hide page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function onAppHide() {
hiddenAt = Date.now()
stop()
}
/**
* Purpose: check supports idle-session.js by holding or executing the check page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function check() {
if (!options || !isLoggedIn() || loggingOut) {
return
}
const idleMs = Date.now() - lastActiveAt
if (idleMs >= options.timeoutMs) {
forceLogout()
return
}
if (idleMs >= options.timeoutMs - options.warningMs && !warningShown) {
showWarning()
}
}
/**
* Purpose: showWarning supports idle-session.js by holding or executing the show warning page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function showWarning() {
if (!options || warningShown || loggingOut) {
return
}
warningShown = true
wx.showModal({
title: options.warningTitle || '登录即将过期',
content: options.warningContent || '长时间未操作,即将退出登录。',
confirmText: options.confirmText || '继续使用',
cancelText: options.cancelText || '退出登录',
success: result => {
warningShown = false
if (result.confirm) {
markActive()
if (typeof options.onContinue === 'function') {
options.onContinue()
}
return
}
forceLogout()
},
fail: () => {
warningShown = false
}
})
}
/**
* Purpose: forceLogout supports idle-session.js by holding or executing the force logout page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function forceLogout() {
if (!options || loggingOut) {
return
}
loggingOut = true
Promise.resolve()
.then(() => (typeof options.onLogout === 'function' ? options.onLogout() : undefined))
.catch(() => undefined)
.finally(() => {
loggingOut = false
warningShown = false
hiddenAt = 0
lastActiveAt = Date.now()
})
}
/**
* Purpose: init supports idle-session.js by holding or executing the init page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function init(nextOptions) {
options = nextOptions || null
lastActiveAt = Date.now()
warningShown = false
loggingOut = false
hiddenAt = 0
ensurePagePatched()
start()
}
module.exports = {
init,
start,
stop,
markActive,
onAppShow,
onAppHide
}
+71
View File
@@ -0,0 +1,71 @@
/**
* Purpose: activeLoadingCount supports loading.js by holding or executing the active loading count page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let activeLoadingCount = 0
/**
* Purpose: showLoading supports loading.js by holding or executing the show loading page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function showLoading(options) {
const config = options || {}
activeLoadingCount += 1
if (activeLoadingCount > 1) {
return
}
wx.showLoading({
title: config.title || '加载中',
mask: config.mask !== false
})
}
/**
* Purpose: hideLoading supports loading.js by holding or executing the hide loading page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function hideLoading() {
activeLoadingCount = Math.max(0, activeLoadingCount - 1)
if (activeLoadingCount > 0) {
return
}
wx.hideLoading({
fail() {}
})
}
/**
* Purpose: resetLoading supports loading.js by holding or executing the reset loading page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function resetLoading() {
activeLoadingCount = 0
wx.hideLoading({
fail() {}
})
}
/**
* Purpose: runWithLoading supports loading.js by holding or executing the run with loading page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function runWithLoading(task, options) {
showLoading(options)
return Promise.resolve()
.then(() => task())
.finally(() => {
hideLoading()
})
}
module.exports = {
showLoading,
hideLoading,
resetLoading,
runWithLoading
}
+226
View File
@@ -0,0 +1,226 @@
/**
* Purpose: auth supports navigation.js by holding or executing the auth page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const auth = require('./auth')
const { TAB_PAGES } = require('./config')
const ADMIN_PAGE_PREFIX = '/admin/pages/'
const ADMIN_TAB_PAGES = TAB_PAGES
/**
* Purpose: buildUrl supports navigation.js by holding or executing the build url page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildUrl(path, params) {
const query = Object.keys(params || {})
.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&')
return query ? `${path}${String(path).includes('?') ? '&' : '?'}${query}` : path
}
function splitUrl(value) {
const target = String(value || '')
const queryIndex = target.indexOf('?')
if (queryIndex < 0) {
return {
path: target,
query: ''
}
}
return {
path: target.slice(0, queryIndex),
query: target.slice(queryIndex)
}
}
function toAdminPagePath(value) {
const { path, query } = splitUrl(value)
if (path.startsWith(ADMIN_PAGE_PREFIX)) {
return `${path}${query}`
}
if (path.startsWith('/pages/')) {
return `/admin${path}${query}`
}
return `${path}${query}`
}
/**
* Purpose: getCurrentPageUrl supports navigation.js by holding or executing the get current page url page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getCurrentPageUrl() {
const pages = getCurrentPages()
const current = pages[pages.length - 1]
if (!current) {
return '/admin/pages/workbench/index'
}
return buildUrl(`/${current.route}`, current.options || {})
}
/**
* Purpose: isTabPage supports navigation.js by holding or executing the is tab page page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isTabPage(path) {
const purePath = String(toAdminPagePath(path) || '').split('?')[0]
return ADMIN_TAB_PAGES.includes(purePath)
}
/**
* Purpose: navigate supports navigation.js by holding or executing the navigate page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function navigate(path, params) {
return new Promise((resolve, reject) => {
wx.navigateTo({
url: toAdminPagePath(buildUrl(path, params)),
success: resolve,
fail: reject
})
})
}
/**
* Purpose: redirect supports navigation.js by holding or executing the redirect page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function redirect(path, params) {
return new Promise((resolve, reject) => {
wx.redirectTo({
url: toAdminPagePath(buildUrl(path, params)),
success: resolve,
fail: reject
})
})
}
/**
* Purpose: switchTab keeps the old admin-tab API while using page redirects in the unified mini-program.
* Usage: call it for admin workbench/orders/manage/profile root pages; these pages are no longer native tabBar entries.
*/
function switchTab(path) {
const target = toAdminPagePath(path)
return new Promise((resolve, reject) => {
wx.redirectTo({
url: target,
success: resolve,
fail(error) {
wx.reLaunch({
url: target,
success: resolve,
fail: reject
})
}
})
})
}
/**
* Purpose: goBack supports navigation.js by holding or executing the go back page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function goBack(fallbackPath) {
const pages = getCurrentPages()
if (pages.length > 1) {
wx.navigateBack()
return
}
const target = toAdminPagePath(fallbackPath || '/pages/workbench/index')
if (isTabPage(target)) {
switchTab(target)
return
}
wx.redirectTo({ url: target })
}
/**
* Purpose: decodeRedirectValue supports navigation.js by holding or executing the decode redirect value page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function decodeRedirectValue(value) {
let current = String(value || '')
for (let index = 0; index < 3; index += 1) {
try {
const decoded = decodeURIComponent(current)
if (decoded === current) {
return decoded
}
current = decoded
} catch (error) {
return current
}
}
return current
}
/**
* Purpose: redirectAfterLogin supports navigation.js by holding or executing the redirect after login page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function redirectAfterLogin(redirectValue) {
const target = redirectValue ? toAdminPagePath(decodeRedirectValue(redirectValue)) : ''
if (!target) {
return switchTab('/pages/workbench/index')
}
const purePath = target.split('?')[0]
if (isTabPage(target)) {
return switchTab(purePath)
}
return redirect(target)
}
/**
* Purpose: openLogin supports navigation.js by holding or executing the open login page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function openLogin(redirectPath) {
return navigate('/pages/login/index', {
redirect: redirectPath ? toAdminPagePath(redirectPath) : getCurrentPageUrl()
})
}
/**
* Purpose: ensureLogin supports navigation.js by holding or executing the ensure login page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function ensureLogin(actionText) {
if (auth.isLoggedIn()) {
return true
}
wx.showToast({
title: `${actionText || '继续操作'}前请先登录`,
icon: 'none'
})
setTimeout(() => {
openLogin()
}, 160)
return false
}
module.exports = {
ADMIN_TAB_PAGES,
buildUrl,
getCurrentPageUrl,
isTabPage,
toAdminPagePath,
navigate,
redirect,
switchTab,
goBack,
redirectAfterLogin,
openLogin,
ensureLogin
}
@@ -0,0 +1,44 @@
const assert = require('assert')
const navigation = require('./navigation')
assert.strictEqual(
navigation.toAdminPagePath('/pages/orders/index'),
'/admin/pages/orders/index'
)
assert.strictEqual(
navigation.toAdminPagePath('/pages/order-detail/index?id=10'),
'/admin/pages/order-detail/index?id=10'
)
assert.strictEqual(
navigation.toAdminPagePath('/admin/pages/manage/index'),
'/admin/pages/manage/index'
)
assert.ok(navigation.ADMIN_TAB_PAGES.includes('/admin/pages/workbench/index'))
assert.ok(navigation.ADMIN_TAB_PAGES.includes('/admin/pages/orders/index'))
assert.ok(navigation.ADMIN_TAB_PAGES.includes('/admin/pages/manage/index'))
assert.ok(navigation.ADMIN_TAB_PAGES.includes('/admin/pages/profile/index'))
let redirectedTo = ''
let relaunchedTo = ''
global.wx = {
redirectTo(options) {
redirectedTo = options.url
if (typeof options.success === 'function') {
options.success()
}
},
reLaunch(options) {
relaunchedTo = options.url
if (typeof options.success === 'function') {
options.success()
}
}
}
navigation.redirectAfterLogin('')
assert.strictEqual(redirectedTo, '/admin/pages/workbench/index')
assert.strictEqual(relaunchedTo, '')
@@ -0,0 +1,40 @@
/**
* Purpose: ensureStore supports page-state.js by holding or executing the ensure store page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function ensureStore() {
const app = getApp()
app.globalData.pageDirtyFlags = app.globalData.pageDirtyFlags || {}
return app.globalData.pageDirtyFlags
}
/**
* Purpose: markDirty supports page-state.js by holding or executing the mark dirty page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function markDirty(key) {
if (!key) {
return
}
const store = ensureStore()
store[key] = true
}
/**
* Purpose: consumeDirty supports page-state.js by holding or executing the consume dirty page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function consumeDirty(key) {
if (!key) {
return false
}
const store = ensureStore()
const value = Boolean(store[key])
delete store[key]
return value
}
module.exports = {
markDirty,
consumeDirty
}
+295
View File
@@ -0,0 +1,295 @@
/**
* Purpose: MANAGE_MODULES supports permission.js by holding or executing the manage modules page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const MANAGE_MODULES = [
{
key: 'users',
title: '用户管理',
description: '用户资料、停用删除、解绑、余额与 VIP',
path: '/pages/users/index',
permissionCodes: ['user:view'],
requiresShopContext: false
},
{
key: 'products',
title: '作品管理',
description: '作品新增、编辑、图片上传、点赞收藏维护',
path: '/pages/products/index',
permissionCodes: ['product:view'],
requiresShopContext: true
},
{
key: 'coupons',
title: '优惠券',
description: '普通券、VIP 自动券、发放与活动配置',
path: '/pages/coupons/index',
permissionCodes: ['coupon:view'],
requiresShopContext: true
},
{
key: 'comments',
title: '评论管理',
description: '查看作品评论与回复,删除不合规内容',
path: '/pages/comments/index',
permissionCodes: ['comment:view'],
requiresShopContext: true
},
{
key: 'tags',
title: '标签管理',
description: '店铺标签、颜色配置与作品关联',
path: '/pages/tags/index',
permissionCodes: ['tag:view'],
requiresShopContext: true
},
{
key: 'artists',
title: '美甲师',
description: '美甲师资料、档期信息与作品绑定',
path: '/pages/artists/index',
permissionCodes: ['nail_artist:view'],
requiresShopContext: true
},
{
key: 'schedules',
title: '排班管理',
description: '查看和维护美甲师班次、休息日与预约容量',
path: '/pages/schedules/index',
permissionCodes: ['schedule:view'],
requiresShopContext: true
},
{
key: 'afterSales',
title: '售后处理',
description: '查看售后申请,完成同意、驳回和处理说明',
path: '/pages/after-sales/index',
permissionCodes: ['after_sale:view'],
requiresShopContext: true
},
{
key: 'inventory',
title: '库存管理',
description: '查看耗材库存、预警并快速调整入库出库',
path: '/pages/inventory/index',
permissionCodes: ['inventory:view'],
requiresShopContext: true
},
{
key: 'campaigns',
title: '活动管理',
description: '查看营销活动、推荐位和轻量活动配置',
path: '/pages/campaigns/index',
permissionCodes: ['campaign:view'],
requiresShopContext: true
},
{
key: 'shops',
title: '店铺管理',
description: '门店创建、启停、轮播图与店铺信息维护',
path: '/pages/shops/index',
permissionCodes: ['shop:view'],
requiresShopContext: false
},
{
key: 'permissions',
title: '权限管理',
description: '权限字典、用户授权与范围控制',
path: '/pages/permissions/index',
permissionCodes: ['permission:view'],
requiresShopContext: false
},
{
key: 'systemMessages',
title: '系统消息',
description: '发布消息、查看弹窗配置和业务跳转信息',
path: '/pages/system-messages/index',
permissionCodes: ['message:view'],
requiresShopContext: false
},
{
key: 'securityAudit',
title: '审计日志',
description: '查看高危操作的成功、失败原因与操作者',
path: '/pages/security-audit/index',
permissionCodes: ['security:audit:view'],
requiresShopContext: false
}
]
/**
* Purpose: getPermissionCodes supports permission.js by holding or executing the get permission codes page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getPermissionCodes(source) {
const list = Array.isArray(source) ? source : []
return list
.map(item => {
if (typeof item === 'string') {
return item
}
return item && item.permissionCode ? item.permissionCode : ''
})
.filter(Boolean)
}
/**
* Purpose: hasPermission supports permission.js by holding or executing the has permission page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function hasPermission(source, permissionCode) {
if (!permissionCode) {
return true
}
const codes = getPermissionCodes(source)
return codes.includes(permissionCode)
}
/**
* Purpose: hasAnyPermission supports permission.js by holding or executing the has any permission page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function hasAnyPermission(source, permissionCodes) {
const codes = Array.isArray(permissionCodes) ? permissionCodes : []
if (!codes.length) {
return true
}
return codes.some(code => hasPermission(source, code))
}
/**
* Purpose: hasAllPermissions supports permission.js by holding or executing the has all permissions page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function hasAllPermissions(source, permissionCodes) {
const codes = Array.isArray(permissionCodes) ? permissionCodes : []
if (!codes.length) {
return true
}
return codes.every(code => hasPermission(source, code))
}
/**
* Purpose: isPlatformAdmin supports permission.js by holding or executing the is platform admin page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isPlatformAdmin(userInfo) {
return Number(userInfo && userInfo.type) === 4
}
/**
* Purpose: isShopManager supports permission.js by holding or executing the is shop manager page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isShopManager(userInfo) {
return Number(userInfo && userInfo.type) === 2
}
/**
* Purpose: isNailArtist supports permission.js by holding or executing the is nail artist page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isNailArtist(userInfo) {
return Number(userInfo && userInfo.type) === 3
}
/**
* Purpose: getRoleLabel supports permission.js by holding or executing the get role label page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getRoleLabel(type) {
const value = Number(type)
if (value === 4) {
return '平台管理员'
}
if (value === 2) {
return '店长'
}
if (value === 3) {
return '美甲师'
}
return '用户'
}
/**
* Purpose: groupPermissionsByGroup supports permission.js by holding or executing the group permissions by group page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function groupPermissionsByGroup(permissions) {
return (Array.isArray(permissions) ? permissions : []).reduce((result, item) => {
const group = item && item.permissionGroup ? item.permissionGroup : '未分组'
if (!result[group]) {
result[group] = []
}
result[group].push(item)
return result
}, {})
}
/**
* Purpose: checkModuleAccess supports permission.js by holding or executing the check module access page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function checkModuleAccess(module, userInfo, permissionCodes, currentShop) {
if (!hasAnyPermission(permissionCodes, module.permissionCodes)) {
return {
allowed: false,
reason: '当前账号没有该板块权限'
}
}
if (module.requiresShopContext && !currentShop) {
if (isPlatformAdmin(userInfo)) {
return {
allowed: true,
reason: '平台总览模式下该模块仅可查看,编辑操作已关闭',
readonly: true
}
}
return {
allowed: false,
reason: '当前账号没有可用店铺'
}
}
return {
allowed: true,
reason: ''
}
}
/**
* Purpose: getManageModules supports permission.js by holding or executing the get manage modules page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getManageModules(userInfo, permissionCodes, currentShop) {
return MANAGE_MODULES.map(module => {
const access = checkModuleAccess(module, userInfo, permissionCodes, currentShop)
return {
...module,
allowed: access.allowed,
readonly: Boolean(access.readonly),
disabledReason: access.reason
}
})
}
module.exports = {
MANAGE_MODULES,
getPermissionCodes,
hasPermission,
hasAnyPermission,
hasAllPermissions,
isPlatformAdmin,
isShopManager,
isNailArtist,
getRoleLabel,
groupPermissionsByGroup,
checkModuleAccess,
getManageModules
}
+560
View File
@@ -0,0 +1,560 @@
/**
* Purpose: auth supports request.js by holding or executing the auth page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const auth = require('./auth')
/**
* Purpose: actionGuard supports request.js by holding or executing the action guard page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const actionGuard = require('./action-guard')
/**
* Purpose: idleSession supports request.js by holding or executing the idle session page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const idleSession = require('./idle-session')
const { ADMIN_API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config')
const { getDeviceId } = require('./device')
const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto')
/**
* Purpose: DEVICE_ID_HEADER supports request.js by holding or executing the device id header page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DEVICE_ID_HEADER = 'X-Device-Id'
/**
* Purpose: HEADER_TIMESTAMP supports request.js by holding or executing the header timestamp page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_TIMESTAMP = 'X-Timestamp'
/**
* Purpose: HEADER_NONCE supports request.js by holding or executing the header nonce page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_NONCE = 'X-Nonce'
/**
* Purpose: HEADER_SIGNATURE supports request.js by holding or executing the header signature page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_SIGNATURE = 'X-Signature'
/**
* Purpose: HEADER_SIGNATURE_VERSION supports request.js by holding or executing the header signature version page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
/**
* Purpose: isRefreshing supports request.js by holding or executing the is refreshing page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let isRefreshing = false
/**
* Purpose: requestQueue supports request.js by holding or executing the request queue page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let requestQueue = []
/**
* Purpose: redirectingToLogin supports request.js by holding or executing the redirecting to login page or API role.
* Usage: import, call, read, or update this let from the owning page/module while preserving the surrounding loading and permission flow.
*/
let redirectingToLogin = false
/**
* Purpose: inflightRequests supports request.js by holding or executing the inflight requests page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const inflightRequests = {}
/**
* Purpose: buildRequestUrl supports request.js by holding or executing the build request url page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildRequestUrl(url, params) {
const query = Object.keys(params || {})
.filter(key => params[key] !== undefined && params[key] !== null && params[key] !== '')
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
.join('&')
const target = `${ADMIN_API_BASE_URL}${url}`
return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target
}
/**
* Purpose: extractPath supports request.js by holding or executing the extract path page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function extractPath(value) {
const target = String(value || '')
if (!target) {
return ''
}
if (/^[a-z][a-z\d+\-.]*:\/\//i.test(target)) {
try {
return new URL(target).pathname
} catch (error) {}
}
return target.split('?')[0] || ''
}
/**
* Purpose: toBackendRequestPath supports request.js by holding or executing the to backend request path page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function toBackendRequestPath(url) {
const path = extractPath(url).replace(/\/+$/, '') || '/'
if (path === '/admin/api') {
return '/admin'
}
if (path.startsWith('/admin/api/')) {
return `/admin/${path.slice('/admin/api/'.length)}`
}
if (path === '/api/admin') {
return '/admin'
}
if (path.startsWith('/api/admin/')) {
return `/admin/${path.slice('/api/admin/'.length)}`
}
if (path === '/admin' || path.startsWith('/admin/')) {
return path
}
return path.startsWith('/') ? `/admin${path}` : `/admin/${path}`
}
/**
* Purpose: isAuthFreePath supports request.js by holding or executing the is auth free path page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isAuthFreePath(url) {
return [
'/auth/login',
'/auth/refresh',
'/auth/login-shops/'
].some(path => String(url || '').includes(path))
}
/**
* Purpose: normalizeError supports request.js by holding or executing the normalize error page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function normalizeError(message, statusCode, raw) {
const error = new Error(message || '\u8bf7\u6c42\u5931\u8d25')
error.statusCode = statusCode
error.raw = raw
return error
}
/**
* Purpose: rawRequest supports request.js by holding or executing the raw request page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function rawRequest(options) {
idleSession.markActive()
return new Promise((resolve, reject) => {
wx.request({
...options,
success: resolve,
fail: reject
})
})
}
/**
* Purpose: queueRequest supports request.js by holding or executing the queue request page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function queueRequest(retry) {
return new Promise((resolve, reject) => {
requestQueue.push({
resolve,
reject,
retry
})
})
}
/**
* Purpose: flushQueue supports request.js by holding or executing the flush queue page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function flushQueue(error) {
const queue = requestQueue.slice()
requestQueue = []
queue.forEach(item => {
if (error) {
item.reject(error)
return
}
item.retry().then(item.resolve).catch(item.reject)
})
}
/**
* Purpose: redirectToLogin supports request.js by holding or executing the redirect to login page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function redirectToLogin() {
if (redirectingToLogin) {
return
}
const pages = getCurrentPages()
const current = pages[pages.length - 1]
if (current && current.route === 'admin/pages/login/index') {
return
}
redirectingToLogin = true
const currentPath = current ? `/${current.route}` : '/admin/pages/workbench/index'
const query = current && current.options ? current.options : {}
const queryString = Object.keys(query)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
.join('&')
const redirect = queryString ? `${currentPath}?${queryString}` : currentPath
wx.showToast({
title: '\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55',
icon: 'none'
})
setTimeout(() => {
wx.reLaunch({
url: `/admin/pages/login/index?redirect=${encodeURIComponent(redirect)}`,
complete() {
redirectingToLogin = false
}
})
}, 240)
}
/**
* Purpose: buildSignatureHeaders supports request.js by holding or executing the build signature headers page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildSignatureHeaders(options) {
const headers = {
[DEVICE_ID_HEADER]: getDeviceId()
}
const method = String(options.method || 'GET').toUpperCase()
const accessToken = auth.getAccessToken()
if (accessToken && !isAuthFreePath(options.url)) {
headers.Authorization = `Bearer ${accessToken}`
}
if (!ENABLE_REQUEST_SIGNING || !accessToken || isAuthFreePath(options.url) || ['GET', 'HEAD', 'OPTIONS'].includes(method)) {
return headers
}
const formData = options.formData
const hasFormData = formData && Object.keys(formData).length > 0
const contentType = String((options.header && options.header['Content-Type']) || options.contentType || 'application/json').toLowerCase()
const payload = contentType.includes('application/json') && !hasFormData
? buildJsonPayload(options.data)
: buildCanonicalParams(formData || options.data || options.params)
const timestamp = String(Date.now())
const nonce = randomNonce()
const canonical = [
method,
toBackendRequestPath(options.url),
timestamp,
nonce,
sha256Hex(payload)
].join('\n')
headers[HEADER_TIMESTAMP] = timestamp
headers[HEADER_NONCE] = nonce
headers[HEADER_SIGNATURE] = hmacSha256Hex(accessToken, canonical)
headers[HEADER_SIGNATURE_VERSION] = 'v1'
return headers
}
/**
* Purpose: refreshToken supports request.js by holding or executing the refresh token page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function refreshToken() {
const refreshTokenValue = auth.getRefreshToken()
if (!refreshTokenValue) {
throw normalizeError('\u7f3a\u5c11\u5237\u65b0\u4ee4\u724c', 401)
}
const response = await rawRequest({
url: `${ADMIN_API_BASE_URL}/auth/refresh`,
method: 'POST',
timeout: REQUEST_TIMEOUT,
header: {
'Content-Type': 'application/json',
[DEVICE_ID_HEADER]: getDeviceId()
},
data: {
refreshToken: refreshTokenValue
}
})
if (response.statusCode === 200 && response.data && response.data.code === 200 && response.data.data) {
auth.setSession(response.data.data)
const app = getApp()
if (app && typeof app.bootstrapAdminSession === 'function') {
app.bootstrapAdminSession()
}
return response.data.data
}
throw normalizeError(
(response.data && response.data.message) || '\u5237\u65b0\u540e\u53f0\u767b\u5f55\u6001\u5931\u8d25',
response.statusCode,
response
)
}
/**
* Purpose: handleUnauthorized supports request.js by holding or executing the handle unauthorized page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function handleUnauthorized(options) {
if (options._retry || isAuthFreePath(options.url)) {
const app = getApp()
if (app && typeof app.clearAdminSession === 'function') {
app.clearAdminSession()
} else {
auth.clearSession()
}
redirectToLogin()
throw normalizeError('\u767b\u5f55\u5df2\u5931\u6548\uff0c\u8bf7\u91cd\u65b0\u767b\u5f55', 401)
}
if (isRefreshing) {
return queueRequest(() => request({
...options,
_retry: true
}))
}
isRefreshing = true
try {
await refreshToken()
flushQueue(null)
return await request({
...options,
_retry: true
})
} catch (error) {
flushQueue(error)
const app = getApp()
if (app && typeof app.clearAdminSession === 'function') {
app.clearAdminSession()
} else {
auth.clearSession()
}
redirectToLogin()
throw error
} finally {
isRefreshing = false
}
}
/**
* Purpose: unwrapResponse supports request.js by holding or executing the unwrap response page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function unwrapResponse(response, options) {
idleSession.markActive()
if (response.statusCode === 401) {
return handleUnauthorized(options)
}
if (response.statusCode === 403) {
throw normalizeError(
(response.data && response.data.message) || '\u6743\u9650\u4e0d\u8db3',
response.statusCode,
response
)
}
if (response.statusCode >= 400) {
throw normalizeError(
(response.data && response.data.message) || '\u7f51\u7edc\u8bf7\u6c42\u5931\u8d25',
response.statusCode,
response
)
}
const payload = response.data
if (payload && typeof payload === 'object' && Object.prototype.hasOwnProperty.call(payload, 'code')) {
if (payload.code === 200) {
return payload.data
}
throw normalizeError(payload.message || '\u8bf7\u6c42\u5931\u8d25', payload.code, payload)
}
return payload
}
/**
* Purpose: buildDedupeKey supports request.js by holding or executing the build dedupe key page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildDedupeKey(options, method) {
if (options.skipDedupe) {
return ''
}
if (options.dedupeKey) {
return `${method}:${options.dedupeKey}`
}
if (method === 'GET') {
return `${method}:${options.url}:${buildCanonicalParams(options.params)}`
}
return ''
}
/**
* Purpose: isSafeMethod supports request.js by holding or executing the is safe method page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function isSafeMethod(method) {
return ['GET', 'HEAD', 'OPTIONS'].includes(method)
}
/**
* Purpose: buildActionFingerprint supports request.js by holding or executing the build action fingerprint page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildActionFingerprint(options, method) {
const paramsText = buildCanonicalParams(options.params)
const payloadText = isSafeMethod(method) ? '' : buildJsonPayload(options.data)
return sha256Hex([
options.url || '',
paramsText,
payloadText
].join('\n'))
}
/**
* Purpose: resolveRepeatMessage supports request.js by holding or executing the resolve repeat message page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function resolveRepeatMessage(url) {
const path = String(url || '')
if (path.includes('/auth/login')) {
return '\u767b\u5f55\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
if (path.includes('/auth/switch-shop')) {
return '\u95e8\u5e97\u5207\u6362\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/auth/logout')) {
return '\u9000\u51fa\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/coupon/distribute') || path.includes('/coupon/assign') || path.includes('/order/update-status')) {
return '\u64cd\u4f5c\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
if (path.includes('/upload')) {
return '\u4e0a\u4f20\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (
path.includes('/user/create')
|| path.includes('/user/update')
|| path.includes('/product/create')
|| path.includes('/product/update')
|| path.includes('/shops/create')
|| path.includes('/shops/update')
|| path.includes('/tag/create')
|| path.includes('/tag/update')
|| path.includes('/permission/create')
|| path.includes('/permission/update')
|| path.includes('/nail-artist/save')
) {
return '\u4fdd\u5b58\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
return '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
}
/**
* Purpose: buildActionGuardConfig supports request.js by holding or executing the build action guard config page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function buildActionGuardConfig(options, method) {
if (options.skipActionGuard || isSafeMethod(method)) {
return null
}
return {
scope: options.guardScope,
key: options.actionKey || `${method}:${options.url}:${buildActionFingerprint(options, method)}`,
message: options.repeatMessage || resolveRepeatMessage(options.url)
}
}
/**
* Purpose: request supports request.js by holding or executing the request page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function request(options) {
const method = String(options.method || 'GET').toUpperCase()
const dedupeKey = buildDedupeKey(options, method)
if (dedupeKey && inflightRequests[dedupeKey]) {
return inflightRequests[dedupeKey]
}
const signatureHeaders = buildSignatureHeaders({
url: options.url,
method,
data: options.data,
params: options.params,
header: options.header
})
const header = {
'Content-Type': 'application/json',
...signatureHeaders,
...(options.header || {})
}
const requestOptions = {
...options,
method,
header
}
const actionGuardConfig = buildActionGuardConfig(options, method)
const executeRequest = () => new Promise((resolve, reject) => {
wx.request({
url: buildRequestUrl(options.url, options.params),
method,
timeout: options.timeout || REQUEST_TIMEOUT,
header,
data: method === 'GET' ? undefined : options.data,
success: async response => {
try {
const data = await unwrapResponse(response, requestOptions)
resolve(data)
} catch (error) {
reject(error)
}
},
fail: error => {
reject(normalizeError(error.errMsg || '\u7f51\u7edc\u5f02\u5e38\uff0c\u8bf7\u7a0d\u540e\u91cd\u8bd5', 0, error))
}
})
})
const task = (actionGuardConfig
? actionGuard.run(actionGuardConfig.scope, actionGuardConfig.key, executeRequest, {
message: actionGuardConfig.message
})
: executeRequest()
).finally(() => {
if (dedupeKey) {
delete inflightRequests[dedupeKey]
}
})
if (dedupeKey) {
inflightRequests[dedupeKey] = task
}
return task
}
request.buildSignatureHeaders = buildSignatureHeaders
request.getDeviceIdHeaderName = () => DEVICE_ID_HEADER
module.exports = request
+81
View File
@@ -0,0 +1,81 @@
/**
* Purpose: STORAGE_KEYS supports storage.js by holding or executing the storage keys page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const STORAGE_KEYS = {
ACCESS_TOKEN: 'adminAccessToken',
REFRESH_TOKEN: 'adminRefreshToken',
USER_INFO: 'adminUserInfo',
PERMISSIONS: 'adminPermissions',
CURRENT_SHOP: 'adminCurrentShop',
DEVICE_ID: 'adminMiniDeviceId'
}
/**
* Purpose: TEMP_RECORD_PREFIX supports storage.js by holding or executing the temp record prefix page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const TEMP_RECORD_PREFIX = 'adminTempRecord:'
/**
* Purpose: getStorage supports storage.js by holding or executing the get storage page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getStorage(key, defaultValue) {
try {
const value = wx.getStorageSync(key)
return value === '' || value === undefined ? defaultValue : value
} catch (error) {
return defaultValue
}
}
/**
* Purpose: setStorage supports storage.js by holding or executing the set storage page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function setStorage(key, value) {
wx.setStorageSync(key, value)
}
/**
* Purpose: removeStorage supports storage.js by holding or executing the remove storage page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function removeStorage(key) {
wx.removeStorageSync(key)
}
/**
* Purpose: setTempRecord supports storage.js by holding or executing the set temp record page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function setTempRecord(name, value) {
setStorage(`${TEMP_RECORD_PREFIX}${name}`, value)
}
/**
* Purpose: getTempRecord supports storage.js by holding or executing the get temp record page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getTempRecord(name, defaultValue) {
return getStorage(`${TEMP_RECORD_PREFIX}${name}`, defaultValue)
}
/**
* Purpose: clearTempRecord supports storage.js by holding or executing the clear temp record page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function clearTempRecord(name) {
removeStorage(`${TEMP_RECORD_PREFIX}${name}`)
}
module.exports = {
STORAGE_KEYS,
getStorage,
setStorage,
removeStorage,
setTempRecord,
getTempRecord,
clearTempRecord
}
+246
View File
@@ -0,0 +1,246 @@
/**
* Purpose: fileApi supports upload.js by holding or executing the file api page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const fileApi = require('../api/file')
/**
* Purpose: getFileSystemManager supports upload.js by holding or executing the get file system manager page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getFileSystemManager() {
return wx.getFileSystemManager()
}
/**
* Purpose: getFileInfo supports upload.js by holding or executing the get file info page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function getFileInfo(filePath) {
return new Promise((resolve, reject) => {
wx.getFileInfo({
filePath,
success: resolve,
fail: reject
})
})
}
/**
* Purpose: readFileBuffer supports upload.js by holding or executing the read file buffer page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function readFileBuffer(filePath) {
return new Promise((resolve, reject) => {
getFileSystemManager().readFile({
filePath,
success: result => resolve(result.data),
fail: reject
})
})
}
/**
* Purpose: writeChunkFile supports upload.js by holding or executing the write chunk file page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function writeChunkFile(filePath, data) {
return new Promise((resolve, reject) => {
getFileSystemManager().writeFile({
filePath,
data,
encoding: 'binary',
success: resolve,
fail: reject
})
})
}
/**
* Purpose: removeFile supports upload.js by holding or executing the remove file page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function removeFile(filePath) {
return new Promise(resolve => {
getFileSystemManager().unlink({
filePath,
success: resolve,
fail: resolve
})
})
}
/**
* Purpose: normalizeSelectedFiles supports upload.js by holding or executing the normalize selected files page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function normalizeSelectedFiles(files) {
return (Array.isArray(files) ? files : []).map((item, index) => {
if (typeof item === 'string') {
return {
tempFilePath: item,
fileName: `image-${index + 1}.jpg`
}
}
return {
tempFilePath: item.tempFilePath || item.path || '',
fileName: item.fileName || item.name || `image-${index + 1}.jpg`
}
}).filter(item => item.tempFilePath)
}
/**
* Purpose: createFingerprint supports upload.js by holding or executing the create fingerprint page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function createFingerprint(seed) {
let hash = 0
const text = String(seed || '')
for (let index = 0; index < text.length; index += 1) {
hash = ((hash << 5) - hash) + text.charCodeAt(index)
hash |= 0
}
return `mini-${Math.abs(hash)}`
}
/**
* Purpose: resolveContentType supports upload.js by holding or executing the resolve content type page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function resolveContentType(fileName) {
const value = String(fileName || '').toLowerCase()
if (value.endsWith('.png')) {
return 'image/png'
}
if (value.endsWith('.webp')) {
return 'image/webp'
}
if (value.endsWith('.gif')) {
return 'image/gif'
}
return 'image/jpeg'
}
/**
* Purpose: uploadSingleFile supports upload.js by holding or executing the upload single file page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function uploadSingleFile(file, scene, onProgress) {
const fileInfo = await getFileInfo(file.tempFilePath)
const buffer = await readFileBuffer(file.tempFilePath)
const contentType = resolveContentType(file.fileName)
const session = await fileApi.initChunkUpload({
fileName: file.fileName,
fileSize: fileInfo.size,
contentType,
fileFingerprint: createFingerprint(`${file.fileName}|${fileInfo.size}|${file.tempFilePath}`),
scene
})
const uploadedChunkSet = new Set(session.uploadedChunks || [])
let uploadedBytes = 0
const chunkSize = Number(session.chunkSize || 0)
const totalChunks = Number(session.totalChunks || 0)
if (!chunkSize || !totalChunks) {
throw new Error('上传会话初始化失败')
}
Array.from(uploadedChunkSet).forEach(chunkIndex => {
const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileInfo.size)
uploadedBytes += Math.max(end - start, 0)
})
onProgress(Math.min((uploadedBytes / Math.max(fileInfo.size, 1)) * 100, 100))
for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex += 1) {
if (uploadedChunkSet.has(chunkIndex)) {
continue
}
const start = chunkIndex * chunkSize
const end = Math.min(start + chunkSize, fileInfo.size)
const chunkBuffer = buffer.slice(start, end)
const chunkPath = `${wx.env.USER_DATA_PATH}/${session.uploadId}-${chunkIndex}.part`
await writeChunkFile(chunkPath, chunkBuffer)
try {
await fileApi.uploadChunkFile({
filePath: chunkPath,
uploadId: session.uploadId,
chunkIndex,
totalChunks,
onProgress(progress) {
const loaded = Number(progress && progress.totalBytesSent) || 0
const currentBytes = Math.min(loaded, end - start)
const percent = ((uploadedBytes + currentBytes) / Math.max(fileInfo.size, 1)) * 100
onProgress(Math.min(percent, 99.9))
}
})
} finally {
await removeFile(chunkPath)
}
uploadedBytes += (end - start)
onProgress(Math.min((uploadedBytes / Math.max(fileInfo.size, 1)) * 100, 99.9))
}
const result = await fileApi.completeChunkUpload(session.uploadId)
onProgress(100)
return result
}
/**
* Purpose: uploadImageFiles supports upload.js by holding or executing the upload image files page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
async function uploadImageFiles(options) {
const files = normalizeSelectedFiles(options && options.files)
const scene = options && options.scene ? options.scene : 'admin-product-image'
const onProgress = typeof options.onProgress === 'function' ? options.onProgress : () => {}
const results = []
for (let index = 0; index < files.length; index += 1) {
const basePercent = (index / Math.max(files.length, 1)) * 100
const filePercentSize = 100 / Math.max(files.length, 1)
const result = await uploadSingleFile(files[index], scene, percent => {
onProgress(Math.min(basePercent + (percent / 100) * filePercentSize, 100))
})
results.push(result)
}
onProgress(100)
return results
}
/**
* Purpose: chooseImageFiles supports upload.js by holding or executing the choose image files page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
function chooseImageFiles(options) {
const config = options || {}
return new Promise((resolve, reject) => {
wx.chooseMedia({
count: config.count || 9,
mediaType: ['image'],
sourceType: ['album', 'camera'],
success: result => {
resolve(normalizeSelectedFiles(result.tempFiles || []))
},
fail: reject
})
})
}
module.exports = {
chooseImageFiles,
uploadImageFiles
}