统一甲屿云命名体系

This commit is contained in:
2026-06-29 23:26:43 +08:00
parent 48c47fe3ff
commit bc8a7d8d4c
1268 changed files with 3477 additions and 3511 deletions
+110
View File
@@ -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
}
+210
View File
@@ -0,0 +1,210 @@
const { STORAGE_KEYS, getStorage, removeStorage, setStorage } = require('./storage')
/**
* Purpose: SIGNED_URL_SAFE_BUFFER_MS supports auth.js by holding or executing the signed url safe buffer ms 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 SIGNED_URL_SAFE_BUFFER_MS = 60 * 1000
/**
* Purpose: parseSignedUrlExpireAt supports auth.js by holding or executing the parse signed url expire at 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 parseSignedUrlExpireAt(url) {
const rawUrl = String(url || '').trim()
if (!rawUrl || rawUrl.indexOf('?') < 0) {
return 0
}
const queryString = rawUrl.slice(rawUrl.indexOf('?') + 1)
const params = {}
queryString.split('&').forEach(segment => {
if (!segment) {
return
}
const dividerIndex = segment.indexOf('=')
const key = dividerIndex >= 0 ? segment.slice(0, dividerIndex) : segment
const value = dividerIndex >= 0 ? segment.slice(dividerIndex + 1) : ''
params[decodeURIComponent(key)] = decodeURIComponent(value)
})
const awsDate = params['X-Amz-Date']
const awsExpireSeconds = Number(params['X-Amz-Expires'] || 0)
if (awsDate && awsExpireSeconds > 0 && awsDate.length >= 16) {
const year = Number(awsDate.slice(0, 4))
const month = Number(awsDate.slice(4, 6)) - 1
const day = Number(awsDate.slice(6, 8))
const hour = Number(awsDate.slice(9, 11))
const minute = Number(awsDate.slice(11, 13))
const second = Number(awsDate.slice(13, 15))
const baseTimestamp = Date.UTC(year, month, day, hour, minute, second)
if (!Number.isNaN(baseTimestamp)) {
return baseTimestamp + awsExpireSeconds * 1000
}
}
const expires = Number(params.Expires || 0)
if (expires > 0) {
return expires * 1000
}
return 0
}
/**
* Purpose: sanitizeStoredUserInfo supports auth.js by holding or executing the sanitize 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 sanitizeStoredUserInfo(userInfo) {
if (!userInfo || typeof userInfo !== 'object') {
return userInfo
}
const nextUserInfo = {
...userInfo
}
const avatarExpireAt = parseSignedUrlExpireAt(nextUserInfo.avatar)
if (avatarExpireAt > 0 && avatarExpireAt <= Date.now() + SIGNED_URL_SAFE_BUFFER_MS) {
nextUserInfo.avatar = ''
}
return nextUserInfo
}
/**
* 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() {
const userInfo = sanitizeStoredUserInfo(getStorage(STORAGE_KEYS.USER_INFO, null))
if (userInfo) {
setStorage(STORAGE_KEYS.USER_INFO, userInfo)
}
return userInfo
}
/**
* Purpose: getNeedSetPassword supports auth.js by holding or executing the get need set password 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 getNeedSetPassword() {
return Boolean(getStorage(STORAGE_KEYS.NEED_SET_PASSWORD, false))
}
/**
* Purpose: getPreferredMiniLoginShopId supports auth.js by holding or executing the get preferred mini login shop 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 getPreferredMiniLoginShopId() {
return getStorage(STORAGE_KEYS.PREFERRED_MINI_LOGIN_SHOP_ID, '')
}
/**
* 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, sanitizeStoredUserInfo(payload.userInfo))
}
if (payload.needSetPassword) {
setStorage(STORAGE_KEYS.NEED_SET_PASSWORD, true)
} else {
removeStorage(STORAGE_KEYS.NEED_SET_PASSWORD)
}
}
/**
* 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, sanitizeStoredUserInfo(userInfo))
}
/**
* Purpose: setNeedSetPassword supports auth.js by holding or executing the set need set password 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 setNeedSetPassword(value) {
if (value) {
setStorage(STORAGE_KEYS.NEED_SET_PASSWORD, true)
return
}
removeStorage(STORAGE_KEYS.NEED_SET_PASSWORD)
}
/**
* 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.NEED_SET_PASSWORD)
}
/**
* Purpose: setPreferredMiniLoginShopId supports auth.js by holding or executing the set preferred mini login shop 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 setPreferredMiniLoginShopId(shopId) {
if (shopId === undefined || shopId === null || shopId === '') {
removeStorage(STORAGE_KEYS.PREFERRED_MINI_LOGIN_SHOP_ID)
return
}
setStorage(STORAGE_KEYS.PREFERRED_MINI_LOGIN_SHOP_ID, String(shopId))
}
module.exports = {
getAccessToken,
getRefreshToken,
getStoredUserInfo,
getNeedSetPassword,
getPreferredMiniLoginShopId,
isLoggedIn,
setSession,
updateStoredUserInfo,
setNeedSetPassword,
setPreferredMiniLoginShopId,
clearSession,
sanitizeStoredUserInfo
}
+49
View File
@@ -0,0 +1,49 @@
const STORAGE_KEY = 'YUMI_BUY_NOW_CONTEXT'
function createBuyNowContext(productId) {
return {
mode: 'buyNow',
productId: String(productId || ''),
createdAt: Date.now()
}
}
function saveBuyNowContext(productId) {
const context = createBuyNowContext(productId)
wx.setStorageSync(STORAGE_KEY, context)
return context
}
function readBuyNowContext(maxAgeMs = 5 * 60 * 1000) {
const context = wx.getStorageSync(STORAGE_KEY)
if (!context || context.mode !== 'buyNow' || !context.productId) {
return null
}
if (Date.now() - Number(context.createdAt || 0) > maxAgeMs) {
return null
}
return context
}
function clearBuyNowContext() {
wx.removeStorageSync(STORAGE_KEY)
}
function consumeBuyNowContext(maxAgeMs = 5 * 60 * 1000) {
const context = readBuyNowContext(maxAgeMs)
clearBuyNowContext()
return context
}
function isBuyNowCartItem(item, productId) {
return Boolean(productId) && String(item && item.productId || '') === String(productId)
}
module.exports = {
STORAGE_KEY,
clearBuyNowContext,
consumeBuyNowContext,
isBuyNowCartItem,
readBuyNowContext,
saveBuyNowContext
}
+152
View File
@@ -0,0 +1,152 @@
/**
* 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 = 'miniCache:'
/**
* 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: 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: 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: clearExpiredEntry supports cache.js by holding or executing the clear expired entry 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 clearExpiredEntry(key, entry) {
if (!entry) {
return
}
if (entry.expireAt && entry.expireAt <= now()) {
delete memoryCache[key]
try {
wx.removeStorageSync(buildKey(key))
} catch (error) {}
}
}
/**
* 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 localEntry = memoryCache[key]
if (localEntry && (!localEntry.expireAt || localEntry.expireAt > now())) {
return localEntry.value
}
clearExpiredEntry(key, localEntry)
try {
const storedEntry = wx.getStorageSync(buildKey(key))
if (storedEntry && (!storedEntry.expireAt || storedEntry.expireAt > now())) {
memoryCache[key] = storedEntry
return storedEntry.value
}
clearExpiredEntry(key, storedEntry)
} 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 expireAt = ttlMs && ttlMs > 0 ? now() + ttlMs : 0
const entry = {
value,
expireAt
}
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: removeByPrefix supports cache.js by holding or executing the remove by prefix 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 removeByPrefix(prefix) {
Object.keys(memoryCache).forEach(key => {
if (key.startsWith(prefix)) {
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,
removeByPrefix,
remember
}
+195
View File
@@ -0,0 +1,195 @@
/**
* 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) {}
try {
if (typeof __wxConfig !== 'undefined' && __wxConfig && __wxConfig.envVersion) {
return __wxConfig.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 {
if (typeof wx.getDeviceInfo === 'function') {
const deviceInfo = wx.getDeviceInfo()
if (deviceInfo && deviceInfo.platform) {
return deviceInfo.platform
}
}
} catch (error) {}
try {
if (typeof wx.getSystemInfoSync === 'function') {
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()
if (!target) {
return ''
}
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
)
const BRAND_CONFIG = {
appName: String(localOverride.appName || 'Jayu Artist'),
appNameEn: String(localOverride.appNameEn || 'Jiayu Designer'),
appTitle: String(localOverride.appTitle || 'Jayu Artist')
}
module.exports = {
ENV_VERSION,
RUNTIME_PLATFORM,
IS_DEVTOOLS,
DEVELOP_TARGET,
API_DOMAIN,
BRAND_CONFIG,
API_BASE_URL: `${API_DOMAIN}/api`,
IS_DEV_ENV: ENV_VERSION === 'develop',
REQUEST_TIMEOUT: Number(localOverride.requestTimeout || 10000),
ENABLE_REQUEST_SIGNING: localOverride.enableRequestSigning !== false,
IDLE_TIMEOUT_MS: 60 * 60 * 1000,
IDLE_WARNING_MS: 2 * 60 * 1000,
CACHE_TTL: {
banner: 5 * 60 * 1000,
publicShops: 5 * 60 * 1000,
tags: 10 * 60 * 1000,
homeList: 2 * 60 * 1000,
signedUrl: 50 * 60 * 1000
},
DEFAULT_AVATAR: 'https://api.dicebear.com/7.x/avataaars/svg?seed=default',
DEFAULT_PRODUCT_IMAGE: '/assets/images/default-product.png',
DEFAULT_SHOP_IMAGE: '/assets/images/default-shop.png',
NO_COUPON_KEY: 'NONE',
TAB_PAGES: [
'/pages/home/index',
'/pages/products/index',
'/pages/cart/index',
'/pages/profile/index'
]
}
@@ -0,0 +1,15 @@
module.exports = {
developTarget: 'local',
appName: 'Jayu Artist',
appNameEn: 'Jiayu Designer',
appTitle: 'Jayu Artist',
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 `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
}
+164
View File
@@ -0,0 +1,164 @@
/**
* Purpose: fileApi supports file.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')
const { DEFAULT_PRODUCT_IMAGE } = require('./config')
const { CACHE_TTL } = require('./config')
const { splitCsv } = require('./format')
const { showRecoveryModal } = require('./recovery')
function handlePreviewRecoveryAction(action) {
if (!action || action.key !== 'products') {
return
}
wx.switchTab({
url: '/pages/products/index',
fail() {}
})
}
/**
* Purpose: urlCache supports file.js by holding or executing the url 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 urlCache = {}
/**
* Purpose: getSignedUrl supports file.js by holding or executing the get signed 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.
*/
async function getSignedUrl(fileId) {
const key = String(fileId || '')
if (!key) {
return ''
}
const cached = urlCache[key]
if (cached && cached.expireAt > Date.now()) {
return cached.value || ''
}
const value = await fileApi.getSignedUrl(key)
urlCache[key] = {
value: value || '',
expireAt: Date.now() + (CACHE_TTL.signedUrl || 50 * 60 * 1000)
}
return urlCache[key].value
}
/**
* Purpose: extractLegacyFileId supports file.js by holding or executing the extract legacy file 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 extractLegacyFileId(value) {
const match = String(value || '')
.replace(/<[^>]*>/g, '')
.match(/\/api\/file\/get\/(\d+)/)
return match && match[1] ? match[1] : ''
}
/**
* Purpose: resolveImageList supports file.js by holding or executing the resolve image list 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 resolveImageList(fileIds, fallbackImage) {
const ids = Array.isArray(fileIds) ? fileIds : splitCsv(fileIds)
if (!ids.length) {
return [fallbackImage || DEFAULT_PRODUCT_IMAGE]
}
const urls = (await Promise.all(ids.map(async fileId => {
try {
return await getSignedUrl(fileId)
} catch (error) {
return ''
}
}))).filter(Boolean)
return urls.length ? urls : [fallbackImage || DEFAULT_PRODUCT_IMAGE]
}
/**
* Purpose: resolveLegacyImage supports file.js by holding or executing the resolve legacy image 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 resolveLegacyImage(value, fallbackImage) {
const fileId = extractLegacyFileId(value)
if (!fileId) {
return fallbackImage || DEFAULT_PRODUCT_IMAGE
}
try {
const url = await getSignedUrl(fileId)
return url || fallbackImage || DEFAULT_PRODUCT_IMAGE
} catch (error) {
return fallbackImage || DEFAULT_PRODUCT_IMAGE
}
}
/**
* Purpose: previewImagesSafely opens wx.previewImage with a user-facing fallback when signed URLs expire or preview fails.
* Usage: pass the current image URL and full URL list from image tap handlers instead of calling wx.previewImage directly.
*/
function previewImagesSafely(current, urls, options) {
const config = options || {}
const list = (Array.isArray(urls) ? urls : [current]).filter(Boolean)
if (!current || !list.length) {
return showRecoveryModal({
title: '图片暂不可预览',
message: config.emptyMessage || '没有可预览的图片,请返回作品列表查看其他款式。',
actions: [
{ key: 'dismiss', text: '知道了' },
{ key: 'products', text: '看作品' }
]
}).then(action => {
handlePreviewRecoveryAction(action)
return action
})
}
return new Promise(resolve => {
wx.previewImage({
current,
urls: list,
success: () => resolve(null),
fail: () => {
showRecoveryModal({
title: '图片预览失败',
message: config.failMessage || '图片链接可能已过期,请重试;仍失败时可以返回作品列表重新进入。',
actions: [
{ key: 'retry', text: '重试' },
{ key: 'products', text: '看作品' }
]
}).then(action => {
if (action && action.key === 'retry') {
previewImagesSafely(current, list, config).then(resolve)
return
}
handlePreviewRecoveryAction(action)
resolve(action)
})
}
})
})
}
module.exports = {
getSignedUrl,
extractLegacyFileId,
resolveImageList,
resolveLegacyImage,
previewImagesSafely,
/**
* Purpose: clearSignedUrlCache supports file.js by holding or executing the clear signed url cache page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
clearSignedUrlCache(fileId) {
if (fileId === undefined || fileId === null || fileId === '') {
Object.keys(urlCache).forEach(key => delete urlCache[key])
return
}
delete urlCache[String(fileId)]
}
}
+105
View File
@@ -0,0 +1,105 @@
/**
* 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 = 'miniDraft:'
/**
* 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: loadDraft supports form-draft.js by holding or executing the load 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 loadDraft(key, defaultValue) {
if (!key) {
return defaultValue
}
try {
const value = wx.getStorageSync(buildDraftKey(key))
return value === undefined || value === '' ? defaultValue : 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: 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) {
const record = loadDraft(key, null)
if (!record || typeof record !== 'object' || !Object.prototype.hasOwnProperty.call(record, 'value')) {
return defaultValue
}
return record.value
}
/**
* 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
}
+147
View File
@@ -0,0 +1,147 @@
/**
* 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: getProductTitle supports format.js by holding or executing the get product title 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 getProductTitle(product) {
return (product && (product.title || product.name)) || '未命名作品'
}
/**
* 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: 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 String(left || '') === String(right || '')
}
/**
* 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: parseAppointmentParts supports format.js by holding or executing the parse appointment parts 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 parseAppointmentParts(value) {
const text = formatDateTime(value)
if (!text) {
return {
date: '',
clock: ''
}
}
const parts = text.split(' ')
return {
date: parts[0] || '',
clock: parts[1] || ''
}
}
/**
* Purpose: buildAppointmentValue supports format.js by holding or executing the build appointment 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 buildAppointmentValue(date, clock) {
if (!date || !clock) {
return ''
}
return `${date} ${clock}:00`
}
/**
* Purpose: isPastAppointment supports format.js by holding or executing the is past appointment 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 isPastAppointment(value) {
if (!value) {
return false
}
return new Date(String(value).replace(' ', 'T')).getTime() < Date.now() + 5 * 60 * 1000
}
/**
* Purpose: getMinDateText supports format.js by holding or executing the get min date 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 getMinDateText() {
const now = new Date()
const year = now.getFullYear()
const month = String(now.getMonth() + 1).padStart(2, '0')
const date = String(now.getDate()).padStart(2, '0')
return `${year}-${month}-${date}`
}
/**
* 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: getOrderStatusClass supports format.js by holding or executing the get order status class 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 getOrderStatusClass(order) {
const status = Number(order && order.status)
if (status === 1) {
return 'pending'
}
if (status === 2) {
return 'completed'
}
return 'cancelled'
}
module.exports = {
formatPrice,
getProductTitle,
splitCsv,
sameId,
formatDateTime,
parseAppointmentParts,
buildAppointmentValue,
isPastAppointment,
getMinDateText,
getOrderStatusText,
getOrderStatusClass
}
+241
View File
@@ -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
}
+299
View File
@@ -0,0 +1,299 @@
/**
* Purpose: DEFAULT_CURSOR_SPACING supports keyboard-safe.js by holding or executing the default cursor spacing 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_CURSOR_SPACING = 96
/**
* Purpose: DEFAULT_SPACER_EXTRA_RPX supports keyboard-safe.js by holding or executing the default spacer extra rpx 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_SPACER_EXTRA_RPX = 48
/**
* Purpose: DEFAULT_SCROLL_DELAY supports keyboard-safe.js by holding or executing the default scroll delay 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_SCROLL_DELAY = 32
/**
* Purpose: MAX_CURSOR_SPACING supports keyboard-safe.js by holding or executing the max cursor spacing 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 MAX_CURSOR_SPACING = 180
/**
* Purpose: getWindowWidth supports keyboard-safe.js by holding or executing the get window width 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 getWindowWidth() {
try {
if (typeof wx.getWindowInfo === 'function') {
const info = wx.getWindowInfo()
if (info && info.windowWidth) {
return info.windowWidth
}
}
const systemInfo = wx.getSystemInfoSync()
return (systemInfo && systemInfo.windowWidth) || 375
} catch (error) {
return 375
}
}
/**
* Purpose: pxToRpx supports keyboard-safe.js by holding or executing the px to rpx 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 pxToRpx(px) {
return Math.round((Number(px) || 0) * 750 / getWindowWidth())
}
/**
* Purpose: createKeyboardSafeData supports keyboard-safe.js by holding or executing the create keyboard safe data 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 createKeyboardSafeData(options = {}) {
const cursorSpacing = Number(options.cursorSpacing) > 0
? Math.round(Number(options.cursorSpacing))
: DEFAULT_CURSOR_SPACING
return {
keyboardVisible: false,
keyboardHeightPx: 0,
keyboardInsetRpx: 0,
keyboardAnchorId: '',
keyboardCursorSpacing: cursorSpacing
}
}
/**
* Purpose: clearKeyboardTimers supports keyboard-safe.js by holding or executing the clear keyboard timers 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 clearKeyboardTimers(state) {
if (!state) {
return
}
if (state.anchorTimer) {
clearTimeout(state.anchorTimer)
state.anchorTimer = null
}
if (state.blurTimer) {
clearTimeout(state.blurTimer)
state.blurTimer = null
}
}
/**
* Purpose: queueAnchorScroll supports keyboard-safe.js by holding or executing the queue anchor scroll 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 queueAnchorScroll(page, anchorId) {
const state = page && page.__keyboardSafe
if (!page || !state || !anchorId) {
return
}
if (state.anchorTimer) {
clearTimeout(state.anchorTimer)
}
const nextDelay = Number(state.options.scrollDelay) || DEFAULT_SCROLL_DELAY
const updateAnchor = () => {
if (!page.__keyboardSafe) {
return
}
page.setData({
keyboardAnchorId: anchorId
})
}
if (page.data && page.data.keyboardAnchorId === anchorId) {
page.setData({
keyboardAnchorId: ''
})
state.anchorTimer = setTimeout(updateAnchor, nextDelay)
return
}
state.anchorTimer = setTimeout(updateAnchor, 0)
}
/**
* Purpose: attachKeyboardSafe supports keyboard-safe.js by holding or executing the attach keyboard safe 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 attachKeyboardSafe(page, options = {}) {
if (!page) {
return
}
detachKeyboardSafe(page)
const state = {
activeAnchorId: '',
anchorTimer: null,
blurTimer: null,
options: {
cursorSpacing: Number(options.cursorSpacing) > 0
? Math.round(Number(options.cursorSpacing))
: DEFAULT_CURSOR_SPACING,
spacerExtraRpx: Number(options.spacerExtraRpx) >= 0
? Number(options.spacerExtraRpx)
: DEFAULT_SPACER_EXTRA_RPX,
scrollDelay: Number(options.scrollDelay) > 0
? Number(options.scrollDelay)
: DEFAULT_SCROLL_DELAY
},
listener: null
}
state.listener = result => {
const nextHeight = Math.max(0, Number(result && result.height) || 0)
const keyboardVisible = nextHeight > 0
const keyboardInsetRpx = keyboardVisible
? pxToRpx(nextHeight) + state.options.spacerExtraRpx
: 0
const keyboardCursorSpacing = keyboardVisible
? Math.max(
state.options.cursorSpacing,
Math.min(MAX_CURSOR_SPACING, Math.round(nextHeight * 0.38))
)
: state.options.cursorSpacing
page.setData({
keyboardVisible,
keyboardHeightPx: nextHeight,
keyboardInsetRpx,
keyboardCursorSpacing,
keyboardAnchorId: keyboardVisible ? page.data.keyboardAnchorId : (state.activeAnchorId ? page.data.keyboardAnchorId : '')
})
if (keyboardVisible && state.activeAnchorId) {
queueAnchorScroll(page, state.activeAnchorId)
}
}
page.__keyboardSafe = state
if (typeof wx.onKeyboardHeightChange === 'function') {
wx.onKeyboardHeightChange(state.listener)
}
}
/**
* Purpose: detachKeyboardSafe supports keyboard-safe.js by holding or executing the detach keyboard safe 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 detachKeyboardSafe(page) {
if (!page || !page.__keyboardSafe) {
return
}
const state = page.__keyboardSafe
clearKeyboardTimers(state)
if (typeof wx.offKeyboardHeightChange === 'function' && state.listener) {
try {
wx.offKeyboardHeightChange(state.listener)
} catch (error) {}
}
delete page.__keyboardSafe
}
/**
* Purpose: handleKeyboardFocus supports keyboard-safe.js by holding or executing the handle keyboard focus 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 handleKeyboardFocus(page, event) {
const state = page && page.__keyboardSafe
if (!page || !state) {
return
}
if (state.blurTimer) {
clearTimeout(state.blurTimer)
state.blurTimer = null
}
const anchorId = String(
event
&& event.currentTarget
&& event.currentTarget.dataset
&& event.currentTarget.dataset.keyboardAnchor
? event.currentTarget.dataset.keyboardAnchor
: ''
)
state.activeAnchorId = anchorId
if (anchorId) {
queueAnchorScroll(page, anchorId)
}
if (!page.data.keyboardCursorSpacing || page.data.keyboardCursorSpacing < state.options.cursorSpacing) {
page.setData({
keyboardCursorSpacing: state.options.cursorSpacing
})
}
}
/**
* Purpose: resetKeyboardSafe supports keyboard-safe.js by holding or executing the reset keyboard safe 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 resetKeyboardSafe(page, options = {}) {
if (!page) {
return
}
const state = page.__keyboardSafe
if (state) {
clearKeyboardTimers(state)
if (options.clearActiveAnchor !== false) {
state.activeAnchorId = ''
}
}
const fallbackCursorSpacing = state ? state.options.cursorSpacing : DEFAULT_CURSOR_SPACING
page.setData({
keyboardVisible: false,
keyboardHeightPx: 0,
keyboardInsetRpx: 0,
keyboardAnchorId: options.keepAnchor ? (page.data.keyboardAnchorId || '') : '',
keyboardCursorSpacing: fallbackCursorSpacing
})
}
/**
* Purpose: handleKeyboardBlur supports keyboard-safe.js by holding or executing the handle keyboard blur 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 handleKeyboardBlur(page) {
const state = page && page.__keyboardSafe
if (!page || !state) {
return
}
if (state.blurTimer) {
clearTimeout(state.blurTimer)
}
state.blurTimer = setTimeout(() => {
if (!page.__keyboardSafe) {
return
}
resetKeyboardSafe(page)
}, 120)
}
module.exports = {
createKeyboardSafeData,
attachKeyboardSafe,
detachKeyboardSafe,
handleKeyboardFocus,
handleKeyboardBlur,
resetKeyboardSafe
}
+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 || '\u52a0\u8f7d\u4e2d',
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
}
@@ -0,0 +1,41 @@
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const root = path.join(__dirname, '..')
const appWxss = fs.readFileSync(path.join(root, 'app.wxss'), 'utf8')
const productCardWxss = fs.readFileSync(path.join(root, 'components', 'product-card', 'product-card.wxss'), 'utf8')
const navigationBarWxss = fs.readFileSync(path.join(root, 'components', 'navigation-bar', 'navigation-bar.wxss'), 'utf8')
const pageRoot = path.join(root, 'pages')
const legacyThemeColorPattern = /#(?:2d2430|1f1b17|8d7a84|7a5262|c6597d|C6597D|FFF7F9|FFF8F4)\b/
function readPageSources(dir) {
return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
return readPageSources(fullPath)
}
if (!/\.(?:wxml|wxss)$/.test(entry.name)) {
return []
}
return [{ file: path.relative(root, fullPath), source: fs.readFileSync(fullPath, 'utf8') }]
})
}
assert.ok(appWxss.includes('--theme-neutral: #4A443F;'))
assert.ok(appWxss.includes('--theme-tertiary: #FDFBF9;'))
assert.ok(appWxss.includes('.jayu-cloud-page'))
assert.ok(appWxss.includes('.jayu-cloud-glass-card'))
assert.ok(appWxss.includes('.jayu-cloud-status-chip'))
assert.ok(appWxss.includes('.jayu-cloud-bottom-action'))
assert.ok(!/--theme-primary:\s*#7c5357/i.test(appWxss))
assert.ok(productCardWxss.includes('background: rgba(255, 255, 255, 0.86);'))
assert.ok(productCardWxss.includes('color: var(--text-primary);'))
assert.ok(productCardWxss.includes('color: var(--text-secondary);'))
assert.ok(navigationBarWxss.includes('backdrop-filter: blur(20rpx);'))
assert.ok(navigationBarWxss.includes('color: var(--theme-neutral);'))
for (const { file, source } of [{ file: 'app.wxss', source: appWxss }, ...readPageSources(pageRoot)]) {
assert.ok(!legacyThemeColorPattern.test(source), `${file} should use Luminous theme variables instead of legacy hardcoded theme colors`)
}
+427
View File
@@ -0,0 +1,427 @@
/**
* 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')
/**
* Purpose: waitingForAutoLoginNavigation supports navigation.js by holding or executing the waiting for auto login navigation 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 waitingForAutoLoginNavigation = false
/**
* 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}?${query}` : path
}
/**
* 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 '/pages/home/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(path || '').split('?')[0]
return 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: buildUrl(path, params),
success: resolve,
fail: reject
})
})
}
/**
* Purpose: switchTab supports navigation.js by holding or executing the switch tab 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 switchTab(path) {
return new Promise((resolve, reject) => {
wx.switchTab({
url: path,
success: resolve,
fail: reject
})
})
}
/**
* Purpose: normalizeActionPath supports navigation.js by holding or executing the normalize action 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 normalizeActionPath(value) {
const rawPath = String(value || '').trim()
if (!rawPath || !rawPath.startsWith('/') || rawPath.startsWith('//')) {
return ''
}
const queryIndex = rawPath.indexOf('?')
const pathOnly = queryIndex >= 0 ? rawPath.slice(0, queryIndex) : rawPath
const query = queryIndex >= 0 ? rawPath.slice(queryIndex) : ''
if (pathOnly.startsWith('/orders/')) {
const id = pathOnly.split('/')[2] || ''
return buildUrl('/pages/order-detail/index', { id })
}
if (pathOnly === '/orders') {
return `/pages/orders/index${query}`
}
if (pathOnly === '/after-sales') {
return `/pages/after-sales/index${query}`
}
if (pathOnly === '/after-sale/apply') {
return `/pages/after-sale-apply/index${query}`
}
if (pathOnly === '/service-progress') {
return `/pages/service-progress/index${query}`
}
if (pathOnly === '/help') {
return `/pages/help/index${query}`
}
if (pathOnly === '/artist-orders') {
return `/pages/artist-orders/index${query}`
}
if (pathOnly === '/artist-calendar') {
return `/pages/artist-calendar/index${query}`
}
if (pathOnly === '/settings/account') {
return `/pages/account-settings/index${query}`
}
if (pathOnly === '/settings/password') {
return `/pages/password-settings/index${query}`
}
if (rawPath.startsWith('/product/')) {
const id = rawPath.split('/')[2] || ''
return buildUrl('/pages/product-detail/index', { id })
}
if (rawPath.startsWith('/shop/')) {
const id = rawPath.split('/')[2] || ''
return buildUrl('/pages/shop-detail/index', { id })
}
if (rawPath === '/coupons' || rawPath.startsWith('/coupons?')) {
return rawPath.replace('/coupons', '/pages/coupons/index')
}
if (rawPath === '/vip-center' || rawPath.startsWith('/vip-center?')) {
return rawPath.replace('/vip-center', '/pages/vip-center/index')
}
if (rawPath === '/cart' || rawPath.startsWith('/cart?')) {
return rawPath.replace('/cart', '/pages/cart/index')
}
if (rawPath.startsWith('/pages/')) {
return rawPath
}
return ''
}
/**
* Purpose: buildMessageActionPath converts backend system-message business fields into a mini-program route.
* Usage: call it when actionPath is absent so review and artist-change popup messages still land on orders.
*/
function buildMessageActionPath(message) {
if (!message) {
return ''
}
const actionPath = normalizeActionPath(message.actionPath)
if (actionPath) {
return actionPath
}
const businessType = String(message.businessType || '').toUpperCase()
const businessId = message.businessId || ''
if (businessType === 'ORDER' && businessId) {
return buildUrl('/pages/order-detail/index', { id: businessId })
}
if (businessType === 'ORDER_ARTIST_CHANGE' && businessId) {
return buildUrl('/pages/service-progress/index', { orderId: businessId })
}
if (businessType === 'ORDER_ARTIST_REVIEW' || businessType === 'ORDER_ARTIST_CHANGE' || businessType === 'ORDER') {
return buildUrl('/pages/orders/index', businessId ? { orderId: businessId } : {})
}
if (businessType === 'AFTER_SALE') {
return buildUrl('/pages/after-sales/index', businessId ? { orderId: businessId } : {})
}
if (businessType === 'PRODUCT') {
return buildUrl('/pages/product-detail/index', businessId ? { id: businessId } : {})
}
if (businessType === 'SHOP') {
return buildUrl('/pages/shop-detail/index', businessId ? { id: businessId } : {})
}
if (businessType === 'VIP') {
return '/pages/vip-center/index'
}
if (businessType === 'COUPON') {
return '/pages/coupons/index'
}
if (businessType === 'CART') {
return '/pages/cart/index'
}
return ''
}
/**
* Purpose: openActionPath supports navigation.js by holding or executing the open action 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 openActionPath(value) {
const target = normalizeActionPath(value)
if (!target) {
return Promise.resolve(false)
}
const purePath = target.split('?')[0]
const openPromise = isTabPage(purePath) ? switchTab(purePath) : navigate(target)
return openPromise
.then(() => true)
.catch(error => {
console.error('Open message action path failed', error)
wx.showToast({
title: '无法打开消息链接',
icon: 'none'
})
return false
})
}
/**
* Purpose: openSystemMessage opens a backend system-message action using actionPath first and business fields as fallback.
* Usage: pass a full system-message record from popup or notification list taps.
*/
function openSystemMessage(message) {
return openActionPath(buildMessageActionPath(message))
}
/**
* 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
}
if (isTabPage(fallbackPath || '/pages/home/index')) {
wx.switchTab({
url: fallbackPath || '/pages/home/index'
})
return
}
wx.redirectTo({
url: fallbackPath || '/pages/home/index'
})
}
/**
* Purpose: parseQuery supports navigation.js by holding or executing the parse query 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 parseQuery(url) {
const queryString = String(url || '').split('?')[1] || ''
if (!queryString) {
return {}
}
return queryString.split('&').reduce((result, item) => {
const parts = item.split('=')
const key = decodeURIComponent(parts[0] || '')
const value = decodeURIComponent(parts[1] || '')
if (key) {
result[key] = value
}
return result
}, {})
}
/**
* 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(redirect) {
const target = redirect ? decodeRedirectValue(redirect) : ''
if (!target) {
return switchTab('/pages/home/index')
}
const purePath = target.split('?')[0]
if (purePath === '/pages/products/index') {
const app = getApp()
app.globalData.pendingProductFilter = parseQuery(target)
return switchTab('/pages/products/index')
}
if (isTabPage(target)) {
return switchTab(purePath)
}
return new Promise((resolve, reject) => {
wx.redirectTo({
url: target,
success: resolve,
fail: reject
})
})
}
/**
* Purpose: openAuth supports navigation.js by holding or executing the open auth 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 openAuth(redirect) {
return navigate('/pages/auth/index', {
redirect: redirect || getCurrentPageUrl()
})
}
/**
* Purpose: showLoginToast supports navigation.js by holding or executing the show login toast 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 showLoginToast(actionText) {
wx.showToast({
title: `${actionText || '继续操作'}前请先登录`,
icon: 'none'
})
}
/**
* Purpose: scheduleOpenAuth supports navigation.js by holding or executing the schedule open auth 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 scheduleOpenAuth(actionText) {
showLoginToast(actionText)
setTimeout(() => {
openAuth()
}, 120)
}
/**
* 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
}
const app = getApp()
const hasAutoLoginHelpers = app
&& typeof app.isWechatMiniAutoLoginPending === 'function'
&& typeof app.waitForWechatMiniAutoLogin === 'function'
if (hasAutoLoginHelpers && app.isWechatMiniAutoLoginPending()) {
if (waitingForAutoLoginNavigation) {
return false
}
waitingForAutoLoginNavigation = true
Promise.resolve(app.waitForWechatMiniAutoLogin())
.catch(() => false)
.then(() => {
if (!auth.isLoggedIn()) {
scheduleOpenAuth(actionText)
}
})
.finally(() => {
waitingForAutoLoginNavigation = false
})
return false
}
scheduleOpenAuth(actionText)
return false
}
module.exports = {
buildUrl,
getCurrentPageUrl,
isTabPage,
navigate,
switchTab,
normalizeActionPath,
buildMessageActionPath,
openActionPath,
openSystemMessage,
goBack,
redirectAfterLogin,
openAuth,
ensureLogin,
/**
* Purpose: openProducts supports navigation.js by holding or executing the open products page or API role.
* Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow.
*/
openProducts(filter) {
const app = getApp()
app.globalData.pendingProductFilter = filter || {}
return switchTab('/pages/products/index')
}
}
+40
View File
@@ -0,0 +1,40 @@
const assert = require('assert')
const navigation = require('./navigation')
const { TAB_PAGES } = require('./config')
assert.strictEqual(
navigation.normalizeActionPath('/orders/10'),
'/pages/order-detail/index?id=10'
)
assert.strictEqual(
navigation.normalizeActionPath('/orders'),
'/pages/orders/index'
)
assert.strictEqual(
navigation.normalizeActionPath('/after-sales?orderId=10'),
'/pages/after-sales/index?orderId=10'
)
assert.strictEqual(
navigation.normalizeActionPath('/after-sale/apply?orderId=10&orderItemId=99'),
'/pages/after-sale-apply/index?orderId=10&orderItemId=99'
)
assert.strictEqual(
navigation.normalizeActionPath('/service-progress?orderId=10'),
'/pages/service-progress/index?orderId=10'
)
assert.strictEqual(
navigation.buildMessageActionPath({ businessType: 'ORDER', businessId: 10 }),
'/pages/order-detail/index?id=10'
)
assert.strictEqual(
navigation.buildMessageActionPath({ businessType: 'AFTER_SALE', businessId: 10 }),
'/pages/after-sales/index?orderId=10'
)
assert.ok(TAB_PAGES.includes('/pages/home/index'))
+51
View File
@@ -0,0 +1,51 @@
const { formatPrice, getProductTitle } = require('./format')
const { resolveImageList } = require('./file')
const { DEFAULT_PRODUCT_IMAGE } = require('./config')
/**
* Purpose: getProductTags supports product.js by holding or executing the get product tags 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 getProductTags(product) {
if (Array.isArray(product && product.tagInfos)) {
return product.tagInfos
.map(tag => tag && tag.tagName)
.filter(Boolean)
.slice(0, 3)
}
return []
}
/**
* Purpose: buildProductCard supports product.js by holding or executing the build product card 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 buildProductCard(product) {
const images = await resolveImageList(product && product.imageFileIds, DEFAULT_PRODUCT_IMAGE)
return {
...product,
displayTitle: getProductTitle(product),
priceText: `¥${formatPrice(product && product.price)}`,
metaText: (product && product.approximateDuration) || '支持预约',
shopNameText: product && product.shopName ? `所属店铺:${product.shopName}` : '',
coverUrl: images[0],
imageUrls: images,
tagsPreview: getProductTags(product),
statsText: `${Number((product && product.likeCount) || 0)}赞 · ${Number((product && product.collectCount) || 0)}藏`
}
}
/**
* Purpose: buildProductCards supports product.js by holding or executing the build product cards 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 buildProductCards(products) {
const list = Array.isArray(products) ? products : []
return Promise.all(list.map(item => buildProductCard(item)))
}
module.exports = {
buildProductCard,
buildProductCards
}
+78
View File
@@ -0,0 +1,78 @@
const DEFAULT_ROUTES = {
cart: '/pages/cart/index',
orders: '/pages/orders/index',
products: '/pages/products/index',
profile: '/pages/profile/index'
}
function normalizeRecoveryMessage(error, fallbackMessage) {
if (typeof error === 'string' && error.trim()) {
return error.trim()
}
if (error && error.message) {
return String(error.message).trim()
}
return fallbackMessage || '操作失败,请稍后重试'
}
function normalizeRecoveryActions(actions) {
return (Array.isArray(actions) ? actions : [])
.filter(action => action && action.key && action.text)
.map((action, index) => ({
key: action.key,
text: action.text,
route: action.route || DEFAULT_ROUTES[action.key] || '',
primary: action.primary !== undefined ? Boolean(action.primary) : index === 0
}))
}
function buildRecoveryState(options) {
const config = options || {}
return {
visible: true,
title: config.title || '操作失败',
message: normalizeRecoveryMessage(config.message || config.error, config.fallbackMessage),
actions: normalizeRecoveryActions(config.actions)
}
}
function clearRecoveryState() {
return {
visible: false,
title: '',
message: '',
actions: []
}
}
function showRecoveryModal(options) {
const state = buildRecoveryState(options)
const primaryAction = state.actions.find(action => action.primary) || state.actions[0]
const secondaryAction = state.actions.find(action => action !== primaryAction)
return new Promise(resolve => {
wx.showModal({
title: state.title,
content: state.message,
confirmText: primaryAction ? primaryAction.text : '知道了',
cancelText: secondaryAction ? secondaryAction.text : '取消',
showCancel: Boolean(secondaryAction),
success: result => {
if (result.confirm) {
resolve(primaryAction || null)
return
}
resolve(secondaryAction || null)
},
fail: () => resolve(null)
})
})
}
module.exports = {
DEFAULT_ROUTES,
normalizeRecoveryMessage,
buildRecoveryState,
clearRecoveryState,
showRecoveryModal
}
+30
View File
@@ -0,0 +1,30 @@
const assert = require('assert')
const recovery = require('./recovery')
const checkoutState = recovery.buildRecoveryState({
title: '下单失败',
message: new Error('库存不足'),
fallbackMessage: '订单创建失败',
actions: [
{ key: 'retry', text: '重试下单' },
{ key: 'orders', text: '查看订单' },
{ key: 'contact', text: '联系客服' },
{ key: 'cart', text: '返回购物车' }
]
})
assert.strictEqual(checkoutState.visible, true)
assert.strictEqual(checkoutState.title, '下单失败')
assert.strictEqual(checkoutState.message, '库存不足')
assert.strictEqual(checkoutState.actions.length, 4)
assert.strictEqual(checkoutState.actions[0].key, 'retry')
assert.strictEqual(checkoutState.actions[0].primary, true)
assert.strictEqual(checkoutState.actions[3].route, '/pages/cart/index')
const emptyState = recovery.clearRecoveryState()
assert.strictEqual(emptyState.visible, false)
assert.deepStrictEqual(emptyState.actions, [])
const normalized = recovery.normalizeRecoveryMessage(null, '图片预览失败')
assert.strictEqual(normalized, '图片预览失败')
+523
View File
@@ -0,0 +1,523 @@
/**
* 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 { API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config')
const { getDeviceId } = require('./device')
const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto')
/**
* 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: 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: 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: redirectingToAuth supports request.js by holding or executing the redirecting to auth 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 redirectingToAuth = 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 = `${API_BASE_URL}${url}`
return query ? `${target}${target.includes('?') ? '&' : '?'}${query}` : target
}
/**
* Purpose: isWhitelistedPath supports request.js by holding or executing the is whitelisted 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 isWhitelistedPath(url) {
return [
'/user/login',
'/user/register',
'/user/check/',
'/user/refresh-token',
'/user/send-verification-code',
'/user/phone-login',
'/user/wechat-mini/',
'/user/reset-password-by-phone',
'/legal-agreement/current',
'/product/get/',
'/product/list/',
'/comment/list/product/',
'/nail-artist/profile/',
'/nail-artist/',
'/shop/get/',
'/shop/trust-profile/',
'/shop/list/public',
'/shop/list/simple',
'/tag/list/all',
'/tag/list/filter-options',
'/file/get-signed-url/'
].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: redirectToAuth supports request.js by holding or executing the redirect to auth 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 redirectToAuth() {
if (redirectingToAuth) {
return
}
redirectingToAuth = true
const pages = getCurrentPages()
const current = pages[pages.length - 1]
const currentPath = current ? `/${current.route}` : '/pages/home/index'
const currentQuery = current && current.options ? current.options : {}
const queryString = Object.keys(currentQuery)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(currentQuery[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: `/pages/auth/index?redirect=${encodeURIComponent(redirect)}`,
complete() {
redirectingToAuth = false
}
})
}, 300)
}
/**
* 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 && !isWhitelistedPath(options.url)) {
headers.Authorization = `Bearer ${accessToken}`
}
if (!ENABLE_REQUEST_SIGNING || !accessToken || isWhitelistedPath(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,
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: `${API_BASE_URL}/user/refresh-token`,
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.bootstrapSession === 'function') {
app.bootstrapSession()
}
return response.data.data
}
throw normalizeError(
(response.data && response.data.message) || '\u5237\u65b0\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 (isWhitelistedPath(options.url)) {
throw normalizeError('\u8bf7\u6c42\u9700\u8981\u767b\u5f55\uff0c\u4f46\u5f53\u524d\u9875\u9762\u5141\u8bb8\u533f\u540d\u67e5\u770b', 401)
}
if (options._retry) {
auth.clearSession()
const app = getApp()
if (app && typeof app.clearUserSession === 'function') {
app.clearUserSession()
}
redirectToAuth()
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)
auth.clearSession()
const app = getApp()
if (app && typeof app.clearUserSession === 'function') {
app.clearUserSession()
}
redirectToAuth()
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(res, options) {
idleSession.markActive()
if (res.statusCode === 401) {
return handleUnauthorized(options)
}
if (res.statusCode >= 400) {
throw normalizeError(
(res.data && res.data.message) || '\u7f51\u7edc\u8bf7\u6c42\u5931\u8d25',
res.statusCode,
res
)
}
const payload = res.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('/user/login')
|| path.includes('/user/phone-login')
|| path.includes('/user/register')
|| path.includes('/user/reset-password-by-phone')
|| path.includes('/user/wechat-mini/')
) {
return '\u767b\u5f55\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u63d0\u4ea4'
}
if (path.includes('/send-verification-code')) {
return '\u9a8c\u8bc1\u7801\u53d1\u9001\u5904\u7406\u4e2d\uff0c\u8bf7\u7a0d\u540e\u518d\u8bd5'
}
if (path.includes('/switch-shop')) {
return '\u95e8\u5e97\u5207\u6362\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/order/create')) {
return '\u8ba2\u5355\u6b63\u5728\u63d0\u4ea4\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb'
}
if (path.includes('/upload')) {
return '\u4e0a\u4f20\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/logout')) {
return '\u9000\u51fa\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
if (path.includes('/cart/')) {
return '\u8d2d\u7269\u8f66\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
}
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, method === 'GET' ? options.params : undefined),
method,
timeout: options.timeout || REQUEST_TIMEOUT,
header,
data: method === 'GET' ? undefined : options.data,
success: async res => {
try {
const data = await unwrapResponse(res, 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
+58
View File
@@ -0,0 +1,58 @@
const CUSTOMER_HOME_PATH = '/pages/home/index'
const ADMIN_LOGIN_PATH = '/admin/pages/login/index'
function getCurrentApp() {
return typeof getApp === 'function' ? getApp() : null
}
function clearCustomerSession() {
const app = getCurrentApp()
if (app && typeof app.clearUserSession === 'function') {
app.clearUserSession()
return
}
try {
wx.removeStorageSync('accessToken')
wx.removeStorageSync('refreshToken')
wx.removeStorageSync('userInfo')
wx.removeStorageSync('needSetPassword')
} catch (error) {}
}
function clearAdminSession() {
const app = getCurrentApp()
if (app && typeof app.clearAdminSession === 'function') {
app.clearAdminSession()
return
}
try {
wx.removeStorageSync('adminAccessToken')
wx.removeStorageSync('adminRefreshToken')
wx.removeStorageSync('adminUserInfo')
wx.removeStorageSync('adminPermissions')
wx.removeStorageSync('adminCurrentShop')
} catch (error) {}
}
function relaunch(url) {
wx.reLaunch({ url })
}
function openAdminLogin() {
clearCustomerSession()
relaunch(ADMIN_LOGIN_PATH)
}
function openCustomerHome() {
clearAdminSession()
relaunch(CUSTOMER_HOME_PATH)
}
module.exports = {
ADMIN_LOGIN_PATH,
CUSTOMER_HOME_PATH,
clearCustomerSession,
clearAdminSession,
openAdminLogin,
openCustomerHome
}
@@ -0,0 +1,43 @@
const assert = require('assert')
let relaunchedTo = ''
let customerCleared = false
let adminCleared = false
global.wx = {
reLaunch(options) {
relaunchedTo = options.url
if (typeof options.success === 'function') {
options.success()
}
},
removeStorageSync() {},
setStorageSync() {},
getStorageSync() {
return ''
},
removeTabBarBadge(options) {
if (options && typeof options.fail === 'function') {
options.fail()
}
}
}
global.getApp = () => ({
clearUserSession() {
customerCleared = true
},
clearAdminSession() {
adminCleared = true
}
})
const sessionSwitch = require('./session-switch')
sessionSwitch.openAdminLogin()
assert.strictEqual(customerCleared, true)
assert.strictEqual(relaunchedTo, '/admin/pages/login/index')
sessionSwitch.openCustomerHome()
assert.strictEqual(adminCleared, true)
assert.strictEqual(relaunchedTo, '/pages/home/index')
+48
View File
@@ -0,0 +1,48 @@
/**
* 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: 'accessToken',
REFRESH_TOKEN: 'refreshToken',
USER_INFO: 'userInfo',
NEED_SET_PASSWORD: 'needSetPassword',
PREFERRED_MINI_LOGIN_SHOP_ID: 'preferredMiniLoginShopId',
DEVICE_ID: 'miniDeviceId'
}
/**
* 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)
}
module.exports = {
STORAGE_KEYS,
getStorage,
setStorage,
removeStorage
}
+201
View File
@@ -0,0 +1,201 @@
/**
* Purpose: HEX_COLOR_PATTERN supports theme.js by holding or executing the hex color pattern 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 HEX_COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/
/**
* Purpose: normalizeHexColor supports theme.js by holding or executing the normalize hex color 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 normalizeHexColor(value) {
if (!value || typeof value !== 'string') {
return ''
}
const normalized = value.trim()
return HEX_COLOR_PATTERN.test(normalized) ? normalized.toUpperCase() : ''
}
/**
* Purpose: hexToRgb supports theme.js by holding or executing the hex to rgb 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 hexToRgb(color) {
const value = color.replace('#', '')
return {
r: parseInt(value.slice(0, 2), 16),
g: parseInt(value.slice(2, 4), 16),
b: parseInt(value.slice(4, 6), 16)
}
}
/**
* Purpose: toHex supports theme.js by holding or executing the 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 toHex(value) {
return Math.min(255, Math.max(0, value)).toString(16).padStart(2, '0').toUpperCase()
}
/**
* Purpose: rgbToHex supports theme.js by holding or executing the rgb 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 rgbToHex(rgb) {
return `#${toHex(rgb.r)}${toHex(rgb.g)}${toHex(rgb.b)}`
}
/**
* Purpose: mixColor supports theme.js by holding or executing the mix color 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 mixColor(foreground, background, backgroundWeight) {
const fg = hexToRgb(foreground)
const bg = hexToRgb(background)
const weight = Math.min(1, Math.max(0, backgroundWeight))
return rgbToHex({
r: Math.round(fg.r * (1 - weight) + bg.r * weight),
g: Math.round(fg.g * (1 - weight) + bg.g * weight),
b: Math.round(fg.b * (1 - weight) + bg.b * weight)
})
}
/**
* Purpose: buildStyleVars supports theme.js by holding or executing the build style vars 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 buildStyleVars(theme) {
const styleVars = [
`--theme-primary: ${theme.primaryColor};`,
`--theme-secondary: ${theme.secondaryColor};`,
`--theme-accent: ${theme.accentColor};`,
`--theme-neutral: ${theme.neutralColor || theme.accentColor};`,
`--theme-tertiary: ${theme.tertiaryColor || theme.pageBgColor};`,
`--theme-primary-action: ${theme.primaryActionColor};`,
`--theme-page-bg: ${theme.pageBgColor};`,
`--theme-card-bg: ${theme.cardBgColor};`,
`--theme-border: ${theme.borderColor};`,
`--theme-primary-soft: ${theme.primarySoftColor};`,
`--theme-secondary-soft: ${theme.secondarySoftColor};`,
`--theme-gradient: ${theme.gradient};`,
`--theme-gradient-soft: ${theme.softGradient};`,
`--text-primary: ${theme.textPrimary};`,
`--text-secondary: ${theme.textSecondary};`
]
if (theme.backgroundImageUrl) {
styleVars.push(
`background-image: url("${theme.backgroundImageUrl}");`,
'background-size: cover;',
'background-position: center top;'
)
}
return styleVars.join(' ')
}
/**
* Purpose: resolveShopTheme supports theme.js by holding or executing the resolve shop theme 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 resolveShopTheme(source) {
const themeSource = source || {}
const normalizedPrimaryColor = normalizeHexColor(themeSource.themePrimaryColor)
const primaryColor = normalizedPrimaryColor || DEFAULT_SHOP_THEME.primaryColor
const secondaryColor = normalizeHexColor(themeSource.themeSecondaryColor)
|| (normalizedPrimaryColor ? mixColor(primaryColor, DEFAULT_SHOP_THEME.secondaryColor, 0.35) : DEFAULT_SHOP_THEME.secondaryColor)
const neutralColor = normalizeHexColor(themeSource.themeAccentColor)
|| (normalizedPrimaryColor ? mixColor(DEFAULT_SHOP_THEME.neutralColor, primaryColor, 0.14) : DEFAULT_SHOP_THEME.neutralColor)
const accentColor = neutralColor
const tertiaryColor = normalizeHexColor(themeSource.themePageBgColor) || DEFAULT_SHOP_THEME.tertiaryColor
const pageBgColor = tertiaryColor
const cardBgColor = normalizeHexColor(themeSource.themeCardBgColor) || DEFAULT_SHOP_THEME.cardBgColor
const textPrimary = neutralColor
const textSecondary = mixColor(neutralColor, cardBgColor, 0.18)
const borderColor = mixColor(primaryColor, cardBgColor, 0.72)
const primarySoftColor = mixColor(primaryColor, cardBgColor, 0.78)
const secondarySoftColor = mixColor(secondaryColor, pageBgColor, 0.66)
const primaryActionColor = mixColor(neutralColor, primaryColor, 0.28)
const gradient = `linear-gradient(135deg, ${primaryActionColor} 0%, ${secondaryColor} 100%)`
const softGradient = `linear-gradient(145deg, ${cardBgColor} 0%, ${secondarySoftColor} 58%, ${mixColor(primaryColor, pageBgColor, 0.62)} 100%)`
const backgroundImageFileId = themeSource.themeBackgroundImageFileId
? String(themeSource.themeBackgroundImageFileId).trim()
: ''
const backgroundImageUrl = themeSource.themeBackgroundImageUrl
? String(themeSource.themeBackgroundImageUrl).trim()
: ''
const theme = {
primaryColor,
secondaryColor,
accentColor,
tertiaryColor,
neutralColor,
pageBgColor,
cardBgColor,
textPrimary,
textSecondary,
borderColor,
primarySoftColor,
secondarySoftColor,
primaryActionColor,
gradient,
softGradient,
backgroundImageFileId,
backgroundImageUrl
}
theme.styleVars = buildStyleVars(theme)
return theme
}
/**
* Purpose: DEFAULT_SHOP_THEME supports theme.js by holding or executing the default shop theme 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_SHOP_THEME = {
primaryColor: '#E8B4B8',
secondaryColor: '#C5A059',
accentColor: '#4A443F',
tertiaryColor: '#FDFBF9',
neutralColor: '#4A443F',
pageBgColor: '#FDFBF9',
cardBgColor: '#FFFFFF',
textPrimary: '#4A443F',
textSecondary: '#6B6662',
borderColor: '#F9EAEC',
primarySoftColor: '#FAEFF0',
secondarySoftColor: '#EADCC2',
primaryActionColor: '#766361',
gradient: 'linear-gradient(135deg, #766361 0%, #C5A059 100%)',
softGradient: 'linear-gradient(145deg, #FFFFFF 0%, #EADCC2 58%, #F5E0E0 100%)',
backgroundImageFileId: '',
backgroundImageUrl: ''
}
DEFAULT_SHOP_THEME.styleVars = buildStyleVars(DEFAULT_SHOP_THEME)
/**
* Purpose: pageThemeData supports theme.js by holding or executing the page theme data 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 pageThemeData(theme, backgroundImageUrl) {
const resolved = theme || DEFAULT_SHOP_THEME
const themeData = backgroundImageUrl
? {
...resolved,
backgroundImageUrl: String(backgroundImageUrl).trim()
}
: resolved
if (backgroundImageUrl) {
themeData.styleVars = buildStyleVars(themeData)
}
return {
theme: themeData,
themeVars: themeData.styleVars,
navThemeColor: themeData.primaryColor,
navThemeBackground: themeData.pageBgColor
}
}
module.exports = {
DEFAULT_SHOP_THEME,
resolveShopTheme,
pageThemeData
}
+62
View File
@@ -0,0 +1,62 @@
/**
* Purpose: assert supports theme.test.js by holding or executing the assert 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 assert = require('assert')
/**
* Purpose: theme supports theme.test.js by holding or executing the theme 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 theme = require('./theme')
assert.strictEqual(theme.DEFAULT_SHOP_THEME.primaryColor, '#E8B4B8')
assert.strictEqual(theme.DEFAULT_SHOP_THEME.secondaryColor, '#C5A059')
assert.strictEqual(theme.DEFAULT_SHOP_THEME.accentColor, '#4A443F')
assert.strictEqual(theme.DEFAULT_SHOP_THEME.pageBgColor, '#FDFBF9')
assert.ok(theme.DEFAULT_SHOP_THEME.styleVars.includes('--theme-neutral: #4A443F;'))
assert.ok(theme.DEFAULT_SHOP_THEME.styleVars.includes('--theme-tertiary: #FDFBF9;'))
/**
* Purpose: customized supports theme.test.js by holding or executing the customized 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 customized = theme.resolveShopTheme({
themePrimaryColor: '#8b4f65',
themeSecondaryColor: '#f2c9d4',
themeAccentColor: '#b86f84',
themePageBgColor: '#fff8fa',
themeCardBgColor: '#ffffff',
themeBackgroundImageFileId: 'bg-file'
})
assert.strictEqual(customized.primaryColor, '#8B4F65')
assert.strictEqual(customized.secondaryColor, '#F2C9D4')
assert.strictEqual(customized.accentColor, '#B86F84')
assert.strictEqual(customized.pageBgColor, '#FFF8FA')
assert.strictEqual(customized.cardBgColor, '#FFFFFF')
assert.strictEqual(customized.backgroundImageFileId, 'bg-file')
assert.ok(customized.styleVars.includes('--theme-primary: #8B4F65;'))
assert.ok(customized.styleVars.includes('--theme-neutral: #B86F84;'))
assert.ok(customized.styleVars.includes('--theme-primary-action: #AB667B;'))
assert.ok(customized.styleVars.includes('--theme-gradient: linear-gradient(135deg, #AB667B 0%, #F2C9D4 100%);'))
/**
* Purpose: themedPageData supports theme.test.js by holding or executing the themed page data 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 themedPageData = theme.pageThemeData(customized, 'https://static.example.test/bg.jpg')
assert.ok(themedPageData.themeVars.includes('background-image: url("https://static.example.test/bg.jpg");'))
assert.strictEqual(themedPageData.theme.backgroundImageUrl, 'https://static.example.test/bg.jpg')
/**
* Purpose: fallback supports theme.test.js by holding or executing the fallback 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 fallback = theme.resolveShopTheme({
themePrimaryColor: '#fff',
themeSecondaryColor: 'blue'
})
assert.strictEqual(fallback.primaryColor, theme.DEFAULT_SHOP_THEME.primaryColor)
assert.strictEqual(fallback.secondaryColor, theme.DEFAULT_SHOP_THEME.secondaryColor)
assert.ok(fallback.styleVars.includes('--theme-page-bg:'))