repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
stan-js | github_2023 | codemask-labs | typescript | getAction | const getAction = <K extends TKey>(key: K) => actions[getActionKey(key)] as (value: unknown) => void | // @ts-expect-error - TS doesn't know that all keys are in actions object | https://github.com/codemask-labs/stan-js/blob/2bee695bc462a15d4fc5f4fe610ddabbe81ae3b2/src/vanilla/createStore.ts#L43-L43 | 2bee695bc462a15d4fc5f4fe610ddabbe81ae3b2 |
nuxt-oidc-auth | github_2023 | itpropro | typescript | refresh | async function refresh(): Promise<void> {
const currentProvider = sessionState.value?.provider || undefined
sessionState.value = (await useRequestFetch()('/api/_auth/refresh', {
headers: {
Accept: 'text/json',
},
method: 'POST',
}).catch(() => login()) as UserSession)
if (!logg... | /**
* Manually refreshes the authentication session.
*
* @returns {Promise<void>}
*/ | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/composables/oidcAuth.ts#L28-L39 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
nuxt-oidc-auth | github_2023 | itpropro | typescript | login | async function login(provider?: ProviderKeys | 'dev', params?: Record<string, string>): Promise<void> {
const queryParams = params ? `?${new URLSearchParams(params).toString()}` : ''
await navigateTo(`/auth${provider ? `/${provider}` : ''}/login${queryParams}`, { external: true, redirectCode: 302 })
} | /**
* Signs in the user by navigating to the appropriate sign-in URL.
*
* @param {ProviderKeys | 'dev'} [provider] - The authentication provider to use. If not specified, uses the default provider.
* @param {Record<string, string>} [params] - Additional parameters to include in the login request. Each param... | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/composables/oidcAuth.ts#L48-L51 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
nuxt-oidc-auth | github_2023 | itpropro | typescript | logout | async function logout(provider?: ProviderKeys | 'dev', logoutRedirectUri?: string): Promise<void> {
await navigateTo(`/auth${provider ? `/${provider}` : currentProvider.value ? `/${currentProvider.value}` : ''}/logout${logoutRedirectUri ? `?logout_redirect_uri=${logoutRedirectUri}` : ''}`, { external: true, redirec... | /**
* Logs out the user by navigating to the appropriate logout URL.
*
* @param {ProviderKeys | 'dev'} [provider] - The provider key or 'dev' for development. If provided, the user will be logged out from the specified provider.
* @param {string} [logoutRedirectUri] - The URI to redirect to after logout if ... | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/composables/oidcAuth.ts#L60-L65 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
nuxt-oidc-auth | github_2023 | itpropro | typescript | clear | async function clear() {
await useRequestFetch()(('/api/_auth/session'), {
method: 'DELETE',
headers: {
Accept: 'text/json',
},
onResponse({ response: { headers } }: { response: { headers: Headers } }) {
// See https://github.com/atinux/nuxt-auth-utils/blob/main/src/runtime/a... | /**
* Clears the current user session. Mainly for debugging, in production, always use the `logout` function, which completely cleans the state.
*/ | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/composables/oidcAuth.ts#L70-L89 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
nuxt-oidc-auth | github_2023 | itpropro | typescript | encryptMessage | async function encryptMessage(text: string, key: CryptoKey, iv: Uint8Array) {
const encoded = new TextEncoder().encode(text)
const ciphertext = await subtle.encrypt(
{
name: 'AES-GCM',
iv,
},
key,
encoded,
)
return arrayBufferToBase64(ciphertext, { urlSafe: false })
} | /**
* Encrypts a message with AES-GCM.
* @param text The text to encrypt.
* @param key The key to use for encryption.
* @returns The base64 encoded encrypted message.
*/ | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/server/utils/security.ts#L59-L70 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
nuxt-oidc-auth | github_2023 | itpropro | typescript | decryptMessage | async function decryptMessage(text: string, key: CryptoKey, iv: Uint8Array) {
const decoded = base64ToUint8Array(text)
return await subtle.decrypt({ name: 'AES-GCM', iv }, key, decoded)
} | /**
* Decrypts a message with AES-GCM.
* @param text The text to decrypt.
* @param key The key to use for decryption.
* @returns The decrypted message.
*/ | https://github.com/itpropro/nuxt-oidc-auth/blob/bc044d93f213d9e5e732c9c114181acc9e5fb94a/src/runtime/server/utils/security.ts#L78-L81 | bc044d93f213d9e5e732c9c114181acc9e5fb94a |
aspoem | github_2023 | meetqy | typescript | getLocale | function getLocale() {
const headers = { "accept-language": defaultLocale };
const languages = new Negotiator({ headers }).languages();
return match(languages, locales, defaultLocale); // -> 'en-US'
} | // Get the preferred locale, similar to the above or using a library | https://github.com/meetqy/aspoem/blob/5812d0166754b004b344410385961f0568a232d2/src/middleware.ts#L7-L12 | 5812d0166754b004b344410385961f0568a232d2 |
aspoem | github_2023 | meetqy | typescript | createContext | const createContext = async (req: NextRequest) => {
return createTRPCContext({
headers: req.headers,
});
}; | /**
* This wraps the `createTRPCContext` helper and provides the required context for the tRPC API when
* handling a HTTP request (e.g. when you make requests from Client Components).
*/ | https://github.com/meetqy/aspoem/blob/5812d0166754b004b344410385961f0568a232d2/src/app/api/trpc/[trpc]/route.ts#L12-L16 | 5812d0166754b004b344410385961f0568a232d2 |
FluentRead | github_2023 | Bistutu | typescript | clearAllTranslations | function clearAllTranslations() {
// 1. 移除所有翻译结果元素
document.querySelectorAll('.fluent-read-translation').forEach(el => el.remove());
// 2. 移除所有加载状态
document.querySelectorAll('.fluent-read-loading').forEach(el => el.remove());
// 3. 移除所有错误状态
document.querySelectorAll('.fluent-read-failu... | // 清除所有翻译的函数 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/content.ts#L174-L193 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | shouldSkipNode | function shouldSkipNode(node: any, tag: string): boolean {
// 1. 判断标签是否在 skipSet 内
// 2. 检查是否具有 notranslate 类
// 3. 判断节点是否可编辑
// 4. 判断文本是否过长
return skipSet.has(tag) ||
node.classList?.contains('notranslate') ||
node.isContentEditable ||
isTextTooLong(node);
} | // 检查是否应该跳过节点 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L65-L74 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | isTextTooLong | function isTextTooLong(node: any): boolean {
// 1. 若文本内容长度超过 3072
// 2. 或者 outerHTML 长度超过 4096,都视为过长
return node.textContent.length > 3072 ||
(node.outerHTML && node.outerHTML.length > 4096);
} | // 检查文本长度 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L77-L82 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | isButton | function isButton(node: any, tag: string): boolean {
// 1. 若当前标签就是 button
// 2. 或者当前标签为 span 并且其父节点为 button,则视为按钮
return tag === 'button' ||
(tag === 'span' && node.parentNode?.tagName.toLowerCase() === 'button');
} | // 检查是否为按钮 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L85-L90 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | handleButtonTranslation | function handleButtonTranslation(node: any): void {
// 1. 若文本非空,则调用 handleBtnTranslation 进行按钮文本翻译处理
if (node.textContent.trim()) {
handleBtnTranslation(node);
}
} | // 处理按钮翻译 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L93-L98 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | isInlineElement | function isInlineElement(node: any, tag: string): boolean {
// 1. 判断是否在 inlineSet 中
// 2. 判断是否文本节点
// 3. 检查子元素中是否包含非内联元素
return inlineSet.has(tag) ||
node.nodeType === Node.TEXT_NODE ||
detectChildMeta(node);
} | // 检查是否为内联元素 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L101-L108 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | findTranslatableParent | function findTranslatableParent(node: any): any {
// 1. 递归调用 grabNode 查找父节点是否可翻译
// 2. 若父节点不可翻译,则返回当前节点
const parentResult = grabNode(node.parentNode);
return parentResult || node;
} | // 查找可翻译的父节点 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L111-L116 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | handleFirstLineText | function handleFirstLineText(node: any): boolean {
// 1. 遍历子节点,找到首个文本节点
// 2. 若存在可翻译文本,则通过 browser.runtime.sendMessage 进行翻译
// 3. 翻译成功后,替换该文本;出现错误时,打印错误日志
let child = node.firstChild;
while (child) {
if (child.nodeType === Node.TEXT_NODE && child.textContent.trim()) {
browser.run... | // 处理首行文本 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L119-L137 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | detectChildMeta | function detectChildMeta(parent: any): boolean {
// 1. 逐个检查子节点
// 2. 若发现非内联元素则返回 false;否则全部检查通过则返回 true
let child = parent.firstChild;
while (child) {
if (child.nodeType === Node.ELEMENT_NODE && !inlineSet.has(child.nodeName.toLowerCase())) {
return false;
}
child = c... | // 检测子元素中是否包含指定标签以外的元素 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L140-L151 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | replaceSensitiveWords | function replaceSensitiveWords(text: string): string {
// 1. 使用正则匹配大小写敏感词
// 2. 逐个替换为正确大小写形式
return text.replace(/viewbox|preserveaspectratio|clippathunits|gradienttransform|patterncontentunits|lineargradient|clippath/gi, (match) => {
switch (match.toLowerCase()) {
case 'viewbox':
... | // 替换 svg 标签中的一些大小写敏感的词(html 不区分大小写,但 svg 标签区分大小写) | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/dom.ts#L183-L206 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | translating | const translating = (failCount = 0) => {
browser.runtime.sendMessage({context: document.title, origin: origin})
.then((text: string) => {
clearTimeout(timeout);
spinner.remove();
htmlSet.delete(nodeOuterHTML);
bilingualAppendChild(node,... | // 正在翻译...允许失败重试 3 次 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/trans.ts#L117-L136 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | translating | const translating = (failCount = 0) => {
browser.runtime.sendMessage({context: document.title, origin: origin})
.then((text: string) => {
clearTimeout(timeout);
spinner.remove();
text = beautyHTML(text);
if (!text || origin === text) ... | // 正在翻译...允许失败重试 3 次 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/main/trans.ts#L154-L183 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | parseJwt | function parseJwt(token: string) {
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(c => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
... | // 解析 jwt,返回解析后对象 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/microsoft.ts#L40-L51 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | tongyi | async function tongyi(message: any) {
// 构建请求头
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', `Bearer ${config.token[services.tongyi]}`);
// 判断是否使用代理
let url: string = config.proxy[config.service] ? config.proxy[config.service] :... | // 文档:https://help.aliyun.com/zh/dashscope/developer-reference/tongyi-thousand-questions-metering-and-billing | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/tongyi.ts#L7-L30 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | yiyan | async function yiyan(message: any) {
let model = config.model[services.yiyan]
// model 参数转换
if (model === "ERNIE-Bot 4.0") model = "completions_pro"
else if (model === "ERNIE-Bot") model = "completions"
else if (model === "ERNIE-Speed-8K") model = "ernie_speed"
else if (model === "ERNIE-Speed-1... | // ERNIE-Bot 4.0 模型,模型定价页面:https://console.bce.baidu.com/qianfan/chargemanage/list | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/yiyan.ts#L10-L37 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | zhipu | async function zhipu(message: any) {
// 智谱根据 token 获取 secret(签名密钥) 和 expiration
let token = config.token[services.zhipu];
let secret, expiration;
config.extra[services.zhipu] && ({secret, expiration} = config.extra[services.zhipu]);
if (!secret || expiration <= Date.now()) {
secret = generat... | // 文档参考:https://open.bigmodel.cn/dev/api#nosdk | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/zhipu.ts#L9-L41 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | generateJWT | function generateJWT(secret: string, header: any, payload: any) {
// 对header和payload部分进行UTF-8编码,然后转换为Base64URL格式
const encodedHeader = base64UrlSafe(btoa(JSON.stringify(header)));
const encodedPayload = base64UrlSafe(btoa(JSON.stringify(payload)));
// 生成 jwt 签名
let hmacsha256 = base64UrlSafe(CryptoJ... | // 生成JWT(JSON Web Token) | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/zhipu.ts#L59-L66 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | base64UrlSafe | function base64UrlSafe(base64String: string) {
return base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
} | // 将Base64字符串转换为Base64URL格式的函数 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/service/zhipu.ts#L69-L71 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | buildKey | function buildKey(message: string) {
const { service, model, to, style, customModel } = config;
const selectedModel = model[service] === customModelString ? customModel[service] : model[service];
// 前缀_服务_模型_目标语言_消息
return [prefix, style, service, selectedModel, to, message].join('_');
} | // fluent read cache | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/cache.ts#L8-L13 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | loadConfig | async function loadConfig() {
try {
// 获取存储中的配置
const value = await storage.getItem('local:config');
if (isValidConfig(value)) {
// 如果配置有效,合并到当前 config 中
Object.assign(config, JSON.parse(value));
}
} catch (error) {
console.error('Error getting con... | // 异步加载配置并应用 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/config.ts#L7-L18 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | isValidConfig | function isValidConfig(value: any): value is string {
return typeof value === 'string' && value.trim().length > 0;
} | // 检查配置是否有效 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/config.ts#L21-L23 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | handleRetryClick | function handleRetryClick(node: HTMLElement, wrapper: HTMLElement) {
return (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
wrapper.remove(); // 移除错误提示元素,重新翻译
node.classList.remove("fluent-read-failure"); // 移除失败标记
// 根据当前配置的翻译模式决定使用哪种翻译方式
if (config.display === sty... | // 处理重试按钮点击事件 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/icon.ts#L58-L73 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | handleErrorClick | function handleErrorClick(errMsg: string) {
return (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
const message = getErrorMessage(errMsg);
sendErrorMessage(message); // 发送错误提示
};
} | // 处理错误提示按钮点击事件 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/icon.ts#L76-L84 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | getErrorMessage | function getErrorMessage(errMsg: string): string {
if (errMsg.includes("auth failed") || errMsg.includes("API key")) {
return "Token 似乎有点问题,请前往设置页面重新配置后再试。";
} else if (errMsg.includes("quota") || errMsg.includes("limit")) {
const service = options.services.find((s: { value: string; label: string }) => s.va... | // 根据错误信息返回错误提示 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/icon.ts#L87-L102 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | createIconElement | function createIconElement(iconContent: string): HTMLElement {
const iconElement = document.createElement("div");
iconElement.innerHTML = iconContent;
return iconElement;
} | // 创建图标元素 | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/icon.ts#L105-L109 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | Config.constructor | constructor() {
this.on = true;
this.from = defaultOption.from;
this.to = defaultOption.to;
this.style = defaultOption.style;
this.display = defaultOption.display;
this.hotkey = defaultOption.hotkey;
this.service = defaultOption.service;
this.token = {};
... | // 主题模式:'auto' | 'light' | 'dark' | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/model.ts#L36-L59 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | systemRoleFactory | function systemRoleFactory(): IMapping {
let systems_role: IMapping = {};
Object.keys(services).forEach(key => systems_role[key] = defaultOption.system_role);
return systems_role;
} | // 构建所有服务的 system_role | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/model.ts#L63-L67 | 9b513e9fd44e62926de681b0ef366baa0615836a |
FluentRead | github_2023 | Bistutu | typescript | userRoleFactory | function userRoleFactory(): IMapping {
let users_role: IMapping = {};
Object.keys(services).forEach(key => users_role[key] = defaultOption.user_role);
return users_role;
} | // 构建所有服务的 user_role | https://github.com/Bistutu/FluentRead/blob/9b513e9fd44e62926de681b0ef366baa0615836a/entrypoints/utils/model.ts#L70-L74 | 9b513e9fd44e62926de681b0ef366baa0615836a |
counterscale | github_2023 | benvinegar | typescript | getMidnightDate | function getMidnightDate(): Date {
const midnight = new Date();
midnight.setHours(0, 0, 0, 0);
return midnight;
} | // Cookieless visitor/session tracking | https://github.com/benvinegar/counterscale/blob/d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e/packages/server/app/analytics/collect.ts#L11-L15 | d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e |
counterscale | github_2023 | benvinegar | typescript | accumulateCountsFromRowResult | function accumulateCountsFromRowResult(
counts: AnalyticsCountResult,
row: {
count: number;
isVisitor: number;
isBounce: number;
},
) {
if (row.isVisitor == 1) {
counts.visitors += Number(row.count);
}
if (row.isBounce && row.isBounce != 0) {
// bounce is ... | /** Given an AnalyticsCountResult object, and an object representing a row returned from
* CF Analytics Engine w/ counts grouped by isVisitor, accumulate view,
* visit, and visitor counts.
*/ | https://github.com/benvinegar/counterscale/blob/d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e/packages/server/app/analytics/query.ts#L30-L46 | d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e |
counterscale | github_2023 | benvinegar | typescript | generateEmptyRowsOverInterval | function generateEmptyRowsOverInterval(
intervalType: "DAY" | "HOUR",
startDateTime: Date,
endDateTime: Date,
tz?: string,
): { [key: string]: AnalyticsCountResult } {
if (!tz) {
tz = "Etc/UTC";
}
const initialRows: { [key: string]: AnalyticsCountResult } = {};
while (startDate... | /**
* returns an object with keys of the form "YYYY-MM-DD HH:00:00" and values of 0
* example:
* {
* "2021-01-01 00:00:00": 0,
* "2021-01-01 02:00:00": 0,
* "2021-01-01 04:00:00": 0,
* ...
* }
*
* */ | https://github.com/benvinegar/counterscale/blob/d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e/packages/server/app/analytics/query.ts#L86-L127 | d0b8e1960fb170b286f35bd6bfa3e6f9d95c8b4e |
pinia-colada | github_2023 | posva | typescript | delay | function delay(str: string) {
return new Promise((resolve) =>
setTimeout(() => {
resolve(str)
}, 200),
)
} | // delay to imitate fetch | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/playground/src/queries/issue-174.ts#L15-L21 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | shouldScheduleRefetch | function shouldScheduleRefetch(options: UseQueryOptions) {
const queryEnabled = toValue(options.autoRefetch) ?? autoRefetch
const staleTime = options.staleTime
return Boolean(queryEnabled && staleTime)
} | /**
* Whether to schedule a refetch for the given entry
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/plugins/auto-refetch/src/index.ts#L65-L69 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | applyTextStyles | function applyTextStyles(text: string) {
const styles: Array<{ pos: number, style: [string, string] }> = []
const newText = text
.replace(MD_BOLD_RE, (_m, text, pos) => {
styles.push({
pos,
style: ['font-weight: bold;', 'font-weight: normal;'],
})
return `%c${text}%c`
})
... | /**
* Applies italic and bold style to markdown text.
* @param text - The text to apply styles to
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/plugins/debug/src/index.ts#L124-L153 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | track | function track(
entry: UseQueryEntry,
effect: EffectScope | ComponentInternalInstance | null | undefined,
) {
if (!effect) return
entry.deps.add(effect)
// clearTimeout ignores anything that isn't a timerId
clearTimeout(entry.gcTimeout)
entry.gcTimeout = undefined
triggerCache()
} | /**
* Tracks an effect or component that uses a query.
*
* @param entry - the entry of the query
* @param effect - the effect or component to untrack
*
* @see {@link untrack}
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/query-store.ts#L380-L390 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | untrack | function untrack(
entry: UseQueryEntry,
effect: EffectScope | ComponentInternalInstance | undefined | null,
) {
// avoid clearing an existing timeout
if (!effect || !entry.deps.has(effect)) return
entry.deps.delete(effect)
triggerCache()
if (entry.deps.size > 0 || !entry.options) return
... | /**
* Untracks an effect or component that uses a query.
*
* @param entry - the entry of the query
* @param effect - the effect or component to untrack
*
* @see {@link track}
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/query-store.ts#L400-L418 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | getQueryData | function getQueryData<TResult = unknown>(key: EntryKey): TResult | undefined {
return caches.value.get(toCacheKey(key))?.state.value.data as TResult | undefined
} | /**
* Gets the data of a query entry in the cache based on the key of the query.
*
* @param key - the key of the query
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/query-store.ts#L765-L767 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | _serialize | function _serialize([key, tree]: [
key: EntryNodeKey,
tree: TreeMapNode<UseQueryEntry>,
]): UseQueryEntryNodeSerialized {
return [
key,
tree.value && queryEntry_toJSON(tree.value),
tree.children && [...tree.children.entries()].map(_serialize),
]
} | /**
* Internal function to recursively transform the tree into a compressed array.
* @internal
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/query-store.ts#L833-L842 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | appendToTree | function appendToTree(
parent: TreeMapNode<UseQueryEntry>,
[key, value, children]: UseQueryEntryNodeSerialized,
parentKey: EntryNodeKey[] = [],
) {
parent.children ??= new Map()
const node = new TreeMapNode<UseQueryEntry>(
[],
// NOTE: this could happen outside of an effect scope but since it's only f... | /**
* @deprecated only used by {@link reviveTreeMap}
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/query-store.ts#L869-L887 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | TreeMapNode.set | set(keys: EntryNodeKey[], value?: T) {
if (keys.length === 0) {
this.value = value
} else {
// this.children ??= new Map<EntryNodeKey,
const [top, ...otherKeys] = keys
const node: TreeMapNode<T> | undefined = this.children?.get(top)
if (node) {
node.set(otherKeys, value)
... | /**
* Sets the value while building the tree
*
* @param keys - key as an array
* @param value - value to set
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/tree-map.ts#L30-L44 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | TreeMapNode.find | find(keys: EntryNodeKey[]): TreeMapNode<T> | undefined {
if (keys.length === 0) {
return this
} else {
const [top, ...otherKeys] = keys
return this.children?.get(top)?.find(otherKeys)
}
} | /**
* Finds the node at the given path of keys.
*
* @param keys - path of keys
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/tree-map.ts#L51-L58 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | TreeMapNode.get | get(keys: EntryNodeKey[]): T | undefined {
return this.find(keys)?.value
} | /**
* Gets the value at the given path of keys.
*
* @param keys - path of keys
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/tree-map.ts#L65-L67 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | TreeMapNode.delete | delete(keys: EntryNodeKey[]) {
if (keys.length === 1) {
this.children?.delete(keys[0])
} else {
const [top, ...otherKeys] = keys
this.children?.get(top)?.delete(otherKeys)
}
} | /**
* Delete the node at the given path of keys and all its children.
*
* @param keys - path of keys
*/ | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/tree-map.ts#L74-L81 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
pinia-colada | github_2023 | posva | typescript | errorCatcher | const errorCatcher = () => entry.value.state.value | // adapter that returns the entry state | https://github.com/posva/pinia-colada/blob/8a3d0df2ebc87a69120f1eb737bb423fab0daf0e/src/use-query.ts#L165-L165 | 8a3d0df2ebc87a69120f1eb737bb423fab0daf0e |
LeagueAkari | github_2023 | Hanxven | typescript | AutoGameflowMain._adjustDodgeTimer | private _adjustDodgeTimer(msLeft: number, threshold: number) {
const dodgeIn = Math.max(msLeft - threshold * 1e3, 0)
this._log.info(`时间校正:将在 ${dodgeIn} ms 后秒退`)
this._dodgeTask.start(dodgeIn)
this.state.setDodgeAt(Date.now() + dodgeIn)
} | /**
* @deprecated 已无法使用
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/auto-gameflow/index.ts#L306-L311 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AutoSelectMain._calculateAppropriateDelayMs | private _calculateAppropriateDelayMs(delayMs: number, margin: number = 1200) {
const info = this.state.currentPhaseTimerInfo
if (!info || info.isInfinite) {
return delayMs
}
const maxAllowedDelayMs = info.totalTimeInPhase - margin
const desiredDelayMs = Math.min(delayMs, maxAllowedDelayMs)
... | /**
* 确保用户设置时间的合理性
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/auto-select/index.ts#L180-L191 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | ClientInstallationMain._updateTencentPathsByReg | private async _updateTencentPathsByReg() {
try {
const list: string[] = []
if (!this.state.tencentInstallationPath) {
list.push(ClientInstallationMain.TENCENT_REG_INSTALL_PATH)
}
if (!this.state.weGameExecutablePath) {
list.push(ClientInstallationMain.WEGAME_DEFAULTICON_PAT... | /**
* 通过注册表来找寻位置
* @returns
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/client-installation/index.ts#L68-L140 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | ClientInstallationMain._updateTencentPathsByFile | private async _updateTencentPathsByFile() {
if (this.state.tencentInstallationPath) {
return
}
const drives = await this._getDrives()
this._log.info('当前的逻辑磁盘', drives)
for (const drive of drives) {
const installation = path.join(
drive,
ClientInstallationMain.TENCENT_I... | /**
* 通过扫盘来更新腾讯服安装位置
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/client-installation/index.ts#L158-L204 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | ConfigMigrateMain._migrateFrom126 | private async _migrateFrom126(manager: EntityManager) {
const hasMigratedSymbol = await manager.findOneBy(Setting, {
key: Equal(ConfigMigrateMain.MIGRATION_FROM_126)
})
if (hasMigratedSymbol) {
return
}
this._log.info('开始迁移设置项', ConfigMigrateMain.MIGRATION_FROM_126)
await this._do... | // NOTE: drop support before League Akari 1.1.x | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/config-migrate/index.ts#L44-L207 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | GameClientMain._completeSpectatorCredential | private async _completeSpectatorCredential(config: LaunchSpectatorConfig) {
const {
sgpServerId,
gameId,
gameMode,
locale = 'zh_CN',
observerEncryptionKey,
observerServerIp,
observerServerPort
} = config
if (this._lc.state.connectionState === 'connected') {
t... | /**
* 连接情况下, 通过 LCU API 获取安装位置
* 未连接的情况下, 默认使用腾讯服务端的安装位置
* @param config
* @returns
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/game-client/index.ts#L190-L279 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | InGameSendMain._sendSeparatedStringLines | private async _sendSeparatedStringLines(
messages: string[],
type: 'champ-select-chat' | 'keyboard' = 'keyboard', // 选人界面发送 or 键盘模拟游戏中发送
identifier: string | null = null
) {
const tasks: (() => Promise<void>)[] = []
const interval = this.settings.sendInterval
if (type === 'champ-select-chat')... | /**
* 模拟游戏中的发送流程
* @param messages
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/in-game-send/index.ts#L139-L201 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | InGameSendMain._deleteCustomSend | private async _deleteCustomSend(id: string) {
const targetId = `${InGameSendMain.id}/custom-send/${id}`
if (this._kbd.unregisterByTargetId(targetId)) {
this._log.info(`已删除快捷键 ${targetId}`)
}
this._setting.set(
'customSend',
this.settings.customSend.filter((item) => item.id !== id)
... | /**
* 删除快捷键并更新状态
* @param id
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/in-game-send/index.ts#L452-L465 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | InGameSendMain._dryRunStatsSend | private async _dryRunStatsSend(target = 'all') {
if (this._og.state.queryStage.phase === 'unavailable') {
this._log.warn('Dry-Run: 当前不在可发送阶段,无数据')
return { error: true, reason: 'stage-unavailable', data: [] }
}
const usingFn = this.settings.sendStatsUseDefaultTemplate
? this._defaultCompl... | /**
* 仅用于测试发送内容, 返回字符串
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/in-game-send/index.ts#L756-L788 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AkariIpcMain._handleRendererRegister | private _handleRendererRegister(event: IpcMainInvokeEvent, action = 'register') {
const id = event.sender.id
if (action === 'register' && !this._renderers.has(id)) {
this._renderers.add(id)
event.sender.on('destroyed', () => this._renderers.delete(id))
return { success: true }
} else if (... | /**
* 处理来自渲染进程的事件订阅
* @param event
* @param action 可选值 register / unregister
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ipc/index.ts#L56-L69 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AkariIpcMain.sendEvent | sendEvent(namespace: string, eventName: string, ...args: any[]) {
this._renderers.forEach((id) =>
webContents.fromId(id)?.send('akari-event', namespace, eventName, ...args)
)
} | /**
* 发送到所有已注册的渲染进程, 事件名使用 kebab-case
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ipc/index.ts#L100-L104 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AkariIpcMain.onCall | onCall(
namespace: string,
fnName: string,
cb: (event: IpcMainInvokeEvent, ...args: any[]) => Promise<any> | any
) {
const key = `${namespace}:${fnName}`
if (this._callMap.has(key)) {
throw new Error(`Function "${fnName}" in namespace "${namespace}" already exists`)
}
this._callMap.... | /**
* 处理来自渲染进程的调用, 方法名使用 camelCase
* @param cb
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ipc/index.ts#L122-L133 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AkariIpcMain._handleError | private static _handleError(error: any): IpcMainDataType {
if (isAxiosError(error)) {
const errorWithResponse = {
response: error.response
? {
status: error.response.status,
statusText: error.response.statusText,
data: error.response.data
... | /**
* 处理一般错误和 axios 错误, 包含特例, 对业务错误网开一面
* @param error
* @returns
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ipc/index.ts#L140-L176 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | AkariIpcMain.getRegisteredRendererIds | getRegisteredRendererIds() {
return Array.from(this._renderers)
} | /**
* 获取已注册的渲染进程 ID 列表
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ipc/index.ts#L181-L183 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | KeyboardShortcutsMain._correctTrackingState | private async _correctTrackingState() {
const states = await input.getAllKeyStatesAsync()
this._pressedModifierKeys.clear()
this._pressedOtherKeys.clear()
states.forEach((key) => {
const { vkCode, pressed } = key
// 你知道吗? 当微信启动的时候, 会伸出一个无形的大手将 F22 (VK_CODE 133) 按下, 然后永远不松开
// 使用此逻辑以... | /**
* 修正当前的按键状态, 最大程度上保证状态的一致性
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/keyboard-shortcuts/index.ts#L278-L309 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | KeyboardShortcutsMain.register | register(
targetId: string,
shortcutId: string,
type: 'last-active' | 'normal',
cb: (details: ShortcutDetails) => void
) {
if (!this._app.state.isAdministrator) {
this._log.info(`当前位于普通权限, 忽略快捷键注册: ${shortcutId} (${type})`)
return
}
const originShortcut = this._targetIdMap.get... | /**
* 注册一个精准快捷键
* 同 targetId 的快捷键允许被覆盖, 否则会抛出异常
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/keyboard-shortcuts/index.ts#L315-L342 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | LeagueClientUxMain.update | async update() {
try {
this.state.setLaunchedClients(await this._queryUxCommandLine())
if (this._pollTimerId) {
clearInterval(this._pollTimerId)
}
this._pollTimerId = setInterval(
() => this.update(),
LeagueClientUxMain.CLIENT_CMD_DEFAULT_POLL_INTERVAL
)
} ... | /**
* 立即更新状态
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/league-client-ux/index.ts#L99-L114 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | LeagueClientMain._disconnect | private _disconnect() {
if (this._ws) {
this._ws.close()
}
this._ws = null
this._http = null
this._api = null
this.state.setDisconnected()
} | /**
* 断开与 LeagueClient 的连接, 主要是 WebSocket
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/league-client/index.ts#L256-L266 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | LeagueClientMain.fixWindowMethodA | async fixWindowMethodA(config?: { baseHeight: number; baseWidth: number }) {
const { data: zoom } = await this.http.get<number>('/riotclient/zoom-scale')
tools.fixWindowMethodA(zoom, config)
} | /**
* https://github.com/LeagueTavern/fix-lcu-window
* 不知道现在是否需要
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/league-client/index.ts#L569-L573 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | retryFetching | const retryFetching = async () => {
if (retryCount < LeagueClientSyncedData.SUMMONER_FETCH_MAX_RETRIES) {
try {
const data = (await this._i.api.summoner.getCurrentSummoner()).data
this.summoner.setMe(data)
retryCount = 0
this.summoner.setNewIdSystemEnabled(Boolean(d... | /**
* 个人信息获取十分关键,因此必须优先获取,以实现后续功能
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/league-client/lc-state/index.ts#L925-L946 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | LoggerFactoryMain.create | create(namespace: string) {
return new AkariLogger(this, namespace)
} | /**
* 创建一个日志记录器实例, 应该用于每个对应模块中
* @param namespace
* @returns
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/logger-factory/index.ts#L93-L95 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | MobxUtilsMain.propSync | propSync<T extends object>(
namespace: string,
stateId: string,
obj: T,
propPath: Paths<T> | Paths<T>[]
) {
const key = `${namespace}:${stateId}`
if (!this._rendererSubscription.has(key)) {
this._rendererSubscription.set(key, new Set())
}
if (!this._registeredStates.has(key)) {... | /**
* 在本地的 Mobx 状态对象上注册任意个属性, 当发生变化时, 推送一个事件
* @param namespace 命名空间
* @param stateId 状态 ID
* @param obj Mobx 状态对象
* @param propPath 属性路径
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/mobx-utils/index.ts#L128-L180 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | MobxUtilsMain.reaction | reaction<T, FireImmediately extends boolean = false>(
expression: (r: IReactionPublic) => T,
effect: (
arg: T,
prev: FireImmediately extends true ? T | undefined : T,
r: IReactionPublic
) => void,
opts?: IReactionOptions<T, FireImmediately>
): () => void {
const disposer = reacti... | /**
* 和 Mobx 的 reaction 方法类似, 但是会管理 reaction 的销毁
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/mobx-utils/index.ts#L185-L203 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameMain._champSelect | private _champSelect(options: { mhSignal: AbortSignal; signal: AbortSignal; force: boolean }) {
const { mhSignal, signal, force } = options
const puuids = this.getPuuidsToLoadForPlayers()
puuids.forEach((puuid) => {
this._loadPlayerMatchHistory(puuid, {
signal,
mhSignal,
force... | /**
*
* @param options 其中的 force, 用于标识是否强制刷新. 若为 false, 在查询条件未发生变动时不会重新加载
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/index.ts#L324-L349 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameMain._inGame | private _inGame(options: { mhSignal: AbortSignal; signal: AbortSignal; force: boolean }) {
const { mhSignal, signal, force } = options
const puuids = this.getPuuidsToLoadForPlayers()
puuids.forEach((puuid) => {
this._loadPlayerMatchHistory(puuid, {
signal,
mhSignal,
force,
... | /** 目前实现同 #._champSelect */ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/index.ts#L352-L377 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameState.championSelections | get championSelections() {
if (this.queryStage.phase === 'champ-select') {
if (!this._lcData.champSelect.session) {
return {}
}
const selections: Record<string, number> = {}
this._lcData.champSelect.session.myTeam.forEach((p) => {
if (p.puuid && p.puuid !== EMPTY_PUUID) {
... | /**
* 当前进行的英雄选择
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/state.ts#L82-L130 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameState.teams | get teams() {
if (this.queryStage.phase === 'champ-select') {
if (!this._lcData.champSelect.session) {
return {}
}
const teams: Record<string, string[]> = {}
this._lcData.champSelect.session.myTeam
.filter((p) => p.puuid && p.puuid !== EMPTY_PUUID)
.forEach((p) => {... | /**
* 当前对局的队伍分配
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/state.ts#L205-L260 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameState.queryStage | get queryStage() {
if (
this._lcData.gameflow.session &&
this._lcData.gameflow.session.phase === 'ChampSelect' &&
this._lcData.champSelect.session
) {
return {
phase: 'champ-select' as 'champ-select' | 'in-game',
gameInfo: {
queueId: this._lcData.gameflow.sessio... | /**
* 当前游戏的进行状态简化,用于区分 League Akari 的几个主要阶段
*
* unavailable - 不需要介入的状态
*
* champ-select - 正在英雄选择阶段
*
* in-game - 在游戏中或游戏结算中
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/state.ts#L271-L312 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | OngoingGameState.isInEog | get isInEog() {
return (
this._lcData.gameflow.phase === 'WaitingForStats' ||
this._lcData.gameflow.phase === 'PreEndOfGame' ||
this._lcData.gameflow.phase === 'EndOfGame'
)
} | /**
* 在游戏结算时,League Akari 会额外进行一些操作
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/ongoing-game/state.ts#L317-L323 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | RespawnTimerState.selfChampionInGameSelection | get selfChampionInGameSelection() {
if (!this._lcData.gameflow.session || !this._lcData.summoner.me) {
return null
}
const self = [
...this._lcData.gameflow.session.gameData.teamOne,
...this._lcData.gameflow.session.gameData.teamTwo
].find((v) => v.summonerId === this._lcData.summoner... | /**
* 依赖于 LeagueClientSyncedData 的计算属性
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/respawn-timer/state.ts#L31-L42 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | RiotClientMain.constructor | constructor(deps: any) {
this._ipc = deps['akari-ipc-main']
this._mobx = deps['mobx-utils-main']
this._lc = deps['league-client-main']
this._loggerFactory = deps['logger-factory-main']
this._protocol = deps['akari-protocol-main']
this._log = this._loggerFactory.create(RiotClientMain.id)
thi... | // private _eventBus = new RadixEventEmitter() | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/riot-client/index.ts#L47-L56 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | RiotClientMain.request | async request<T = any, D = any>(config: AxiosRequestConfig<D>) {
if (!this._http) {
throw new Error('RC Uninitialized')
}
return this._http.request<T>(config)
} | /**
* RC 的请求, 🐰
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/riot-client/index.ts#L160-L166 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SavedPlayerMain.queryEncounteredGames | async queryEncounteredGames(query: EncounteredGameQueryDto) {
const pageSize = query.pageSize || SavedPlayerMain.ENCOUNTERED_GAME_QUERY_DEFAULT_PAGE_SIZE
const page = query.page || 1
const take = pageSize
const skip = (page - 1) * pageSize
const encounteredGames = await this._storage.dataSource.ma... | /**
*
* @param query
* @returns
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/saved-player/index.ts#L44-L63 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SavedPlayerMain.getPlayerTags | async getPlayerTags(query: SavedPlayerQueryDto) {
if (!query.puuid || !query.selfPuuid) {
throw new Error('puuid, selfPuuid or region cannot be empty')
}
const players = await this._storage.dataSource.manager.findBy(SavedPlayer, {
puuid: Equal(query.puuid)
})
return players
.filt... | /**
* 查询玩家的所有标记, 包括非此账号标记的
* 不可跨区服查询
* @param query
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/saved-player/index.ts#L162-L179 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SavedPlayerMain.updatePlayerTag | async updatePlayerTag(dto: UpdateTagDto) {
// 这里的 selfPuuid 是标记者的 puuid
if (!dto.puuid || !dto.selfPuuid) {
throw new Error('puuid, selfPuuid cannot be empty')
}
const player = await this._storage.dataSource.manager.findOneBy(SavedPlayer, {
puuid: Equal(dto.puuid),
selfPuuid: Equal(dt... | /**
* 更改某个玩家的 Tag, 提供标记者和被标记者的 puuid
* 提供为空则为删除标记
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/saved-player/index.ts#L185-L217 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SelfUpdateMain._updateReleaseUpdatesInfo | private async _updateReleaseUpdatesInfo(debug = false) {
if (this.state.isCheckingUpdates) {
return {
result: 'is-checking-updates'
}
}
this.state.setCheckingUpdates(true)
const sourceUrl = SelfUpdateMain.UPDATE_SOURCE[this.settings.downloadSource]
try {
const release = ... | /**
* 尝试加载更新信息
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/self-update/index.ts#L224-L275 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain._hasKeyInStorage | _hasKeyInStorage(namespace: string, key: string) {
const key2 = `${namespace}/${key}`
return this._storage.dataSource.manager.existsBy(Setting, { key: key2 })
} | /**
* 拥有指定设置项吗?
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L73-L76 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain._saveToStorage | async _saveToStorage(namespace: string, key: string, value: any) {
const key2 = `${namespace}/${key}`
if (!key2 || value === undefined) {
throw new Error('key or value cannot be empty')
}
await this._storage.dataSource.manager.save(Setting.create(key2, value))
} | /**
* 设置指定设置项的值
* @param key
* @param value
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L104-L112 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain._removeFromStorage | async _removeFromStorage(namespace: string, key: string) {
const key2 = `${namespace}/${key}`
if (!key2) {
throw new Error('key is required')
}
await this._storage.dataSource.manager.delete(Setting, { key: key2 })
} | /**
* 删除设置项, 但通常没有用过
* @param key
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L118-L125 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain.readFromJsonConfigFile | async readFromJsonConfigFile<T = any>(namespace: string, filename: string): Promise<T> {
if (!namespace) {
throw new Error('domain is required')
}
const jsonPath = path.join(
app.getPath('userData'),
SetterSettingService.CONFIG_DIR_NAME,
namespace,
filename
)
if (!fs.... | /**
* 从应用目录读取某个 JSON 文件,提供一个文件名
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L130-L149 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain.writeToJsonConfigFile | async writeToJsonConfigFile(namespace: string, filename: string, data: any) {
if (!namespace) {
throw new Error('domain is required')
}
const jsonPath = path.join(
app.getPath('userData'),
SetterSettingService.CONFIG_DIR_NAME,
namespace,
filename
)
await fs.promises.m... | /**
* 将某个东西写入到 JSON 文件中,提供一个文件名
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L154-L168 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SettingFactoryMain.jsonConfigFileExists | async jsonConfigFileExists(namespace: string, filename: string) {
if (!namespace) {
throw new Error('domain is required')
}
const jsonPath = path.join(
app.getPath('userData'),
SetterSettingService.CONFIG_DIR_NAME,
namespace,
filename
)
return fs.existsSync(jsonPath)
... | /**
* 检查某个 json 配置文件是否存在
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/index.ts#L173-L186 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SetterSettingService._getAllFromStorage | async _getAllFromStorage() {
const items: Record<string, any> = {}
const jobs = Object.entries(this._schema).map(async ([key, schema]) => {
const value = await this._ins._getFromStorage(this._namespace, key as any, schema.default)
items[key] = value
})
await Promise.all(jobs)
return item... | /**
* 获取所有设置项
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/setter-setting-service.ts#L34-L42 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SetterSettingService.applyToState | async applyToState() {
const items = await this._getAllFromStorage()
Object.entries(items).forEach(([key, value]) => {
_.set(this._obj, key, value)
})
return items
} | /**
* 获取设置项, 并存储到这个 mobx 对象中
* @param obj Mobx Observable
* @returns 所有设置项
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/setter-setting-service.ts#L49-L56 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SetterSettingService.onChange | onChange(key: string, fn: OnChangeCallback) {
if (!this._schema[key]) {
throw new Error(`key ${key} not found in schema`)
}
const _fn = this._schema[key].onChange
// 重复设置, 会报错
if (_fn) {
throw new Error(`onChange for key ${key} already set`)
}
this._schema[key].onChange = fn
... | /**
* 当某个设置项发生变化时, 拦截此行为
* @param newValue
* @param extra
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/setter-setting-service.ts#L75-L87 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SetterSettingService.set | async set(key: string, newValue: any) {
const fn = this._schema[key]?.onChange
if (fn) {
const oldValue = this._obj[key as any]
await fn(newValue, {
oldValue,
key,
setter: async (v?: any) => {
if (v === undefined) {
runInAction(() => _.set(this._obj, ke... | /**
* 设置设置项的新值, 并更新状态
* @param key
* @param newValue
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/setter-setting-service.ts#L94-L131 | f75d7cd05ff40722c81517152cc11097052c9433 |
LeagueAkari | github_2023 | Hanxven | typescript | SetterSettingService.remove | remove(key: string): never {
console.error(`Deemo will finally find his ${key}, not Celia but Alice`)
throw new Error('not implemented')
} | /**
* placeholder
* @param key
*/ | https://github.com/Hanxven/LeagueAkari/blob/f75d7cd05ff40722c81517152cc11097052c9433/src/main/shards/setting-factory/setter-setting-service.ts#L141-L144 | f75d7cd05ff40722c81517152cc11097052c9433 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.