// ==UserScript== // @name 💯【超星学习通满分助手】支持LLM智能答题 // @namespace askAuto // @version 3.8.0 // @author HaoduoYv // @description 💯超星学习通满分助手,挂机解放时间,无需任何操作自动完成所有任务点。内置独立多题库模块(不挂科/icodef/万能/爱点/题库海/言溪/柠檬+自定义接口+自建tikuAdapter),每个题库独立开关与排序,支持并行最快命中与顺序调用;支持LLM智能答题(OpenAI/DeepSeek/kimi/智谱/千问/小米Mimo等),题库无答案时自动调用AI解答。 // @icon https://vitejs.dev/logo.svg // @match *://*.chaoxing.com/* // @match *://*.edu.cn/* // @match *://*.nbdlib.cn/* // @match *://*.hnsyu.net/* // @match *://*.gdhkmooc.com/* // @require https://cdn.staticfile.org/vue/3.3.4/vue.global.prod.js // @require https://cdn.staticfile.org/vue-demi/0.14.0/index.iife.min.js // @require https://cdn.staticfile.org/element-plus-icons-vue/2.1.0/global.iife.min.js // @require data:application/javascript,window.Vue%3DVue%3B // @require https://cdn.staticfile.org/pinia/2.1.6/pinia.iife.prod.js // @require https://cdn.staticfile.org/element-plus/2.3.12/index.full.min.js // @require https://cdn.staticfile.org/blueimp-md5/2.19.0/js/md5.min.js // @require https://cdn.staticfile.org/jquery/3.7.1/jquery.min.js // @resource element-plus https://cdn.staticfile.org/element-plus/2.3.12/index.css // @resource ttf https://www.forestpolice.org/ttf/2.0/table.json // @tag free // @connect api.openai.com // @connect api.deepseek.com // @connect api.anthropic.com // @connect open.bigmodel.cn // @connect dashscope.aliyuncs.com // @connect api.xiaomimimo.com // @connect token-plan-cn.xiaomimimo.com // @connect api.moonshot.cn // @connect api.moonshot.ai // @connect ark.cn-beijing.volces.com // @connect api.hunyuan.cloud.tencent.com // @connect api.baichuan-ai.com // @connect api.stepfun.com // @connect api.minimax.chat // @connect api.siliconflow.cn // @connect openrouter.ai // @connect generativelanguage.googleapis.com // @connect www.baidu.com // @connect www.bing.com // @connect cn.bing.com // @connect duckduckgo.com // @connect cx.icodef.com // @connect easylearn.baidu.com // @connect lyck6.cn // @connect api.tikuhai.com // @connect new.api.51aidian.com // @connect tk.enncy.cn // @connect api.lemtk.xyz // @connect localhost // @connect 127.0.0.1 // @connect tokenhub.tencentmaas.com // @connect maas.qianwenaiapi.com // @connect * // @grant GM_addStyle // @grant GM_getResourceText // @grant GM_getValue // @grant GM_info // @grant GM_setValue // @grant GM_xmlhttpRequest // @grant unsafeWindow // @run-at document-end // @license MIT // ==/UserScript== (t => { if (typeof GM_addStyle == "function") { GM_addStyle(t); return } const i = document.createElement("style"); i.textContent = t, document.head.append(i) })("/* ===== 超星学习通满分助手 现代简洁 UI ===== */:root{--cx-bg:#f8fafc;--cx-surface:#ffffff;--cx-surface-raised:#ffffff;--cx-primary:#4f46e5;--cx-primary-light:#6366f1;--cx-primary-soft:#e0e7ff;--cx-primary-dark:#4338ca;--cx-success:#16a34a;--cx-warning:#d97706;--cx-danger:#dc2626;--cx-info:#0891b2;--cx-text:#0f172a;--cx-text-secondary:#475569;--cx-text-tertiary:#94a3b8;--cx-border:#e2e8f0;--cx-border-light:#f1f5f9;--cx-radius-lg:16px;--cx-radius:12px;--cx-radius-sm:8px;--cx-radius-xs:6px;--cx-shadow:0 10px 30px -10px rgba(15,23,42,.12);--cx-shadow-sm:0 2px 8px rgba(15,23,42,.06);--cx-shadow-lg:0 20px 40px -12px rgba(15,23,42,.18);--cx-transition:all .2s cubic-bezier(.4,0,.2,1)}#csbutton,#csbutton[data-v-6ed29f7f],#csbutton[data-v-c3c6b09f]{position:fixed;bottom:24px;right:24px;z-index:99999;width:56px;height:56px;border-radius:16px!important;font-size:22px;box-shadow:var(--cx-shadow);transition:var(--cx-transition);border:none!important;background:var(--cx-primary)!important;color:#fff!important}#csbutton:hover,#csbutton[data-v-6ed29f7f]:hover,#csbutton[data-v-c3c6b09f]:hover{transform:translateY(-2px);box-shadow:var(--cx-shadow-lg)}#zeokdjg,#zeokdjg[data-v-c3c6b09f]{position:fixed;right:24px;bottom:96px;z-index:99999;width:56px;height:56px;border-radius:16px!important;font-size:22px;box-shadow:var(--cx-shadow);transition:var(--cx-transition);border:none!important;background:var(--cx-primary)!important;color:#fff!important;padding:0!important;display:flex;align-items:center;justify-content:center}#zeokdjg:hover,#zeokdjg[data-v-c3c6b09f]:hover{transform:translateY(-2px);box-shadow:var(--cx-shadow-lg)}#zeokdjg .el-button__text,#zeokdjg span{font-size:0!important}#zeokdjg .el-icon{font-size:22px!important}.el-dialog{border-radius:var(--cx-radius-lg)!important;box-shadow:var(--cx-shadow-lg)!important;background:var(--cx-surface)!important}.cx-config-dialog{width:900px!important;max-width:calc(100vw - 32px)!important}.cx-ask-dialog{width:480px!important;max-width:calc(100vw - 40px)!important}.el-dialog__header{padding:20px 24px 0!important;font-size:16px;font-weight:600;color:var(--cx-text);border-bottom:none}.el-dialog__body{padding:0!important;color:var(--cx-text-secondary);font-size:14px;line-height:1.6}.el-dialog__footer{padding:16px 24px!important;border-top:1px solid var(--cx-border);margin-top:0;display:flex;justify-content:flex-end;gap:12px}.el-dialog__headerbtn{top:18px!important;right:20px!important;font-size:18px!important;width:32px;height:32px;border-radius:var(--cx-radius-sm);transition:var(--cx-transition)}.el-dialog__headerbtn:hover{background:var(--cx-border-light);transform:rotate(90deg)}.cx-config-layout{display:flex;min-height:420px;max-height:70vh}.cx-config-nav{width:160px;flex-shrink:0;background:var(--cx-bg);border-right:1px solid var(--cx-border);padding:16px 12px;display:flex;flex-direction:column;gap:4px;border-radius:var(--cx-radius-lg) 0 0 var(--cx-radius-lg)}.cx-config-nav-item{width:100%;text-align:left;padding:10px 12px;border-radius:var(--cx-radius-sm);font-size:13px;font-weight:500;color:var(--cx-text-secondary);cursor:pointer;transition:var(--cx-transition);border:none;background:transparent}.cx-config-nav-item:hover{background:var(--cx-border-light);color:var(--cx-text)}.cx-config-nav-item.active{background:var(--cx-primary-soft);color:var(--cx-primary)}.cx-config-content{flex:1;min-width:0;padding:24px;overflow-y:auto}.cx-config-section-title{font-size:18px;font-weight:600;color:var(--cx-text);margin-bottom:8px}.cx-config-section-desc{font-size:13px;color:var(--cx-text-secondary);margin-bottom:24px}.cx-config-actions{display:flex;gap:8px;margin-top:24px;padding-top:20px;border-top:1px solid var(--cx-border)}.cx-config-group-title{font-size:14px;font-weight:600;color:var(--cx-text);margin:24px 0 12px;padding-bottom:8px;border-bottom:1px solid var(--cx-border-light)}.cx-config-group-title:first-child{margin-top:0}.el-form-item{margin-bottom:20px!important}.el-form-item__label{font-weight:500;color:var(--cx-text);padding-bottom:4px!important;font-size:13px}.el-form-item__content{line-height:1.5}.el-switch.is-checked .el-switch__core{background:var(--cx-primary)!important;border-color:var(--cx-primary)!important}.el-button--primary{--el-button-primary-bg-color:var(--cx-primary);--el-button-primary-border-color:var(--cx-primary)}.el-button--primary:hover{--el-button-primary-bg-color:var(--cx-primary-light);--el-button-primary-border-color:var(--cx-primary-light)}.el-button--danger{--el-button-danger-bg-color:var(--cx-danger);--el-button-danger-border-color:var(--cx-danger)}.el-button{border-radius:var(--cx-radius-sm)!important;font-weight:500!important;transition:var(--cx-transition)}.el-input__wrapper,.el-textarea__inner{border-radius:var(--cx-radius-sm)!important;box-shadow:0 0 0 1px var(--cx-border) inset!important}.el-input__wrapper:hover,.el-textarea__inner:hover{box-shadow:0 0 0 1px var(--cx-primary-light) inset!important}.el-input__wrapper.is-focus{box-shadow:0 0 0 1px var(--cx-primary) inset!important}.el-select{width:100%}.el-checkbox__input.is-checked .el-checkbox__inner{background:var(--cx-primary)!important;border-color:var(--cx-primary)!important}.el-checkbox__label{font-size:13px!important;color:var(--cx-text-secondary)}.el-checkbox-group.cx-checkbox-horizontal{display:flex;flex-wrap:wrap;gap:16px}.cx-runtime{padding:20px 24px}.cx-runtime-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;padding:12px 16px;background:var(--cx-bg);border-radius:var(--cx-radius-sm)}.cx-runtime-header-title{font-size:14px;font-weight:600;color:var(--cx-text)}.cx-runtime-header-meta{font-size:12px;color:var(--cx-text-secondary)}.cx-question-card{margin-bottom:16px;border-radius:var(--cx-radius)!important;border:1px solid var(--cx-border)!important;background:var(--cx-surface)!important}.cx-question-card .el-card__body{padding:20px!important}.cx-question-index{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:var(--cx-radius-xs);background:var(--cx-primary-soft);color:var(--cx-primary);font-size:12px;font-weight:600;margin-right:8px}.cx-question-title{font-size:15px;font-weight:500;color:var(--cx-text);line-height:1.6;margin-bottom:12px;word-break:break-word}.cx-question-answer{background:var(--cx-bg);border-radius:var(--cx-radius-sm);padding:12px;font-size:13px;color:var(--cx-text);white-space:pre-wrap;word-break:break-word;line-height:1.6}.cx-question-empty{display:flex;flex-direction:column;gap:12px;padding:8px 0}.cx-question-nav{display:flex;gap:8px;margin:16px 0;padding:8px 0}.cx-question-nav .el-button{min-width:36px;height:36px;padding:0 12px;border-radius:18px!important;font-size:13px;font-weight:500}.cx-source-list{display:flex;flex-direction:column;gap:12px;margin-top:16px}.cx-source-item{padding:14px 16px;border:1px solid var(--cx-border);border-radius:var(--cx-radius-sm);background:var(--cx-surface-raised)}.cx-source-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}.cx-source-name{font-size:13px;font-weight:600;color:var(--cx-text)}.cx-source-answer{font-size:13px;color:var(--cx-text-secondary);line-height:1.6;white-space:pre-wrap;word-break:break-word}.cx-source-meta{display:flex;gap:8px;margin-top:10px}.cx-ask-tabs{margin-top:8px}.cx-source-tabs .el-tabs__item{max-width:120px;overflow:hidden;text-overflow:ellipsis}.cx-source-answer{font-size:13px;line-height:1.6;word-break:break-word}.cx-question-answer{white-space:pre-wrap;word-break:break-word;font-family:inherit;font-size:14px;margin:0}#cx-ask-fab{font-size:13px;font-weight:600;border-radius:22px!important}.cx-ask-panel{position:fixed;right:24px;top:72px;width:420px;max-height:calc(100vh - 100px);overflow:auto;z-index:100000;background:#fff;border-radius:12px;box-shadow:0 20px 40px -12px rgba(15,23,42,.18);font-size:13px;color:#0f172a;user-select:none}.cx-ask-panel.collapsed .cx-panel-body{display:none}.cx-ask-panel.collapsed{width:auto!important;min-width:200px;height:auto!important}.cx-panel-toggle.pause{background:#fee2e2;color:#b91c1c}.cx-panel-toggle.pause:hover{background:#fecaca}.cx-panel-toggle{border:none;background:#e2e8f0;border-radius:6px;width:28px;height:28px;cursor:pointer;font-size:18px;line-height:1;flex-shrink:0}.cx-panel-body{padding:0 0 12px}.cx-video-tip{margin:12px;padding:10px 12px;background:#fef3c7;color:#b45309;border-radius:8px;font-weight:600;font-size:13px}.cx-follow-btn{border:none;background:#4f46e5;color:#fff;border-radius:6px;padding:2px 8px;font-size:11px;cursor:pointer;flex-shrink:0}.cx-badge{font-size:11px;padding:2px 8px;border-radius:99px;background:#e0e7ff;color:#4f46e5;font-weight:600;flex-shrink:0}.cx-badge.warn{background:#fef3c7;color:#b45309}.cx-drag-bar{display:flex;align-items:center;gap:8px;padding:10px 12px;background:#f8fafc;border-bottom:1px solid #e2e8f0;cursor:move;border-radius:12px 12px 0 0;position:sticky;top:0;z-index:2}.cx-drag-title{font-weight:600;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cx-panel-close{margin-left:auto;border:none;background:#f1f5f9;border-radius:6px;width:28px;height:28px;cursor:pointer;font-size:18px;line-height:1;flex-shrink:0}.cx-q-title{font-size:14px;font-weight:600;line-height:1.5;margin:12px 12px 8px}.cx-question-answer{margin:0 12px 8px;padding:10px;background:#f8fafc;border-radius:8px;white-space:pre-wrap;word-break:break-word;font-family:inherit}.cx-q-nav{display:flex;flex-wrap:wrap;gap:6px;margin:10px 12px}.cx-q-nav .question_btn{width:36px;height:36px;border-radius:8px;border:1px solid #e2e8f0;background:#f8fafc;cursor:pointer;font-weight:600}.cx-q-nav .question_btn.question_btn.active{background:#eef2ff;color:#4f46e5;border:2px solid #4f46e5;transform:scale(1.25);box-shadow:0 0 0 3px rgba(79,70,229,.25);z-index:2;font-size:16px}.cx-q-nav .question_btn.primary{background:#4f46e5;color:#fff;border-color:#4f46e5}.cx-q-nav .question_btn.danger{background:#fee2e2;color:#dc2626;border-color:#fecaca}.cx-source-item{border:1px solid #e2e8f0;border-radius:8px;padding:8px 10px;margin:6px 12px}.cx-source-header{display:flex;align-items:center;gap:8px;margin-bottom:4px}.cx-source-name{font-weight:600;flex:1}.cx-source-tag{font-size:11px;padding:2px 8px;border-radius:99px}.cx-source-tag.ok{background:#dcfce7;color:#166534}.cx-source-tag.no{background:#f1f5f9;color:#64748b}.cx-log-title{margin:12px 12px 4px;font-size:12px;font-weight:600;color:#64748b}.cx-log-list{padding:0 12px 12px;display:flex;flex-direction:column;gap:4px}.cx-log-item{font-size:12px;color:#475569;line-height:1.5}.cx-log-msg.success{color:#16a34a}.cx-log-msg.error{color:#dc2626}.cx-log-msg.info{color:#0891b2}.cx-fab{display:flex;align-items:center;justify-content:center;gap:6px;padding:0 14px;height:44px;width:auto;min-width:44px;position:fixed!important;right:24px!important;bottom:96px!important;z-index:100001;width:56px;height:56px;border-radius:16px!important;border:none!important;background:var(--cx-primary,#4f46e5)!important;color:#fff!important;font-size:22px;cursor:pointer;box-shadow:0 10px 30px -10px rgba(15,23,42,.2)}#cx-ask-fab{font-size:13px;font-weight:600;border-radius:22px!important}.cx-ask-panel{position:fixed;right:24px;top:72px;width:420px;height:calc(100vh - 100px);max-height:calc(100vh - 100px);overflow:auto;z-index:100000;background:#fff;border-radius:12px;box-shadow:0 20px 40px -12px rgba(15,23,42,.18);padding:14px 16px;font-size:13px;color:#0f172a}.cx-panel-close{margin-left:auto;border:none;background:#f1f5f9;border-radius:6px;width:28px;height:28px;cursor:pointer;font-size:18px;line-height:1}.cx-q-title{font-size:14px;font-weight:600;line-height:1.5;margin:8px 0}.cx-q-nav{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0}.cx-q-nav .question_btn{width:36px;height:36px;border-radius:8px;border:1px solid #e2e8f0;background:#f8fafc;cursor:pointer;font-weight:600}.cx-q-nav .question_btn.primary{background:#4f46e5;color:#fff;border-color:#4f46e5}.cx-q-nav .question_btn.danger{background:#fee2e2;color:#dc2626;border-color:#fecaca}.cx-empty{padding:24px;text-align:center;color:#64748b}.cx-video-tip{padding:16px;text-align:center;color:#dc2626;font-weight:600}.cx-source-item{border:1px solid #e2e8f0;border-radius:8px;padding:8px 10px;margin:6px 0}.cx-source-header{display:flex;align-items:center;gap:8px;margin-bottom:4px}.cx-source-name{font-weight:600;flex:1}.cx-source-tag{font-size:11px;padding:2px 8px;border-radius:99px}.cx-source-tag.ok{background:#dcfce7;color:#166534}.cx-source-tag.no{background:#f1f5f9;color:#64748b}.cx-debug-line{margin:8px 0;padding:8px 10px;background:#fff7ed;border:1px solid #fdba74;border-radius:8px;font-size:12px;color:#c2410c;font-weight:600}.cx-log-title{margin:12px 4px 6px;font-size:12px;font-weight:600;letter-spacing:.04em;color:var(--cx-text-secondary)}.cx-log-list{display:flex;flex-direction:column;gap:8px;padding:16px 24px;height:216px;overflow-y:auto}.cx-log-item{display:flex;gap:12px;align-items:flex-start;padding:10px 12px;border-radius:var(--cx-radius-sm);background:var(--cx-bg);transition:var(--cx-transition)}.cx-log-item:hover{background:var(--cx-border-light)}.cx-log-time{font-size:12px;color:var(--cx-text-tertiary);white-space:nowrap;min-width:64px}.cx-log-dot{width:6px;height:6px;border-radius:50%;margin-top:7px;flex-shrink:0}.cx-log-dot.success{background:var(--cx-success)}.cx-log-dot.error{background:var(--cx-danger)}.cx-log-dot.info{background:var(--cx-info)}.cx-log-msg{font-size:13px;color:var(--cx-text-secondary);line-height:1.5;flex:1;word-break:break-word}.cx-log-msg.success{color:var(--cx-success)}.cx-log-msg.error{color:var(--cx-danger)}.cx-log-msg.info{color:var(--cx-info)}.cx-notice{padding:20px 24px}.cx-notice-card{border-radius:var(--cx-radius)!important;border:1px solid var(--cx-border)!important;background:var(--cx-surface)!important}.cx-notice-card .el-card__body{padding:20px!important;font-size:14px;line-height:1.8;color:var(--cx-text-secondary)}.el-tabs__item{font-size:13px;font-weight:500;padding:0 14px!important;transition:var(--cx-transition);color:var(--cx-text-secondary)}.el-tabs__item.is-active{color:var(--cx-primary)!important}.el-tabs__active-bar{background:var(--cx-primary)!important;height:2px;border-radius:2px}.el-tag{border-radius:var(--cx-radius-xs)!important;font-weight:500!important;border:none!important}.el-alert{border-radius:var(--cx-radius-sm)!important;border:none!important}.el-empty__description p{color:var(--cx-text-secondary)!important}.el-scrollbar__view{padding:2px 0}.el-skeleton__item{--el-skeleton-circle-size:8px}.el-divider__text{font-size:12px;color:var(--cx-text-secondary);background:var(--cx-surface)}.el-overlay{overflow:visible!important}.el-select-dropdown,.el-tooltip__popper,.el-popper,.el-select__popper,.el-picker__popper{z-index:999999!important}.el-message-box__wrapper{z-index:99999!important}.dialog-footer button[data-v-6ed29f7f]:first-child{margin-right:10px}.dialog-footer button[data-v-c3c6b09f]:first-child{margin-right:10px}.question_btn[data-v-c3c6b09f]{width:36px;height:36px;border-radius:18px!important;margin:4px;font-weight:500!important;transition:var(--cx-transition);padding:0!important}.question_btn[data-v-c3c6b09f]:hover{transform:scale(1.05);z-index:2}.question_div[data-v-c3c6b09f]{padding:4px 0}.question_ti[data-v-c3c6b09f]{margin:12px 0 16px;line-height:1.5;font-size:15px;font-weight:500}.cx_log[data-v-c3c6b09f]{margin:3px 0;padding:6px 10px;border-radius:6px;background:var(--cx-bg);transition:var(--cx-transition);font-size:13px}.cx_log[data-v-c3c6b09f]:hover{background:var(--cx-border-light)}.status_log[data-v-c3c6b09f]{margin-top:12px}.cx-log-success{color:var(--cx-success)}.cx-log-error{color:var(--cx-danger)}.cx-log-info{color:var(--cx-info)}.vjs-big-play-button{display:none!important}@media (max-width:640px){.cx-config-dialog,.cx-ask-dialog{width:100vw!important;max-width:100vw!important;margin:0!important;border-radius:0!important;height:100vh!important;max-height:100vh!important}.cx-config-layout{flex-direction:column;min-height:auto;max-height:calc(100vh - 55px)}.cx-config-nav{width:100%;flex-direction:row;overflow-x:auto;padding:8px;gap:8px;border-right:none;border-bottom:1px solid var(--cx-border);border-radius:0}.cx-config-nav-item{width:auto;white-space:nowrap;padding:8px 12px}.cx-config-content{padding:16px;max-height:calc(100vh - 120px)}.cx-runtime{padding:16px}.cx-ask-tabs{margin-top:8px}.cx-source-tabs .el-tabs__item{max-width:120px;overflow:hidden;text-overflow:ellipsis}.cx-source-answer{font-size:13px;line-height:1.6;word-break:break-word}.cx-question-answer{white-space:pre-wrap;word-break:break-word;font-family:inherit;font-size:14px;margin:0}#cx-ask-fab{font-size:13px;font-weight:600;border-radius:22px!important}.cx-ask-panel{position:fixed;right:24px;top:72px;width:420px;max-height:calc(100vh - 100px);overflow:auto;z-index:100000;background:#fff;border-radius:12px;box-shadow:0 20px 40px -12px rgba(15,23,42,.18);font-size:13px;color:#0f172a;user-select:none}.cx-ask-panel.collapsed .cx-panel-body{display:none}.cx-ask-panel.collapsed{width:auto!important;min-width:200px;height:auto!important}.cx-panel-toggle.pause{background:#fee2e2;color:#b91c1c}.cx-panel-toggle.pause:hover{background:#fecaca}.cx-panel-toggle{border:none;background:#e2e8f0;border-radius:6px;width:28px;height:28px;cursor:pointer;font-size:18px;line-height:1;flex-shrink:0}.cx-panel-body{padding:0 0 12px}.cx-video-tip{margin:12px;padding:10px 12px;background:#fef3c7;color:#b45309;border-radius:8px;font-weight:600;font-size:13px}.cx-follow-btn{border:none;background:#4f46e5;color:#fff;border-radius:6px;padding:2px 8px;font-size:11px;cursor:pointer;flex-shrink:0}.cx-badge{font-size:11px;padding:2px 8px;border-radius:99px;background:#e0e7ff;color:#4f46e5;font-weight:600;flex-shrink:0}.cx-badge.warn{background:#fef3c7;color:#b45309}.cx-drag-bar{display:flex;align-items:center;gap:8px;padding:10px 12px;background:#f8fafc;border-bottom:1px solid #e2e8f0;cursor:move;border-radius:12px 12px 0 0;position:sticky;top:0;z-index:2}.cx-drag-title{font-weight:600;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.cx-panel-close{margin-left:auto;border:none;background:#f1f5f9;border-radius:6px;width:28px;height:28px;cursor:pointer;font-size:18px;line-height:1;flex-shrink:0}.cx-q-title{font-size:14px;font-weight:600;line-height:1.5;margin:12px 12px 8px}.cx-question-answer{margin:0 12px 8px;padding:10px;background:#f8fafc;border-radius:8px;white-space:pre-wrap;word-break:break-word;font-family:inherit}.cx-q-nav{display:flex;flex-wrap:wrap;gap:6px;margin:10px 12px}.cx-q-nav .question_btn{width:36px;height:36px;border-radius:8px;border:1px solid #e2e8f0;background:#f8fafc;cursor:pointer;font-weight:600}.cx-q-nav .question_btn.question_btn.active{background:#eef2ff;color:#4f46e5;border:2px solid #4f46e5;transform:scale(1.25);box-shadow:0 0 0 3px rgba(79,70,229,.25);z-index:2;font-size:16px}.cx-q-nav .question_btn.primary{background:#4f46e5;color:#fff;border-color:#4f46e5}.cx-q-nav .question_btn.danger{background:#fee2e2;color:#dc2626;border-color:#fecaca}.cx-source-item{border:1px solid #e2e8f0;border-radius:8px;padding:8px 10px;margin:6px 12px}.cx-source-header{display:flex;align-items:center;gap:8px;margin-bottom:4px}.cx-source-name{font-weight:600;flex:1}.cx-source-tag{font-size:11px;padding:2px 8px;border-radius:99px}.cx-source-tag.ok{background:#dcfce7;color:#166534}.cx-source-tag.no{background:#f1f5f9;color:#64748b}.cx-log-title{margin:12px 12px 4px;font-size:12px;font-weight:600;color:#64748b}.cx-log-list{padding:0 12px 12px;display:flex;flex-direction:column;gap:4px}.cx-log-item{font-size:12px;color:#475569;line-height:1.5}.cx-log-msg.success{color:#16a34a}.cx-log-msg.error{color:#dc2626}.cx-log-msg.info{color:#0891b2}.cx-fab{display:flex;align-items:center;justify-content:center;gap:6px;padding:0 14px;height:44px;width:auto;min-width:44px;position:fixed!important;right:24px!important;bottom:96px!important;z-index:100001;width:56px;height:56px;border-radius:16px!important;border:none!important;background:var(--cx-primary,#4f46e5)!important;color:#fff!important;font-size:22px;cursor:pointer;box-shadow:0 10px 30px -10px rgba(15,23,42,.2)}#cx-ask-fab{font-size:13px;font-weight:600;border-radius:22px!important}.cx-ask-panel{position:fixed;right:24px;top:72px;width:420px;height:calc(100vh - 100px);max-height:calc(100vh - 100px);overflow:auto;z-index:100000;background:#fff;border-radius:12px;box-shadow:0 20px 40px -12px rgba(15,23,42,.18);padding:14px 16px;font-size:13px;color:#0f172a}.cx-panel-close{margin-left:auto;border:none;background:#f1f5f9;border-radius:6px;width:28px;height:28px;cursor:pointer;font-size:18px;line-height:1}.cx-q-title{font-size:14px;font-weight:600;line-height:1.5;margin:8px 0}.cx-q-nav{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0}.cx-q-nav .question_btn{width:36px;height:36px;border-radius:8px;border:1px solid #e2e8f0;background:#f8fafc;cursor:pointer;font-weight:600}.cx-q-nav .question_btn.primary{background:#4f46e5;color:#fff;border-color:#4f46e5}.cx-q-nav .question_btn.danger{background:#fee2e2;color:#dc2626;border-color:#fecaca}.cx-empty{padding:24px;text-align:center;color:#64748b}.cx-video-tip{padding:16px;text-align:center;color:#dc2626;font-weight:600}.cx-source-item{border:1px solid #e2e8f0;border-radius:8px;padding:8px 10px;margin:6px 0}.cx-source-header{display:flex;align-items:center;gap:8px;margin-bottom:4px}.cx-source-name{font-weight:600;flex:1}.cx-source-tag{font-size:11px;padding:2px 8px;border-radius:99px}.cx-source-tag.ok{background:#dcfce7;color:#166534}.cx-source-tag.no{background:#f1f5f9;color:#64748b}.cx-debug-line{margin:8px 0;padding:8px 10px;background:#fff7ed;border:1px solid #fdba74;border-radius:8px;font-size:12px;color:#c2410c;font-weight:600}.cx-log-title{margin:12px 4px 6px;font-size:12px;font-weight:600;letter-spacing:.04em;color:var(--cx-text-secondary)}.cx-log-list{padding:16px}.cx-notice{padding:16px}}"); (async function (vue, pinia$1, ElementPlus, md5, $$1) { 'use strict'; var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; ((e) => { const t = GM_getResourceText(e); GM_addStyle(t); })("element-plus"); var _GM_getResourceText = (() => "undefined" != typeof GM_getResourceText ? GM_getResourceText : void 0)(), _GM_getValue = (() => "undefined" != typeof GM_getValue ? GM_getValue : void 0)(), _GM_info = (() => "undefined" != typeof GM_info ? GM_info : void 0)(), _GM_setValue = (() => "undefined" != typeof GM_setValue ? GM_setValue : void 0)(), _GM_xmlhttpRequest = (() => "undefined" != typeof GM_xmlhttpRequest ? GM_xmlhttpRequest : void 0)(), _unsafeWindow = (() => "undefined" != typeof unsafeWindow ? unsafeWindow : void 0)(); const encryptApiKey = (k) => k ? btoa(k.split("").reverse().join("")) : ""; const decryptApiKey = (e) => { if (!e) return ""; try { return atob(e).split("").reverse().join("") } catch { return e } }; /* ===== LLM Provider Kit v1(与 mooc.js 保持一致,勿单方面修改) ===== */ const PROVIDER_CATALOG = [ { id: "hunyuan", label: "腾讯TokenHub(免费额度)", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://tokenhub.tencentmaas.com/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "", apiKeyUrl: "https://console.cloud.tencent.com/tokenhub/apikey", quotaUrl: "https://console.cloud.tencent.com/tokenhub/open-management", cacheMode: "none", vision: false }, { id: "qwen", label: "阿里云百炼(免费额度)", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://maas.qianwenaiapi.com/compatible-mode/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "", apiKeyUrl: "https://platform.qianwenai.com/home/api-keys", quotaUrl: "https://bailian.console.aliyun.com/cn-beijing/costing-balance/free-quota", cacheMode: "none", vision: true }, { id: "deepseek", label: "DeepSeek", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://api.deepseek.com/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "deepseek-chat", apiKeyUrl: "https://platform.deepseek.com/api_keys", cacheMode: "none", vision: false }, { id: "zhipu", label: "智谱 GLM", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://open.bigmodel.cn/api/paas/v4", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "glm-4-flash", apiKeyUrl: "https://open.bigmodel.cn/usercenter/apikeys", cacheMode: "none", vision: true }, { id: "kimi", label: "Kimi (月之暗面)", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://api.moonshot.cn/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "moonshot-v1-8k", apiKeyUrl: "https://platform.moonshot.cn/console/api-keys", cacheMode: "key", vision: false }, { id: "volc", label: "火山方舟", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://ark.cn-beijing.volces.com/api/v3", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "", apiKeyUrl: "https://console.volcengine.com/ark", cacheMode: "none", vision: false }, { id: "baichuan", label: "百川智能", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://api.baichuan-ai.com/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "Baichuan4", apiKeyUrl: "https://platform.baichuan-ai.com/console/apikey", cacheMode: "none", vision: false }, { id: "stepfun", label: "阶跃星辰", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://api.stepfun.com/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "step-1-8k", apiKeyUrl: "https://platform.stepfun.com/interface-key", cacheMode: "none", vision: false }, { id: "minimax", label: "MiniMax", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://api.minimax.chat/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "abab6.5s-chat", apiKeyUrl: "https://www.minimaxi.com/user-center/basic-information/interface-key", cacheMode: "none", vision: false }, { id: "siliconflow", label: "硅基流动", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://api.siliconflow.cn/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "Qwen/Qwen2.5-7B-Instruct", apiKeyUrl: "https://cloud.siliconflow.cn/account/ak", cacheMode: "none", vision: true }, { id: "openrouter", label: "OpenRouter", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://openrouter.ai/api/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "openai/gpt-4o-mini", apiKeyUrl: "https://openrouter.ai/keys", cacheMode: "key", vision: true }, { id: "openai", label: "OpenAI", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://api.openai.com/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "gpt-4o-mini", apiKeyUrl: "https://platform.openai.com/api-keys", cacheMode: "key", vision: true }, { id: "anthropic", label: "Anthropic (Claude)", apiStyle: "anthropic", authStyle: "x-api-key", baseUrl: "https://api.anthropic.com/v1", chatPath: "/messages", modelsPath: "/models", defaultModel: "claude-sonnet-4-5", apiKeyUrl: "https://console.anthropic.com/settings/keys", extraHeaders: { "anthropic-version": "2023-06-01" }, cacheMode: "breakpoint", vision: true }, { id: "gemini", label: "Google Gemini", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "gemini-2.5-flash", apiKeyUrl: "https://aistudio.google.com/app/apikey", cacheMode: "none", vision: true }, { id: "xiaomimimo", label: "小米 Mimo", apiStyle: "openai", authStyle: "bearer", baseUrl: "https://api.xiaomimimo.com/v1", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "", apiKeyUrl: "", cacheMode: "none", vision: false }, { id: "custom", label: "自定义", apiStyle: "openai", authStyle: "bearer", baseUrl: "", chatPath: "/chat/completions", modelsPath: "/models", defaultModel: "", apiKeyUrl: "", cacheMode: "none", vision: false } ]; // 兼容视图:userConfig 下拉与 onProviderChange 仍按 {label,value,baseUrl,suffix,apiKeyUrl} 消费 const llmProviderPresets = PROVIDER_CATALOG.map(p => ({ label: p.label, value: p.id, baseUrl: p.baseUrl, suffix: p.chatPath, models: [], apiKeyUrl: p.apiKeyUrl, quotaUrl: p.quotaUrl || "", provider: p })); function normalizeBaseUrl(raw) { let u = String(raw == null ? "" : raw).trim(); if (!u) return ""; if (!/^https?:\/\//i.test(u)) u = "https://" + u; return u.replace(/\/+$/, ""); } function splitEndpoint(fullUrl, defaultChatPath) { const u = normalizeBaseUrl(fullUrl); const m = u.match(/^(.*?)(\/(?:chat\/completions|messages|completions))$/); if (m) return { baseUrl: m[1], chatPath: m[2] }; return { baseUrl: u, chatPath: defaultChatPath }; } function buildChatUrl(baseUrl, chatPath) { const b = normalizeBaseUrl(baseUrl); const p = chatPath || "/chat/completions"; const path = p.charAt(0) === "/" ? p : "/" + p; if (!b) return path; if (b.slice(-path.length) === path) return b; return b + path; } function buildModelsUrl(baseUrl, modelsPath) { // CX_AUDIT_LLM_V1:baseUrl 可能已含 /chat/completions(对话侧 buildChatUrl 会去重, // 但 models 侧直接拼会变成 .../chat/completions/models → 404)。先剥掉再拼。 const stem = splitEndpoint(baseUrl, "/chat/completions").baseUrl; return buildChatUrl(stem, modelsPath || "/models"); } function buildAuthHeaders(provider, apiKey) { const h = { "Content-Type": "application/json" }; if (!apiKey) return h; if (provider && provider.authStyle === "x-api-key") { h["x-api-key"] = apiKey; if (provider.extraHeaders) Object.assign(h, provider.extraHeaders); } else if (provider && provider.authStyle === "query") { // key 由调用方拼到 query,此处不加请求头 } else { h["Authorization"] = "Bearer " + apiKey; } return h; } // 图片加载器:下载超星图床图片并转 base64(带 Referer,否则 403) const LLM_IMG_LOADER = createImageLoader(_GM_xmlhttpRequest, () => { try { return (typeof _unsafeWindow !== "undefined" && _unsafeWindow && _unsafeWindow.top && _unsafeWindow.top.location && _unsafeWindow.top.location.href) || ""; } catch (e) { return ""; } }); // 统一入口:body 构造完成后按 provider.cacheMode 附加缓存参数;cacheCtx 缺省则不附加 function LLM_APPLY_CACHE(body, provider, cacheCtx) { if (!cacheCtx) return body; try { return applyCacheParams(body, provider, cacheCtx); } catch (e) { return body; } } function buildChatBody(provider, opts, cacheCtx) { const style = (provider && provider.apiStyle) || "openai"; const maxTokens = opts.maxTokens || 1000; if (style === "anthropic") { const _imgs = Array.isArray(opts.images) ? opts.images : []; const _content = _imgs.length ? [{ type: "text", text: opts.user }].concat(_imgs.map(u => { const sp = splitDataUrl(u); return sp ? { type: "image", source: { type: "base64", media_type: sp.mediaType, data: sp.data } } : null; }).filter(Boolean)) : opts.user; const ab = { model: opts.model, max_tokens: maxTokens, messages: [{ role: "user", content: _content }] }; if (opts.system) ab.system = opts.system; if (opts.temperature != null) ab.temperature = opts.temperature; // 缓存断点由 applyCacheParams 统一处理(system 块上标 cache_control) return LLM_APPLY_CACHE(ab, provider, cacheCtx); } const messages = []; if (opts.system) messages.push({ role: "system", content: opts.system }); const _imgs2 = Array.isArray(opts.images) ? opts.images : []; messages.push({ role: "user", content: _imgs2.length ? [{ type: "text", text: opts.user }].concat(_imgs2.map(u => ({ type: "image_url", image_url: { url: u } }))) : opts.user }); const body = { model: opts.model, messages }; // CX_AUDIT_LLM_V1:OpenAI 的 o1/o3/o4/gpt-5 系列只接受 max_completion_tokens, // 发 max_tokens 会被 400 拒绝(Unsupported parameter)。 const _useMaxCompletion = provider && provider.id === "openai" && /^(o1|o3|o4|gpt-5)/i.test(String(opts.model || "")); body[_useMaxCompletion ? "max_completion_tokens" : "max_tokens"] = maxTokens; if (opts.temperature != null && !_useMaxCompletion) body.temperature = opts.temperature; return LLM_APPLY_CACHE(body, provider, cacheCtx); } function extractText(data) { if (!data) return ""; let text = ""; if (data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content) { text = data.choices[0].message.content; } else if (Array.isArray(data.content)) { const t = data.content.find(c => c && c.type === "text" && c.text); if (t) text = t.text; } else if (data.content && data.content[0] && data.content[0].text) { text = data.content[0].text; } return typeof text === "string" ? text.trim() : ""; } function parseModelList(json) { const arr = json && Array.isArray(json.data) ? json.data : (Array.isArray(json) ? json : []); return arr.map(m => m && (m.id || m.name)).filter(Boolean); } function getProviderById(id, baseUrl) { const byId = PROVIDER_CATALOG.find(p => p.id === id); if (byId) return byId; const b = normalizeBaseUrl(baseUrl); const stem = splitEndpoint(b, "/chat/completions").baseUrl; return PROVIDER_CATALOG.find(p => stem && normalizeBaseUrl(p.baseUrl) === stem) || PROVIDER_CATALOG.find(p => p.id === "custom"); } function isWellFormedUrl(u) { if (!u) return false; let parsed; try { parsed = new URL(u); } catch (e) { return false; } if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false; const host = parsed.hostname; if (/^(localhost|127\.0\.0\.1|\[::1\])$/i.test(host)) return true; return host.indexOf(".") !== -1; } function filterChatModels(ids) { const bad = /(embed|bge-|whisper|tts|speech|dall-|moderation|rerank|stable-diffusion|clip)/i; const ok = ids.filter(id => !bad.test(id)); return ok.length ? ok : ids; } function classifyProbe(status) { const s = Number(status) || 0; if (s === 0) return { code: "unreachable", label: "网络不可达(DNS、超时或被拦截,不一定是 URL 错误)" }; if (s === 200 || s === 204) return { code: "ok", label: "端点有效" }; if (s === 401) return { code: "auth", label: "URL 有效 · API Key 无效或未填写" }; if (s === 403) return { code: "forbidden", label: "端点存在但被拒绝(鉴权方式、地区或风控拦截)" }; if (s === 404 || s === 405 || s === 410) return { code: "not-found", label: "路径不存在,请检查 Base URL 是否缺/多了 /v1" }; if (s === 429) return { code: "rate-limited", label: "端点存在,但被限流" }; if (s >= 500) return { code: "server", label: "服务端错误(HTTP " + s + "),端点可达" }; return { code: "other", label: "HTTP " + s }; } // 探测端点并尝试获取模型列表:先不带 key,仅在 401/403 且 host 与预设一致时才带 key 二次探测 function probeModels(baseUrl, chatPath, modelsPath, provider, apiKey, sender) { const t0 = Date.now(); const modelsUrl = buildModelsUrl(baseUrl, modelsPath); const done = (state, status, label, models, usedKey) => ({ state, status, label, models: models || [], usedKey: !!usedKey, url: modelsUrl, elapsedMs: Date.now() - t0 }); if (!isWellFormedUrl(modelsUrl)) return Promise.resolve(done("invalid", 0, "Base URL 格式不合法", [], false)); const send = (withKey) => new Promise(resolve => { sender({ method: "GET", url: modelsUrl, headers: buildAuthHeaders(provider, withKey ? apiKey : ""), timeout: withKey ? 12000 : 9000, onload: (r) => { let json = null; try { json = JSON.parse(r.responseText); } catch (e) { json = null; } resolve({ status: r.status, json }); }, onerror: () => resolve({ status: 0, json: null }), ontimeout: () => resolve({ status: 0, json: null }) }); }); return send(false).then(r1 => { const c1 = classifyProbe(r1.status); if (c1.code === "ok") { const m1 = filterChatModels(parseModelList(r1.json)); return done("ok", 200, m1.length ? ("有效 · " + m1.length + " 个模型") : "可达 · 未返回模型列表", m1, false); } let sameHost = true; if (provider && provider.id !== "custom" && provider.baseUrl) { try { sameHost = new URL(modelsUrl).hostname === new URL(provider.baseUrl).hostname; } catch (e) { sameHost = false; } } if (!apiKey || !provider || !sameHost || (c1.code !== "auth" && c1.code !== "forbidden")) { return done(c1.code, r1.status, c1.label, [], false); } return send(true).then(r2 => { const c2 = classifyProbe(r2.status); if (c2.code === "ok") { const m2 = filterChatModels(parseModelList(r2.json)); return done("ok", 200, m2.length ? ("有效 · " + m2.length + " 个模型") : "可达 · 未返回模型列表", m2, true); } return done(c2.code, r2.status, c2.label, [], true); }); }); } /* ===== LLM Provider Kit v1 end ===== */ /* ===== LLM Cache Kit v1(prompt cache 参数与命中观测,独立可摘出) ===== */ // 各家最小可缓存前缀(token):Anthropic 512、OpenAI(GPT-5.6+) 1024、DeepSeek 自动分块 // 低于阈值时加参数也不会产生 cache 条目,这里只负责"把参数发对",不负责扩写 prompt。 const LLM_CACHE_MODES = { // key → 请求体加 prompt_cache_key(稳定值,影响路由) // breakpoint → anthropic 原生,system 块上标 cache_control:ephemeral // none → 不发任何缓存参数(自动缓存的供应商,或未知兼容网关) none: "none", key: "key", breakpoint: "breakpoint" }; // 稳定会话键:同一供应商 + 同一模型下恒定,跨题/跨页面复用。 // 用随机 UUID 或时间戳会让每次请求的键都不同,反而破坏前缀匹配,故不用。 function llmCacheKey(config, provider) { const pid = String((provider && provider.id) || (config && config.llmProvider) || "custom"); const model = String((config && config.llmModel) || ""); const raw = "cx-ask-" + pid + (model ? "-" + model : ""); // 去掉可能破坏键值的字符,并限制长度 return raw.replace(/[^A-Za-z0-9._:-]/g, "-").slice(0, 64); } // 从响应 data 里抽缓存命中量;取不到时返回 null(多数兼容网关不返回 usage) function parseUsage(data, provider) { if (!data || typeof data !== "object") return null; const u = data.usage; if (!u || typeof u !== "object") return null; // Anthropic:cache_read_input_tokens / cache_creation_input_tokens if (typeof u.cache_read_input_tokens === "number" || typeof u.cache_creation_input_tokens === "number") { const hit = Number(u.cache_read_input_tokens) || 0; const created = Number(u.cache_creation_input_tokens) || 0; const input = Number(u.input_tokens) || 0; const total = hit + created + input; return { hit, total, mode: "breakpoint", provider: (provider && provider.id) || "anthropic" }; } // DeepSeek:prompt_cache_hit_tokens / prompt_cache_miss_tokens if (typeof u.prompt_cache_hit_tokens === "number" || typeof u.prompt_cache_miss_tokens === "number") { const hit = Number(u.prompt_cache_hit_tokens) || 0; const miss = Number(u.prompt_cache_miss_tokens) || 0; return { hit, total: hit + miss, mode: "auto", provider: (provider && provider.id) || "deepseek" }; } // OpenAI / Kimi:prompt_tokens_details.cached_tokens const details = u.prompt_tokens_details; if (details && typeof details === "object" && typeof details.cached_tokens === "number") { const hit = Number(details.cached_tokens) || 0; const total = Number(u.prompt_tokens) || hit; return { hit, total, mode: "key", provider: (provider && provider.id) || "openai" }; } // 有 usage 但没有缓存字段:仍给出 total,hit 记 0(说明这家不返回缓存信息) if (typeof u.prompt_tokens === "number") { return { hit: 0, total: Number(u.prompt_tokens) || 0, mode: "unknown", provider: (provider && provider.id) || "" }; } return null; } // 累计统计(模块作用域,跨题累积;面板日志按需读取) function createLlmCacheStats() { const s = { requests: 0, withUsage: 0, hit: 0, total: 0 }; return { record(parsed) { s.requests++; if (!parsed) return null; s.withUsage++; s.hit += parsed.hit || 0; s.total += parsed.total || 0; return { hit: parsed.hit || 0, total: parsed.total || 0, pct: parsed.total ? Math.round((parsed.hit / parsed.total) * 100) : 0, cumulative: { hit: s.hit, total: s.total, pct: s.total ? Math.round((s.hit / s.total) * 100) : 0 } }; }, snapshot() { return { ...s }; } }; } // 给 chat body 加缓存参数(就地返回新对象,不改原 body) // provider.cacheMode 决定形态:key → prompt_cache_key;breakpoint → system 块数组;none → 原样返回 function applyCacheParams(body, provider, config) { if (!body || typeof body !== "object") return body; const mode = (provider && provider.cacheMode) || LLM_CACHE_MODES.none; if (mode === LLM_CACHE_MODES.none) return body; const out = Object.assign({}, body); if (mode === LLM_CACHE_MODES.key) { out.prompt_cache_key = llmCacheKey(config, provider); return out; } if (mode === LLM_CACHE_MODES.breakpoint) { // anthropic 原生:system 从字符串改成带 cache_control 的块数组,文本内容逐字不变 if (typeof out.system === "string" && out.system) { out.system = [{ type: "text", text: out.system, cache_control: { type: "ephemeral" } }]; } else if (Array.isArray(out.system) && out.system.length) { const blocks = out.system.map((b, i) => (i === out.system.length - 1 && b && typeof b === "object" && !b.cache_control) ? Object.assign({}, b, { cache_control: { type: "ephemeral" } }) : b); out.system = blocks; } return out; } return body; } /* ===== LLM Cache Kit v1 end ===== */ /* ===== LLM Vision Kit v1(图片抽取 / 下载转 base64 / 白名单判定,独立可摘出) ===== */ // 目的:题目里的 目前只是以 HTML 文本进入 prompt,模型"看不见"图。 // 这里把图片真正下载成 data URL,按各家多模态格式发给 LLM;不支持视觉的供应商直接跳过。 const IMG_UNSUPPORTED_MSG = "图片内容无法解析,无法确定具体题目,无法给出准确答案"; // 上限:多图题罕见,且每张图都会显著增加 token 与耗时 const IMG_MAX_COUNT = 3; // 单图体积上限:base64 后约膨胀 33%,多数 API 单图限制在几 MB 内 const IMG_MAX_BYTES = 1500000; const IMG_TIMEOUT_MS = 8000; const IMG_CACHE_MAX = 20; // 从 HTML 片段里提取图片地址;跳过 data:(已经是内联 base64,无需下载) function extractImageUrls(html, baseHref) { if (!html || typeof html !== "string") return []; const out = []; const re = /]*\bsrc\s*=\s*["']([^"']+)["']/gi; let m; while ((m = re.exec(html)) !== null) { let src = (m[1] || "").trim(); if (!src) continue; // data: 已经是 base64,直接可用,但这里只收集"需要下载"的 if (/^data:/i.test(src)) { out.push({ dataUrl: src, fromHtml: true }); continue; } // 相对路径补全 if (!/^https?:/i.test(src)) { try { src = new URL(src, baseHref || (typeof location !== "undefined" ? location.href : "")).href; } catch (e) { continue; } } if (!/^https?:/i.test(src)) continue; out.push({ url: src, fromHtml: true }); } return out; } // 从图片地址或 data URL 推断 MIME function imageMediaType(src) { const s = String(src || ""); const m = s.match(/^data:(image\/[a-z0-9.+-]+);base64/i); if (m) return m[1].toLowerCase(); const m2 = s.match(/\.([a-z0-9]+)(?:[?#]|$)/i); if (m2) { const ext = m2[1].toLowerCase(); if (ext === "jpg" || ext === "jpeg") return "image/jpeg"; if (ext === "png") return "image/png"; if (ext === "gif") return "image/gif"; if (ext === "webp") return "image/webp"; if (ext === "bmp") return "image/bmp"; } return "image/png"; } // 用文件头魔数判断响应体到底是不是图片(HTTP 200 也可能是错误页) function imgLooksLikeImage(body) { try { const a = new Uint8Array(body); if (!a || a.length < 12) return false; const h = (i) => a[i]; if (h(0) === 0x89 && h(1) === 0x50 && h(2) === 0x4e && h(3) === 0x47) return true; // PNG if (h(0) === 0xff && h(1) === 0xd8 && h(2) === 0xff) return true; // JPEG if (h(0) === 0x47 && h(1) === 0x49 && h(2) === 0x46) return true; // GIF if (h(0) === 0x42 && h(1) === 0x4d) return true; // BMP if (h(0) === 0x52 && h(1) === 0x49 && h(2) === 0x46 && h(3) === 0x46 && h(8) === 0x57 && h(9) === 0x45 && h(10) === 0x42 && h(11) === 0x50) return true; // WEBP return false; } catch (e) { return false; } } // 从响应头取 image/* 的 MIME;取不到返回空串,由调用方回退到后缀推断 function imgContentType(headers) { try { const m = String(headers || "").match(/content-type\s*:\s*(image\/[a-z0-9.+-]+)/i); return m ? m[1].toLowerCase() : ""; } catch (e) { return ""; } } function bytesToBase64(bytes) { const arr = new Uint8Array(bytes); const chunks = []; const CHUNK = 0x8000; // 避免超长 btoa 参数导致栈溢出 for (let i = 0; i < arr.length; i += CHUNK) { chunks.push(String.fromCharCode.apply(null, arr.subarray(i, i + CHUNK))); } return btoa(chunks.join("")); } // 把 data URL 拆成 anthropic 需要的 { media_type, data } function splitDataUrl(dataUrl) { const s = String(dataUrl || ""); const m = s.match(/^data:(image\/[a-z0-9.+-]+);base64,([\s\S]+)$/i); if (!m) return null; return { mediaType: m[1].toLowerCase(), data: m[2] }; } /** * 图片加载器:下载 → data URL,带缓存与体积上限 * @param xhr GM_xmlhttpRequest 实现 * @param getReferer 取当前页面 URL 的函数(超星图床需要 Referer,否则 403) */ function createImageLoader(xhr, getReferer) { const cache = new Map(); // url -> dataUrl | null function remember(key, val) { if (cache.size >= IMG_CACHE_MAX) cache.clear(); cache.set(key, val); } function downloadOne(url) { return new Promise((resolve) => { let settled = false; const done = (v) => { if (!settled) { settled = true; resolve(v); } }; try { xhr({ method: "GET", url, responseType: "arraybuffer", timeout: IMG_TIMEOUT_MS, headers: { // 不带 Referer 时超星图床常返回 403 "Referer": (getReferer && getReferer()) || "", "Accept": "image/avif,image/webp,image/png,image/*,*/*;q=0.8" }, onload: (res) => { try { if (!(res && res.status >= 200 && res.status < 300)) { done(null); return; } const body = res.response; if (!body) { done(null); return; } const size = body.byteLength || body.length || 0; if (size > IMG_MAX_BYTES) { done(null); return; } // CX_AUDIT_LLM_V1:200 不代表是图片。空 body 会得到 "data:image/png;base64,", // 防盗链/登录页 HTML 会被当成 png 发出去。用魔数兜住。 if (!imgLooksLikeImage(body)) { done(null); return; } const _hdrType = imgContentType(res.responseHeaders); done("data:" + (_hdrType || imageMediaType(url)) + ";base64," + bytesToBase64(body)); } catch (e) { done(null); } }, ontimeout: () => done(null), onerror: () => done(null), onabort: () => done(null) }); } catch (e) { done(null); } }); } return { /** * 把 HTML 里的图片下载成 data URL 数组 * @returns {Promise<{ dataUrls: string[], total: number, failed: number }>} */ async loadFromHtml(html, baseHref) { const items = extractImageUrls(html, baseHref); const total = items.length; if (!total) return { dataUrls: [], total: 0, failed: 0 }; const picked = items.slice(0, IMG_MAX_COUNT); const out = []; let failed = 0; for (const it of picked) { if (it.dataUrl) { out.push(it.dataUrl); continue; } if (cache.has(it.url)) { const hit = cache.get(it.url); if (hit) out.push(hit); else failed++; continue; } const dataUrl = await downloadOne(it.url); // CX_AUDIT_LLM_V1:失败结果不写缓存。原来把 null 也缓存 20 条, // 一次瞬时 403(Referer 不对)会让同一 URL 在后续页面永远退化为纯文本。 if (dataUrl) { remember(it.url, dataUrl); out.push(dataUrl); } else { failed++; } } return { dataUrls: out, total, failed: Math.max(failed, total - IMG_MAX_COUNT) }; } }; } // HTML 是否含图片 function hasImage(html) { return /]*\bsrc\s*=/i.test(String(html || "")); } /* ===== LLM Vision Kit v1 end ===== */ /* ===== LLM Busy Indicator v1(LLM 思考期间在面板上显示实时状态) ===== */ // 目的:LLM 主要服务填空题,单题可能要几十秒。原实现 task.status 只被赋值、渲染函数从不使用它, // 界面完全静止,用户以为卡死。这里用一个独立的小模块维护「忙碌态」,并驱动面板头部的状态条。 // 状态条文案:由阶段 + 已耗时组成 function llmPhaseLabel(phase) { switch (phase) { case "probe": return "LLM 直接作答中"; case "search": return "联网搜索中"; case "answer-with-info": return "LLM 结合资料作答中"; case "retry": return "LLM 重试中"; default: return "LLM 思考中"; } } // 把毫秒格式化成「12.3 秒」/「1 分 05 秒」 function llmElapsedText(ms) { const clamped = Math.max(0, ms || 0); const total = Math.floor(clamped / 1000); if (total < 60) { const tenth = Math.floor((clamped % 1000) / 100); return total + "." + tenth + " 秒"; } const m = Math.floor(total / 60); const sec = total % 60; return m + " 分 " + (sec < 10 ? "0" + sec : sec) + " 秒"; } /** * 忙碌态控制器 * - begin(phase, tip):开始一个阶段,记录起始时间,启动心跳(每 900ms 递增 tick 触发重渲染) * - setPhase(phase, tip):切换阶段(例如 probe → search),计时继续累加 * - end():结束,清掉定时器 * - snapshot():供渲染读取的不可变快照 */ function createLlmBusyTracker(opts) { opts = opts || {}; const tickMs = opts.tickMs || 900; const state = { active: false, phase: "", tip: "", startedAt: 0, wrongSince: 0, // 超时提醒:超过 softLimitMs 后提示可能较慢 questionIndex: -1, questionTotal: 0 }; let timer = null; const notify = opts.onChange || (() => { }); function stopTimer() { if (timer) { clearInterval(timer); timer = null; } } function startTimer() { stopTimer(); timer = setInterval(() => { if (state.active) notify(); }, tickMs); } return { begin(phase, tip, meta) { state.active = true; state.phase = phase || "thinking"; state.tip = tip || ""; state.startedAt = Date.now(); state.wrongSince = 0; if (meta) { if (meta.index != null) state.questionIndex = meta.index; if (meta.total != null) state.questionTotal = meta.total; } startTimer(); notify(); }, setPhase(phase, tip, meta) { if (!state.active) { this.begin(phase, tip, meta); return; } state.phase = phase || state.phase; if (tip != null) state.tip = tip; if (meta) { if (meta.index != null) state.questionIndex = meta.index; if (meta.total != null) state.questionTotal = meta.total; } notify(); }, end() { state.active = false; state.phase = ""; state.tip = ""; state.startedAt = 0; stopTimer(); notify(); }, snapshot() { if (!state.active) return { active: false, label: "", elapsed: "", tip: "", slow: false, questionText: "" }; const ms = Date.now() - state.startedAt; const slow = ms >= (opts.softLimitMs || 20000); const qt = state.questionIndex >= 0 ? ("第 " + (state.questionIndex + 1) + (state.questionTotal ? "/" + state.questionTotal : "") + " 题") : ""; return { active: true, label: llmPhaseLabel(state.phase), elapsed: llmElapsedText(ms), tip: state.tip || "", slow, questionText: qt, phase: state.phase }; } }; } /* ===== LLM Busy Indicator v1 end ===== */ /* ===== Tiku Bank Kit v1(多题库模块,独立可摘出;适配器语义对齐 tikuAdapter) ===== */ // 用法:const kit = createTikuBankKit({ xhr, log, getReferer }); const TIKU_BASE_KEY = "34cab29ef956d78afd"; // 不挂科解密固定前缀(tikuAdapter internal/search/buguake.go:80) const TIKU_PLACEHOLDER = ["付费题库", "暂无答案", "略"]; // 题库目录:enabled=true 的条目参与调用;数组顺序即顺序模式的调用顺序 // tokenUrl = 密钥获取页(点「获取密钥」跳转);无密钥需求的题库不填 const DEFAULT_TIKU_BANKS = [ { id: "icodef", label: "icodef题库", paid: false, needToken: false, enabled: true, token: "", timeout: 8, tokenUrl: "https://q.icodef.com/", tokenNote: "官网注册后可获取密钥" }, { id: "buguake", label: "不挂科(百度)", paid: false, needToken: false, enabled: true, token: "", timeout: 8 }, { id: "wanneng", label: "万能题库", paid: true, needToken: false, enabled: false, token: "", timeout: 8, tokenUrl: "https://lyck6.cn/pay", tokenNote: "购买 10 位密钥" }, { id: "aidian", label: "爱点题库", paid: true, needToken: false, enabled: false, token: "", timeout: 8, tokenUrl: "https://www.51aidian.com", tokenNote: "购买 YToken" }, { id: "tikuhai", label: "题库海", paid: true, needToken: true, enabled: false, token: "", timeout: 8, tokenUrl: "https://shop.tikuhai.com/links/2C63E8E8", tokenNote: "购买卡密" }, { id: "enncy", label: "言溪enncy", paid: true, needToken: true, enabled: false, token: "", timeout: 8, tokenUrl: "https://tk.enncy.cn", tokenNote: "注册后获取密钥" }, { id: "lemon", label: "柠檬题库", paid: true, needToken: true, enabled: false, token: "", timeout: 8, tokenUrl: "https://www.lemtk.xyz", tokenNote: "注册后获取密钥" }, { id: "adapter", label: "自建tikuAdapter", paid: false, needToken: false, enabled: false, url: "http://localhost:8060/adapter-service/search", use: "", timeout: 12, tokenUrl: "https://github.com/itihey/tikuAdapter", tokenNote: "部署文档" }, { id: "custom", label: "自定义接口", paid: false, needToken: false, enabled: false, url: "", method: "POST", headers: [], body: '{"question":"${question}"}', answerPath: "", timeout: 8 } ]; const tikuClone = (o) => JSON.parse(JSON.stringify(o)); const tikuDefaultBanks = () => tikuClone(DEFAULT_TIKU_BANKS); // 旧配置归一:按 id 合并补齐字段、保留用户顺序、保留用户自建条目、补齐目录中缺省项 function normalizeTikuBanks(saved) { const defaults = {}; for (const b of DEFAULT_TIKU_BANKS) defaults[b.id] = b; if (!Array.isArray(saved) || !saved.length) return tikuDefaultBanks(); const out = [], seen = {}; for (const raw of saved) { if (!raw || typeof raw !== "object") continue; const base = defaults[raw.id]; if (!base) { if (raw.url) { // 未知 id 但有 url:视为用户自建,按 custom 处理 // CX_AUDIT_TIKU_V1:必须写 seen,否则末尾补默认项时又插一条空的 custom,列表里出现两条 if (!seen.custom) { out.push(Object.assign(tikuClone(defaults.custom), raw, { id: "custom", label: raw.label || "自定义接口" })); seen.custom = 1; } } continue; // 已下线的 id 直接丢弃 } // id/label/paid/needToken/tokenUrl 以目录为准,避免旧配置缺字段或用户误改 out.push(Object.assign(tikuClone(base), raw, { id: base.id, label: base.label, paid: base.paid, needToken: base.needToken, tokenUrl: base.tokenUrl || "", tokenNote: base.tokenNote || "" })); seen[base.id] = 1; } for (const b of DEFAULT_TIKU_BANKS) if (!seen[b.id]) out.push(tikuClone(b)); return out; } // ---------- 通用工具 ---------- const tikuStripTags = (s) => String(s == null ? "" : s).replace(/<[^>]+>/g, "").replace(/ /g, " ").trim(); const tikuSplitHash = (s) => String(s == null ? "" : s).split("#").map(x => x.trim()).filter(Boolean); const tikuIsPlaceholder = (s) => { const t = String(s == null ? "" : s).trim(); if (!t) return true; return TIKU_PLACEHOLDER.some(w => t.indexOf(w) >= 0); }; // 脚本题型(0..9) → tikuAdapter 题型(0单选 1多选 2填空 3判断 4问答) function tikuTypeOf(type) { const t = Number(type); if (t === 0 || t === 1 || t === 2 || t === 3) return t; if (isNaN(t)) return 0; return 4; } // 与脚本内 _strSim 同公式的编辑距离相似度(模块自带,不依赖 getAnswerByLLM 的局部变量) function tikuSimilarity(a, b) { if (!a && !b) return 1; if (!a || !b) return 0; a = String(a).toLowerCase().trim(); b = String(b).toLowerCase().trim(); if (a === b) return 1; const la = a.length, lb = b.length; if (!la || !lb) return 0; let prev = [], curr = []; for (let j = 0; j <= lb; j++) prev[j] = j; for (let i = 1; i <= la; i++) { curr[0] = i; for (let j = 1; j <= lb; j++) curr[j] = a[i - 1] === b[j - 1] ? prev[j - 1] : 1 + Math.min(prev[j], curr[j - 1], prev[j - 1]); const t = prev; prev = curr; curr = t; } return 1 - prev[lb] / Math.max(la, lb); } // ---------- 不挂科解密(buguake.go:79-110 等价实现) ---------- function tikuBuguakeDecrypt(t, r) { if (!t) return ""; const key = TIKU_BASE_KEY + String(r || ""); let bytes; try { bytes = atob(String(t)); } catch (e) { return ""; } const i = []; for (let c = 0; c < bytes.length; c++) i[c] = bytes.charCodeAt(c) ^ key.charCodeAt(c % key.length); let l = ""; for (let p = 0; p < i.length - 1; p += 2) l += String.fromCharCode(i[p] ^ i[p + 1]); let h = l; try { h = decodeURIComponent(l); } catch (e) { } return h.split("+").join(" "); } // 路径取值:'a.b.0.c';'#' 表示“展开数组”只在末段生效 function tikuPickPath(obj, path) { if (!path) return null; const parts = String(path).split(".").filter(Boolean); let cur = obj; for (const p of parts) { if (cur == null) return null; if (p === "#") return Array.isArray(cur) ? cur : null; cur = /^\d+$/.test(p) ? (Array.isArray(cur) ? cur[Number(p)] : null) : cur[p]; } return cur; } // 无 answerPath 时递归探测答案字段 function tikuProbeAnswer(obj, depth) { depth = depth || 0; if (obj == null || depth > 5) return null; if (typeof obj === "string") return tikuIsPlaceholder(obj) ? null : tikuStripTags(obj); if (Array.isArray(obj)) { const arr = []; for (const x of obj) { if (typeof x === "string") { if (!tikuIsPlaceholder(x)) arr.push(tikuStripTags(x)); } else if (Array.isArray(x)) { const v = tikuProbeAnswer(x, depth + 1); if (v) arr.push.apply(arr, Array.isArray(v) ? v : [v]); } else if (x && typeof x === "object") { const v = tikuProbeAnswer(x, depth + 1); if (v) arr.push.apply(arr, Array.isArray(v) ? v : [v]); } } return arr.length ? arr : null; } if (typeof obj === "object") { for (const k of ["bestAnswer", "answerText", "answer", "answers", "data", "result"]) { if (k in obj) { const v = tikuProbeAnswer(obj[k], depth + 1); if (v) return v; } } } return null; } // 任意探测结果 → string[] function tikuToAnswerArray(v) { if (v == null) return []; if (Array.isArray(v)) { const out = []; for (const x of v) { if (typeof x === "string") { if (!tikuIsPlaceholder(x)) out.push(tikuStripTags(x)); } else if (x && typeof x === "object") out.push.apply(out, tikuToAnswerArray(x.c == null ? x : x.c)); } return out; } return tikuSplitHash(tikuStripTags(v)).filter(x => !tikuIsPlaceholder(x)); } function createTikuBankKit(deps) { deps = deps || {}; const xhr = deps.xhr || (typeof GM_xmlhttpRequest === "function" ? GM_xmlhttpRequest : null); const referer = () => (deps.getReferer ? (deps.getReferer() || "") : ""); // 单次 HTTP;registerAbort 让调度器能中止在途请求。从不抛错。 function request(opts) { const state = { settled: false, handle: null }; const p = new Promise((resolve) => { const finish = (res) => { if (!state.settled) { state.settled = true; resolve(res); } }; state.abort = () => { try { if (state.handle && typeof state.handle.abort === "function") state.handle.abort(); } catch (e) { } }; if (opts.registerAbort) opts.registerAbort(state.abort); if (!xhr) { finish({ ok: false, status: 0, text: "", json: null, error: "GM_xmlhttpRequest 不可用" }); return; } try { state.handle = xhr({ method: opts.method || "GET", url: opts.url, headers: opts.headers || {}, data: opts.data, timeout: opts.timeout || 0, onload: (res) => { const text = res && res.responseText; let json = null; if (typeof text === "string") { try { json = JSON.parse(text); } catch (e) { } } finish({ ok: !!(res && res.status >= 200 && res.status < 300), status: res && res.status, text, json, error: "" }); }, ontimeout: () => finish({ ok: false, status: 0, text: "", json: null, error: "timeout" }), onerror: () => finish({ ok: false, status: 0, text: "", json: null, error: "network" }), onabort: () => finish({ ok: false, status: 0, text: "", json: null, error: "aborted" }) }); } catch (e) { finish({ ok: false, status: 0, text: "", json: null, error: "exception: " + ((e && e.message) || e) }); } }); return p; } // ---------- 适配器:async (bank, q, ctx) => { answer: string[], note? } ---------- const adapters = { // 不挂科(百度题库):GET searchlist → 解密 bdjson → 题干相似度 ≥0.8 → 取 yes=true 选项 buguake: async (bank, q, ctx) => { const url = "https://easylearn.baidu.com/edu-web-go/bgk/searchlist?query=" + encodeURIComponent(q.question) + "&rn=10&pn=0"; const res = await request({ method: "GET", url, timeout: (bank.timeout || 8) * 1000, registerAbort: ctx.registerAbort, headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Referer": referer() || "https://easylearn.baidu.com/" } }); if (!res.ok || !res.json) throw new Error(res.error || ("HTTP " + res.status)); const list = tikuPickPath(res.json, "data.list") || []; for (const item of list) { const dec = tikuBuguakeDecrypt(item && item.bdjson, item && item.actk); if (!dec) continue; let obj; try { obj = JSON.parse(dec); } catch (e) { continue; } const stem = tikuStripTags(tikuPickPath(obj, "que_stem.0.c.0.c") || ""); if (stem && tikuSimilarity(q.question, stem) < 0.8) continue; const opts = tikuPickPath(obj, "que_options.0") || []; const arr = []; for (const o of (Array.isArray(opts) ? opts : [])) { if (o && o.yes === true) { const ret = tikuStripTags(tikuPickPath(o, "ret.0.c.0.c") || ""); if (ret) arr.push(ret); } } if (!arr.length) arr.push.apply(arr, tikuToAnswerArray(tikuPickPath(obj, "que_answer.0.c"))); if (arr.length) return { answer: arr }; } return { answer: [] }; }, // icodef:POST JSON {question};code===1 → data 按 # 切 icodef: async (bank, q, ctx) => { const ip = [0, 0, 0, 0].map(() => Math.floor(255 * Math.random())).join("."); const headers = { "Content-Type": "application/json", "X-Forwarded-For": ip, "X-Real-IP": ip }; if (bank.token) headers["Authorization"] = bank.token; const res = await request({ method: "POST", url: "https://cx.icodef.com/wyn-nb?v=4", headers, data: JSON.stringify({ question: q.question }), timeout: (bank.timeout || 8) * 1000, registerAbort: ctx.registerAbort }); if (!res.ok) throw new Error(res.error || ("HTTP " + res.status)); const data = res.json; if (!data || data.code !== 1) return { answer: [] }; const s = String(data.data || "").replace(/javascript:void\(0\);/g, "").split("\n").join("").trim(); if (/叛逆|公众号|李恒雅|一之/.test(s)) return { answer: [] }; return { answer: tikuSplitHash(s) }; }, // 万能题库:token 为 10 位才走付费端点;answers 中数字是选项下标 wanneng: async (bank, q, ctx) => { const paid = !!(bank.token && bank.token.length === 10); const url = "http://lyck6.cn/scriptService/api/" + (paid ? ("autoAnswer/" + bank.token) : "autoFreeAnswer"); const body = { qid: "", plat: 0, question: q.question, options: q.options || [], type: tikuTypeOf(q.type) }; const res = await request({ method: "POST", url, headers: { "Content-Type": "application/json", "plat": "0" }, data: JSON.stringify(body), timeout: (bank.timeout || 8) * 1000, registerAbort: ctx.registerAbort }); if (!res.ok) throw new Error((res.error || ("HTTP " + res.status)) + "(该题库仅支持 HTTP,HTTPS 页面可能被拦截)"); const data = res.json; if (!data || data.code !== 0) { if (data && data.code === 429) throw new Error("触发限流"); return { answer: [] }; } const r = data.result; if (!r || !r.success) return { answer: [] }; const arr = []; for (const v of (r.answers || [])) { if (typeof v === "number") { const o = (q.options || [])[v]; if (o) arr.push(tikuStripTags(o)); } else if (typeof v === "string" && !tikuIsPlaceholder(v)) arr.push(tikuStripTags(v)); } return { answer: arr, note: paid ? "付费端点" : "免费端点" }; }, // 题库海:code 200 取 data.answer;-1 且 msg 含“有答案”= 未授权 tikuhai: async (bank, q, ctx) => { if (!bank.token) return { answer: [], note: "未填 Token,已跳过" }; const res = await request({ method: "POST", url: "https://api.tikuhai.com/search", headers: { "Content-Type": "application/json", "User-Agent": "tikuhaiAdapter/0.1.0", "v": "0.1.0" }, data: JSON.stringify({ question: q.question, options: q.options || [], type: tikuTypeOf(q.type), key: bank.token, questionData: "" }), timeout: (bank.timeout || 8) * 1000, registerAbort: ctx.registerAbort }); if (!res.ok) throw new Error(res.error || ("HTTP " + res.status)); const data = res.json || {}; if (data.code === 200) return { answer: tikuToAnswerArray(data.data && data.data.answer) }; if (data.code === -1 && /有答案/.test(String(data.msg || ""))) throw new Error("Token 无效或额度不足"); return { answer: [] }; }, // 爱点:有 YToken 走付费 direct,否则免费 freedirect(限流);字母答案映射回选项 aidian: async (bank, q, ctx) => { const paid = !!bank.token; const url = paid ? "http://new.api.51aidian.com/publics/newapi/direct" : "http://new.api.51aidian.com/publics/newapi/freedirect"; const res = await request({ method: "POST", url, headers: { "Content-Type": "application/json" }, data: JSON.stringify({ question: q.question, token: bank.token || "" }), timeout: (bank.timeout || 8) * 1000, registerAbort: ctx.registerAbort }); if (!res.ok) throw new Error((res.error || ("HTTP " + res.status)) + "(该题库仅支持 HTTP,HTTPS 页面可能被拦截)"); const list = tikuPickPath(res.json, "qlist") || []; for (const item of list) { const opts = (item && item.options || []).map(tikuStripTags); const arr = []; for (const s of (item && item.answer || [])) { const t = tikuStripTags(s); if (/^[A-Z]+$/.test(t)) { for (const ch of t) { const o = opts[ch.charCodeAt(0) - 65]; if (o) arr.push(o); } } else if (!tikuIsPlaceholder(t)) arr.push(t); } if (arr.length) return { answer: arr, note: paid ? "付费端点" : "免费端点" }; } return { answer: [] }; }, // 言溪 enncy:GET ?token&title;token 空则不请求 enncy: async (bank, q, ctx) => { if (!bank.token) return { answer: [], note: "未填 Token,已跳过" }; const url = "https://tk.enncy.cn/query?token=" + encodeURIComponent(bank.token) + "&title=" + encodeURIComponent(q.question); const res = await request({ method: "GET", url, timeout: (bank.timeout || 8) * 1000, registerAbort: ctx.registerAbort }); if (!res.ok) throw new Error(res.error || ("HTTP " + res.status)); const data = res.json || {}; if (data.code !== 1) return { answer: [] }; return { answer: tikuSplitHash((data.data && data.data.answer) || "") }; }, // 柠檬:Bearer token;code 1000 lemon: async (bank, q, ctx) => { if (!bank.token) return { answer: [], note: "未填 Token,已跳过" }; const res = await request({ method: "POST", url: "https://api.lemtk.xyz/api/v1/mcx", headers: { "Authorization": "Bearer " + bank.token, "content-type": "application/json" }, data: JSON.stringify({ v: "1.0", question: q.question, uid: bank.uid || "703382225" }), timeout: (bank.timeout || 8) * 1000, registerAbort: ctx.registerAbort }); if (!res.ok) throw new Error(res.error || ("HTTP " + res.status)); const data = res.json || {}; if (data.code !== 1000) return { answer: [] }; return { answer: tikuSplitHash((data.data && data.data.answer) || "") }; }, // 自建 tikuAdapter:POST /adapter-service/search?use=...;取 answer.bestAnswer adapter: async (bank, q, ctx) => { if (!bank.url) return { answer: [], note: "未填服务地址,已跳过" }; let url = bank.url; if (String(bank.use || "").trim()) url += (url.indexOf("?") >= 0 ? "&" : "?") + "use=" + encodeURIComponent(String(bank.use).trim()); const res = await request({ method: "POST", url, headers: { "Content-Type": "application/json" }, data: JSON.stringify({ question: q.question, options: q.options || [], type: tikuTypeOf(q.type) }), timeout: (bank.timeout || 12) * 1000, registerAbort: ctx.registerAbort }); if (!res.ok) throw new Error((res.error || ("HTTP " + res.status)) + "(服务未启动或地址错误)"); const ans = tikuPickPath(res.json, "answer") || {}; const best = Array.isArray(ans.bestAnswer) ? ans.bestAnswer.map(tikuStripTags).filter(x => !tikuIsPlaceholder(x)) : []; return { answer: best.length ? best : tikuSplitHash(ans.answerText || "") }; }, // 自定义接口:URL 中 ${question} 需 URL 编码;JSON body 中需 JSON 转义;answerPath 为空时自动探测 custom: async (bank, q, ctx) => { if (!bank.url) return { answer: [], note: "未填 URL,已跳过" }; const method = String(bank.method || "POST").toUpperCase(); const isGet = method === "GET"; const fillUrl = (s) => String(s == null ? "" : s) .split("${question}").join(encodeURIComponent(q.question == null ? "" : String(q.question))) .split("${type}").join(encodeURIComponent(String(q.type == null ? "" : q.type))); const fillBody = (s) => { const src = String(s == null ? "" : s); const raw = q.question == null ? "" : String(q.question); // JSON 文本里用 JSON.stringify 再剥掉外层引号,避免破坏结构 const escaped = JSON.stringify(raw).slice(1, -1); const looksJson = /^\s*[{[]/.test(src); return src.split("${question}").join(looksJson ? escaped : raw).split("${type}").join(String(q.type == null ? "" : q.type)); }; const headers = {}; for (const kv of (bank.headers || [])) if (kv && kv.key) headers[kv.key] = fillBody(kv.value || ""); let url = isGet ? fillUrl(bank.url) : bank.url; // GET 时 body 视为附加的 query 串(如 'a=1&q=${question}'),非 JSON 才拼接 let data; if (isGet && bank.body && !/^\s*[{[]/.test(bank.body)) { const extra = fillBody(bank.body).trim().replace(/^[?&]+/, ""); if (extra) url += (url.indexOf("?") >= 0 ? "&" : "?") + extra; } if (!isGet) { data = fillBody(bank.body || '{"question":"${question}"}'); if (!Object.keys(headers).some(k => k.toLowerCase() === "content-type")) headers["Content-Type"] = "application/json"; } const res = await request({ method, url, headers, data, timeout: (bank.timeout || 8) * 1000, registerAbort: ctx.registerAbort }); if (!res.ok) throw new Error(res.error || ("HTTP " + res.status)); const picked = bank.answerPath ? tikuPickPath(res.json, bank.answerPath) : tikuProbeAnswer(res.json, 0); return { answer: tikuToAnswerArray(picked) }; } }; // ---------- 单题库调用:统一返回 {bankId, form, answer, status, ms, note, error} ---------- // status ∈ hit | empty | error | timeout | cancelled | skipped async function runOne(bank, q, isUsable, registerAbort) { const t0 = Date.now(); const base = { bankId: bank.id, form: bank.label || bank.id, answer: [], status: "empty", ms: 0, note: "" }; const fn = adapters[bank.id]; if (!fn) return Object.assign(base, { status: "error", error: "未知题库: " + bank.id, ms: Date.now() - t0 }); try { const r = await fn(bank, q, { registerAbort: registerAbort || (() => { }) }); const arr = Array.isArray(r && r.answer) ? r.answer : []; const usable = arr.length > 0 && (!isUsable || isUsable(arr)); return Object.assign(base, { answer: arr, note: (r && r.note) || "", status: usable ? "hit" : "empty", ms: Date.now() - t0 }); } catch (e) { const msg = String((e && e.message) || e); const status = /timeout|超时/i.test(msg) ? "timeout" : "error"; return Object.assign(base, { status, error: msg, ms: Date.now() - t0 }); } } /** * 多题库调度 * @param q {question, options?, type?} * @param opt {mode:"parallel"|"sequential", banks, isUsable, onResult} */ async function ask(q, opt) { opt = opt || {}; const banks = (opt.banks || []).filter(b => b && b.enabled); const isUsable = opt.isUsable || null; if (!banks.length) return []; if (opt.mode === "sequential") { const out = []; let stopped = false; for (const b of banks) { if (stopped) { const r = { bankId: b.id, form: b.label || b.id, answer: [], status: "skipped", ms: 0, note: "" }; out.push(r); if (opt.onResult) opt.onResult(r); continue; } const r = await runOne(b, q, isUsable); out.push(r); if (opt.onResult) opt.onResult(r); if (r.status === "hit") stopped = true; // 首个命中即停 } return out; } // 并行:首个命中即中止其余在途请求;无 abort 能力时用 settled 标志保证语义正确 return new Promise((resolve) => { const n = banks.length; const results = new Array(n); const aborts = new Array(n).fill(null); let done = 0, winner = -1, finished = false; const finalize = () => { if (finished) return; finished = true; for (let i = 0; i < n; i++) { if (results[i]) continue; if (aborts[i]) { try { aborts[i](); } catch (e) { } } results[i] = { bankId: banks[i].id, form: banks[i].label || banks[i].id, answer: [], status: "cancelled", ms: 0, note: "" }; } if (winner >= 0) { const w = results.splice(winner, 1)[0]; results.unshift(w); } resolve(results); }; banks.forEach((b, i) => { Promise.resolve() .then(() => runOne(b, q, isUsable, (fn) => { aborts[i] = fn; })) .then((r) => { if (finished) return; // 已被 winner 中止,丢弃迟到结果 results[i] = r; done++; if (opt.onResult) opt.onResult(r); if (r.status === "hit" && winner < 0) { winner = i; finalize(); return; } if (done === n) finalize(); }) .catch((e) => { if (finished) return; results[i] = { bankId: b.id, form: b.label || b.id, answer: [], status: "error", ms: 0, note: "", error: String((e && e.message) || e) }; done++; if (done === n) finalize(); }); }); }); } // UI「测试」按钮:单题库直跑,不做命中判定 async function testOne(bank, q) { return runOne(bank, q, null); } return { DEFAULT_TIKU_BANKS, tikuDefaultBanks, normalizeTikuBanks, ask, testOne, helpers: { tikuStripTags, tikuSplitHash, tikuIsPlaceholder, tikuTypeOf, tikuSimilarity, tikuBuguakeDecrypt, tikuPickPath, tikuProbeAnswer, tikuToAnswerArray } }; } /* ===== Tiku Bank Kit v1 end ===== */ const TIKU_KIT = createTikuBankKit({ xhr: _GM_xmlhttpRequest, getReferer: () => { try { return (typeof _unsafeWindow !== "undefined" && _unsafeWindow && _unsafeWindow.location && _unsafeWindow.location.href) || ""; } catch (e) { return ""; } } }); /* ===== Tiku Bank List 样式(独立注入,不改动主样式单行) ===== */ const TIKU_BANK_CSS = ` .cx-bank-list{display:flex;flex-direction:column;gap:14px} .cx-bank-testbar{display:flex;align-items:center;gap:10px;padding:10px 12px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;flex-wrap:wrap} .cx-bank-testlabel{font-size:12px;font-weight:600;color:#475569;white-space:nowrap} .cx-bank-testbar .el-input{flex:1 1 240px;min-width:180px} .cx-bank-tip{font-size:11px;color:#94a3b8;flex:1 1 100%} .cx-bank-list-rows{display:flex;flex-direction:column;gap:12px} .cx-bank-row{display:block;padding:12px 14px;border:1px solid #e2e8f0;border-radius:10px;background:#fff} .cx-bank-row-off{opacity:.6;background:#f8fafc} .cx-bank-row-off .cx-bank-id{color:#94a3b8} .cx-bank-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap} .cx-bank-head .cx-bank-id{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .cx-bank-order{display:flex;flex-direction:row;gap:2px;flex-shrink:0} .cx-bank-order .el-button{width:24px;height:22px;min-height:22px;padding:0;font-size:13px;line-height:1} .cx-bank-head .el-switch{flex-shrink:0} .cx-bank-name{font-size:13px;font-weight:600;color:#0f172a;white-space:nowrap} .cx-bank-id{font-size:11px;color:#94a3b8;font-family:ui-monospace,monospace} .cx-bank-actions{display:flex;align-items:center;gap:8px;flex:0 0 auto} .cx-bank-actions .el-button{height:24px;padding:0 8px;font-size:12px;margin-left:0} .cx-bank-hint{font-size:11px;color:#475569;word-break:break-word;margin-top:8px;padding:6px 10px;background:#f8fafc;border-radius:6px} .cx-bank-field{display:flex;align-items:center;gap:10px;margin-top:10px} .cx-bank-field-col{flex-direction:column;align-items:stretch;gap:4px} .cx-bank-fieldlabel{font-size:12px;color:#64748b;white-space:nowrap;flex:0 0 56px;text-align:right} .cx-bank-field .el-input,.cx-bank-field .el-select{flex:1 1 auto;min-width:0} .cx-bank-getkey{font-size:12px;color:#4f46e5;white-space:nowrap;text-decoration:none;flex-shrink:0;padding:0 2px} .cx-bank-getkey:hover{color:#6366f1;text-decoration:underline} .cx-bank-empty{padding:20px;text-align:center;font-size:12px;color:#94a3b8} @media (max-width:640px){ .cx-bank-actions{margin-left:0;flex:1 1 100%} .cx-bank-fieldlabel{flex:0 0 44px} } `; /* ===== Tiku Bank List 样式 end ===== */ /* ===== CX_FIX4:题库行布局收紧,消除右侧大片空白 ===== */ const TIKU_BANK_FIX4_CSS = ` /* 名称与标签占满中间,操作区紧跟其后,不再被推到行尾 */ .cx-bank-head{ display:flex; align-items:center; gap:10px; flex-wrap:wrap; } .cx-bank-actions{ margin-left:8px; flex:0 0 auto; } /* CX_AUDIT_UI_V1:markup 里并没有 .cx-bank-main,原来那条宽度约束是空转的。 让 id 标签吃掉剩余空间,操作区自然贴住右侧内容,不再留大片空白。 */ .cx-bank-head .cx-bank-id{ flex:1 1 auto; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } /* 整行不再预留多余空白 */ .cx-bank-row{ display:block; padding:12px 14px; } /* 密钥行与名称行左对齐,宽度跟随主区 */ .cx-bank-field{ max-width:100%; } `; /* ===== CX_FIX4 样式 end ===== */ /* ===== CX_PANEL_TABS_V1:单列切换运行框 / 运行日志 ===== */ const CX_PANEL_TABS_CSS = ` /* 顶部切换条 */ .cx-ask-tabbar{display:flex;gap:28px;padding:0 16px;border-bottom:1px solid #e2e8f0;flex:0 0 auto} .cx-ask-tabbar .cx-ask-tab{border:none;background:transparent;padding:10px 0 12px;font-size:14px; font-weight:500;color:#64748b;cursor:pointer;position:relative;transition:color .18s} .cx-ask-tabbar .cx-ask-tab:hover{color:#0f172a} .cx-ask-tabbar .cx-ask-tab.active{color:#4f46e5;font-weight:600} .cx-ask-tabbar .cx-ask-tab.active::after{content:'';position:absolute;left:0;right:0;bottom:-1px; height:2px;background:#4f46e5;border-radius:2px} /* 单列:内容区不再用 grid */ .cx-ask-panel .cx-panel-body{ display:block!important; padding:12px!important; } /* 两列的滚动上限沿用 */ .cx-ask-panel .cx-source-list, .cx-ask-panel .cx-log-list{ max-height:220px; overflow-y:auto; } `; /* ===== CX_PANEL_TABS_V1 end ===== */ /* ===== CX_PANEL_HEADER_V1:头部三栏,标题视觉居中 ===== */ const CX_PANEL_HEADER_CSS = ` .cx-ask-panel .cx-drag-bar{ position:relative; display:flex; align-items:center; gap:8px; padding:14px 16px; border-bottom:1px solid #f1f5f9; flex:0 0 auto; } /* 左侧状态区,不参与居中计算 */ .cx-ask-panel .cx-header-left{ display:flex; align-items:center; gap:6px; flex:0 0 auto; z-index:1; } /* 标题绝对居中,不受左右两侧宽度影响 */ .cx-ask-panel .cx-drag-title{ position:absolute; left:50%; transform:translateX(-50%); font-size:16px; font-weight:700; color:#0f172a; white-space:nowrap; pointer-events:none; } /* 左侧状态徽标:脚本在等什么,一眼能看到 */ .cx-ask-panel .cx-status-badge{ font-size:11px; padding:2px 8px; border-radius:99px; background:#fef3c7; color:#b45309; font-weight:600; max-width:220px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; } /* 关闭按钮靠右 */ .cx-ask-panel .cx-panel-close{ margin-left:auto; z-index:1; } `; /* ===== CX_PANEL_HEADER_V1 end ===== */ /* ===== CX_TAB_FIX_V1 占位提示 ===== */ const CX_TAB_FIX_CSS = ` .cx-empty-hint{padding:28px 12px;text-align:center;font-size:12px;color:#94a3b8;line-height:1.6} `; /* ===== CX_TAB_FIX_V1 end ===== */ /* ===== CX_PANEL_ALIGN_V1:任务面板对齐老版 ===== */ const TIKU_PANEL_ALIGN_CSS = ` /* 悬浮按钮:移到左侧垂直居中,渐变背景,常带文字 */ #cx-ask-fab{ position:fixed!important; left:12px!important; right:auto!important; bottom:50vh!important; top:auto!important; z-index:9999!important; width:auto!important; min-width:0!important; height:auto!important; padding:12px 18px!important; border-radius:14px!important; background:linear-gradient(135deg,#4f46e5,#6366f1)!important; color:#fff!important; border:none!important; font-size:13px!important; font-weight:500!important; letter-spacing:.3px; box-shadow:0 10px 30px -10px rgba(15,23,42,.25)!important; transition:all .2s cubic-bezier(.4,0,.2,1); cursor:pointer; } #cx-ask-fab:hover{ transform:translateY(-2px); box-shadow:0 14px 34px -10px rgba(15,23,42,.32)!important; } /* 面板:居中弹窗,固定宽高,不随内容伸缩 */ .cx-ask-panel{ position:fixed!important; /* left/top 不能加 !important:拖拽写内联 left/top,!important 会压过内联样式导致拖不动 */ left:50%; top:50%; right:auto!important; bottom:auto!important; /* 不用 transform 居中:拖拽直接改 left/top,transform 会叠加偏移导致拖不动 */ margin-left:-230px; /* 宽度 460px 的一半 */ margin-top:-230px; /* 高度 460px 的一半(视口不足时会被 height 收住) */ width:460px!important; max-width:calc(100vw - 40px); height:min(520px,calc(100vh - 120px))!important; min-height:0!important; max-height:none!important; /* display 不加 !important:显隐由内联 style 控制(× 按钮与悬浮按钮都要能切换) */ flex-direction:column; overflow:hidden!important; z-index:100000!important; background:#fff; border-radius:16px!important; box-shadow:0 24px 60px -20px rgba(15,23,42,.35)!important; } /* 头部固定,不随内容滚动 */ .cx-ask-panel .cx-drag-bar{ flex:0 0 auto; } /* 状态条固定在头部下方一行,左侧对齐 */ .cx-ask-panel .cx-llm-busy{ flex:0 0 auto; justify-content:flex-start!important; } /* 内容区:固定高度 + 内部滚动 —— 这是「加载一题就闪、大小乱跳」的根治 */ .cx-ask-panel .cx-panel-body{ flex:1 1 auto!important; min-height:0!important; overflow-y:auto!important; overflow-x:hidden; padding:12px!important; } /* 题目区给最小高度,未加载时不塌陷 */ .cx-ask-panel .cx-q-block{ min-height:76px; } /* 折叠按钮已隐藏 */ .cx-hidden{ display:none!important; } /* 拖拽后(内联 left/top 生效)清掉居中偏移,避免双重定位 */ .cx-ask-panel[style*="left:"]:not([style*="left:50%"]){ margin-left:0!important; top:auto; } `; /* ===== CX_PANEL_ALIGN_V1 end ===== */ /* ===== LLM 忙碌状态样式 ===== */ const TIKU_BUSY_CSS = ` .cx-llm-busy{display:flex;align-items:center;flex-wrap:wrap;gap:6px;padding:6px 12px;font-size:11px; font-weight:600;background:#fef3c7;color:#b45309;border-bottom:1px solid #fde68a;line-height:1.4} .cx-llm-busy.slow{background:#fee2e2;color:#b91c1c;border-bottom-color:#fecaca} .cx-llm-dot{width:7px;height:7px;border-radius:50%;background:currentColor;flex:0 0 auto;animation:cx-llm-pulse 1.1s ease-in-out infinite} @keyframes cx-llm-pulse{0%,100%{opacity:.35;transform:scale(.85)}50%{opacity:1;transform:scale(1.15)}} .cx-llm-elapsed{font-variant-numeric:tabular-nums;flex:0 0 auto} .cx-llm-label{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .cx-llm-slowtip{flex:0 0 auto;font-weight:500;opacity:.85} .cx-source-note{margin-top:6px;font-size:12px;color:#b45309;background:#fef3c7;border-radius:6px;padding:4px 8px;line-height:1.5} .cx-job-list{display:flex;flex-direction:column;gap:6px;padding:0 12px 8px} .cx-job-item{display:flex;align-items:center;gap:8px;font-size:12px;color:#475569;padding:6px 8px;background:#f8fafc;border-radius:6px} .cx-job-dot{width:7px;height:7px;border-radius:50%;flex:0 0 auto;background:#94a3b8} .cx-job-dot.success{background:#16a34a}.cx-job-dot.danger{background:#dc2626}.cx-job-dot.info{background:#0891b2} .cx-job-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .cx-job-state{flex:0 0 auto;font-size:11px;color:#94a3b8} `; /* ===== LLM 忙碌状态样式 end ===== */ /* ===== 供应商选择行样式(下拉框独占一行,链接不压缩) ===== */ const PROVIDER_ROW_CSS = ` .cx-provider-row{display:flex;flex-wrap:wrap;align-items:center;gap:8px} .cx-provider-row > .el-select{flex:1 1 100%;width:100%;min-width:0} .cx-provider-row > a{flex:0 0 auto;white-space:nowrap} `; /* ===== 供应商选择行样式 end ===== */ /* ===== Tiku Bank List UI(题库列表组件:开关 / ↑↓ 排序 / Token / 测试) ===== */ function tikuBankListComponent(vue) { return vue.defineComponent({ name: "TikuBankList", props: { modelValue: { type: Array, default: () => [] } }, emits: ["update:modelValue"], setup(props, { emit }) { // 默认测试题:带选项的单选题,便于一次看出「题库返回答案」与「选项匹配」两段是否都正常 const testQ = vue.ref("真理与谬误之间的相互关系是( )"); const testing = vue.ref({}); const hint = vue.ref({}); const expanded = vue.ref({}); // 密钥默认展开:用户反馈"找不到配置入口",折叠会让人以为没有 const collapsedToken = vue.ref({}); const list = vue.computed(() => props.modelValue || []); // 一律生成新数组再 emit,避免与 Pinia 的响应式代理纠缠 const commit = (next) => emit("update:modelValue", next); const update = (index, patch) => { const next = list.value.map((b, i) => (i === index ? Object.assign({}, b, patch) : b)); commit(next); }; const move = (index, dir) => { const to = index + dir; if (to < 0 || to >= list.value.length) return; const next = list.value.slice(); const tmp = next[index]; next[index] = next[to]; next[to] = tmp; commit(next); }; const kit = (typeof TIKU_KIT !== "undefined" && TIKU_KIT) ? TIKU_KIT : null; const runTest = async (bank, index) => { if (!kit) { hint.value[index] = "✗ 模块未就绪"; return; } testing.value[index] = true; hint.value[index] = "测试中..."; try { const q = { question: testQ.value, options: [], type: "3" }; // 打开配置页时 token 已还原为明文,这里直接使用 const r = await kit.testOne(bank, q); const tag = r.status === "hit" ? "✓ 有答案" : (r.status === "empty" ? "✗ 无答案" : "✗ " + r.status); hint.value[index] = tag + (r.note ? "(" + r.note + ")" : "") + (r.error ? ":" + r.error : "") + " · " + r.ms + "ms"; } catch (e) { hint.value[index] = "✗ " + (e && e.message); } finally { testing.value[index] = false; } }; const tagType = (b) => (b.paid ? "warning" : "success"); const tagLabel = (b) => (b.paid ? "付费" : "免费"); return () => { const Switch = vue.resolveComponent("el-switch"); const Button = vue.resolveComponent("el-button"); const Input = vue.resolveComponent("el-input"); const Tag = vue.resolveComponent("el-tag"); const nodes = []; nodes.push(vue.h("div", { class: "cx-bank-testbar" }, [ vue.h("span", { class: "cx-bank-testlabel" }, "测试题目"), vue.h(Input, { size: "small", modelValue: testQ.value, teleported: false, "onUpdate:modelValue": (v) => { testQ.value = v; } }), vue.h("span", { class: "cx-bank-tip" }, "点「测试」单独验证该题库与密钥是否可用") ])); if (!list.value.length) { nodes.push(vue.h("div", { class: "cx-bank-empty" }, "暂无题库,请刷新页面后重试")); return vue.h("div", { class: "cx-bank-list" }, nodes); } nodes.push(vue.h("div", { class: "cx-bank-list-rows" }, list.value.map((b, i) => { const isCustom = b.id === "custom"; const isAdapter = b.id === "adapter"; const canToken = !isCustom && !isAdapter; // --- 第一行:排序 + 开关 + 名称 + 标签 + 操作 --- const head = vue.h("div", { class: "cx-bank-head" }, [ vue.h("div", { class: "cx-bank-order" }, [ vue.h(Button, { size: "small", text: true, disabled: i === 0, title: "上移", onClick: () => move(i, -1) }, { default: () => "↑" }), vue.h(Button, { size: "small", text: true, disabled: i === list.value.length - 1, title: "下移", onClick: () => move(i, 1) }, { default: () => "↓" }) ]), vue.h(Switch, { size: "small", modelValue: !!b.enabled, "onUpdate:modelValue": (v) => update(i, { enabled: !!v }) }), vue.h("span", { class: "cx-bank-name" }, b.label || b.id), vue.h(Tag, { size: "small", type: tagType(b), effect: "plain" }, { default: () => tagLabel(b) }), vue.h("span", { class: "cx-bank-id" }, b.id), vue.h("div", { class: "cx-bank-actions" }, [ canToken ? vue.h(Button, { size: "small", text: true, onClick: () => { collapsedToken.value[i] = !collapsedToken.value[i]; } }, { default: () => (collapsedToken.value[i] ? "填密钥" : "收起密钥") }) : null, (isCustom || isAdapter) ? vue.h(Button, { size: "small", text: true, onClick: () => { expanded.value[i] = !expanded.value[i]; } }, { default: () => (expanded.value[i] ? "收起配置" : "展开配置") }) : null, vue.h(Button, { size: "small", type: "success", plain: true, loading: !!testing.value[i], onClick: () => runTest(b, i) }, { default: () => "测试" }) ]) ]); const body = []; if (hint.value[i]) body.push(vue.h("div", { class: "cx-bank-hint" }, hint.value[i])); // --- 密钥输入:独立整行,默认展开,不放进排序列 --- if (canToken && !collapsedToken.value[i]) { const row = [ vue.h("span", { class: "cx-bank-fieldlabel" }, b.needToken && !b.token ? "密钥*" : "密钥"), vue.h(Input, { size: "small", placeholder: tikuTokenPlaceholder(b.id), modelValue: b.token || "", showPassword: true, clearable: true, "onUpdate:modelValue": (v) => update(i, { token: v }) }) ]; // 「获取密钥」紧跟输入框:语义上它就是在解释这个框里的值从哪来 if (b.tokenUrl) { row.push(vue.h("a", { class: "cx-bank-getkey", href: b.tokenUrl, target: "_blank", rel: "noopener noreferrer", title: b.tokenNote || "打开密钥获取页面" }, "获取密钥")); } body.push(vue.h("div", { class: "cx-bank-field" }, row)); } if (isAdapter) { body.push(vue.h("div", { class: "cx-bank-field" }, [ vue.h("span", { class: "cx-bank-fieldlabel" }, "服务地址"), vue.h(Input, { size: "small", placeholder: "http://localhost:8060/adapter-service/search", modelValue: b.url || "", "onUpdate:modelValue": (v) => update(i, { url: v }) }), b.tokenUrl ? vue.h("a", { class: "cx-bank-getkey", href: b.tokenUrl, target: "_blank", rel: "noopener noreferrer", title: b.tokenNote || "" }, "部署文档") : null ])); body.push(vue.h("div", { class: "cx-bank-field" }, [ vue.h("span", { class: "cx-bank-fieldlabel" }, "use"), vue.h(Input, { size: "small", placeholder: "icodef,lemon(留空=服务端默认)", modelValue: b.use || "", "onUpdate:modelValue": (v) => update(i, { use: v }) }) ])); } if (isCustom) { body.push(vue.h("div", { class: "cx-bank-field" }, [ vue.h("span", { class: "cx-bank-fieldlabel" }, "地址"), vue.h(Input, { size: "small", placeholder: "可用 ${question} / ${type}", modelValue: b.url || "", "onUpdate:modelValue": (v) => update(i, { url: v }) }) ])); if (expanded.value[i]) { body.push(vue.h("div", { class: "cx-bank-field" }, [ vue.h("span", { class: "cx-bank-fieldlabel" }, "方法"), vue.h(vue.resolveComponent("el-select"), { size: "small", modelValue: b.method || "POST", teleported: false, "onUpdate:modelValue": (v) => update(i, { method: v }) }, { default: () => ["POST", "GET"].map(m => vue.h(vue.resolveComponent("el-option"), { key: m, label: m, value: m })) }) ])); body.push(vue.h("div", { class: "cx-bank-field cx-bank-field-col" }, [ vue.h("span", { class: "cx-bank-fieldlabel" }, "请求体"), vue.h(Input, { size: "small", type: "textarea", rows: 2, placeholder: '{"question":"${question}"}', modelValue: b.body || "", "onUpdate:modelValue": (v) => update(i, { body: v }) }) ])); body.push(vue.h("div", { class: "cx-bank-field" }, [ vue.h("span", { class: "cx-bank-fieldlabel" }, "答案路径"), vue.h(Input, { size: "small", placeholder: "data.answer(留空=自动探测)", modelValue: b.answerPath || "", "onUpdate:modelValue": (v) => update(i, { answerPath: v }) }) ])); } } return vue.h("div", { class: "cx-bank-row" + (b.enabled ? "" : " cx-bank-row-off"), key: b.id + "-" + i }, [head].concat(body)); }) )); return vue.h("div", { class: "cx-bank-list" }, nodes); }; } }); } function tikuTokenPlaceholder(id) { if (id === "wanneng") return "万能题库密钥(10 位,留空=免费端点)"; if (id === "icodef") return "icodef 密钥(可留空)"; if (id === "aidian") return "爱点 YToken(留空=免费接口)"; if (id === "tikuhai") return "题库海卡密"; if (id === "enncy") return "言溪 enncy 密钥"; if (id === "lemon") return "柠檬题库密钥"; return "密钥(可留空)"; } /* ===== Tiku Bank List UI end ===== */ (function () { const __css = TIKU_BANK_CSS + TIKU_BUSY_CSS + PROVIDER_ROW_CSS + TIKU_PANEL_ALIGN_CSS + TIKU_BANK_FIX4_CSS + CX_PANEL_TABS_CSS + CX_PANEL_HEADER_CSS + CX_TAB_FIX_CSS; if (typeof GM_addStyle === "function") { try { GM_addStyle(__css); } catch (e) { } } else if (typeof document !== "undefined" && document.head) { const st = document.createElement("style"); st.textContent = __css; document.head.append(st); } })(); const TIKU_BANK_LIST_COMPONENT = tikuBankListComponent(vue); function TIKU_BANK_STATUS_LABEL(item) { if (!item) return ""; const map = { hit: "命中", empty: "暂无", error: "失败", timeout: "超时", cancelled: "已取消", skipped: "已跳过" }; const label = map[item.status] || (item.answer ? "有答案" : "暂无"); return item.ms ? (label + " · " + item.ms + "ms") : label; } // token 与 llmApiKey 同一套混淆约定(btoa + 反转),另加 "enc:" 前缀以区分明文,避免误转 const TIKU_TOKEN_PREFIX = "enc:"; const tikuReverse = (k) => k.split("").reverse().join(""); function tikuEncryptToken(t) { if (typeof t !== "string" || !t) return ""; if (t.indexOf(TIKU_TOKEN_PREFIX) === 0) return t; // 已混淆,幂等 try { return TIKU_TOKEN_PREFIX + btoa(tikuReverse(t)); } catch (e) { return t; } } function tikuDecryptToken(t) { if (typeof t !== "string" || !t) return ""; if (t.indexOf(TIKU_TOKEN_PREFIX) !== 0) return t; // 明文,原样返回 try { return atob(t.slice(TIKU_TOKEN_PREFIX.length)).split("").reverse().join(""); } catch (e) { return ""; } } function tikuDecryptBankTokens(banks) { if (!Array.isArray(banks)) return banks; return banks.map(function (b) { return b ? Object.assign({}, b, { token: tikuDecryptToken(b.token) }) : b; }); } function tikuEncryptBankTokens(banks) { if (!Array.isArray(banks)) return banks; return banks.map(function (b) { return b ? Object.assign({}, b, { token: tikuEncryptToken(b.token) }) : b; }); } // 取运行时题库:配置里 token 是混淆值,调用题库前必须还原成明文 function tikuRuntimeBanks(banks) { return tikuDecryptBankTokens(normalizeTikuBanks(banks)); } // 迁移老配置:修正早期版本的已知错误默认值,不触碰用户自定义地址 const migrateLlmConfig = (c) => { if (!c) return c; if (/^https?:\/\/api\.openai\.com\/?$/.test(c.llmBaseUrl || "")) c.llmBaseUrl = "https://api.openai.com/v1"; const base = normalizeBaseUrl(c.llmBaseUrl || ""); if (/^https?:\/\/api\.mimo\.com(\/|$)/.test(base)) c.llmBaseUrl = base.replace("https://api.mimo.com", "https://api.xiaomimimo.com"); // 旧预设 id → 新预设 id 的别名映射(旧版用 mimo,新版统一为 xiaomimimo) if (c.llmProvider === "mimo") c.llmProvider = "xiaomimimo"; // 旧版 Anthropic 预设被错误地当作 OpenAI 兼容端点,纠正为原生协议 if (c.llmProvider === "anthropic" && /api\.anthropic\.com/.test(String(c.llmBaseUrl || ""))) { c.llmSuffix = "/messages"; } return c; }; const getConfig = () => { try { const gmConfig = _GM_getValue("config", null); if (gmConfig) { const parsed = typeof gmConfig === "string" ? JSON.parse(gmConfig) : gmConfig; if (parsed.llmApiKey) parsed.llmApiKey = decryptApiKey(parsed.llmApiKey); delete parsed.thtoken; delete parsed.yztoken; delete parsed.enncytoken; return migrateLlmConfig({ ...defaultConfig$1, ...parsed, banks: normalizeTikuBanks(parsed.banks) }); } } catch (e) { } const storage = (typeof _unsafeWindow !== 'undefined' && _unsafeWindow.top) ? _unsafeWindow.top.localStorage : localStorage; const config = storage.getItem("config"); if (config) { const parsed = JSON.parse(config); if (parsed.llmApiKey) parsed.llmApiKey = decryptApiKey(parsed.llmApiKey); delete parsed.thtoken; delete parsed.yztoken; delete parsed.enncytoken; return migrateLlmConfig({ ...defaultConfig$1, ...parsed, banks: normalizeTikuBanks(parsed.banks) }); } return { ...defaultConfig$1, banks: normalizeTikuBanks(null) }; }, defaultConfig$1 = { tikuMode: "parallel", tikuTimeout: "8", banks: tikuDefaultBanks(), debugger: false, autoAnswer: true, autoVideo: true, autoJump: true, autoSubmit: true, llmApiKey: "", llmBaseUrl: "https://tokenhub.tencentmaas.com/v1", llmModel: "", llmEnabled: false, llmTimeout: "30", llmMaxTokens: "1000", llmType: ["0", "1", "2", "3", "4", "5", "6", "7"], llmSuffix: "/chat/completions", llmProvider: "hunyuan", llmWebSearch: false, llmSearchEngine: "baidu", llmSearchMode: "smart", llmSearchTypes: ["4", "5", "6", "7"], interval: 3, answerInterval: 3, videoRate: "1", minAccuracy: 0.8, autoExam: true, hideExam: false, notice: "本脚本仅供学习交流使用,严禁用于商业用途,否则后果自负!" }, userConfig = [{ name: "quick", label: "快速配置", config: [{ name: "autoAnswer", label: "自动答题", type: "switch", value: defaultConfig$1.autoAnswer, desc: "开启后会自动答题" }, { name: "autoVideo", label: "自动视频", type: "switch", value: defaultConfig$1.autoVideo, desc: "开启后会自动观看视频" }, { name: "autoJump", label: "自动切换章节", type: "switch", value: defaultConfig$1.autoVideo, desc: "开启后会自动切换章节" }, { name: "autoSubmit", label: "自动提交答案", type: "switch", value: defaultConfig$1.autoSubmit, desc: "开启后自动提交答案" }, { name: "autoExam", label: "考试自动切换", type: "switch", value: defaultConfig$1.autoExam, desc: "开启后考试会自动切换" }, { name: "llmEnabled", label: "启用 LLM 智能答题", type: "switch", value: defaultConfig$1.llmEnabled, desc: "题库无答案时使用 AI 答题" }] }, { name: "base", label: "基础配置", config: [{ name: "interval", label: "通用间隔(秒)", type: "number", value: defaultConfig$1.interval, desc: "通用间隔,用于脚本运行切换" }, { name: "answerInterval", label: "答题间隔(秒)", type: "number", value: defaultConfig$1.answerInterval, desc: "控制答题速度" },] }, { name: "chapter", label: "章节配置", config: [{ name: "videoRate", label: "视频倍速", type: "select", value: defaultConfig$1.videoRate, desc: "视频播放速度。过高容易被平台判定异常,建议 2x", options: [{ label: "1x", value: "1" }, { label: "1.5x", value: "1.5" }, { label: "2x", value: "2" }, { label: "4x", value: "4" }, { label: "8x", value: "8" }, { label: "16x", value: "16" }] }, { name: "autoAnswer", label: "自动答题", type: "switch", value: defaultConfig$1.autoAnswer, desc: "开启后,会自动答题" }, { name: "autoVideo", label: "自动视频", type: "switch", value: defaultConfig$1.autoVideo, desc: "开启后,会自动观看视频" }, { name: "autoJump", label: "自动切换", type: "switch", value: defaultConfig$1.autoVideo, desc: "开启后,会自动切换章节" }, { name: "autoSubmit", label: "自动提交", type: "switch", value: defaultConfig$1.autoSubmit, desc: "开启后,会自动提交答案" }, { name: "minAccuracy", label: "最低正确率", type: "input", value: defaultConfig$1.minAccuracy, desc: "不满足最低正确率则不会自动提交答案" }] }, { name: "exam", label: "作业/考试配置", config: [{ name: "autoExam", label: "考试自动切换", type: "switch", value: defaultConfig$1.autoExam, desc: "开启后,会考试会自动切换" }] }, { name: "llm", label: "LLM配置", config: [{ name: "llmProvider", label: "供应商预设", type: "select", value: defaultConfig$1.llmProvider, desc: "选择供应商", options: llmProviderPresets.map(p => ({ label: p.label, value: p.value })) }, { name: "llmBaseUrl", label: "API Base URL", type: "input", value: defaultConfig$1.llmBaseUrl, desc: "API 基础地址,如 https://api.openai.com/v1" }, { name: "llmSuffix", label: "请求路径后缀", type: "input", value: defaultConfig$1.llmSuffix, desc: "拼接在 Base URL 后的路径,如 /chat/completions" }, { name: "llmApiKey", label: "API Key", type: "password", showPassword: true, value: defaultConfig$1.llmApiKey, desc: "LLM API 密钥" }, { name: "llmModel", label: "模型名称", type: "input", value: defaultConfig$1.llmModel, desc: "填写服务商当前有效的模型 ID,请以官方文档为准(脚本不预置推荐模型)" }, { name: "llmTimeout", label: "LLM 超时时间", type: "select", value: defaultConfig$1.llmTimeout, desc: "推理过长时选不设置,超时或报错自动跳过", options: [{ label: "30秒", value: "30" }, { label: "不设置", value: "0" }] }, { name: "llmMaxTokens", label: "最大输出 Token", type: "select", value: defaultConfig$1.llmMaxTokens, desc: "推理模型需要更大输出空间", options: [{ label: "1000", value: "1000" }, { label: "2000", value: "2000" }, { label: "4000", value: "4000" }, { label: "8000", value: "8000" }] }, { name: "llmEnabled", label: "启用 LLM 答题", type: "switch", value: defaultConfig$1.llmEnabled, desc: "开启后题库无答案时使用 LLM 进行答题" }, { name: "llmWebSearch", label: "启用联网搜索", type: "switch", value: defaultConfig$1.llmWebSearch, desc: "LLM 回答前先联网搜索相关资料" }, { name: "llmSearchEngine", label: "搜索引擎", type: "select", value: defaultConfig$1.llmSearchEngine, desc: "选择联网搜索引擎", options: [{ label: "百度", value: "baidu" }, { label: "Bing", value: "bing" }, { label: "DuckDuckGo", value: "duckduckgo" }] }, { name: "llmSearchMode", label: "搜索模式", type: "select", value: defaultConfig$1.llmSearchMode, desc: "始终搜索:每次都搜索;智能搜索:LLM 不确定时才搜索", options: [{ label: "始终搜索", value: "always" }, { label: "智能搜索", value: "smart" }] }, { name: "llmSearchTypes", label: "联网搜索题型", type: "checkbox", value: defaultConfig$1.llmSearchTypes, desc: "选中后,对应题型才会联网搜索;客观题建议关闭,直答更准也更省请求", options: [{ label: "单选题", value: "0" }, { label: "多选题", value: "1" }, { label: "填空题", value: "2" }, { label: "判断题", value: "3" }, { label: "简答题", value: "4" }, { label: "名词解释", value: "5" }, { label: "论述题", value: "6" }, { label: "计算题", value: "7" }] }, { name: "llmType", label: "允许使用 LLM 的题型", type: "checkbox", value: defaultConfig$1.llmType, desc: "选中后,将使用 LLM 回答对应题型", options: [{ label: "单选题", value: "0" }, { label: "多选题", value: "1" }, { label: "填空题", value: "2" }, { label: "判断题", value: "3" }, { label: "简答题", value: "4" }, { label: "名词解释", value: "5" }, { label: "论述题", value: "6" }, { label: "计算题", value: "7" }] }] }, { name: "tiku", label: "题库设置", config: [{ name: "tikuMode", label: "调用方式", type: "select", value: defaultConfig$1.tikuMode, desc: "并行:所有题库同时查,最快命中即用并中止其余;顺序:按列表顺序逐个查,命中即停", options: [{ label: "并行(最快命中即用)", value: "parallel" }, { label: "顺序(按列表顺序)", value: "sequential" }] }, { name: "tikuTimeout", label: "单题库超时(秒)", type: "select", value: defaultConfig$1.tikuTimeout, desc: "各题库自带默认超时,此处为备用项", options: [{ label: "8秒", value: "8" }, { label: "15秒", value: "15" }, { label: "不设置", value: "0" }] }, { name: "banks", label: "题库列表", type: "banklist", value: [], desc: "" }] }], useformStore = pinia$1.defineStore({ id: "formstore", state: () => ({ forminput: getConfig(), dialogV: false, activeName: "quick" }), actions: { saveConfig(forminput) { var config; config = { ...forminput }; if (config.llmApiKey) config.llmApiKey = encryptApiKey(config.llmApiKey); config.banks = normalizeTikuBanks(tikuEncryptBankTokens(config.banks)); _GM_setValue("config", JSON.stringify(config)), (typeof _unsafeWindow !== 'undefined' && _unsafeWindow.top ? _unsafeWindow.top.localStorage : localStorage).setItem("config", JSON.stringify(config)); } } }); var export_helper_default = (sfc, props) => { let target = sfc.__vccOpts || sfc; for (let [key, val] of props) target[key] = val; return target; }, aim_vue_vue_type_script_lang_default = { name: "Aim" }, _hoisted_12$1 = { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 1024 1024" }, _hoisted_42 = [vue.createElementVNode("path", { fill: "currentColor", d: "M512 896a384 384 0 1 0 0-768 384 384 0 0 0 0 768zm0 64a448 448 0 1 1 0-896 448 448 0 0 1 0 896z" }, null, -1), vue.createElementVNode("path", { fill: "currentColor", d: "M512 96a32 32 0 0 1 32 32v192a32 32 0 0 1-64 0V128a32 32 0 0 1 32-32zm0 576a32 32 0 0 1 32 32v192a32 32 0 1 1-64 0V704a32 32 0 0 1 32-32zM96 512a32 32 0 0 1 32-32h192a32 32 0 0 1 0 64H128a32 32 0 0 1-32-32zm576 0a32 32 0 0 1 32-32h192a32 32 0 1 1 0 64H704a32 32 0 0 1-32-32z" }, null, -1)]; var aim_default = export_helper_default(aim_vue_vue_type_script_lang_default, [["render", function (_ctx, _cache, $props, $setup, $data, $options) { return vue.openBlock(), vue.createElementBlock("svg", _hoisted_12$1, _hoisted_42); }], ["__file", "aim.vue"]]), setting_vue_vue_type_script_lang_default = { name: "Setting" }, _hoisted_1231 = { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 1024 1024" }, _hoisted_3230 = [vue.createElementVNode("path", { fill: "currentColor", d: "M600.704 64a32 32 0 0 1 30.464 22.208l35.2 109.376c14.784 7.232 28.928 15.36 42.432 24.512l112.384-24.192a32 32 0 0 1 34.432 15.36L944.32 364.8a32 32 0 0 1-4.032 37.504l-77.12 85.12a357.12 357.12 0 0 1 0 49.024l77.12 85.248a32 32 0 0 1 4.032 37.504l-88.704 153.6a32 32 0 0 1-34.432 15.296L708.8 803.904c-13.44 9.088-27.648 17.28-42.368 24.512l-35.264 109.376A32 32 0 0 1 600.704 960H423.296a32 32 0 0 1-30.464-22.208L357.696 828.48a351.616 351.616 0 0 1-42.56-24.64l-112.32 24.256a32 32 0 0 1-34.432-15.36L79.68 659.2a32 32 0 0 1 4.032-37.504l77.12-85.248a357.12 357.12 0 0 1 0-48.896l-77.12-85.248A32 32 0 0 1 79.68 364.8l88.704-153.6a32 32 0 0 1 34.432-15.296l112.32 24.256c13.568-9.152 27.776-17.408 42.56-24.64l35.2-109.312A32 32 0 0 1 423.232 64H600.64zm-23.424 64H446.72l-36.352 113.088-24.512 11.968a294.113 294.113 0 0 0-34.816 20.096l-22.656 15.36-116.224-25.088-65.28 113.152 79.68 88.192-1.92 27.136a293.12 293.12 0 0 0 0 40.192l1.92 27.136-79.808 88.192 65.344 113.152 116.224-25.024 22.656 15.296a294.113 294.113 0 0 0 34.816 20.096l24.512 11.968L446.72 896h130.688l36.48-113.152 24.448-11.904a288.282 288.282 0 0 0 34.752-20.096l22.592-15.296 116.288 25.024 65.28-113.152-79.744-88.192 1.92-27.136a293.12 293.12 0 0 0 0-40.256l-1.92-27.136 79.808-88.128-65.344-113.152-116.288 24.96-22.592-15.232a287.616 287.616 0 0 0-34.752-20.096l-24.448-11.904L577.344 128zM512 320a192 192 0 1 1 0 384 192 192 0 0 1 0-384zm0 64a128 128 0 1 0 0 256 128 128 0 0 0 0-256z" }, null, -1)]; var setting_default = export_helper_default(setting_vue_vue_type_script_lang_default, [["render", function (_ctx, _cache, $props, $setup, $data, $options) { return vue.openBlock(), vue.createElementBlock("svg", _hoisted_1231, _hoisted_3230); }], ["__file", "setting.vue"]]); const _sfc_main$1 = vue.defineComponent({ components: {}, setup() { const formstoreObj = useformStore(), { forminput, dialogV, activeName } = pinia$1.storeToRefs(formstoreObj); vue.watch(dialogV, v => { if (v) { const fresh = getConfig(); fresh.banks = tikuDecryptBankTokens(normalizeTikuBanks(fresh.banks)); Object.assign(forminput.value, fresh); modelOptions.value = fresh.llmModel ? [fresh.llmModel] : []; modelsHint.value = ''; } }); const ruleFormRef = vue.ref(), rules = vue.reactive({ interval: [{ required: true, message: "间隔时间不能为空" }, { type: "number", message: "间隔时间必须为数字" }, { validator: (rule, value) => value >= 1 ? Promise.resolve() : Promise.reject("间隔时间必须大于等于1") }], answerInterval: [{ required: true, message: "答题间隔不能为空" }, { type: "number", message: "答题间隔必须为数字" }, { validator: (rule, value) => value >= 1 ? Promise.resolve() : Promise.reject("答题间隔必须大于等于1") }], token: [{ validator: (rule, value) => { if (value) { return /^[a-zA-Z0-9]{6,}$/.test(value) ? Promise.resolve() : Promise.reject("token格式错误"); } return Promise.resolve(); } }] }); const importDialogV = vue.ref(false), // CX_AUDIT_LLM_V1:记上一次选中的供应商。原实现在 v-model 写入之后才比较,changed 恒为 false。 _lastProvider = forminput.value.llmProvider, importText = vue.ref(''), currentProviderUrl = vue.ref((() => { const _p = llmProviderPresets.find(x => x.value === forminput.value.llmProvider); return _p ? _p.apiKeyUrl || '' : ''; })()), currentQuotaUrl = vue.ref((() => { const _q = llmProviderPresets.find(x => x.value === forminput.value.llmProvider); return _q ? _q.quotaUrl || '' : ''; })()); const modelOptions = vue.ref([]), modelsLoading = vue.ref(false), modelsHint = vue.ref(""); return { importDialogV, importText, currentProviderUrl, currentQuotaUrl, modelOptions, modelsLoading, modelsHint, dialogV, activeName, ruleFormRef, forminput, rules, llmProviderPresets, onProviderChange: (v) => { const p = llmProviderPresets.find(x => x.value === v); if (p) { const changed = _lastProvider !== v; _lastProvider = v; forminput.value.llmBaseUrl = p.baseUrl; forminput.value.llmSuffix = p.suffix || "/chat/completions"; currentProviderUrl.value = p.apiKeyUrl || ""; currentQuotaUrl.value = p.quotaUrl || ""; modelOptions.value = p.provider && p.provider.defaultModel ? [p.provider.defaultModel] : []; modelsHint.value = ""; if (changed && p.provider) forminput.value.llmModel = p.provider.defaultModel || ""; } }, fetchModels: () => { if (modelsLoading.value) return; const f = forminput.value; const provider = getProviderById(f.llmProvider, f.llmBaseUrl); if (!isWellFormedUrl(buildModelsUrl(f.llmBaseUrl, provider.modelsPath))) { modelsHint.value = "✗ Base URL 格式不合法"; ElementPlus.ElNotification({ title: "地址不合法", message: "请检查 Base URL 格式", type: "error" }); return; } modelsLoading.value = true; modelsHint.value = "正在获取模型列表..."; probeModels(f.llmBaseUrl, f.llmSuffix, provider.modelsPath, provider, f.llmApiKey, _GM_xmlhttpRequest).then((r) => { modelsLoading.value = false; if (r.state === "ok" && r.models.length) { modelOptions.value = r.models; if (!f.llmModel && r.models.length === 1) forminput.value.llmModel = r.models[0]; modelsHint.value = "✓ " + r.label + " · " + r.elapsedMs + " ms"; ElementPlus.ElNotification({ title: "已获取模型", message: `共 ${r.models.length} 个,可在下拉中选择或直接输入`, type: "success" }); } else if (r.state === "ok") { modelsHint.value = "△ 端点有效,但未返回模型列表"; ElementPlus.ElNotification({ title: "端点有效", message: "该供应商未返回模型列表,请手动填写模型 ID", type: "warning" }); } else { modelsHint.value = "✗ " + r.label; ElementPlus.ElNotification({ title: "获取失败", message: r.label, type: "error" }); } }); }, verifyUrl: () => { const f = forminput.value; const provider = getProviderById(f.llmProvider, f.llmBaseUrl); if (!isWellFormedUrl(buildModelsUrl(f.llmBaseUrl, provider.modelsPath))) { modelsHint.value = "✗ Base URL 格式不合法"; ElementPlus.ElNotification({ title: "地址不合法", message: "请检查 Base URL 格式", type: "error" }); return; } modelsHint.value = "校验中..."; probeModels(f.llmBaseUrl, f.llmSuffix, provider.modelsPath, provider, f.llmApiKey, _GM_xmlhttpRequest).then((r) => { modelsHint.value = (r.state === "ok" ? "✓ " : "△ ") + r.label; if (r.state === "ok" && r.models.length) modelOptions.value = r.models; ElementPlus.ElNotification({ title: r.state === "ok" ? "校验通过" : "校验结果", message: r.label + "(" + r.url + ")", type: r.state === "ok" ? "success" : "warning" }); }); }, isCustomProvider: vue.computed(() => forminput.value.llmProvider === "custom"), submitForm: async (formEl) => { formEl && await formEl.validate((valid, fields) => { valid && (formstoreObj.saveConfig(forminput.value), ElementPlus.ElNotification({ title: "Success", message: "配置保存成功,请自行刷新页面", type: "success" }), dialogV.value = false); }); }, exportConfig: () => { const _exp = { ...forminput.value }; delete _exp.thtoken; delete _exp.yztoken; delete _exp.enncytoken; const txt = JSON.stringify(_exp, null, 2); navigator.clipboard?.writeText(txt).then(() => ElementPlus.ElNotification({ title: '已导出', message: '配置已复制到剪贴板', type: 'success' })).catch(() => { const ta = document.createElement('textarea'); ta.value = txt; document.body.append(ta); ta.select(); document.execCommand('copy'); ta.remove(); ElementPlus.ElNotification({ title: '已导出', message: '配置已复制到剪贴板', type: 'success' }) }) }, importConfig: () => { importText.value = ''; importDialogV.value = true; }, doImport: () => { try { const parsed = JSON.parse(importText.value); if (parsed.llmApiKey === undefined) throw new Error('无效配置'); forminput.value = migrateLlmConfig({ ...forminput.value, ...parsed }); const _ip = llmProviderPresets.find(x => x.value === forminput.value.llmProvider); currentProviderUrl.value = _ip ? (_ip.apiKeyUrl || '') : ''; currentQuotaUrl.value = _ip ? (_ip.quotaUrl || '') : ''; modelsHint.value = ''; modelOptions.value = forminput.value.llmModel ? [forminput.value.llmModel] : []; ElementPlus.ElNotification({ title: '已导入', message: '配置已加载,点击保存生效', type: 'success' }); importDialogV.value = false; } catch { ElementPlus.ElNotification({ title: '导入失败', message: 'JSON格式错误', type: 'error' }); } }, testLLM: async () => { const f = forminput.value; const llmApiKey = f.llmApiKey, llmBaseUrl = f.llmBaseUrl, llmModel = f.llmModel; if (!llmApiKey || !llmBaseUrl || !llmModel) { ElementPlus.ElNotification({ title: '测试失败', message: '请先填写完整的 LLM 配置', type: 'error' }); return } const provider = getProviderById(f.llmProvider, llmBaseUrl); const url = buildChatUrl(llmBaseUrl, f.llmSuffix); const headers = buildAuthHeaders(provider, llmApiKey); const body = buildChatBody(provider, { model: llmModel, system: '只回复OK', user: '测试', maxTokens: 16 }); ElementPlus.ElNotification({ title: '测试中', message: '正在连接 LLM 服务...', type: 'info' }); _GM_xmlhttpRequest({ method: 'POST', url, data: JSON.stringify(body), headers, timeout: 1e4, onload: (res) => { let text = ''; let errMsg = ''; try { const data = JSON.parse(res.responseText); text = extractText(data); errMsg = (data && data.error && (data.error.message || data.error.type)) || ''; } catch (e) { } if (res.status === 200 && text) { ElementPlus.ElNotification({ title: '连接成功', message: `${llmModel} 响应:${text.slice(0, 30)}`, type: 'success' }); } else { ElementPlus.ElNotification({ title: '连接失败', message: `HTTP ${res.status}: ${errMsg || String(res.responseText || '').slice(0, 100)}`, type: 'error' }); } }, onerror: () => { ElementPlus.ElNotification({ title: '连接失败', message: '无法连接到 LLM 服务(请检查 @connect 与网络)', type: 'error' }) }, ontimeout: () => { ElementPlus.ElNotification({ title: '连接超时', message: 'LLM 服务未响应', type: 'error' }) } }) }, userConfig, Setting: setting_default }; } }), _export_sfc = (sfc, props) => { const target = sfc.__vccOpts || sfc; for (const [key, val] of props) target[key] = val; return target; }, _hoisted_1$1 = { class: "dialog-footer" }; const App = _export_sfc(_sfc_main$1, [['render', function (e, l, o, t, a, n) { const u = vue.resolveComponent('el-button'), c = vue.resolveComponent('el-switch'), r = vue.resolveComponent('el-input'), m = vue.resolveComponent('el-option'), d = vue.resolveComponent('el-select'), v = vue.resolveComponent('el-checkbox'), i = vue.resolveComponent('el-checkbox-group'), p = vue.resolveComponent('el-tooltip'), s = vue.resolveComponent('el-form-item'), k = vue.resolveComponent('el-form'), V = vue.resolveComponent('el-dialog'); return vue.openBlock(), vue.createElementBlock(vue.Fragment, null, [vue.createVNode(u, { type: 'primary', id: 'csbutton', icon: e.Setting, circle: '', 'aria-label': '打开设置', onClick: l[0] || (l[0] = l => e.dialogV = !e.dialogV) }, null, 8, ['icon']), vue.createVNode(V, { modelValue: e.dialogV, 'onUpdate:modelValue': l[1] || (l[1] = l => e.dialogV = l), title: '超星学习通满分助手', width: '900px', modal: !1, center: '', appendToBody: !0, draggable: !0, class: 'cx-config-dialog', 'z-index': 1e5 }, { footer: vue.withCtx(() => [vue.createElementVNode('span', _hoisted_1$1, [vue.createVNode(u, { onClick: l[2] || (l[2] = l => e.dialogV = !1) }, { default: vue.withCtx(() => [vue.createTextVNode('取消')]), _: 1 }), vue.createVNode(u, { type: 'primary', onClick: l[3] || (l[3] = l => e.submitForm(e.ruleFormRef)) }, { default: vue.withCtx(() => [vue.createTextVNode('保存')]), _: 1 })])]), default: vue.withCtx(() => [vue.createVNode(k, { ref: 'ruleFormRef', rules: e.rules, model: e.forminput, class: 'demo-ruleForm', 'label-position': 'top' }, { default: vue.withCtx(() => [vue.createElementVNode('div', { class: 'cx-config-layout' }, [vue.createElementVNode('div', { class: 'cx-config-nav' }, [(vue.openBlock(!0), vue.createElementBlock(vue.Fragment, null, vue.renderList(e.userConfig, l => (vue.openBlock(), vue.createElementBlock('button', { key: l.name, type: 'button', class: vue.normalizeClass(['cx-config-nav-item', { active: e.activeName === l.name }]), onClick: o => e.activeName = l.name }, vue.toDisplayString(l.label), 11, ['class', 'onClick']))), 128))]), vue.createElementVNode('div', { class: 'cx-config-content' }, [(vue.openBlock(!0), vue.createElementBlock(vue.Fragment, null, vue.renderList(e.userConfig, l => (vue.openBlock(), vue.createElementBlock(vue.Fragment, { key: l.name }, [e.activeName === l.name ? (vue.openBlock(), vue.createElementBlock('div', { key: 0 }, [vue.createElementVNode('div', { class: 'cx-config-section-title' }, vue.toDisplayString(l.label), 1), vue.createElementVNode('div', { class: 'cx-config-section-desc' }, '调整以下选项以自定义脚本行为', -1), (vue.openBlock(!0), vue.createElementBlock(vue.Fragment, null, vue.renderList(l.config, l => (vue.openBlock(), vue.createBlock(s, { label: l.label, prop: l.name }, { default: vue.withCtx(() => ['banklist' === l.type ? (vue.openBlock(), vue.createBlock(vue.resolveComponent('TikuBankList'), { key: 5, modelValue: e.forminput[l.name], 'onUpdate:modelValue': o => e.forminput[l.name] = o }, null, 8, ['modelValue', 'onUpdate:modelValue'])) : vue.createVNode(p, { class: 'box-item', effect: 'dark', content: l.desc || '', placement: 'top', teleported: !1 }, { default: vue.withCtx(() => ['switch' === l.type ? (vue.openBlock(), vue.createBlock(c, { key: 0, modelValue: e.forminput[l.name], 'onUpdate:modelValue': o => e.forminput[l.name] = o }, null, 8, ['modelValue', 'onUpdate:modelValue'])) : 'password' === l.type ? (vue.openBlock(), vue.createBlock(r, { key: 1, modelValue: e.forminput[l.name], 'onUpdate:modelValue': o => e.forminput[l.name] = o, type: 'password', showPassword: !0 }, null, 8, ['modelValue', 'onUpdate:modelValue'])) : 'input' === l.type && 'llmModel' === l.name ? (vue.openBlock(), vue.createElementBlock('div', { key: 9, style: { width: '100%' } }, [vue.createElementBlock('div', { style: { display: 'flex', alignItems: 'center', gap: '8px', width: '100%' } }, [vue.createVNode(d, { modelValue: e.forminput[l.name], 'onUpdate:modelValue': o => e.forminput[l.name] = o, filterable: !0, allowCreate: !0, defaultFirstOption: !0, clearable: !0, loading: e.modelsLoading, placeholder: '输入模型 ID,或点右侧获取', teleported: !1, style: { flex: '1' } }, { default: vue.withCtx(() => [(vue.openBlock(!0), vue.createElementBlock(vue.Fragment, null, vue.renderList(e.modelOptions, it => (vue.openBlock(), vue.createBlock(m, { key: it, label: it, value: it }, null, 8, ['label', 'value']))), 128))]), _: 2 }, 1032, ['modelValue', 'onUpdate:modelValue', 'loading']), vue.createVNode(u, { size: 'small', loading: e.modelsLoading, onClick: e.fetchModels }, { default: vue.withCtx(() => [vue.createTextVNode('获取模型')]), _: 2 }, 1032, ['loading', 'onClick'])], 4), e.modelsHint ? (vue.openBlock(), vue.createElementBlock('div', { key: 'hint', style: { fontSize: '12px', marginTop: '4px', color: /^✓/.test(e.modelsHint) ? '#16a34a' : (/^✗/.test(e.modelsHint) ? '#dc2626' : '#94a3b8') } }, vue.toDisplayString(e.modelsHint), 5)) : vue.createCommentVNode('', !0)], 4)) : 'input' === l.type && 'llmBaseUrl' === l.name ? (vue.openBlock(), vue.createBlock(r, { key: 1, modelValue: e.forminput[l.name], 'onUpdate:modelValue': o => e.forminput[l.name] = o, disabled: !e.isCustomProvider }, null, 8, ['modelValue', 'onUpdate:modelValue', 'disabled'])) : 'input' === l.type ? (vue.openBlock(), vue.createBlock(r, { key: 1, modelValue: e.forminput[l.name], 'onUpdate:modelValue': o => e.forminput[l.name] = o }, null, 8, ['modelValue', 'onUpdate:modelValue'])) : 'number' === l.type ? (vue.openBlock(), vue.createBlock(r, { key: 2, modelValue: e.forminput[l.name], 'onUpdate:modelValue': o => e.forminput[l.name] = 1 * o, type: 'number', min: '1', style: { width: '120px' } }, null, 8, ['modelValue', 'onUpdate:modelValue'])) : 'select' === l.type && 'llmProvider' === l.name ? (vue.openBlock(), vue.createElementBlock('div', { key: 3, class: 'cx-provider-row', style: { display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: '8px' } }, [vue.createVNode(d, { modelValue: e.forminput[l.name], 'onUpdate:modelValue': o => { e.forminput[l.name] = o, e.onProviderChange(o) }, placeholder: '请选择', teleported: !1, style: { flex: '1 1 100%', width: '100%', minWidth: '0' } }, { default: vue.withCtx(() => [(vue.openBlock(!0), vue.createElementBlock(vue.Fragment, null, vue.renderList(l.options, e => (vue.openBlock(), vue.createBlock(m, { key: e.value, label: e.label, value: e.value }, null, 8, ['label', 'value']))), 128))]), _: 2 }, 1032, ['modelValue', 'onUpdate:modelValue']), e.currentProviderUrl ? (vue.openBlock(), vue.createElementBlock('a', { key: 0, href: e.currentProviderUrl, target: '_blank', style: { fontSize: '12px', color: '#409eff', whiteSpace: 'nowrap', textDecoration: 'none' } }, '获取 API Key')) : vue.createCommentVNode('', !0), e.currentQuotaUrl ? (vue.openBlock(), vue.createElementBlock('a', { key: 1, href: e.currentQuotaUrl, target: '_blank', style: { fontSize: '12px', color: '#16a34a', whiteSpace: 'nowrap', textDecoration: 'none' } }, '领取额度')) : vue.createCommentVNode('', !0)])) : 'select' === l.type ? (vue.openBlock(), vue.createBlock(d, { key: 3, modelValue: e.forminput[l.name], 'onUpdate:modelValue': o => e.forminput[l.name] = o, placeholder: '请选择', teleported: !1 }, { default: vue.withCtx(() => [(vue.openBlock(!0), vue.createElementBlock(vue.Fragment, null, vue.renderList(l.options, e => (vue.openBlock(), vue.createBlock(m, { key: e.value, label: e.label, value: e.value }, null, 8, ['label', 'value']))), 128))]), _: 2 }, 1032, ['modelValue', 'onUpdate:modelValue'])) : 'checkbox' === l.type ? (vue.openBlock(), vue.createBlock(i, { key: 4, modelValue: e.forminput[l.name], 'onUpdate:modelValue': o => e.forminput[l.name] = o, class: 'cx-checkbox-horizontal' }, { default: vue.withCtx(() => [(vue.openBlock(!0), vue.createElementBlock(vue.Fragment, null, vue.renderList(l.options, e => (vue.openBlock(), vue.createBlock(v, { key: e.value, label: e.value, name: e.value }, { default: vue.withCtx(() => [vue.createTextVNode(vue.toDisplayString(e.label), 1)]), _: 2 }, 1032, ['label', 'name']))), 128))]), _: 2 }, 1032, ['modelValue', 'onUpdate:modelValue'])) : vue.createCommentVNode('', !0)]), _: 2 }, 1032, ['content'])]), _: 2 }, 1032, ['label', 'prop']))), 256)), 'llm' === l.name ? (vue.openBlock(), vue.createElementBlock('div', { key: 'llm-actions', class: 'cx-config-actions' }, [vue.createVNode(u, { size: 'small', onClick: e.exportConfig }, { default: vue.withCtx(() => [vue.createTextVNode('导出配置')]), _: 1 }, 8, ['onClick']), vue.createVNode(u, { size: 'small', onClick: e.importConfig }, { default: vue.withCtx(() => [vue.createTextVNode('导入配置')]), _: 1 }, 8, ['onClick']), vue.createVNode(u, { size: 'small', type: 'success', plain: '', onClick: e.verifyUrl }, { default: vue.withCtx(() => [vue.createTextVNode('校验 URL')]), _: 1 }, 8, ['onClick']), vue.createVNode(u, { size: 'small', type: 'success', plain: '', onClick: e.testLLM }, { default: vue.withCtx(() => [vue.createTextVNode('测试 LLM')]), _: 1 }, 8, ['onClick'])])) : vue.createCommentVNode('', !0)])) : vue.createCommentVNode('', !0)]))), 128))])])]), _: 1 }, 8, ['rules', 'model'])]), _: 1 }, 8, ['modelValue']), vue.createVNode(V, { modelValue: e.importDialogV, 'onUpdate:modelValue': l[5] || (l[5] = l => e.importDialogV = l), title: '导入配置', width: '400px', modal: !1, center: '', 'z-index': 100001 }, { footer: vue.withCtx(() => [vue.createElementVNode('span', null, [vue.createVNode(u, { onClick: l[6] || (l[6] = l => e.importDialogV = !1) }, { default: vue.withCtx(() => [vue.createTextVNode('取消')]), _: 1 }), vue.createVNode(u, { type: 'primary', onClick: e.doImport }, { default: vue.withCtx(() => [vue.createTextVNode('确定')]), _: 1 })])]), default: vue.withCtx(() => [vue.createElementVNode('p', { style: { 'margin-bottom': '8px', color: '#64748b', 'font-size': '13px' } }, '请粘贴配置JSON'), vue.createVNode(r, { modelValue: e.importText, 'onUpdate:modelValue': l[4] || (l[4] = l => e.importText = l), type: 'textarea', rows: 6, placeholder: '{ "interval": 3, ... }' }, null, 8, ['modelValue'])]), _: 1 }, 8, ['modelValue'])], 64) }], ['__scopeId', 'data-v-6ed29f7f']]); let defaultConfig = getConfig(); class ServerApi { constructor(window2 = _unsafeWindow) { __publicField(this, "windowz", _unsafeWindow); this.windowz = window2; } /** 解析响应 usage 并写缓存命中日志;没有 usage 字段的供应商静默跳过 */ _logCacheUsage(data, provider) { try { const parsed = parseUsage(data, provider); if (!parsed || !parsed.total) return; const pct = Math.round((parsed.hit / parsed.total) * 100); if (parsed.hit > 0) { log(`[LLM 缓存] ${parsed.provider} 命中 ${parsed.hit}/${parsed.total} token (${pct}%)`, "success"); } else { log(`[LLM 缓存] ${parsed.provider} 命中 0/${parsed.total} token(前缀未达可缓存长度或该家不支持)`, "info"); } } catch (e) { } } // CX_AUDIT_TASK_V1:补上缺失的 s()。原实现调用 this.ServerApi.s(),类里却没有这个方法, // 每次「已完成作业任务点」的核对都抛 TypeError 并被静默吞掉。这里改为只做本地汇总与日志, // 不引入任何后端依赖。 async s(questionList, pageHref) { try { const list = Array.isArray(questionList) ? questionList.filter(Boolean) : []; if (!list.length) return; const hasAnswer = (q) => { const a = q && q.answer; if (a == null) return false; if (Array.isArray(a)) return a.length > 0; return String(a).trim().length > 0; }; const ok = list.filter(hasAnswer).length; log(`[核对] 已解析 ${list.length} 题,其中 ${ok} 题带答案`, ok ? "success" : "info"); } catch (e) { } } // CX_AUDIT_SEARCH_V1:搜索结果里的标题/摘要带着 HTML 实体(& ' " …), // 不还原会把乱码喂给模型。三个引擎统一过这一道。 _decodeHtmlEntities(str) { let t = String(str == null ? "" : str); t = t.replace(/<[^>]+>/g, ""); t = t.replace(/ /gi, " ") .replace(/</gi, "<") .replace(/>/gi, ">") .replace(/"/gi, "\"") .replace(/�*39;/g, "'") .replace(/'/gi, "'") .replace(/&/gi, "&"); t = t.replace(/&#x([0-9a-f]+);/gi, (m, h) => { try { return String.fromCodePoint(parseInt(h, 16)); } catch (e) { return m; } }); t = t.replace(/&#(\d+);/g, (m, d) => { try { return String.fromCodePoint(parseInt(d, 10)); } catch (e) { return m; } }); return t.replace(/\s+/g, " ").trim(); } // 探针答案「值不值得信」。原实现只查低置信词表,但 system prompt 要求「只返回答案本身」, // 模型几乎不会输出「不确定」→ 判为高置信 → 搜索永不触发。这里补齐空/过短/占位词。 _isSuspectAnswer(text) { const t = String(text == null ? "" : text).trim(); if (!t) return true; if (t.length < 2) return true; if (/^(略|无|暂无|不知道|不确定|无法确定|无法回答|无法判断|无法给出|暂无答案|暂无解析)$/.test(t)) return true; if (/无法确定|无法回答|无法判断|不确定|不太确定|不清楚|没有把握|not sure|uncertain|i don.t know/i.test(t)) return true; return this.checkConfidence(t); } getSearchCountByType(questionType) { const countMap = { "0": 2, "1": 3, "2": 3, "3": 2, "4": 5, "5": 5, "6": 5, "7": 5 }; return countMap[questionType] || 3; } async searchBaidu(query, count) { return new Promise((resolve) => { const url = "https://www.baidu.com/s?wd=" + encodeURIComponent(query) + "&rn=" + count; _GM_xmlhttpRequest({ method: "GET", url, headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }, timeout: 10000, onload: (res) => { try { if (typeof res.status === "number" && (res.status < 200 || res.status >= 300)) { log("[WebSearch] 引擎返回 HTTP " + res.status, "error"); resolve([]); return; } const html = res.responseText; const results = []; const itemRegex = /]*class="[^"]*result[^"]*"[^>]*>[\s\S]*?]*>[\s\S]*?]*>([\s\S]*?)<\/a>[\s\S]*?<\/h3>[\s\S]*?]*class="[^"]*content-right_[^"]*"[^>]*>([\s\S]*?)<\/span>/gi; let match; while ((match = itemRegex.exec(html)) !== null && results.length < count) { const title = this._decodeHtmlEntities(match[1]); const snippet = this._decodeHtmlEntities(match[2]); if (title && snippet) results.push({ title, snippet }); } if (results.length === 0) { // 新版百度结果页不再用 content-right_,摘要挂在 c-color-text / c-abstract 上 const blockRegex = /]*class="[^"]*result[^"]*"[^>]*>([\s\S]*?)(?=]*class="[^"]*result[^"]*"|$)/gi; while ((match = blockRegex.exec(html)) !== null && results.length < count) { const block = match[1] || ""; const tm = block.match(/]*>[\s\S]*?]*>([\s\S]*?)<\/a>/i); if (!tm) continue; const title = this._decodeHtmlEntities(tm[1]); if (!title) continue; const sm = block.match(/]*class="[^"]*c-color-text[^"]*"[^>]*>([\s\S]*?)<\/span>/i) || block.match(/]*class="[^"]*c-abstract[^"]*"[^>]*>([\s\S]*?)<\/div>/i); const snippet = sm ? this._decodeHtmlEntities(sm[1]) : ""; results.push({ title, snippet }); } } if (results.length === 0) { const fallbackRegex = /]*>[\s\S]*?]*>([\s\S]*?)<\/a>/gi; while ((match = fallbackRegex.exec(html)) !== null && results.length < count) { const title = this._decodeHtmlEntities(match[1]); if (title) results.push({ title, snippet: "" }); } } log(`[WebSearch] 百度搜索完成,获取 ${results.length} 条结果`, "info"); resolve(results); } catch (e) { log("[WebSearch] 百度搜索解析失败", "error"); resolve([]); } }, ontimeout: () => { log("[WebSearch] 百度搜索超时", "error"); resolve([]); }, onerror: () => { log("[WebSearch] 百度搜索失败", "error"); resolve([]); } }); }); } async searchBing(query, count) { return new Promise((resolve) => { // 使用 cn.bing.com 中文版搜索,参考 bing-cn-mcp-server 实现 const url = "https://cn.bing.com/search?q=" + encodeURIComponent(query) + "&first=1"; _GM_xmlhttpRequest({ method: "GET", url, // CX_AUDIT_SEARCH_V1:原来显式发 Accept-Encoding: gzip, deflate, br。 // GM_xmlhttpRequest 不保证自动解压,部分实现下 responseText 直接是乱码 → 解析永远 0 条。 // 保持默认编码协商(由实现自己处理),只发必要的 UA / 语言偏好。 headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8" }, timeout: 15000, onload: (res) => { try { if (typeof res.status === "number" && (res.status < 200 || res.status >= 300)) { log("[WebSearch] 引擎返回 HTTP " + res.status, "error"); resolve([]); return; } const html = res.responseText; const results = []; // 使用与 bing-cn-mcp-server 相同的选择器解析 // 1. 先尝试 .b_algo 选择器(Bing标准格式) const bAlgoRegex = /]*class="b_algo"[^>]*>([\s\S]*?)<\/li>/gi; let match; while ((match = bAlgoRegex.exec(html)) !== null && results.length < count) { const block = match[1]; // 提取标题和链接: h2 > a const titleMatch = block.match(/]*>\s*]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/i); if (!titleMatch) continue; const url = titleMatch[1]; const title = this._decodeHtmlEntities(titleMatch[2]); // 提取摘要: .b_caption p 或 p const snippetMatch = block.match(/]*class="[^"]*b_caption[^"]*"[^>]*>\s*

([\s\S]*?)<\/p>/i) || block.match(/]*>([\s\S]*?)<\/p>/i); const snippet = snippetMatch ? this._decodeHtmlEntities(snippetMatch[1]) : ""; if (title && url) results.push({ title, snippet, url }); } // 2. 兜底:使用更宽泛的正则 if (results.length === 0) { const fallbackRegex = /]*>\s*]*href="(https?:\/\/[^"]*)"[^>]*>([\s\S]*?)<\/a>/gi; while ((match = fallbackRegex.exec(html)) !== null && results.length < count) { const url = match[1]; const title = this._decodeHtmlEntities(match[2]); if (title && !url.includes("bing.com")) results.push({ title, snippet: "", url }); } } log(`[WebSearch] Bing(cn) 搜索完成,获取 ${results.length} 条结果`, "info"); resolve(results); } catch (e) { log("[WebSearch] Bing 搜索解析失败", "error"); resolve([]); } }, ontimeout: () => { log("[WebSearch] Bing 搜索超时", "error"); resolve([]); }, onerror: () => { log("[WebSearch] Bing 搜索失败", "error"); resolve([]); } }); }); } async searchDuckDuckGo(query, count) { return new Promise((resolve) => { // CX_AUDIT_SEARCH_V1:html.duckduckgo.com 的 result__a / result__snippet 结构二十年未变, // 而 duckduckgo.com/html/ 常被重定向到 JS 版,抓到的页面里没有任何结果节点。 const url = "https://html.duckduckgo.com/html/?q=" + encodeURIComponent(query); _GM_xmlhttpRequest({ method: "GET", url, headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" }, timeout: 10000, onload: (res) => { try { if (typeof res.status === "number" && (res.status < 200 || res.status >= 300)) { log("[WebSearch] 引擎返回 HTTP " + res.status, "error"); resolve([]); return; } const html = res.responseText; const results = []; const itemRegex = /]*class="result[^"]*"[^>]*>[\s\S]*?]*class="result__a"[^>]*>([\s\S]*?)<\/a>[\s\S]*?]*class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi; let match; while ((match = itemRegex.exec(html)) !== null && results.length < count) { const title = this._decodeHtmlEntities(match[1]); const snippet = this._decodeHtmlEntities(match[2]); if (title) results.push({ title, snippet }); } log(`[WebSearch] DuckDuckGo 搜索完成,获取 ${results.length} 条结果`, "info"); resolve(results); } catch (e) { log("[WebSearch] DuckDuckGo 搜索解析失败", "error"); resolve([]); } }, ontimeout: () => { log("[WebSearch] DuckDuckGo 搜索超时", "error"); resolve([]); }, onerror: () => { log("[WebSearch] DuckDuckGo 搜索失败", "error"); resolve([]); } }); }); } async searchWeb(query, engine, count) { // 题目题干可能很长(含图片标签、选项),直接拼进 URL 会被引擎截断或 414 let q = String(query == null ? "" : query).replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(); if (q.length > 200) q = q.slice(0, 200); log(`[WebSearch] 开始搜索 - 引擎: ${engine}, 关键词: ${q.substring(0, 30)}`, "info"); let out = []; try { if (engine === "bing") out = await this.searchBing(q, count); else if (engine === "duckduckgo") out = await this.searchDuckDuckGo(q, count); else out = await this.searchBaidu(q, count); } catch (e) { log(`[WebSearch] ${engine} 搜索异常: ${(e && e.message) || e}`, "error"); out = []; } log(`[WebSearch] ${engine} 返回 ${out.length} 条结果`, out.length ? "success" : "info"); return out; } checkConfidence(answer) { if (!answer) return false; const lowConfidenceWords = ["不确定", "可能", "也许", "大概", "或许", "不太清楚", "无法确定", "不太确定", "没有把握", "不太了解", "不太熟悉", "不太明确", "不太肯定", "not sure", "maybe", "uncertain", "unclear", "i think", "might be", "possibly", "probably"]; const lowerAnswer = answer.toLowerCase(); return lowConfidenceWords.some(word => lowerAnswer.includes(word)); } async answerWithSearchInfo(questionData, searchInfo) { return new Promise(async (resolve) => { const config = getConfig(); const questionTypeMap = { "0": "单选题", "1": "多选题", "2": "填空题", "3": "判断题", "4": "简答题", "5": "名词解释", "6": "论述题", "7": "计算题" }; const questionType = questionTypeMap[questionData.type] || "未知题型"; let prompt = `你是一个专业的答题助手。请根据以下参考资料和题目,给出正确答案。 参考资料可能包含与题目无关的网页内容,请只采用真正相关的部分;若参考资料均不相关,请凭已有知识直接作答,不要因为资料缺失而拒绝回答。 参考资料: ${searchInfo} 题目:${questionData.question} `; let optionsText = []; if (questionData.options && questionData.options.length > 0) { prompt += "选项:\n"; questionData.options.forEach((opt, idx) => { const letter = String.fromCharCode(65 + idx); prompt += `${letter}. ${opt}\n`; optionsText.push({ letter, text: opt }); }); } if (questionData.type === "0") { prompt += "\n请只返回正确选项的字母(如 A),不要返回其他内容。"; } else if (questionData.type === "1") { prompt += "\n这是多选题,请返回所有正确选项的字母,用逗号分隔(如 A,B),不要返回其他内容。"; } else if (questionData.type === "3") { prompt += "\n请只返回\"正确\"或\"错误\",不要返回其他内容。"; } else if (questionData.type === "2") { prompt += "\n这是填空题,请直接返回填空内容。如果有多个空,请用\"###\"分隔每个空的答案。"; } else { prompt += "\n请直接给出答案,简洁明了。"; } const provider = getProviderById(config.llmProvider, config.llmBaseUrl); const apiUrl = buildChatUrl(config.llmBaseUrl, config.llmSuffix); const headers = buildAuthHeaders(provider, config.llmApiKey); // 图片题:优先下载成 base64 真正发给模型;供应商不支持视觉时退回纯文本(不放弃) let _imgRes = { dataUrls: [], total: 0, failed: 0 }; const _imgHtml = String(questionData.question || "") + " " + (questionData.options || []).join(" "); const _hasImg = hasImage(_imgHtml); let _imgNote = ""; if (_hasImg) { if (provider && provider.vision === true) { _imgRes = await LLM_IMG_LOADER.loadFromHtml(_imgHtml, (typeof _unsafeWindow !== "undefined" && _unsafeWindow && _unsafeWindow.location && _unsafeWindow.location.href) || ""); if (_imgRes.dataUrls.length) { log("[图片] 已加载 " + _imgRes.dataUrls.length + "/" + _imgRes.total + " 张图片", "success"); } else { _imgNote = IMG_UNSUPPORTED_MSG; log("[图片] 共 " + _imgRes.total + " 张图,全部下载失败", "error"); } } else { _imgNote = IMG_UNSUPPORTED_MSG; log("[图片] 当前供应商不支持图片识别,退回纯文本作答", "info"); } } const body = buildChatBody(provider, { model: config.llmModel, system: "你是一个专业的在线课程答题助手。根据题目类型,只返回答案本身,不要添加任何解释、不要使用markdown格式、不要询问更多信息。", user: prompt, images: _imgRes.dataUrls, maxTokens: parseInt(config.llmMaxTokens) || 1000 }, config); log("[LLM API] 使用联网搜索结果增强回答", "info"); _GM_xmlhttpRequest({ method: "POST", url: apiUrl, data: JSON.stringify(body), headers, timeout: config.llmTimeout === "0" ? 600000 : (parseInt(config.llmTimeout) || 30) * 1000, onload: (res) => { try { const data = JSON.parse(res.responseText); this._logCacheUsage(data, provider); let rawAnswer = extractText(data); if (rawAnswer) { log(`[LLM API] 联网搜索增强回答: ${rawAnswer.substring(0, 50)}`, "success"); const answer = this.parseAnswer(questionData, rawAnswer, optionsText); resolve({ form: "LLM(联网搜索)", answer, model: config.llmModel, note: _imgNote }); } else { resolve({ form: "LLM(联网搜索)", answer: "" }); } } catch (e) { resolve({ form: "LLM(联网搜索)", answer: "" }); } }, ontimeout: () => { log("[LLM API] 联网搜索增强回答超时", "error"); resolve({ form: "LLM(联网搜索)", answer: "" }); }, onerror: () => { log("[LLM API] 联网搜索增强回答失败", "error"); resolve({ form: "LLM(联网搜索)", answer: "" }); } }); }); } parseAnswer(questionData, rawAnswer, optionsText) { const _strSim = (a, b) => { if (!a && !b) return 1; if (!a || !b) return 0; a = a.toLowerCase().trim(); b = b.toLowerCase().trim(); if (a === b) return 1; const la = a.length, lb = b.length; if (!la || !lb) return 0; let prev = [], curr = []; for (let j = 0; j <= lb; j++) prev[j] = j; for (let i = 1; i <= la; i++) { curr[0] = i; for (let j = 1; j <= lb; j++) curr[j] = a[i - 1] === b[j - 1] ? prev[j - 1] : 1 + Math.min(prev[j], curr[j - 1], prev[j - 1]);[prev, curr] = [curr, prev]; } return 1 - prev[lb] / Math.max(la, lb); }; if (questionData.type === "0") { const letter = rawAnswer.replace(/[^A-Za-z]/g, "").toUpperCase()[0]; const matched = optionsText.find(o => o.letter === letter); if (matched) return [matched.text]; let bestIdx = -1, bestScore = 0; optionsText.forEach((o, i) => { const s = _strSim(o.text, rawAnswer); if (s > bestScore) { bestScore = s; bestIdx = i; } }); return bestIdx >= 0 && bestScore >= 0.5 ? [optionsText[bestIdx].text] : ""; } else if (questionData.type === "1") { const letters = rawAnswer.replace(/[^A-Za-z,,]/g, "").toUpperCase().replace(/,/g, ",").split(","); let answer = letters.map(l => { const matched = optionsText.find(o => o.letter === l.trim()); return matched ? matched.text : null; }).filter(x => x); if (answer.length === 0) { const parts = rawAnswer.split(/[||,,]/); answer = parts.map(part => { let bi = -1, bs = 0; optionsText.forEach((o, i) => { const s = _strSim(o.text, part.trim()); if (s > bs) { bs = s; bi = i; } }); return bi >= 0 && bs >= 0.5 ? optionsText[bi].text : null; }).filter(x => x); } return answer; } else if (questionData.type === "3") { const _judgeNorm = rawAnswer.replace(/[。,.,!!\s]/g, "").toLowerCase(); const _trueWords = ["正确", "是", "对", "√", "t", "true", "ri", "right", "yes"]; const _falseWords = ["错误", "否", "错", "×", "f", "false", "wr", "wrong", "no"]; let _judgeResult = null; for (const w of _trueWords) { if (_judgeNorm === w) { _judgeResult = "正确"; break; } } if (!_judgeResult) { for (const w of _falseWords) { if (_judgeNorm === w) { _judgeResult = "错误"; break; } } } if (!_judgeResult) { for (const w of _falseWords) { if (_judgeNorm.includes(w)) { _judgeResult = "错误"; break; } } } if (!_judgeResult) { for (const w of _trueWords) { if (_judgeNorm.includes(w)) { _judgeResult = "正确"; break; } } } return _judgeResult || rawAnswer; } else if (questionData.type === "2") { return rawAnswer.split("###").map(s => s.trim()).filter(s => s); } else { return [rawAnswer]; } } async getAnswerByLLM(questionData) { // 用 async IIFE 包一层 try/catch:原实现是 new Promise(async resolve => …), // 内部 await 抛错时 resolve 永不被调用,会让这道题永久卡住整个答题循环 try { return await this._answerByLLMInner(questionData); } catch (e) { log("[LLM API] 异常: " + ((e && e.message) || e), "error"); return { form: "LLM", answer: "" }; } } async _answerByLLMInner(questionData) { const config = getConfig(); log(`[LLM API] 开始调用 - 模型: ${config.llmModel}`, "info"); if (!config.llmEnabled || !config.llmApiKey || !config.llmBaseUrl) { log("[LLM API] 配置不完整", "error"); return { form: "LLM", answer: "" }; } const provider = getProviderById(config.llmProvider, config.llmBaseUrl); // 联网搜索只对配置里勾选的题型生效;默认仅主观题(简答/名词解释/论述/计算) // 客观题有选项约束,LLM 直答通常比拼接搜索摘要更准,且能省掉整条搜索链路 const searchTypes = Array.isArray(config.llmSearchTypes) ? config.llmSearchTypes.map(String) : ["4", "5", "6", "7"]; const typeStr = String(questionData.type == null ? "" : questionData.type); const typeAllowsSearch = searchTypes.indexOf(typeStr) >= 0; let probe = null; // smart 模式的探针结果,供回退复用,避免同一 prompt 重发第二次 if (config.llmWebSearch && typeAllowsSearch) { if (config.llmSearchMode === "smart") { LLM_BUSY.setPhase("probe", "直接作答"); log("[WebSearch] 智能模式:先尝试直接回答", "info"); // 探针单独放行「不确定」出口,否则它永远返回一个看起来确定的答案 probe = await this.answerDirectly(questionData, config, { allowUncertain: true }); const probeText = Array.isArray(probe.answer) ? probe.answer.join(",") : probe.answer; const probeTextStr = Array.isArray(probeText) ? probeText.join(",") : String(probeText || ""); if (!this._isSuspectAnswer(probeTextStr)) { log("[WebSearch] 直接回答可信,跳过搜索", "info"); return probe; } log("[WebSearch] 直接回答可疑(" + probeTextStr.slice(0, 20) + "),触发联网搜索", "info"); } LLM_BUSY.setPhase("search", "联网搜索"); const searchCount = this.getSearchCountByType(questionData.type); const searchResults = await this.searchWeb(questionData.question, config.llmSearchEngine, searchCount); if (searchResults.length > 0) { // 相关性判定那一步已删除:它的失败路径等价于"不判断",成功路径只是把同一批文本 // 再喂一次 LLM。改为在作答 prompt 里让模型自行取舍无关资料。 const searchInfo = searchResults.map(r => r.title + (r.snippet ? ": " + r.snippet : "")).join("\n"); LLM_BUSY.setPhase("answer-with-info", "结合资料作答"); const result = await this.answerWithSearchInfo(questionData, searchInfo); if (result.answer) return result; log("[WebSearch] 带资料作答失败,回退直接回答", "info"); } else { log("[WebSearch] 引擎返回 0 条结果,跳过带资料作答", "info"); } } else if (config.llmWebSearch) { log(`[WebSearch] 题型 ${typeStr || "?"} 未启用联网搜索,直接作答`, "info"); } // 回退:优先复用探针结果(同一个 prompt,重发纯属浪费) if (probe && probe.answer) return probe; LLM_BUSY.setPhase("probe", "直接作答"); return await this.answerDirectly(questionData, config); } // opts.allowUncertain:仅探针调用时传 true。 // 原实现让探针复用「只返回答案本身」的 prompt,模型几乎不会说「不确定」, // 于是 smart 模式的 checkConfidence 永远判定为高置信 → 联网搜索从不触发。 async answerDirectly(questionData, config, opts) { opts = opts || {}; return new Promise(async (resolve) => { const questionTypeMap = { "0": "单选题", "1": "多选题", "2": "填空题", "3": "判断题", "4": "简答题", "5": "名词解释", "6": "论述题", "7": "计算题" }; const questionType = questionTypeMap[questionData.type] || "未知题型"; let prompt = `你是一个专业的答题助手。请根据以下${questionType},给出正确答案。 题目:${questionData.question} `; let optionsText = []; if (questionData.options && questionData.options.length > 0) { prompt += "选项:\n"; questionData.options.forEach((opt, idx) => { const letter = String.fromCharCode(65 + idx); prompt += `${letter}. ${opt}\n`; optionsText.push({ letter, text: opt }); }); } if (questionData.type === "0") { prompt += "\n请只返回正确选项的字母(如 A),不要返回其他内容。"; } else if (questionData.type === "1") { prompt += "\n这是多选题,请返回所有正确选项的字母,用逗号分隔(如 A,B),不要返回其他内容。"; } else if (questionData.type === "3") { prompt += "\n请只返回\"正确\"或\"错误\",不要返回其他内容。"; } else if (questionData.type === "2") { prompt += "\n这是填空题,请直接返回填空内容。如果有多个空,请用\"###\"分隔每个空的答案。"; } else { prompt += "\n请直接给出答案,简洁明了。"; } // 探针专用:给模型一个「不确定」出口,否则它永远编一个看起来确定的答案 if (opts.allowUncertain) { prompt += "\n如果你对该题没有把握,请只输出「不确定」三个字,不要编造答案。"; } const provider = getProviderById(config.llmProvider, config.llmBaseUrl); const apiUrl = buildChatUrl(config.llmBaseUrl, config.llmSuffix); const headers = buildAuthHeaders(provider, config.llmApiKey); // 图片题:优先下载成 base64 真正发给模型;供应商不支持视觉时退回纯文本(不放弃) let _imgRes = { dataUrls: [], total: 0, failed: 0 }; const _imgHtml = String(questionData.question || "") + " " + (questionData.options || []).join(" "); const _hasImg = hasImage(_imgHtml); let _imgNote = ""; if (_hasImg) { if (provider && provider.vision === true) { _imgRes = await LLM_IMG_LOADER.loadFromHtml(_imgHtml, (typeof _unsafeWindow !== "undefined" && _unsafeWindow && _unsafeWindow.location && _unsafeWindow.location.href) || ""); if (_imgRes.dataUrls.length) { log("[图片] 已加载 " + _imgRes.dataUrls.length + "/" + _imgRes.total + " 张图片", "success"); } else { _imgNote = IMG_UNSUPPORTED_MSG; log("[图片] 共 " + _imgRes.total + " 张图,全部下载失败", "error"); } } else { _imgNote = IMG_UNSUPPORTED_MSG; log("[图片] 当前供应商不支持图片识别,退回纯文本作答", "info"); } } const body = buildChatBody(provider, { model: config.llmModel, system: "你是一个专业的在线课程答题助手。根据题目类型,只返回答案本身,不要添加任何解释、不要使用markdown格式、不要询问更多信息。", user: prompt, images: _imgRes.dataUrls, maxTokens: parseInt(config.llmMaxTokens) || 1000 }, config); log(`[LLM API] 请求: ${apiUrl}`, "info"); _GM_xmlhttpRequest({ method: "POST", url: apiUrl, data: JSON.stringify(body), headers, timeout: config.llmTimeout === "0" ? 600000 : (parseInt(config.llmTimeout) || 30) * 1000, onload: (res) => { log(`[LLM API] 响应状态: ${res.status}`, res.status === 200 ? "success" : "error"); try { const data = JSON.parse(res.responseText); this._logCacheUsage(data, provider); let rawAnswer = extractText(data); if (rawAnswer) { log(`[LLM API] 回答: ${rawAnswer.substring(0, 50)}`, "success"); const answer = this.parseAnswer(questionData, rawAnswer, optionsText); resolve({ form: "LLM", answer, model: config.llmModel, note: _imgNote }); } else { resolve({ form: "LLM", answer: "" }); } } catch (e) { resolve({ form: "LLM", answer: "" }); } }, ontimeout: () => { log("[LLM API] 请求超时", "error"); resolve({ form: "LLM", answer: "" }); }, onerror: () => { log("[LLM API] 请求失败", "error"); resolve({ form: "LLM", answer: "" }); } }); }); } } function getDefaultExportFromCjs(x) { return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x.default : x; } var Typr = { parse: function (buff) { var bin = Typr._bin, data = new Uint8Array(buff), offset = 0; bin.readFixed(data, offset), offset += 4; var numTables = bin.readUshort(data, offset); offset += 2, bin.readUshort(data, offset), offset += 2, bin.readUshort(data, offset), offset += 2, bin.readUshort(data, offset), offset += 2; for (var tags = ["cmap", "head", "hhea", "maxp", "hmtx", "name", "OS/2", "post", "loca", "glyf", "kern", "CFF ", "GPOS", "GSUB", "SVG "], obj = { _data: data }, tabs = {}, i = 0; i < numTables; i++) { var tag = bin.readASCII(data, offset, 4); offset += 4, bin.readUint(data, offset), offset += 4; var toffset = bin.readUint(data, offset); offset += 4; var length = bin.readUint(data, offset); offset += 4, tabs[tag] = { offset: toffset, length }; } for (i = 0; i < tags.length; i++) { var t = tags[i]; tabs[t] && (obj[t.trim()] = Typr[t.trim()].parse(data, tabs[t].offset, tabs[t].length, obj)); } return obj; }, _tabOffset: function (data, tab) { for (var bin = Typr._bin, numTables = bin.readUshort(data, 4), offset = 12, i = 0; i < numTables; i++) { var tag = bin.readASCII(data, offset, 4); offset += 4, bin.readUint(data, offset), offset += 4; var toffset = bin.readUint(data, offset); if (offset += 4, bin.readUint(data, offset), offset += 4, tag == tab) return toffset; } return 0; } }; Typr._bin = { readFixed: function (data, o) { return (data[o] << 8 | data[o + 1]) + (data[o + 2] << 8 | data[o + 3]) / 65540; }, readF2dot14: function (data, o) { return Typr._bin.readShort(data, o) / 16384; }, readInt: function (buff, p) { var a = Typr._bin.t.uint8; return a[0] = buff[p + 3], a[1] = buff[p + 2], a[2] = buff[p + 1], a[3] = buff[p], Typr._bin.t.int32[0]; }, readInt8: function (buff, p) { return Typr._bin.t.uint8[0] = buff[p], Typr._bin.t.int8[0]; }, readShort: function (buff, p) { var a = Typr._bin.t.uint8; return a[1] = buff[p], a[0] = buff[p + 1], Typr._bin.t.int16[0]; }, readUshort: function (buff, p) { return buff[p] << 8 | buff[p + 1]; }, readUshorts: function (buff, p, len) { for (var arr = [], i = 0; i < len; i++) arr.push(Typr._bin.readUshort(buff, p + 2 * i)); return arr; }, readUint: function (buff, p) { var a = Typr._bin.t.uint8; return a[3] = buff[p], a[2] = buff[p + 1], a[1] = buff[p + 2], a[0] = buff[p + 3], Typr._bin.t.uint32[0]; }, readUint64: function (buff, p) { return 4294967296 * Typr._bin.readUint(buff, p) + Typr._bin.readUint(buff, p + 4); }, readASCII: function (buff, p, l) { for (var s = "", i = 0; i < l; i++) s += String.fromCharCode(buff[p + i]); return s; }, readUnicode: function (buff, p, l) { for (var s = "", i = 0; i < l; i++) { var c = buff[p++] << 8 | buff[p++]; s += String.fromCharCode(c); } return s; }, _tdec: window.TextDecoder ? new window.TextDecoder() : null, readUTF8: function (buff, p, l) { var tdec = Typr._bin._tdec; return tdec && 0 == p && l == buff.length ? tdec.decode(buff) : Typr._bin.readASCII(buff, p, l); }, readBytes: function (buff, p, l) { for (var arr = [], i = 0; i < l; i++) arr.push(buff[p + i]); return arr; }, readASCIIArray: function (buff, p, l) { for (var s = [], i = 0; i < l; i++) s.push(String.fromCharCode(buff[p + i])); return s; } }, Typr._bin.t = { buff: new ArrayBuffer(8) }, Typr._bin.t.int8 = new Int8Array(Typr._bin.t.buff), Typr._bin.t.uint8 = new Uint8Array(Typr._bin.t.buff), Typr._bin.t.int16 = new Int16Array(Typr._bin.t.buff), Typr._bin.t.uint16 = new Uint16Array(Typr._bin.t.buff), Typr._bin.t.int32 = new Int32Array(Typr._bin.t.buff), Typr._bin.t.uint32 = new Uint32Array(Typr._bin.t.buff), Typr._lctf = {}, Typr._lctf.parse = function (data, offset, length, font, subt) { var bin = Typr._bin, obj = {}, offset0 = offset; bin.readFixed(data, offset), offset += 4; var offScriptList = bin.readUshort(data, offset); offset += 2; var offFeatureList = bin.readUshort(data, offset); offset += 2; var offLookupList = bin.readUshort(data, offset); return offset += 2, obj.scriptList = Typr._lctf.readScriptList(data, offset0 + offScriptList), obj.featureList = Typr._lctf.readFeatureList(data, offset0 + offFeatureList), obj.lookupList = Typr._lctf.readLookupList(data, offset0 + offLookupList, subt), obj; }, Typr._lctf.readLookupList = function (data, offset, subt) { var bin = Typr._bin, offset0 = offset, obj = [], count = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < count; i++) { var noff = bin.readUshort(data, offset); offset += 2; var lut = Typr._lctf.readLookupTable(data, offset0 + noff, subt); obj.push(lut); } return obj; }, Typr._lctf.readLookupTable = function (data, offset, subt) { var bin = Typr._bin, offset0 = offset, obj = { tabs: [] }; obj.ltype = bin.readUshort(data, offset), offset += 2, obj.flag = bin.readUshort(data, offset), offset += 2; var cnt = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < cnt; i++) { var noff = bin.readUshort(data, offset); offset += 2; var tab = subt(data, obj.ltype, offset0 + noff); obj.tabs.push(tab); } return obj; }, Typr._lctf.numOfOnes = function (n) { for (var num = 0, i = 0; i < 32; i++) 0 != (n >>> i & 1) && num++; return num; }, Typr._lctf.readClassDef = function (data, offset) { var bin = Typr._bin, obj = [], format = bin.readUshort(data, offset); if (offset += 2, 1 == format) { var startGlyph = bin.readUshort(data, offset); offset += 2; var glyphCount = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < glyphCount; i++) obj.push(startGlyph + i), obj.push(startGlyph + i), obj.push(bin.readUshort(data, offset)), offset += 2; } if (2 == format) { var count = bin.readUshort(data, offset); offset += 2; for (i = 0; i < count; i++) obj.push(bin.readUshort(data, offset)), offset += 2, obj.push(bin.readUshort(data, offset)), offset += 2, obj.push(bin.readUshort(data, offset)), offset += 2; } return obj; }, Typr._lctf.getInterval = function (tab, val) { for (var i = 0; i < tab.length; i += 3) { var start = tab[i], end = tab[i + 1]; if (tab[i + 2], start <= val && val <= end) return i; } return -1; }, Typr._lctf.readValueRecord = function (data, offset, valFmt) { var bin = Typr._bin, arr = []; return arr.push(1 & valFmt ? bin.readShort(data, offset) : 0), offset += 1 & valFmt ? 2 : 0, arr.push(2 & valFmt ? bin.readShort(data, offset) : 0), offset += 2 & valFmt ? 2 : 0, arr.push(4 & valFmt ? bin.readShort(data, offset) : 0), offset += 4 & valFmt ? 2 : 0, arr.push(8 & valFmt ? bin.readShort(data, offset) : 0), offset += 8 & valFmt ? 2 : 0, arr; }, Typr._lctf.readCoverage = function (data, offset) { var bin = Typr._bin, cvg = {}; cvg.fmt = bin.readUshort(data, offset), offset += 2; var count = bin.readUshort(data, offset); return offset += 2, 1 == cvg.fmt && (cvg.tab = bin.readUshorts(data, offset, count)), 2 == cvg.fmt && (cvg.tab = bin.readUshorts(data, offset, 3 * count)), cvg; }, Typr._lctf.coverageIndex = function (cvg, val) { var tab = cvg.tab; if (1 == cvg.fmt) return tab.indexOf(val); if (2 == cvg.fmt) { var ind = Typr._lctf.getInterval(tab, val); if (-1 != ind) return tab[ind + 2] + (val - tab[ind]); } return -1; }, Typr._lctf.readFeatureList = function (data, offset) { var bin = Typr._bin, offset0 = offset, obj = [], count = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < count; i++) { var tag = bin.readASCII(data, offset, 4); offset += 4; var noff = bin.readUshort(data, offset); offset += 2, obj.push({ tag: tag.trim(), tab: Typr._lctf.readFeatureTable(data, offset0 + noff) }); } return obj; }, Typr._lctf.readFeatureTable = function (data, offset) { var bin = Typr._bin; bin.readUshort(data, offset), offset += 2; var lookupCount = bin.readUshort(data, offset); offset += 2; for (var indices = [], i = 0; i < lookupCount; i++) indices.push(bin.readUshort(data, offset + 2 * i)); return indices; }, Typr._lctf.readScriptList = function (data, offset) { var bin = Typr._bin, offset0 = offset, obj = {}, count = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < count; i++) { var tag = bin.readASCII(data, offset, 4); offset += 4; var noff = bin.readUshort(data, offset); offset += 2, obj[tag.trim()] = Typr._lctf.readScriptTable(data, offset0 + noff); } return obj; }, Typr._lctf.readScriptTable = function (data, offset) { var bin = Typr._bin, offset0 = offset, obj = {}, defLangSysOff = bin.readUshort(data, offset); offset += 2, obj.default = Typr._lctf.readLangSysTable(data, offset0 + defLangSysOff); var langSysCount = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < langSysCount; i++) { var tag = bin.readASCII(data, offset, 4); offset += 4; var langSysOff = bin.readUshort(data, offset); offset += 2, obj[tag.trim()] = Typr._lctf.readLangSysTable(data, offset0 + langSysOff); } return obj; }, Typr._lctf.readLangSysTable = function (data, offset) { var bin = Typr._bin, obj = {}; bin.readUshort(data, offset), offset += 2, obj.reqFeature = bin.readUshort(data, offset), offset += 2; var featureCount = bin.readUshort(data, offset); return offset += 2, obj.features = bin.readUshorts(data, offset, featureCount), obj; }, Typr.CFF = {}, Typr.CFF.parse = function (data, offset, length) { var bin = Typr._bin; (data = new Uint8Array(data.buffer, offset, length))[offset = 0], data[++offset], data[++offset], data[++offset], offset++; var ninds = []; offset = Typr.CFF.readIndex(data, offset, ninds); for (var names = [], i = 0; i < ninds.length - 1; i++) names.push(bin.readASCII(data, offset + ninds[i], ninds[i + 1] - ninds[i])); offset += ninds[ninds.length - 1]; var tdinds = []; offset = Typr.CFF.readIndex(data, offset, tdinds); var topDicts = []; for (i = 0; i < tdinds.length - 1; i++) topDicts.push(Typr.CFF.readDict(data, offset + tdinds[i], offset + tdinds[i + 1])); offset += tdinds[tdinds.length - 1]; var topdict = topDicts[0], sinds = []; offset = Typr.CFF.readIndex(data, offset, sinds); var strings = []; for (i = 0; i < sinds.length - 1; i++) strings.push(bin.readASCII(data, offset + sinds[i], sinds[i + 1] - sinds[i])); if (offset += sinds[sinds.length - 1], Typr.CFF.readSubrs(data, offset, topdict), topdict.CharStrings) { offset = topdict.CharStrings; sinds = []; offset = Typr.CFF.readIndex(data, offset, sinds); var cstr = []; for (i = 0; i < sinds.length - 1; i++) cstr.push(bin.readBytes(data, offset + sinds[i], sinds[i + 1] - sinds[i])); topdict.CharStrings = cstr; } topdict.Encoding && (topdict.Encoding = Typr.CFF.readEncoding(data, topdict.Encoding, topdict.CharStrings.length)), topdict.charset && (topdict.charset = Typr.CFF.readCharset(data, topdict.charset, topdict.CharStrings.length)), topdict.Private && (offset = topdict.Private[1], topdict.Private = Typr.CFF.readDict(data, offset, offset + topdict.Private[0]), topdict.Private.Subrs && Typr.CFF.readSubrs(data, offset + topdict.Private.Subrs, topdict.Private)); var obj = {}; for (var p in topdict) -1 != ["FamilyName", "FullName", "Notice", "version", "Copyright"].indexOf(p) ? obj[p] = strings[topdict[p] - 426 + 35] : obj[p] = topdict[p]; return obj; }, Typr.CFF.readSubrs = function (data, offset, obj) { var bin = Typr._bin, gsubinds = []; offset = Typr.CFF.readIndex(data, offset, gsubinds); var bias, nSubrs = gsubinds.length; bias = nSubrs < 1240 ? 107 : nSubrs < 33900 ? 1131 : 32768, obj.Bias = bias, obj.Subrs = []; for (var i = 0; i < gsubinds.length - 1; i++) obj.Subrs.push(bin.readBytes(data, offset + gsubinds[i], gsubinds[i + 1] - gsubinds[i])); }, Typr.CFF.tableSE = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 0, 111, 112, 113, 114, 0, 115, 116, 117, 118, 119, 120, 121, 122, 0, 123, 0, 124, 125, 126, 127, 128, 129, 130, 131, 0, 132, 133, 0, 134, 135, 136, 137, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 138, 0, 139, 0, 0, 0, 0, 140, 141, 142, 143, 0, 0, 0, 0, 0, 144, 0, 0, 0, 145, 0, 0, 146, 147, 148, 149, 0, 0, 0, 0], Typr.CFF.glyphByUnicode = function (cff, code) { for (var i = 0; i < cff.charset.length; i++) if (cff.charset[i] == code) return i; return -1; }, Typr.CFF.glyphBySE = function (cff, charcode) { return charcode < 0 || charcode > 255 ? -1 : Typr.CFF.glyphByUnicode(cff, Typr.CFF.tableSE[charcode]); }, Typr.CFF.readEncoding = function (data, offset, num) { Typr._bin; var array = [".notdef"], format = data[offset]; if (offset++, 0 != format) throw "error: unknown encoding format: " + format; var nCodes = data[offset]; offset++; for (var i = 0; i < nCodes; i++) array.push(data[offset + i]); return array; }, Typr.CFF.readCharset = function (data, offset, num) { var bin = Typr._bin, charset = [".notdef"], format = data[offset]; if (offset++, 0 == format) for (var i = 0; i < num; i++) { var first = bin.readUshort(data, offset); offset += 2, charset.push(first); } else { if (1 != format && 2 != format) throw "error: format: " + format; for (; charset.length < num;) { first = bin.readUshort(data, offset); offset += 2; var nLeft = 0; 1 == format ? (nLeft = data[offset], offset++) : (nLeft = bin.readUshort(data, offset), offset += 2); for (i = 0; i <= nLeft; i++) charset.push(first), first++; } } return charset; }, Typr.CFF.readIndex = function (data, offset, inds) { var bin = Typr._bin, count = bin.readUshort(data, offset), offsize = data[offset += 2]; if (offset++, 1 == offsize) for (var i = 0; i < count + 1; i++) inds.push(data[offset + i]); else if (2 == offsize) for (i = 0; i < count + 1; i++) inds.push(bin.readUshort(data, offset + 2 * i)); else if (3 == offsize) for (i = 0; i < count + 1; i++) inds.push(16777215 & bin.readUint(data, offset + 3 * i - 1)); else if (0 != count) throw "unsupported offset size: " + offsize + ", count: " + count; return (offset += (count + 1) * offsize) - 1; }, Typr.CFF.getCharString = function (data, offset, o) { var bin = Typr._bin, b0 = data[offset], b1 = data[offset + 1]; data[offset + 2], data[offset + 3], data[offset + 4]; var vs = 1, op = null, val = null; b0 <= 20 && (op = b0, vs = 1), 12 == b0 && (op = 100 * b0 + b1, vs = 2), 21 <= b0 && b0 <= 27 && (op = b0, vs = 1), 28 == b0 && (val = bin.readShort(data, offset + 1), vs = 3), 29 <= b0 && b0 <= 31 && (op = b0, vs = 1), 32 <= b0 && b0 <= 246 && (val = b0 - 139, vs = 1), 247 <= b0 && b0 <= 250 && (val = 256 * (b0 - 247) + b1 + 108, vs = 2), 251 <= b0 && b0 <= 254 && (val = 256 * -(b0 - 251) - b1 - 108, vs = 2), 255 == b0 && (val = bin.readInt(data, offset + 1) / 65535, vs = 5), o.val = null != val ? val : "o" + op, o.size = vs; }, Typr.CFF.readCharString = function (data, offset, length) { for (var end = offset + length, bin = Typr._bin, arr = []; offset < end;) { var b0 = data[offset], b1 = data[offset + 1]; data[offset + 2], data[offset + 3], data[offset + 4]; var vs = 1, op = null, val = null; b0 <= 20 && (op = b0, vs = 1), 12 == b0 && (op = 100 * b0 + b1, vs = 2), 19 != b0 && 20 != b0 || (op = b0, vs = 2), 21 <= b0 && b0 <= 27 && (op = b0, vs = 1), 28 == b0 && (val = bin.readShort(data, offset + 1), vs = 3), 29 <= b0 && b0 <= 31 && (op = b0, vs = 1), 32 <= b0 && b0 <= 246 && (val = b0 - 139, vs = 1), 247 <= b0 && b0 <= 250 && (val = 256 * (b0 - 247) + b1 + 108, vs = 2), 251 <= b0 && b0 <= 254 && (val = 256 * -(b0 - 251) - b1 - 108, vs = 2), 255 == b0 && (val = bin.readInt(data, offset + 1) / 65535, vs = 5), arr.push(null != val ? val : "o" + op), offset += vs; } return arr; }, Typr.CFF.readDict = function (data, offset, end) { for (var bin = Typr._bin, dict = {}, carr = []; offset < end;) { var b0 = data[offset], b1 = data[offset + 1]; data[offset + 2], data[offset + 3], data[offset + 4]; var vs = 1, key = null, val = null; if (28 == b0 && (val = bin.readShort(data, offset + 1), vs = 3), 29 == b0 && (val = bin.readInt(data, offset + 1), vs = 5), 32 <= b0 && b0 <= 246 && (val = b0 - 139, vs = 1), 247 <= b0 && b0 <= 250 && (val = 256 * (b0 - 247) + b1 + 108, vs = 2), 251 <= b0 && b0 <= 254 && (val = 256 * -(b0 - 251) - b1 - 108, vs = 2), 255 == b0) throw val = bin.readInt(data, offset + 1) / 65535, vs = 5, "unknown number"; if (30 == b0) { var nibs = []; for (vs = 1; ;) { var b = data[offset + vs]; vs++; var nib0 = b >> 4, nib1 = 15 & b; if (15 != nib0 && nibs.push(nib0), 15 != nib1 && nibs.push(nib1), 15 == nib1) break; } for (var s = "", chars = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ".", "e", "e-", "reserved", "-", "endOfNumber"], i = 0; i < nibs.length; i++) s += chars[nibs[i]]; val = parseFloat(s); } if (b0 <= 21) { if (key = ["version", "Notice", "FullName", "FamilyName", "Weight", "FontBBox", "BlueValues", "OtherBlues", "FamilyBlues", "FamilyOtherBlues", "StdHW", "StdVW", "escape", "UniqueID", "XUID", "charset", "Encoding", "CharStrings", "Private", "Subrs", "defaultWidthX", "nominalWidthX"][b0], vs = 1, 12 == b0) key = ["Copyright", "isFixedPitch", "ItalicAngle", "UnderlinePosition", "UnderlineThickness", "PaintType", "CharstringType", "FontMatrix", "StrokeWidth", "BlueScale", "BlueShift", "BlueFuzz", "StemSnapH", "StemSnapV", "ForceBold", 0, 0, "LanguageGroup", "ExpansionFactor", "initialRandomSeed", "SyntheticBase", "PostScript", "BaseFontName", "BaseFontBlend", 0, 0, 0, 0, 0, 0, "ROS", "CIDFontVersion", "CIDFontRevision", "CIDFontType", "CIDCount", "UIDBase", "FDArray", "FDSelect", "FontName"][b1], vs = 2; } null != key ? (dict[key] = 1 == carr.length ? carr[0] : carr, carr = []) : carr.push(val), offset += vs; } return dict; }, Typr.cmap = {}, Typr.cmap.parse = function (data, offset, length) { data = new Uint8Array(data.buffer, offset, length), offset = 0; var bin = Typr._bin, obj = {}; bin.readUshort(data, offset), offset += 2; var numTables = bin.readUshort(data, offset); offset += 2; var offs = []; obj.tables = []; for (var i = 0; i < numTables; i++) { var platformID = bin.readUshort(data, offset); offset += 2; var encodingID = bin.readUshort(data, offset); offset += 2; var noffset = bin.readUint(data, offset); offset += 4; var id = "p" + platformID + "e" + encodingID, tind = offs.indexOf(noffset); if (-1 == tind) { var subt; tind = obj.tables.length, offs.push(noffset); var format = bin.readUshort(data, noffset); 0 == format ? subt = Typr.cmap.parse0(data, noffset) : 4 == format ? subt = Typr.cmap.parse4(data, noffset) : 6 == format ? subt = Typr.cmap.parse6(data, noffset) : 12 == format ? subt = Typr.cmap.parse12(data, noffset) : console.log("unknown format: " + format, platformID, encodingID, noffset), obj.tables.push(subt); } if (null != obj[id]) throw "multiple tables for one platform+encoding"; obj[id] = tind; } return obj; }, Typr.cmap.parse0 = function (data, offset) { var bin = Typr._bin, obj = {}; obj.format = bin.readUshort(data, offset), offset += 2; var len = bin.readUshort(data, offset); offset += 2, bin.readUshort(data, offset), offset += 2, obj.map = []; for (var i = 0; i < len - 6; i++) obj.map.push(data[offset + i]); return obj; }, Typr.cmap.parse4 = function (data, offset) { var bin = Typr._bin, offset0 = offset, obj = {}; obj.format = bin.readUshort(data, offset), offset += 2; var length = bin.readUshort(data, offset); offset += 2, bin.readUshort(data, offset), offset += 2; var segCountX2 = bin.readUshort(data, offset); offset += 2; var segCount = segCountX2 / 2; obj.searchRange = bin.readUshort(data, offset), offset += 2, obj.entrySelector = bin.readUshort(data, offset), offset += 2, obj.rangeShift = bin.readUshort(data, offset), offset += 2, obj.endCount = bin.readUshorts(data, offset, segCount), offset += 2 * segCount, offset += 2, obj.startCount = bin.readUshorts(data, offset, segCount), offset += 2 * segCount, obj.idDelta = []; for (var i = 0; i < segCount; i++) obj.idDelta.push(bin.readShort(data, offset)), offset += 2; for (obj.idRangeOffset = bin.readUshorts(data, offset, segCount), offset += 2 * segCount, obj.glyphIdArray = []; offset < offset0 + length;) obj.glyphIdArray.push(bin.readUshort(data, offset)), offset += 2; return obj; }, Typr.cmap.parse6 = function (data, offset) { var bin = Typr._bin, obj = {}; obj.format = bin.readUshort(data, offset), offset += 2, bin.readUshort(data, offset), offset += 2, bin.readUshort(data, offset), offset += 2, obj.firstCode = bin.readUshort(data, offset), offset += 2; var entryCount = bin.readUshort(data, offset); offset += 2, obj.glyphIdArray = []; for (var i = 0; i < entryCount; i++) obj.glyphIdArray.push(bin.readUshort(data, offset)), offset += 2; return obj; }, Typr.cmap.parse12 = function (data, offset) { var bin = Typr._bin, obj = {}; obj.format = bin.readUshort(data, offset), offset += 2, offset += 2, bin.readUint(data, offset), offset += 4, bin.readUint(data, offset), offset += 4; var nGroups = bin.readUint(data, offset); offset += 4, obj.groups = []; for (var i = 0; i < nGroups; i++) { var off = offset + 12 * i, startCharCode = bin.readUint(data, off + 0), endCharCode = bin.readUint(data, off + 4), startGlyphID = bin.readUint(data, off + 8); obj.groups.push([startCharCode, endCharCode, startGlyphID]); } return obj; }, Typr.glyf = {}, Typr.glyf.parse = function (data, offset, length, font) { for (var obj = [], g = 0; g < font.maxp.numGlyphs; g++) obj.push(null); return obj; }, Typr.glyf._parseGlyf = function (font, g) { var bin = Typr._bin, data = font._data, offset = Typr._tabOffset(data, "glyf") + font.loca[g]; if (font.loca[g] == font.loca[g + 1]) return null; var gl = {}; if (gl.noc = bin.readShort(data, offset), offset += 2, gl.xMin = bin.readShort(data, offset), offset += 2, gl.yMin = bin.readShort(data, offset), offset += 2, gl.xMax = bin.readShort(data, offset), offset += 2, gl.yMax = bin.readShort(data, offset), offset += 2, gl.xMin >= gl.xMax || gl.yMin >= gl.yMax) return null; if (gl.noc > 0) { gl.endPts = []; for (var i = 0; i < gl.noc; i++) gl.endPts.push(bin.readUshort(data, offset)), offset += 2; var instructionLength = bin.readUshort(data, offset); if (offset += 2, data.length - offset < instructionLength) return null; gl.instructions = bin.readBytes(data, offset, instructionLength), offset += instructionLength; var crdnum = gl.endPts[gl.noc - 1] + 1; gl.flags = []; for (i = 0; i < crdnum; i++) { var flag = data[offset]; if (offset++, gl.flags.push(flag), 0 != (8 & flag)) { var rep = data[offset]; offset++; for (var j = 0; j < rep; j++) gl.flags.push(flag), i++; } } gl.xs = []; for (i = 0; i < crdnum; i++) { var i8 = 0 != (2 & gl.flags[i]), same = 0 != (16 & gl.flags[i]); i8 ? (gl.xs.push(same ? data[offset] : -data[offset]), offset++) : same ? gl.xs.push(0) : (gl.xs.push(bin.readShort(data, offset)), offset += 2); } gl.ys = []; for (i = 0; i < crdnum; i++) { i8 = 0 != (4 & gl.flags[i]), same = 0 != (32 & gl.flags[i]); i8 ? (gl.ys.push(same ? data[offset] : -data[offset]), offset++) : same ? gl.ys.push(0) : (gl.ys.push(bin.readShort(data, offset)), offset += 2); } var x = 0, y = 0; for (i = 0; i < crdnum; i++) x += gl.xs[i], y += gl.ys[i], gl.xs[i] = x, gl.ys[i] = y; } else { var flags; gl.parts = []; do { flags = bin.readUshort(data, offset), offset += 2; var part = { m: { a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0 }, p1: -1, p2: -1 }; if (gl.parts.push(part), part.glyphIndex = bin.readUshort(data, offset), offset += 2, 1 & flags) { var arg1 = bin.readShort(data, offset); offset += 2; var arg2 = bin.readShort(data, offset); offset += 2; } else { arg1 = bin.readInt8(data, offset); offset++; arg2 = bin.readInt8(data, offset); offset++; } 2 & flags ? (part.m.tx = arg1, part.m.ty = arg2) : (part.p1 = arg1, part.p2 = arg2), 8 & flags ? (part.m.a = part.m.d = bin.readF2dot14(data, offset), offset += 2) : 64 & flags ? (part.m.a = bin.readF2dot14(data, offset), offset += 2, part.m.d = bin.readF2dot14(data, offset), offset += 2) : 128 & flags && (part.m.a = bin.readF2dot14(data, offset), offset += 2, part.m.b = bin.readF2dot14(data, offset), offset += 2, part.m.c = bin.readF2dot14(data, offset), offset += 2, part.m.d = bin.readF2dot14(data, offset), offset += 2); } while (32 & flags); if (256 & flags) { var numInstr = bin.readUshort(data, offset); offset += 2, gl.instr = []; for (i = 0; i < numInstr; i++) gl.instr.push(data[offset]), offset++; } } return gl; }, Typr.GPOS = {}, Typr.GPOS.parse = function (data, offset, length, font) { return Typr._lctf.parse(data, offset, length, font, Typr.GPOS.subt); }, Typr.GPOS.subt = function (data, ltype, offset) { if (2 != ltype) return null; var bin = Typr._bin, offset0 = offset, tab = {}; tab.format = bin.readUshort(data, offset), offset += 2; var covOff = bin.readUshort(data, offset); offset += 2, tab.coverage = Typr._lctf.readCoverage(data, covOff + offset0), tab.valFmt1 = bin.readUshort(data, offset), offset += 2, tab.valFmt2 = bin.readUshort(data, offset), offset += 2; var ones1 = Typr._lctf.numOfOnes(tab.valFmt1), ones2 = Typr._lctf.numOfOnes(tab.valFmt2); if (1 == tab.format) { tab.pairsets = []; var count = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < count; i++) { var psoff = bin.readUshort(data, offset); offset += 2, psoff += offset0; var pvcount = bin.readUshort(data, psoff); psoff += 2; for (var arr = [], j = 0; j < pvcount; j++) { var gid2 = bin.readUshort(data, psoff); psoff += 2, 0 != tab.valFmt1 && (value1 = Typr._lctf.readValueRecord(data, psoff, tab.valFmt1), psoff += 2 * ones1), 0 != tab.valFmt2 && (value2 = Typr._lctf.readValueRecord(data, psoff, tab.valFmt2), psoff += 2 * ones2), arr.push({ gid2, val1: value1, val2: value2 }); } tab.pairsets.push(arr); } } if (2 == tab.format) { var classDef1 = bin.readUshort(data, offset); offset += 2; var classDef2 = bin.readUshort(data, offset); offset += 2; var class1Count = bin.readUshort(data, offset); offset += 2; var class2Count = bin.readUshort(data, offset); offset += 2, tab.classDef1 = Typr._lctf.readClassDef(data, offset0 + classDef1), tab.classDef2 = Typr._lctf.readClassDef(data, offset0 + classDef2), tab.matrix = []; for (i = 0; i < class1Count; i++) { var row = []; for (j = 0; j < class2Count; j++) { var value1 = null, value2 = null; 0 != tab.valFmt1 && (value1 = Typr._lctf.readValueRecord(data, offset, tab.valFmt1), offset += 2 * ones1), 0 != tab.valFmt2 && (value2 = Typr._lctf.readValueRecord(data, offset, tab.valFmt2), offset += 2 * ones2), row.push({ val1: value1, val2: value2 }); } tab.matrix.push(row); } } return tab; }, Typr.GSUB = {}, Typr.GSUB.parse = function (data, offset, length, font) { return Typr._lctf.parse(data, offset, length, font, Typr.GSUB.subt); }, Typr.GSUB.subt = function (data, ltype, offset) { var bin = Typr._bin, offset0 = offset, tab = {}; if (1 != ltype && 4 != ltype && 5 != ltype) return null; tab.fmt = bin.readUshort(data, offset), offset += 2; var covOff = bin.readUshort(data, offset); if (offset += 2, tab.coverage = Typr._lctf.readCoverage(data, covOff + offset0), 1 == ltype) { if (1 == tab.fmt) tab.delta = bin.readShort(data, offset), offset += 2; else if (2 == tab.fmt) { var cnt = bin.readUshort(data, offset); offset += 2, tab.newg = bin.readUshorts(data, offset, cnt), offset += 2 * tab.newg.length; } } else if (4 == ltype) { tab.vals = []; cnt = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < cnt; i++) { var loff = bin.readUshort(data, offset); offset += 2, tab.vals.push(Typr.GSUB.readLigatureSet(data, offset0 + loff)); } } else if (5 == ltype) if (2 == tab.fmt) { var cDefOffset = bin.readUshort(data, offset); offset += 2, tab.cDef = Typr._lctf.readClassDef(data, offset0 + cDefOffset), tab.scset = []; var subClassSetCount = bin.readUshort(data, offset); offset += 2; for (i = 0; i < subClassSetCount; i++) { var scsOff = bin.readUshort(data, offset); offset += 2, tab.scset.push(0 == scsOff ? null : Typr.GSUB.readSubClassSet(data, offset0 + scsOff)); } } else console.log("unknown table format", tab.fmt); return tab; }, Typr.GSUB.readSubClassSet = function (data, offset) { var rUs = Typr._bin.readUshort, offset0 = offset, lset = [], cnt = rUs(data, offset); offset += 2; for (var i = 0; i < cnt; i++) { var loff = rUs(data, offset); offset += 2, lset.push(Typr.GSUB.readSubClassRule(data, offset0 + loff)); } return lset; }, Typr.GSUB.readSubClassRule = function (data, offset) { var rUs = Typr._bin.readUshort, rule = {}, gcount = rUs(data, offset), scount = rUs(data, offset += 2); offset += 2, rule.input = []; for (var i = 0; i < gcount - 1; i++) rule.input.push(rUs(data, offset)), offset += 2; return rule.substLookupRecords = Typr.GSUB.readSubstLookupRecords(data, offset, scount), rule; }, Typr.GSUB.readSubstLookupRecords = function (data, offset, cnt) { for (var rUs = Typr._bin.readUshort, out = [], i = 0; i < cnt; i++) out.push(rUs(data, offset), rUs(data, offset + 2)), offset += 4; return out; }, Typr.GSUB.readChainSubClassSet = function (data, offset) { var bin = Typr._bin, offset0 = offset, lset = [], cnt = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < cnt; i++) { var loff = bin.readUshort(data, offset); offset += 2, lset.push(Typr.GSUB.readChainSubClassRule(data, offset0 + loff)); } return lset; }, Typr.GSUB.readChainSubClassRule = function (data, offset) { for (var bin = Typr._bin, rule = {}, pps = ["backtrack", "input", "lookahead"], pi = 0; pi < pps.length; pi++) { var cnt = bin.readUshort(data, offset); offset += 2, 1 == pi && cnt--, rule[pps[pi]] = bin.readUshorts(data, offset, cnt), offset += 2 * rule[pps[pi]].length; } cnt = bin.readUshort(data, offset); return offset += 2, rule.subst = bin.readUshorts(data, offset, 2 * cnt), offset += 2 * rule.subst.length, rule; }, Typr.GSUB.readLigatureSet = function (data, offset) { var bin = Typr._bin, offset0 = offset, lset = [], lcnt = bin.readUshort(data, offset); offset += 2; for (var j = 0; j < lcnt; j++) { var loff = bin.readUshort(data, offset); offset += 2, lset.push(Typr.GSUB.readLigature(data, offset0 + loff)); } return lset; }, Typr.GSUB.readLigature = function (data, offset) { var bin = Typr._bin, lig = { chain: [] }; lig.nglyph = bin.readUshort(data, offset), offset += 2; var ccnt = bin.readUshort(data, offset); offset += 2; for (var k = 0; k < ccnt - 1; k++) lig.chain.push(bin.readUshort(data, offset)), offset += 2; return lig; }, Typr.head = {}, Typr.head.parse = function (data, offset, length) { var bin = Typr._bin, obj = {}; return bin.readFixed(data, offset), offset += 4, obj.fontRevision = bin.readFixed(data, offset), offset += 4, bin.readUint(data, offset), offset += 4, bin.readUint(data, offset), offset += 4, obj.flags = bin.readUshort(data, offset), offset += 2, obj.unitsPerEm = bin.readUshort(data, offset), offset += 2, obj.created = bin.readUint64(data, offset), offset += 8, obj.modified = bin.readUint64(data, offset), offset += 8, obj.xMin = bin.readShort(data, offset), offset += 2, obj.yMin = bin.readShort(data, offset), offset += 2, obj.xMax = bin.readShort(data, offset), offset += 2, obj.yMax = bin.readShort(data, offset), offset += 2, obj.macStyle = bin.readUshort(data, offset), offset += 2, obj.lowestRecPPEM = bin.readUshort(data, offset), offset += 2, obj.fontDirectionHint = bin.readShort(data, offset), offset += 2, obj.indexToLocFormat = bin.readShort(data, offset), offset += 2, obj.glyphDataFormat = bin.readShort(data, offset), offset += 2, obj; }, Typr.hhea = {}, Typr.hhea.parse = function (data, offset, length) { var bin = Typr._bin, obj = {}; return bin.readFixed(data, offset), offset += 4, obj.ascender = bin.readShort(data, offset), offset += 2, obj.descender = bin.readShort(data, offset), offset += 2, obj.lineGap = bin.readShort(data, offset), offset += 2, obj.advanceWidthMax = bin.readUshort(data, offset), offset += 2, obj.minLeftSideBearing = bin.readShort(data, offset), offset += 2, obj.minRightSideBearing = bin.readShort(data, offset), offset += 2, obj.xMaxExtent = bin.readShort(data, offset), offset += 2, obj.caretSlopeRise = bin.readShort(data, offset), offset += 2, obj.caretSlopeRun = bin.readShort(data, offset), offset += 2, obj.caretOffset = bin.readShort(data, offset), offset += 2, offset += 8, obj.metricDataFormat = bin.readShort(data, offset), offset += 2, obj.numberOfHMetrics = bin.readUshort(data, offset), offset += 2, obj; }, Typr.hmtx = {}, Typr.hmtx.parse = function (data, offset, length, font) { for (var bin = Typr._bin, obj = { aWidth: [], lsBearing: [] }, aw = 0, lsb = 0, i = 0; i < font.maxp.numGlyphs; i++) i < font.hhea.numberOfHMetrics && (aw = bin.readUshort(data, offset), offset += 2, lsb = bin.readShort(data, offset), offset += 2), obj.aWidth.push(aw), obj.lsBearing.push(lsb); return obj; }, Typr.kern = {}, Typr.kern.parse = function (data, offset, length, font) { var bin = Typr._bin, version = bin.readUshort(data, offset); if (offset += 2, 1 == version) return Typr.kern.parseV1(data, offset - 2, length, font); var nTables = bin.readUshort(data, offset); offset += 2; for (var map = { glyph1: [], rval: [] }, i = 0; i < nTables; i++) { offset += 2; length = bin.readUshort(data, offset); offset += 2; var coverage = bin.readUshort(data, offset); offset += 2; var format = coverage >>> 8; if (0 != (format &= 15)) throw "unknown kern table format: " + format; offset = Typr.kern.readFormat0(data, offset, map); } return map; }, Typr.kern.parseV1 = function (data, offset, length, font) { var bin = Typr._bin; bin.readFixed(data, offset), offset += 4; var nTables = bin.readUint(data, offset); offset += 4; for (var map = { glyph1: [], rval: [] }, i = 0; i < nTables; i++) { bin.readUint(data, offset), offset += 4; var coverage = bin.readUshort(data, offset); offset += 2, bin.readUshort(data, offset), offset += 2; var format = coverage >>> 8; if (0 != (format &= 15)) throw "unknown kern table format: " + format; offset = Typr.kern.readFormat0(data, offset, map); } return map; }, Typr.kern.readFormat0 = function (data, offset, map) { var bin = Typr._bin, pleft = -1, nPairs = bin.readUshort(data, offset); offset += 2, bin.readUshort(data, offset), offset += 2, bin.readUshort(data, offset), offset += 2, bin.readUshort(data, offset), offset += 2; for (var j = 0; j < nPairs; j++) { var left = bin.readUshort(data, offset); offset += 2; var right = bin.readUshort(data, offset); offset += 2; var value = bin.readShort(data, offset); offset += 2, left != pleft && (map.glyph1.push(left), map.rval.push({ glyph2: [], vals: [] })); var rval = map.rval[map.rval.length - 1]; rval.glyph2.push(right), rval.vals.push(value), pleft = left; } return offset; }, Typr.loca = {}, Typr.loca.parse = function (data, offset, length, font) { var bin = Typr._bin, obj = [], ver = font.head.indexToLocFormat, len = font.maxp.numGlyphs + 1; if (0 == ver) for (var i = 0; i < len; i++) obj.push(bin.readUshort(data, offset + (i << 1)) << 1); if (1 == ver) for (i = 0; i < len; i++) obj.push(bin.readUint(data, offset + (i << 2))); return obj; }, Typr.maxp = {}, Typr.maxp.parse = function (data, offset, length) { var bin = Typr._bin, obj = {}, ver = bin.readUint(data, offset); return offset += 4, obj.numGlyphs = bin.readUshort(data, offset), offset += 2, 65536 == ver && (obj.maxPoints = bin.readUshort(data, offset), offset += 2, obj.maxContours = bin.readUshort(data, offset), offset += 2, obj.maxCompositePoints = bin.readUshort(data, offset), offset += 2, obj.maxCompositeContours = bin.readUshort(data, offset), offset += 2, obj.maxZones = bin.readUshort(data, offset), offset += 2, obj.maxTwilightPoints = bin.readUshort(data, offset), offset += 2, obj.maxStorage = bin.readUshort(data, offset), offset += 2, obj.maxFunctionDefs = bin.readUshort(data, offset), offset += 2, obj.maxInstructionDefs = bin.readUshort(data, offset), offset += 2, obj.maxStackElements = bin.readUshort(data, offset), offset += 2, obj.maxSizeOfInstructions = bin.readUshort(data, offset), offset += 2, obj.maxComponentElements = bin.readUshort(data, offset), offset += 2, obj.maxComponentDepth = bin.readUshort(data, offset), offset += 2), obj; }, Typr.name = {}, Typr.name.parse = function (data, offset, length) { var bin = Typr._bin, obj = {}; bin.readUshort(data, offset), offset += 2; var count = bin.readUshort(data, offset); offset += 2, bin.readUshort(data, offset); for (var tname, offset0 = offset += 2, i = 0; i < count; i++) { var platformID = bin.readUshort(data, offset); offset += 2; var encodingID = bin.readUshort(data, offset); offset += 2; var languageID = bin.readUshort(data, offset); offset += 2; var nameID = bin.readUshort(data, offset); offset += 2; length = bin.readUshort(data, offset); offset += 2; var noffset = bin.readUshort(data, offset); offset += 2; var plat = "p" + platformID; null == obj[plat] && (obj[plat] = {}); var str, cname = ["copyright", "fontFamily", "fontSubfamily", "ID", "fullName", "version", "postScriptName", "trademark", "manufacturer", "designer", "description", "urlVendor", "urlDesigner", "licence", "licenceURL", "---", "typoFamilyName", "typoSubfamilyName", "compatibleFull", "sampleText", "postScriptCID", "wwsFamilyName", "wwsSubfamilyName", "lightPalette", "darkPalette"][nameID], soff = offset0 + 12 * count + noffset; if (0 == platformID) str = bin.readUnicode(data, soff, length / 2); else if (3 == platformID && 0 == encodingID) str = bin.readUnicode(data, soff, length / 2); else if (0 == encodingID) str = bin.readASCII(data, soff, length); else if (1 == encodingID) str = bin.readUnicode(data, soff, length / 2); else if (3 == encodingID) str = bin.readUnicode(data, soff, length / 2); else { if (1 != platformID) throw "unknown encoding " + encodingID + ", platformID: " + platformID; str = bin.readASCII(data, soff, length), console.log("reading unknown MAC encoding " + encodingID + " as ASCII"); } obj[plat][cname] = str, obj[plat]._lang = languageID; } for (var p in obj) if (null != obj[p].postScriptName && 1033 == obj[p]._lang) return obj[p]; for (var p in obj) if (null != obj[p].postScriptName && 3084 == obj[p]._lang) return obj[p]; for (var p in obj) if (null != obj[p].postScriptName) return obj[p]; for (var p in obj) { tname = p; break; } return console.log("returning name table with languageID " + obj[tname]._lang), obj[tname]; }, Typr["OS/2"] = {}, Typr["OS/2"].parse = function (data, offset, length) { var ver = Typr._bin.readUshort(data, offset); offset += 2; var obj = {}; if (0 == ver) Typr["OS/2"].version0(data, offset, obj); else if (1 == ver) Typr["OS/2"].version1(data, offset, obj); else if (2 == ver || 3 == ver || 4 == ver) Typr["OS/2"].version2(data, offset, obj); else { if (5 != ver) throw "unknown OS/2 table version: " + ver; Typr["OS/2"].version5(data, offset, obj); } return obj; }, Typr["OS/2"].version0 = function (data, offset, obj) { var bin = Typr._bin; return obj.xAvgCharWidth = bin.readShort(data, offset), offset += 2, obj.usWeightClass = bin.readUshort(data, offset), offset += 2, obj.usWidthClass = bin.readUshort(data, offset), offset += 2, obj.fsType = bin.readUshort(data, offset), offset += 2, obj.ySubscriptXSize = bin.readShort(data, offset), offset += 2, obj.ySubscriptYSize = bin.readShort(data, offset), offset += 2, obj.ySubscriptXOffset = bin.readShort(data, offset), offset += 2, obj.ySubscriptYOffset = bin.readShort(data, offset), offset += 2, obj.ySuperscriptXSize = bin.readShort(data, offset), offset += 2, obj.ySuperscriptYSize = bin.readShort(data, offset), offset += 2, obj.ySuperscriptXOffset = bin.readShort(data, offset), offset += 2, obj.ySuperscriptYOffset = bin.readShort(data, offset), offset += 2, obj.yStrikeoutSize = bin.readShort(data, offset), offset += 2, obj.yStrikeoutPosition = bin.readShort(data, offset), offset += 2, obj.sFamilyClass = bin.readShort(data, offset), offset += 2, obj.panose = bin.readBytes(data, offset, 10), offset += 10, obj.ulUnicodeRange1 = bin.readUint(data, offset), offset += 4, obj.ulUnicodeRange2 = bin.readUint(data, offset), offset += 4, obj.ulUnicodeRange3 = bin.readUint(data, offset), offset += 4, obj.ulUnicodeRange4 = bin.readUint(data, offset), offset += 4, obj.achVendID = [bin.readInt8(data, offset), bin.readInt8(data, offset + 1), bin.readInt8(data, offset + 2), bin.readInt8(data, offset + 3)], offset += 4, obj.fsSelection = bin.readUshort(data, offset), offset += 2, obj.usFirstCharIndex = bin.readUshort(data, offset), offset += 2, obj.usLastCharIndex = bin.readUshort(data, offset), offset += 2, obj.sTypoAscender = bin.readShort(data, offset), offset += 2, obj.sTypoDescender = bin.readShort(data, offset), offset += 2, obj.sTypoLineGap = bin.readShort(data, offset), offset += 2, obj.usWinAscent = bin.readUshort(data, offset), offset += 2, obj.usWinDescent = bin.readUshort(data, offset), offset += 2; }, Typr["OS/2"].version1 = function (data, offset, obj) { var bin = Typr._bin; return offset = Typr["OS/2"].version0(data, offset, obj), obj.ulCodePageRange1 = bin.readUint(data, offset), offset += 4, obj.ulCodePageRange2 = bin.readUint(data, offset), offset += 4; }, Typr["OS/2"].version2 = function (data, offset, obj) { var bin = Typr._bin; return offset = Typr["OS/2"].version1(data, offset, obj), obj.sxHeight = bin.readShort(data, offset), offset += 2, obj.sCapHeight = bin.readShort(data, offset), offset += 2, obj.usDefault = bin.readUshort(data, offset), offset += 2, obj.usBreak = bin.readUshort(data, offset), offset += 2, obj.usMaxContext = bin.readUshort(data, offset), offset += 2; }, Typr["OS/2"].version5 = function (data, offset, obj) { var bin = Typr._bin; return offset = Typr["OS/2"].version2(data, offset, obj), obj.usLowerOpticalPointSize = bin.readUshort(data, offset), offset += 2, obj.usUpperOpticalPointSize = bin.readUshort(data, offset), offset += 2; }, Typr.post = {}, Typr.post.parse = function (data, offset, length) { var bin = Typr._bin, obj = {}; return obj.version = bin.readFixed(data, offset), offset += 4, obj.italicAngle = bin.readFixed(data, offset), offset += 4, obj.underlinePosition = bin.readShort(data, offset), offset += 2, obj.underlineThickness = bin.readShort(data, offset), offset += 2, obj; }, Typr.SVG = {}, Typr.SVG.parse = function (data, offset, length) { var bin = Typr._bin, obj = { entries: [] }, offset0 = offset; bin.readUshort(data, offset), offset += 2; var svgDocIndexOffset = bin.readUint(data, offset); offset += 4, bin.readUint(data, offset), offset += 4, offset = svgDocIndexOffset + offset0; var numEntries = bin.readUshort(data, offset); offset += 2; for (var i = 0; i < numEntries; i++) { var startGlyphID = bin.readUshort(data, offset); offset += 2; var endGlyphID = bin.readUshort(data, offset); offset += 2; var svgDocOffset = bin.readUint(data, offset); offset += 4; var svgDocLength = bin.readUint(data, offset); offset += 4; for (var sbuf = new Uint8Array(data.buffer, offset0 + svgDocOffset + svgDocIndexOffset, svgDocLength), svg = bin.readUTF8(sbuf, 0, sbuf.length), f = startGlyphID; f <= endGlyphID; f++) obj.entries[f] = svg; } return obj; }, Typr.SVG.toPath = function (str) { var pth = { cmds: [], crds: [] }; if (null == str) return pth; for (var svg = new DOMParser().parseFromString(str, "image/svg+xml").firstChild; "svg" != svg.tagName;) svg = svg.nextSibling; var vb = svg.getAttribute("viewBox"); vb = vb ? vb.trim().split(" ").map(parseFloat) : [0, 0, 1e3, 1e3], Typr.SVG._toPath(svg.children, pth); for (var i = 0; i < pth.crds.length; i += 2) { var x = pth.crds[i], y = pth.crds[i + 1]; x -= vb[0], y = -(y -= vb[1]), pth.crds[i] = x, pth.crds[i + 1] = y; } return pth; }, Typr.SVG._toPath = function (nds, pth, fill) { for (var ni = 0; ni < nds.length; ni++) { var nd = nds[ni], tn = nd.tagName, cfl = nd.getAttribute("fill"); if (null == cfl && (cfl = fill), "g" == tn) Typr.SVG._toPath(nd.children, pth, cfl); else if ("path" == tn) { pth.cmds.push(cfl || "#000000"); var d = nd.getAttribute("d"), toks = Typr.SVG._tokens(d); Typr.SVG._toksToPath(toks, pth), pth.cmds.push("X"); } else "defs" == tn || console.log(tn, nd); } }, Typr.SVG._tokens = function (d) { for (var ts = [], off = 0, rn = false, cn = ""; off < d.length;) { var cc = d.charCodeAt(off), ch = d.charAt(off); off++; var isNum = 48 <= cc && cc <= 57 || "." == ch || "-" == ch; rn ? "-" == ch ? (ts.push(parseFloat(cn)), cn = ch) : isNum ? cn += ch : (ts.push(parseFloat(cn)), "," != ch && " " != ch && ts.push(ch), rn = false) : isNum ? (cn = ch, rn = true) : "," != ch && " " != ch && ts.push(ch); } return rn && ts.push(parseFloat(cn)), ts; }, Typr.SVG._toksToPath = function (ts, pth) { for (var i = 0, x = 0, y = 0, ox = 0, oy = 0, pc = { M: 2, L: 2, H: 1, V: 1, S: 4, C: 6 }, cmds = pth.cmds, crds = pth.crds; i < ts.length;) { var cmd = ts[i]; if (i++, "z" == cmd) cmds.push("Z"), x = ox, y = oy; else for (var cmu = cmd.toUpperCase(), ps = pc[cmu], reps = Typr.SVG._reps(ts, i, ps), j = 0; j < reps; j++) { var xi = 0, yi = 0; if (cmd != cmu && (xi = x, yi = y), "M" == cmu) x = xi + ts[i++], y = yi + ts[i++], cmds.push("M"), crds.push(x, y), ox = x, oy = y; else if ("L" == cmu) x = xi + ts[i++], y = yi + ts[i++], cmds.push("L"), crds.push(x, y); else if ("H" == cmu) x = xi + ts[i++], cmds.push("L"), crds.push(x, y); else if ("V" == cmu) y = yi + ts[i++], cmds.push("L"), crds.push(x, y); else if ("C" == cmu) { var x1 = xi + ts[i++], y1 = yi + ts[i++], x2 = xi + ts[i++], y2 = yi + ts[i++], x3 = xi + ts[i++], y3 = yi + ts[i++]; cmds.push("C"), crds.push(x1, y1, x2, y2, x3, y3), x = x3, y = y3; } else if ("S" == cmu) { var co = Math.max(crds.length - 4, 0); x1 = x + x - crds[co], y1 = y + y - crds[co + 1], x2 = xi + ts[i++], y2 = yi + ts[i++], x3 = xi + ts[i++], y3 = yi + ts[i++]; cmds.push("C"), crds.push(x1, y1, x2, y2, x3, y3), x = x3, y = y3; } else console.log("Unknown SVG command " + cmd); } } }, Typr.SVG._reps = function (ts, off, ps) { for (var i = off; i < ts.length && "string" != typeof ts[i];) i += ps; return (i - off) / ps; }, null == Typr && (Typr = {}), null == Typr.U && (Typr.U = {}), Typr.U.codeToGlyph = function (font, code) { var cmap = font.cmap, tind = -1; if (null != cmap.p0e4 ? tind = cmap.p0e4 : null != cmap.p3e1 ? tind = cmap.p3e1 : null != cmap.p1e0 && (tind = cmap.p1e0), -1 == tind) throw "no familiar platform and encoding!"; var tab = cmap.tables[tind]; if (0 == tab.format) return code >= tab.map.length ? 0 : tab.map[code]; if (4 == tab.format) { for (var sind = -1, i = 0; i < tab.endCount.length; i++) if (code <= tab.endCount[i]) { sind = i; break; } if (-1 == sind) return 0; if (tab.startCount[sind] > code) return 0; return 65535 & (0 != tab.idRangeOffset[sind] ? tab.glyphIdArray[code - tab.startCount[sind] + (tab.idRangeOffset[sind] >> 1) - (tab.idRangeOffset.length - sind)] : code + tab.idDelta[sind]); } if (12 == tab.format) { if (code > tab.groups[tab.groups.length - 1][1]) return 0; for (i = 0; i < tab.groups.length; i++) { var grp = tab.groups[i]; if (grp[0] <= code && code <= grp[1]) return grp[2] + (code - grp[0]); } return 0; } throw "unknown cmap table format " + tab.format; }, Typr.U.glyphToPath = function (font, gid) { var path = { cmds: [], crds: [] }; if (font.SVG && font.SVG.entries[gid]) { var p = font.SVG.entries[gid]; return null == p ? path : ("string" == typeof p && (p = Typr.SVG.toPath(p), font.SVG.entries[gid] = p), p); } if (font.CFF) { var state = { x: 0, y: 0, stack: [], nStems: 0, haveWidth: false, width: font.CFF.Private ? font.CFF.Private.defaultWidthX : 0, open: false }; Typr.U._drawCFF(font.CFF.CharStrings[gid], state, font.CFF, path); } else font.glyf && Typr.U._drawGlyf(gid, font, path); return path; }, Typr.U._drawGlyf = function (gid, font, path) { var gl = font.glyf[gid]; null == gl && (gl = font.glyf[gid] = Typr.glyf._parseGlyf(font, gid)), null != gl && (gl.noc > -1 ? Typr.U._simpleGlyph(gl, path) : Typr.U._compoGlyph(gl, font, path)); }, Typr.U._simpleGlyph = function (gl, p) { for (var c = 0; c < gl.noc; c++) { for (var i0 = 0 == c ? 0 : gl.endPts[c - 1] + 1, il = gl.endPts[c], i = i0; i <= il; i++) { var pr = i == i0 ? il : i - 1, nx = i == il ? i0 : i + 1, onCurve = 1 & gl.flags[i], prOnCurve = 1 & gl.flags[pr], nxOnCurve = 1 & gl.flags[nx], x = gl.xs[i], y = gl.ys[i]; if (i == i0) if (onCurve) { if (!prOnCurve) { Typr.U.P.moveTo(p, x, y); continue; } Typr.U.P.moveTo(p, gl.xs[pr], gl.ys[pr]); } else prOnCurve ? Typr.U.P.moveTo(p, gl.xs[pr], gl.ys[pr]) : Typr.U.P.moveTo(p, (gl.xs[pr] + x) / 2, (gl.ys[pr] + y) / 2); onCurve ? prOnCurve && Typr.U.P.lineTo(p, x, y) : nxOnCurve ? Typr.U.P.qcurveTo(p, x, y, gl.xs[nx], gl.ys[nx]) : Typr.U.P.qcurveTo(p, x, y, (x + gl.xs[nx]) / 2, (y + gl.ys[nx]) / 2); } Typr.U.P.closePath(p); } }, Typr.U._compoGlyph = function (gl, font, p) { for (var j = 0; j < gl.parts.length; j++) { var path = { cmds: [], crds: [] }, prt = gl.parts[j]; Typr.U._drawGlyf(prt.glyphIndex, font, path); for (var m = prt.m, i = 0; i < path.crds.length; i += 2) { var x = path.crds[i], y = path.crds[i + 1]; p.crds.push(x * m.a + y * m.b + m.tx), p.crds.push(x * m.c + y * m.d + m.ty); } for (i = 0; i < path.cmds.length; i++) p.cmds.push(path.cmds[i]); } }, Typr.U._getGlyphClass = function (g, cd) { var intr = Typr._lctf.getInterval(cd, g); return -1 == intr ? 0 : cd[intr + 2]; }, Typr.U.getPairAdjustment = function (font, g1, g2) { if (font.GPOS) { for (var ltab = null, i = 0; i < font.GPOS.featureList.length; i++) { var fl = font.GPOS.featureList[i]; if ("kern" == fl.tag) for (var j = 0; j < fl.tab.length; j++) 2 == font.GPOS.lookupList[fl.tab[j]].ltype && (ltab = font.GPOS.lookupList[fl.tab[j]]); } if (ltab) for (i = 0; i < ltab.tabs.length; i++) { var tab = ltab.tabs[i], ind = Typr._lctf.coverageIndex(tab.coverage, g1); if (-1 != ind) { if (1 == tab.format) { var right = tab.pairsets[ind]; for (j = 0; j < right.length; j++) right[j].gid2 == g2 && (adj = right[j]); if (null == adj) continue; } else if (2 == tab.format) var c1 = Typr.U._getGlyphClass(g1, tab.classDef1), c2 = Typr.U._getGlyphClass(g2, tab.classDef2), adj = tab.matrix[c1][c2]; return adj.val1[2]; } } } if (font.kern) { var ind1 = font.kern.glyph1.indexOf(g1); if (-1 != ind1) { var ind2 = font.kern.rval[ind1].glyph2.indexOf(g2); if (-1 != ind2) return font.kern.rval[ind1].vals[ind2]; } } return 0; }, Typr.U.stringToGlyphs = function (font, str) { for (var gls = [], i = 0; i < str.length; i++) { var cc = str.codePointAt(i); cc > 65535 && i++, gls.push(Typr.U.codeToGlyph(font, cc)); } var gsub = font.GSUB; if (null == gsub) return gls; for (var llist = gsub.lookupList, flist = gsub.featureList, wsep = '\n " ,.:;!?() ،', R = "آأؤإاةدذرزوٱٲٳٵٶٷڈډڊڋڌڍڎڏڐڑڒړڔڕږڗژڙۀۃۄۅۆۇۈۉۊۋۍۏےۓەۮۯܐܕܖܗܘܙܞܨܪܬܯݍݙݚݛݫݬݱݳݴݸݹࡀࡆࡇࡉࡔࡧࡩࡪࢪࢫࢬࢮࢱࢲࢹૅેૉ૊૎૏ૐ૑૒૝ૡ૤૯஁ஃ஄அஉ஌எஏ஑னப஫஬", ci = 0; ci < gls.length; ci++) { var gl = gls[ci], slft = 0 == ci || -1 != wsep.indexOf(str[ci - 1]), srgt = ci == gls.length - 1 || -1 != wsep.indexOf(str[ci + 1]); slft || -1 == R.indexOf(str[ci - 1]) || (slft = true), srgt || -1 == R.indexOf(str[ci]) || (srgt = true), srgt || -1 == "ꡲ્૗".indexOf(str[ci + 1]) || (srgt = true), slft || -1 == "ꡲ્૗".indexOf(str[ci]) || (slft = true); var feat = null; feat = slft ? srgt ? "isol" : "init" : srgt ? "fina" : "medi"; for (var fi = 0; fi < flist.length; fi++) if (flist[fi].tag == feat) for (var ti = 0; ti < flist[fi].tab.length; ti++) { 1 == (tab = llist[flist[fi].tab[ti]]).ltype && Typr.U._applyType1(gls, ci, tab); } } var cligs = ["rlig", "liga", "mset"]; for (ci = 0; ci < gls.length; ci++) { gl = gls[ci]; var rlim = Math.min(3, gls.length - ci - 1); for (fi = 0; fi < flist.length; fi++) { var fl = flist[fi]; if (-1 != cligs.indexOf(fl.tag)) { for (ti = 0; ti < fl.tab.length; ti++) for (var tab = llist[fl.tab[ti]], j = 0; j < tab.tabs.length; j++) if (null != tab.tabs[j]) { var ind = Typr._lctf.coverageIndex(tab.tabs[j].coverage, gl); if (-1 != ind) { if (4 == tab.ltype) for (var vals = tab.tabs[j].vals[ind], k = 0; k < vals.length; k++) { var lig = vals[k], rl = lig.chain.length; if (!(rl > rlim)) { for (var good = true, l = 0; l < rl; l++) lig.chain[l] != gls[ci + (1 + l)] && (good = false); if (good) { gls[ci] = lig.nglyph; for (l = 0; l < rl; l++) gls[ci + l + 1] = -1; } } } else if (5 == tab.ltype) { var ltab = tab.tabs[j]; if (2 != ltab.fmt) continue; var cind = Typr._lctf.getInterval(ltab.cDef, gl), cls = ltab.cDef[cind + 2], scs = ltab.scset[cls]; for (i = 0; i < scs.length; i++) { var sc = scs[i], inp = sc.input; if (!(inp.length > rlim)) { for (good = true, l = 0; l < inp.length; l++) { var cind2 = Typr._lctf.getInterval(ltab.cDef, gls[ci + 1 + l]); if (-1 == cind && ltab.cDef[cind2 + 2] != inp[l]) { good = false; break; } } if (good) { var lrs = sc.substLookupRecords; for (k = 0; k < lrs.length; k += 2) lrs[k], lrs[k + 1]; } } } } } } } } } return gls; }, Typr.U._applyType1 = function (gls, ci, tab) { for (var gl = gls[ci], j = 0; j < tab.tabs.length; j++) { var ttab = tab.tabs[j], ind = Typr._lctf.coverageIndex(ttab.coverage, gl); -1 != ind && (1 == ttab.fmt ? gls[ci] = gls[ci] + ttab.delta : gls[ci] = ttab.newg[ind]); } }, Typr.U.glyphsToPath = function (font, gls, clr) { for (var tpath = { cmds: [], crds: [] }, x = 0, i = 0; i < gls.length; i++) { var gid = gls[i]; if (-1 != gid) { for (var gid2 = i < gls.length - 1 && -1 != gls[i + 1] ? gls[i + 1] : 0, path = Typr.U.glyphToPath(font, gid), j = 0; j < path.crds.length; j += 2) tpath.crds.push(path.crds[j] + x), tpath.crds.push(path.crds[j + 1]); clr && tpath.cmds.push(clr); for (j = 0; j < path.cmds.length; j++) tpath.cmds.push(path.cmds[j]); clr && tpath.cmds.push("X"), x += font.hmtx.aWidth[gid], i < gls.length - 1 && (x += Typr.U.getPairAdjustment(font, gid, gid2)); } } return tpath; }, Typr.U.pathToSVG = function (path, prec) { null == prec && (prec = 5); for (var out = [], co = 0, lmap = { M: 2, L: 2, Q: 4, C: 6 }, i = 0; i < path.cmds.length; i++) { var cmd = path.cmds[i], cn = co + (lmap[cmd] ? lmap[cmd] : 0); for (out.push(cmd); co < cn;) { var c = path.crds[co++]; out.push(parseFloat(c.toFixed(prec)) + (co == cn ? "" : " ")); } } return out.join(""); }, Typr.U.pathToContext = function (path, ctx) { for (var c = 0, crds = path.crds, j = 0; j < path.cmds.length; j++) { var cmd = path.cmds[j]; "M" == cmd ? (ctx.moveTo(crds[c], crds[c + 1]), c += 2) : "L" == cmd ? (ctx.lineTo(crds[c], crds[c + 1]), c += 2) : "C" == cmd ? (ctx.bezierCurveTo(crds[c], crds[c + 1], crds[c + 2], crds[c + 3], crds[c + 4], crds[c + 5]), c += 6) : "Q" == cmd ? (ctx.quadraticCurveTo(crds[c], crds[c + 1], crds[c + 2], crds[c + 3]), c += 4) : "#" == cmd.charAt(0) ? (ctx.beginPath(), ctx.fillStyle = cmd) : "Z" == cmd ? ctx.closePath() : "X" == cmd && ctx.fill(); } }, Typr.U.P = {}, Typr.U.P.moveTo = function (p, x, y) { p.cmds.push("M"), p.crds.push(x, y); }, Typr.U.P.lineTo = function (p, x, y) { p.cmds.push("L"), p.crds.push(x, y); }, Typr.U.P.curveTo = function (p, a, b, c, d, e, f) { p.cmds.push("C"), p.crds.push(a, b, c, d, e, f); }, Typr.U.P.qcurveTo = function (p, a, b, c, d) { p.cmds.push("Q"), p.crds.push(a, b, c, d); }, Typr.U.P.closePath = function (p) { p.cmds.push("Z"); }, Typr.U._drawCFF = function (cmds, state, font, p) { for (var stack = state.stack, nStems = state.nStems, haveWidth = state.haveWidth, width = state.width, open = state.open, i = 0, x = state.x, y = state.y, c1x = 0, c1y = 0, c2x = 0, c2y = 0, c3x = 0, c3y = 0, c4x = 0, c4y = 0, jpx = 0, jpy = 0, o = { val: 0, size: 0 }; i < cmds.length;) { Typr.CFF.getCharString(cmds, i, o); var v = o.val; if (i += o.size, "o1" == v || "o18" == v) stack.length % 2 != 0 && !haveWidth && (width = stack.shift() + font.Private.nominalWidthX), nStems += stack.length >> 1, stack.length = 0, haveWidth = true; else if ("o3" == v || "o23" == v) { stack.length % 2 != 0 && !haveWidth && (width = stack.shift() + font.Private.nominalWidthX), nStems += stack.length >> 1, stack.length = 0, haveWidth = true; } else if ("o4" == v) stack.length > 1 && !haveWidth && (width = stack.shift() + font.Private.nominalWidthX, haveWidth = true), open && Typr.U.P.closePath(p), y += stack.pop(), Typr.U.P.moveTo(p, x, y), open = true; else if ("o5" == v) for (; stack.length > 0;) x += stack.shift(), y += stack.shift(), Typr.U.P.lineTo(p, x, y); else if ("o6" == v || "o7" == v) for (var count = stack.length, isX = "o6" == v, j = 0; j < count; j++) { var sval = stack.shift(); isX ? x += sval : y += sval, isX = !isX, Typr.U.P.lineTo(p, x, y); } else if ("o8" == v || "o24" == v) { count = stack.length; for (var index = 0; index + 6 <= count;) c1x = x + stack.shift(), c1y = y + stack.shift(), c2x = c1x + stack.shift(), c2y = c1y + stack.shift(), x = c2x + stack.shift(), y = c2y + stack.shift(), Typr.U.P.curveTo(p, c1x, c1y, c2x, c2y, x, y), index += 6; "o24" == v && (x += stack.shift(), y += stack.shift(), Typr.U.P.lineTo(p, x, y)); } else { if ("o11" == v) break; if ("o1234" == v || "o1235" == v || "o1236" == v || "o1237" == v) "o1234" == v && (c1y = y, c2x = (c1x = x + stack.shift()) + stack.shift(), jpy = c2y = c1y + stack.shift(), c3y = c2y, c4y = y, x = (c4x = (c3x = (jpx = c2x + stack.shift()) + stack.shift()) + stack.shift()) + stack.shift(), Typr.U.P.curveTo(p, c1x, c1y, c2x, c2y, jpx, jpy), Typr.U.P.curveTo(p, c3x, c3y, c4x, c4y, x, y)), "o1235" == v && (c1x = x + stack.shift(), c1y = y + stack.shift(), c2x = c1x + stack.shift(), c2y = c1y + stack.shift(), jpx = c2x + stack.shift(), jpy = c2y + stack.shift(), c3x = jpx + stack.shift(), c3y = jpy + stack.shift(), c4x = c3x + stack.shift(), c4y = c3y + stack.shift(), x = c4x + stack.shift(), y = c4y + stack.shift(), stack.shift(), Typr.U.P.curveTo(p, c1x, c1y, c2x, c2y, jpx, jpy), Typr.U.P.curveTo(p, c3x, c3y, c4x, c4y, x, y)), "o1236" == v && (c1x = x + stack.shift(), c1y = y + stack.shift(), c2x = c1x + stack.shift(), jpy = c2y = c1y + stack.shift(), c3y = c2y, c4x = (c3x = (jpx = c2x + stack.shift()) + stack.shift()) + stack.shift(), c4y = c3y + stack.shift(), x = c4x + stack.shift(), Typr.U.P.curveTo(p, c1x, c1y, c2x, c2y, jpx, jpy), Typr.U.P.curveTo(p, c3x, c3y, c4x, c4y, x, y)), "o1237" == v && (c1x = x + stack.shift(), c1y = y + stack.shift(), c2x = c1x + stack.shift(), c2y = c1y + stack.shift(), jpx = c2x + stack.shift(), jpy = c2y + stack.shift(), c3x = jpx + stack.shift(), c3y = jpy + stack.shift(), c4x = c3x + stack.shift(), c4y = c3y + stack.shift(), Math.abs(c4x - x) > Math.abs(c4y - y) ? x = c4x + stack.shift() : y = c4y + stack.shift(), Typr.U.P.curveTo(p, c1x, c1y, c2x, c2y, jpx, jpy), Typr.U.P.curveTo(p, c3x, c3y, c4x, c4y, x, y)); else if ("o14" == v) { if (stack.length > 0 && !haveWidth && (width = stack.shift() + font.nominalWidthX, haveWidth = true), 4 == stack.length) { var adx = stack.shift(), ady = stack.shift(), bchar = stack.shift(), achar = stack.shift(), bind = Typr.CFF.glyphBySE(font, bchar), aind = Typr.CFF.glyphBySE(font, achar); Typr.U._drawCFF(font.CharStrings[bind], state, font, p), state.x = adx, state.y = ady, Typr.U._drawCFF(font.CharStrings[aind], state, font, p); } open && (Typr.U.P.closePath(p), open = false); } else if ("o19" == v || "o20" == v) { stack.length % 2 != 0 && !haveWidth && (width = stack.shift() + font.Private.nominalWidthX), nStems += stack.length >> 1, stack.length = 0, haveWidth = true, i += nStems + 7 >> 3; } else if ("o21" == v) stack.length > 2 && !haveWidth && (width = stack.shift() + font.Private.nominalWidthX, haveWidth = true), y += stack.pop(), x += stack.pop(), open && Typr.U.P.closePath(p), Typr.U.P.moveTo(p, x, y), open = true; else if ("o22" == v) stack.length > 1 && !haveWidth && (width = stack.shift() + font.Private.nominalWidthX, haveWidth = true), x += stack.pop(), open && Typr.U.P.closePath(p), Typr.U.P.moveTo(p, x, y), open = true; else if ("o25" == v) { for (; stack.length > 6;) x += stack.shift(), y += stack.shift(), Typr.U.P.lineTo(p, x, y); c1x = x + stack.shift(), c1y = y + stack.shift(), c2x = c1x + stack.shift(), c2y = c1y + stack.shift(), x = c2x + stack.shift(), y = c2y + stack.shift(), Typr.U.P.curveTo(p, c1x, c1y, c2x, c2y, x, y); } else if ("o26" == v) for (stack.length % 2 && (x += stack.shift()); stack.length > 0;) c1x = x, c1y = y + stack.shift(), x = c2x = c1x + stack.shift(), y = (c2y = c1y + stack.shift()) + stack.shift(), Typr.U.P.curveTo(p, c1x, c1y, c2x, c2y, x, y); else if ("o27" == v) for (stack.length % 2 && (y += stack.shift()); stack.length > 0;) c1y = y, c2x = (c1x = x + stack.shift()) + stack.shift(), c2y = c1y + stack.shift(), x = c2x + stack.shift(), y = c2y, Typr.U.P.curveTo(p, c1x, c1y, c2x, c2y, x, y); else if ("o10" == v || "o29" == v) { var obj = "o10" == v ? font.Private : font; if (0 == stack.length) console.log("error: empty stack"); else { var ind = stack.pop(), subr = obj.Subrs[ind + obj.Bias]; state.x = x, state.y = y, state.nStems = nStems, state.haveWidth = haveWidth, state.width = width, state.open = open, Typr.U._drawCFF(subr, state, font, p), x = state.x, y = state.y, nStems = state.nStems, haveWidth = state.haveWidth, width = state.width, open = state.open; } } else if ("o30" == v || "o31" == v) { var count1 = stack.length, alternate = (index = 0, "o31" == v); for (index += count1 - (count = -3 & count1); index < count;) alternate ? (c1y = y, c2x = (c1x = x + stack.shift()) + stack.shift(), y = (c2y = c1y + stack.shift()) + stack.shift(), count - index == 5 ? (x = c2x + stack.shift(), index++) : x = c2x, alternate = false) : (c1x = x, c1y = y + stack.shift(), c2x = c1x + stack.shift(), c2y = c1y + stack.shift(), x = c2x + stack.shift(), count - index == 5 ? (y = c2y + stack.shift(), index++) : y = c2y, alternate = true), Typr.U.P.curveTo(p, c1x, c1y, c2x, c2y, x, y), index += 4; } else { if ("o" == (v + "").charAt(0)) throw console.log("Unknown operation: " + v, cmds), v; stack.push(v); } } } state.x = x, state.y = y, state.nStems = nStems, state.haveWidth = haveWidth, state.width = width, state.open = open; }; const Typr$1 = getDefaultExportFromCjs(Typr), questionType = { "单选题": "0", "多选题": "1", "填空题": "2", "判断题": "3", "简答题": "4", "名词解释": "5", "论述题": "6", "计算题": "7" }, log = (data, type = "info") => { var _a; const style = `color: ${{ info: "orange", success: "green", error: "red" }[type]}; font-weight: bold;`; if (Array.isArray(data) || "object" == typeof data ? console.log(`%c${JSON.stringify(data, null, 2)}`, style) : console.log(`%c${data}`, style), defaultConfig$1.debugger) { const caller = (((_a = new Error().stack) == null ? void 0 : _a.split("\n")) || [])[2].trim(); console.log(`${caller}`); } }, sleep = (time) => new Promise((resolve) => { setTimeout(() => { resolve(); }, 1e3 * time); }), waitIframeLoaded = (iframe) => new Promise((resolve) => { // 兜底:15 秒仍未加载完成则放行,避免永久挂起(叠加运行锁后会锁死整个循环) let _timer = null, _done = false; const _settle = () => { if (_done) return; _done = true; if (_timer) { clearInterval(_timer); _timer = null; } try { resolve(); } catch (e) { } }; const _guard = setTimeout(_settle, 15000); _timer = setInterval(() => { var _a; if (!iframe) { clearTimeout(_guard); _settle(); return; } iframe.contentDocument && "complete" === ((_a = iframe.contentDocument) == null ? void 0 : _a.readyState) ? (clearTimeout(_guard), _settle()) : iframe.addEventListener("load", () => { clearTimeout(_guard); _settle(); }, { once: true }); }, 100); }), waitElementLoaded = (iframeWindow, selector) => new Promise((resolve) => { // 兜底:15 秒仍未出现则放行,避免永久挂起(锁在 finally 里,挂起会导致整锁不释放) let _timer = null, _done = false; const _settle = () => { if (_done) return; _done = true; if (_timer) { clearInterval(_timer); _timer = null; } try { resolve(); } catch (e) { } }; const _guard = setTimeout(_settle, 15000); _timer = setInterval(() => { try { if (iframeWindow && iframeWindow.document && iframeWindow.document.querySelector(selector)) { clearTimeout(_guard); _settle(); } } catch (e) { clearTimeout(_guard); _settle(); } }, 100); }), removeHtml = (html) => null == html ? "" : html.replace(/<((?!img|sub|sup|br)[^>]+)>/g, "").replace(/ /g, " ").replace(/\s+/g, " ").replace(//g, "\n").replace(//g, '').trim(), cl = (str) => str.replace(/^【.*?】\s*/, "").replace(/\s*(\d+\.\d+分)$/, ""), getQuestion = (type, html) => { let questionHtml, questionText, questionTypeId, optionHtml, tokenHtml, workType, optionText, index; switch (type) { case "1": return workType = "zj", questionHtml = Array.from(html.querySelectorAll(".clearfix .fontLabel")), questionText = cl(removeHtml(questionHtml[0].innerHTML)), questionTypeId = html.querySelectorAll("input[name^=answertype]")[0].value, optionHtml = Array.from(html.querySelectorAll("ul")[0].querySelectorAll("li .after")), tokenHtml = html.innerHTML, optionText = [], optionHtml.forEach(function (item) { optionText.push(removeHtml(item.innerHTML)); }), { question: questionText, options: optionText, type: questionTypeId, questionData: tokenHtml, workType }; case "2": workType = "zy", questionHtml = Array.from(html.querySelectorAll(".mark_name")), index = questionHtml[0].innerHTML.indexOf(""), questionText = cl(removeHtml(questionHtml[0].innerHTML.substring(index + 7))), questionHtml[0].getElementsByTagName("span")[0].innerHTML.replace("(", "").replace(")", "").split(",")[0], questionTypeId = html.querySelectorAll("input[name^=answertype]")[0].value, optionHtml = Array.from(html.querySelectorAll(".answer_p")), tokenHtml = html.innerHTML, optionText = []; for (let i = 0; i < optionHtml.length; i++) optionText.push(removeHtml(optionHtml[i].innerHTML)); return { question: questionText, options: optionText, type: questionTypeId, questionData: tokenHtml, workType }; case "3": workType = "ks", questionHtml = Array.from(document.getElementsByClassName("mark_name colorDeep")), index = questionHtml[0].innerHTML.indexOf(""), questionText = cl(removeHtml(questionHtml[0].innerHTML.substring(index + 7))), questionHtml[0].getElementsByTagName("span")[0].innerHTML.replace("(", "").replace(")", "").split(",")[0], questionTypeId = document.querySelectorAll("input[name^=type]")[1].value, optionHtml = Array.from(document.getElementsByClassName("answer_p")), tokenHtml = document.getElementsByClassName("mark_table")[0].innerHTML, optionText = []; for (let i = 0; i < optionHtml.length; i++) optionText.push(removeHtml(optionHtml[i].innerHTML)); return { question: questionText, options: optionText, type: questionTypeId, questionData: tokenHtml, workType }; } }, decode = (iframeWindow) => { var _a; const styleElements = iframeWindow.document.querySelectorAll("style"); let tipElement = null; if (styleElements.forEach((styleElement) => { var _a2; -1 !== ((_a2 = styleElement.textContent) == null ? void 0 : _a2.indexOf("font-cxsecret")) && (tipElement = styleElement); }), !tipElement) return; const fontMatch = (_a = tipElement.textContent) == null ? void 0 : _a.match(/base64,([\w\W]+?)'/); if (!fontMatch) return; const fontData = ((base64) => { const decodedData = atob(base64), array = new Uint8Array(decodedData.length); for (let i = 0; i < decodedData.length; i++) array[i] = decodedData.charCodeAt(i); return array; })(fontMatch[1]), font = Typr$1.parse(fontData), table = JSON.parse(_GM_getResourceText("ttf")); let text = {}; for (let i = 19968; i < 40870; i++) { let t = Typr$1.U.codeToGlyph(font, i); t && (t = Typr$1.U.glyphToPath(font, t), t = md5(JSON.stringify(t)).slice(24), text[i] = table[t]); } iframeWindow.document.querySelectorAll(".font-cxsecret").forEach((fontElement) => { let html = fontElement.innerHTML; Object.keys(text).forEach((key) => { const regex = new RegExp(String.fromCharCode(key), "g"); html = html.replace(regex, String.fromCharCode(text[key])); }), fontElement.innerHTML = html, fontElement.classList.remove("font-cxsecret"); }); }, getAnswers = async (questionData, windowz = _unsafeWindow) => { const cfg = getConfig(); // 全局超时只是「备用项」:单题库自带 timeout 时以它为准 const banks = tikuRuntimeBanks(cfg.banks).map(function (b) { if (!b) return b; if (b.timeout) return b; if (!cfg.tikuTimeout || cfg.tikuTimeout === "0") return b; return Object.assign({}, b, { timeout: Number(cfg.tikuTimeout) || 8 }); }); // 命中判定用调用期闭包:matchAnswer 定义在本函数之后,不能在模块初始化时引用(TDZ) const isUsable = (arr) => { if (!arr || !arr.length) return false; const type = String(questionData.type == null ? "" : questionData.type); if (type === "0" || type === "1") { const opts = questionData.options || []; return opts.length > 0 && matchAnswer(arr, opts).length > 0; } if (type === "3") { const opts = questionData.options || []; // 判断题:只要答案是明确的正确/错误就算可用,不依赖选项是否已渲染 const hasJudge = arr.some(function (x) { return !!normalizeJudgeToken(x); }); if (hasJudge) return true; return opts.length > 0 && matchAnswer(arr, opts).length > 0; } return arr.some(x => !!x && !/付费题库|暂无答案/.test(String(x)) && String(x) !== "略"); }; const results = await TIKU_KIT.ask(questionData, { mode: cfg.tikuMode, banks, isUsable, onResult: (r) => { if (r.status === "hit") log(`[题库] ${r.form}: ${JSON.stringify(r.answer).slice(0, 60)} (${r.ms}ms)`, "success"); } }); return results; }, fillAnswer = (answer, questionData, html, iframeWindow) => { answer = answer.filter((item) => item.answer.length > 0), console.log(answer); for (let i = 0; i < answer.length; i++) { if ("string" == typeof answer[i].answer) { if (-1 !== answer[i].answer.indexOf("付费题库") || -1 !== answer[i].answer.indexOf("暂无答案") || "略" == answer[i].answer) continue; answer[i].answer = [answer[i].answer]; } let tmp = setAnswer(answer[i].answer, questionData, html, iframeWindow); if (tmp) return tmp; } return false; }, setAnswer = (answer, questionData, html, iframeWindow) => { switch (questionData.type) { case "0": case "1": const matchArr = matchAnswer(answer, questionData.options); matchArr.length > 0 && clearCurrent(html, iframeWindow); for (var i = 0; i < matchArr.length; i++) console.log($$1(html).find("li").eq(matchArr[i]), matchArr[i]), $$1(html).find("ul:eq(0) li :radio,:checkbox,textarea").eq(matchArr[i]).click(), $$1(html).find(".answerBg").eq(matchArr[i]).click(), $$1(html).find("li").eq(matchArr[i]).click(); return matchArr.length > 0 && answer; case "3": { clearCurrent(html, iframeWindow); if (answer instanceof Array) answer = answer[0]; const side = normalizeJudgeToken(answer); const wantTrue = side === "T" || !!String(answer).match(/(^|,)(True|true|正确|是|对|√|T|ri)(,|$)/); const wantFalse = side === "F" || !!String(answer).match(/(^|,)(False|false|错误|否|错|×|F|wr)(,|$)/); $$1(html).find("ul:eq(0) li :radio,:checkbox,textarea").each(function () { const v = String($$1(this).val()); const label = String($$1(this).closest("li").text() || $$1(this).parent().text() || ""); const lside = judgeOptionSide(label); if (v === "true" || v === "1" || lside === "T") { if (wantTrue) $$1(this).click(); } else if (v === "false" || v === "0" || lside === "F") { if (wantFalse) $$1(this).click(); } }); $$1(html).find(".answerBg").each(function () { const d = $$1(this).find(".num_option").attr("data"); const label = String($$1(this).text() || ""); const lside = judgeOptionSide(label); if (d === "true" || lside === "T") { if (wantTrue) $$1(this).click(); } else if (d === "false" || lside === "F") { if (wantFalse) $$1(this).click(); } }); if (!$$1(html).find("ul:eq(0) li :radio,:checkbox,textarea").is(":checked") && !$$1(html).find(".check_answer").length && !$$1(html).find(".check_answer_dx").length) { const optTexts = []; $$1(html).find("ul:eq(0) li").each(function () { optTexts.push($$1(this).text()); }); const m = matchAnswer([answer], optTexts); if (m.length) { m.forEach((idx) => { $$1(html).find("ul:eq(0) li").eq(idx).find(":radio,:checkbox,textarea").click(); $$1(html).find("ul:eq(0) li").eq(idx).click(); $$1(html).find(".answerBg").eq(idx).click(); }); } } return (!!($$1(html).find("ul:eq(0) li :radio,:checkbox,textarea").is(":checked") || $$1(html).find(".check_answer").length > 0 || $$1(html).find(".check_answer_dx").length > 0)) && answer; } case "2": case "9": case "4": case "5": case "6": case "7": const _tas = $$1(html).find("textarea"); if (_tas.length === 0) return false; clearCurrent(html, iframeWindow); if (_tas.length === answer.length) { _tas.each(function (index) { iframeWindow.UE.getEditor($$1(this).attr("name")).ready(function () { this.setContent(answer[index].replace(/第.空:/g, "")); }); }); } else if (_tas.length === 1) { // 只有一个textarea,把多个答案用顿号拼接填入 const joined = answer.map(a => a.replace(/第.空:/g, "")).join("、"); iframeWindow.UE.getEditor(_tas.eq(0).attr("name")).ready(function () { this.setContent(joined); }); } else { // textarea数量与答案数量不一致,按实际textarea数量填写 _tas.each(function (index) { const val = (answer[index] || answer[answer.length - 1]).replace(/第.空:/g, ""); iframeWindow.UE.getEditor($$1(this).attr("name")).ready(function () { this.setContent(val); }); }); } return answer; default: return false; } }, normalizeJudgeToken = (s) => { if (s == null) return ""; let t = String(s); t = t.replace(/<[^>]+>/g, "").replace(/ /g, " ").trim(); t = t.replace(/^[A-Da-d][.、.\s]+/, "").trim(); t = t.replace(/[。..!!??\s]+$/, ""); const pos = /^(正确|对|是|√|✓|T|t|True|true|TRUE|ri|right|yes|Y)$/; const neg = /^(错误|错|否|×|✗|X|x|F|f|False|false|FALSE|wr|wrong|no|N)$/; if (pos.test(t)) return "T"; if (neg.test(t)) return "F"; if (/正确|对(?![的定])|^是|靠谱|成立/.test(t) && !/不正确|不对|错误|错$/.test(t)) return "T"; if (/错误|不对|错$|不成立|假/.test(t)) return "F"; return ""; }, judgeOptionSide = (opt) => { if (opt == null) return ""; let t = String(opt).replace(/<[^>]+>/g, "").replace(/ /g, " ").trim(); t = t.replace(/^[A-Da-d][.、.\s]+/, "").trim(); return normalizeJudgeToken(t); }, normalizeMatchText = (s) => String(s == null ? "" : removeHtml(String(s))) // CX_AUDIT_TIKU_V1:sub/sup 是排版标签,标签内的字母必须保留,但标签名本身不能被当成正文 .replace(/<\/?(?:sub|sup)\b[^>]*>/gi, "") .replace(/ /g, " ") .replace(/^[A-Za-z]\s*[.、.,,::))\]】]\s*/, "") .replace(/[\s ]+/g, "").replace(/[。.\.,,、;;::!!??"'“”‘’()()【】\[\]<>《》]/g, "") .toLowerCase(), letterIndices = (text, options) => { const t = String(text || "").trim().toUpperCase(); if (!/^[A-Z]+$/.test(t)) return []; const out = []; for (const ch of t) { const idx = ch.charCodeAt(0) - 65; if (idx >= 0 && idx < options.length) out.push(idx); } return out; }, matchAnswer = (answer, options) => { if (!options || !options.length) return []; let ans = []; if (answer instanceof Array) ans = answer.filter(x => null != x).map(x => removeHtml(String(x))); else if ("string" == typeof answer) ans = [removeHtml(cl(answer))]; ans = ans.filter(x => String(x).trim()); if (!ans.length) return []; // CX_AUDIT_TIKU_V1:逐项匹配,而不是逐级「任一命中即整体返回」。 // 后者在多选题里会让其余项永远走不到低级匹配(如 A 项全等命中 → 直接 return,B 项被丢弃)。 const normOptions = options.map(normalizeMatchText); const hits = []; const addHit = (idx) => { if (idx >= 0 && idx < options.length && hits.indexOf(idx) < 0) hits.push(idx); }; for (const a of ans) { const raw = String(a).trim(); if (!raw) continue; // 1) 字母答案("A" / "ABC" / "A,B")直接映射下标 const letters = raw.replace(/[,,、;;\s]/g, "").trim().toUpperCase(); if (/^[A-Z]+$/.test(letters)) { const mapped = letterIndices(letters, options); if (mapped.length) { mapped.forEach(addHit); continue; } } const na = normalizeMatchText(raw); if (!na) continue; // 2) 归一化后全等(容忍 A. 前缀、全半角、标点、空白差异) let matchedThis = false; for (let j = 0; j < normOptions.length; j++) { if (normOptions[j] && na === normOptions[j]) { addHit(j); matchedThis = true; } } if (matchedThis) continue; // 3) 模糊匹配:该项取最相似选项(≥0.72 且优于次优,或近乎全等) let best = -1, bestScore = 0, second = 0; for (let j = 0; j < normOptions.length; j++) { const score = tikuSimilarity(na, normOptions[j]); if (score > bestScore) { second = bestScore; bestScore = score; best = j; } else if (score > second) second = score; } if (best >= 0 && bestScore >= 0.72 && (bestScore - second >= 0.05 || bestScore >= 0.95)) { addHit(best); continue; } } // 全部项匹配完毕才返回:多项命中一次拿全 if (hits.length) return hits; // 4) 判断题兜底 var judgeHits = []; for (var i2 = 0; i2 < ans.length; i2++) { var side = normalizeJudgeToken(ans[i2]); if (!side) continue; for (var j2 = 0; j2 < options.length; j2++) { var oside = judgeOptionSide(options[j2]); if (oside && oside === side && judgeHits.indexOf(j2) < 0) judgeHits.push(j2); } if (judgeHits.length === 0 && options.length === 2) { var t0 = normalizeJudgeToken(options[0]), t1 = normalizeJudgeToken(options[1]); if (t0 === "T" && t1 === "F") judgeHits.push(side === "T" ? 0 : 1); else if (t0 === "F" && t1 === "T") judgeHits.push(side === "T" ? 1 : 0); } } return judgeHits; }, clearCurrent = (item, iframeWindow) => { $$1(item).find(".answerBg, .textDIV, .eidtDiv").each(function () { ($$1(this).find(".check_answer").length || $$1(this).find(".check_answer_dx").length) && $$1(this).click(); }), $$1(item).find("textarea").each(function () { iframeWindow.UE.getEditor($$1(this).attr("name")).ready(function () { this.setContent(""); }); }), $$1(item).find(":radio, :checkbox").prop("checked", false), $$1(item).find("textarea").each(function () { iframeWindow.UE.getEditor($$1(this).attr("name")).ready(function () { this.setContent(""); }); }); }, useAskStore = () => askUI; const __isTopFrame = (() => { try { if (typeof window !== "undefined" && window && window.top && window === window.top) return true; } catch (e) { } try { if (_unsafeWindow && _unsafeWindow.top && _unsafeWindow === _unsafeWindow.top) return true; } catch (e) { } try { return !!(document && document.querySelector && document.querySelector("#iframe, .main, .studentstudy") && window === window.top); } catch (e) { } return false; })(); if (!__isTopFrame) { return; } const askUI = vue.reactive({ dialogVisible: true, askTab: "first", // CX_TAB_FIX_V1: 'first' 运行框 / 'second' 运行日志 paused: false, panelLeft: null, panelTop: null, count: 0, // CX_AUDIT_SESSION_V1:面板会话号。reset() 推进它,用于让「上一章还没跑完的答题循环」 // 在下一个 await 处立刻收手,避免把旧题单写进刚被清空的面板。 session: 0, llmBusy: null, // LLM 思考状态快照,由 LLM_BUSY 控制器写入 tick: 0, questionList: [], task: { name: "暂未加载", work: { questionList: [], inx: 0, viewInx: 0, follow: true }, video: [], log: [], status: "", jobs: [] }, reset() { this.session = (this.session || 0) + 1; // 作废所有在途的答题循环 this.task.name = "暂未加载"; this.task.work = { questionList: [], inx: 0, viewInx: 0, follow: true }; this.task.video = []; this.task.status = ""; this.task.jobs = []; this.llmBusy = null; this.count = 0; // 保持用户的收起/展开状态:切换任务不再强制弹出面板 this.tick = this.tick + 1; }, select(index) { const q = this.task.work.questionList[index]; if (!q) return; q.selected = true; this.task.work.viewInx = index; this.task.work.follow = (index === this.task.work.inx); this.tick++; try { q.dom && q.dom.scrollIntoView && q.dom.scrollIntoView({ block: "center" }); } catch (e) { } }, followLatest() { this.task.work.viewInx = this.task.work.inx; this.task.work.follow = true; this.tick++; }, togglePause() { this.paused = !this.paused; this.task.status = this.paused ? "已暂停" : ""; this.tick++; }, async waitIfPaused() { while (this.paused) { await new Promise((r) => setTimeout(r, 300)); } }, get(index) { return this.task.work.questionList[index]; }, insert(question) { const list = this.task.work.questionList.slice(); list.push(question); this.task.work.questionList = list; this.task.work.inx = list.length - 1; if (this.task.work.follow !== false) this.task.work.viewInx = this.task.work.inx; this.tick = this.tick + 1; }, patch(index, fields) { const q = this.task.work.questionList[index]; if (q && fields) { Object.keys(fields).forEach((k) => { q[k] = fields[k]; }); this.tick++; } }, update(index, question) { this.task.work.questionList[index] = question; this.tick++; }, log(msg, level = "info") { if (this.task.log.length > 20) this.task.log.shift(); this.task.log.push({ time: (new Date()).toLocaleTimeString(), msg, type: level }); this.tick++; }, msg(msg) { this.task.status = msg; this.tick++; } }); // LLM 忙碌状态控制器:快照写入 askUI 触发重渲染,同时直写 DOM 兜底 // ===== 任务点识别辅助 ===== // 原实现只用 .ans-job-icon,课件类任务点 DOM 结构不同就完全扫不到; // 这里加多级兜底:图标找不到时退回任务点容器。 function __collectJobItems(doc) { try { const icons = Array.from(doc.querySelectorAll(".ans-job-icon")); if (icons.length) return icons.map(el => ({ node: el, host: el.parentElement || el })); // 兜底:超星的任务点容器(不同版本 class 名不一致,用属性选择器兜住) const hosts = Array.from(doc.querySelectorAll(".ans-attach-ct, .ans-job, [class*='ans-job']")) // 状态标记节点本身不是任务点,只是挂在任务点上的 class .filter(h => !/ans-job-(finished|unfinish|icon)\b/.test(String((h && h.className) || ""))); // 去重:只保留最外层,避免同一任务点被多次处理 const picked = hosts.filter(h => !hosts.some(o => o !== h && o.contains(h))); return picked.map(el => ({ node: el, host: el })); } catch (e) { return []; } } // 完成态判定:class 可能挂在父层甚至祖父层,向上找 4 层 function __isJobFinished(host) { try { let n = host; for (let d = 0; d < 4 && n; d++, n = n.parentElement) { if (n.classList && n.classList.contains("ans-job-finished")) return true; } } catch (e) { } return false; } // 通用课件兜底:滚动到任务点、点开、等待完成标记出现 // 返回 true 表示「已尽力处理」(无论平台是否真的记为完成),false 表示处理过程出错 async function __handleGenericJob(host, logFn) { try { try { host.scrollIntoView && host.scrollIntoView({ block: "center" }); } catch (e) { } try { host.click && host.click(); } catch (e) { } // 若内部有 iframe,等它加载后尝试滚动到底(文档类课件的常见完成方式) const ifr = host.querySelector && host.querySelector("iframe"); if (ifr) { try { await new Promise(r => setTimeout(r, 1500)); const w = ifr.contentWindow; if (w && w.document) { const pv = w.document.querySelector("#panView"); if (pv && pv.contentWindow && pv.contentWindow.document) { pv.contentWindow.scrollTo(0, pv.contentWindow.document.body.scrollHeight); } else if (w.document.body) { w.scrollTo(0, w.document.body.scrollHeight); } } } catch (e) { } } // 等待完成标记最多 20 秒 for (let i = 0; i < 20; i++) { if (__isJobFinished(host)) return true; await new Promise(r => setTimeout(r, 1000)); } return true; // 超时也算「已尽力」,不阻塞后续章节 } catch (e) { return false; } } const LLM_BUSY = createLlmBusyTracker({ onChange: () => { try { const snap = LLM_BUSY.snapshot(); askUI.llmBusy = snap; askUI.tick = askUI.tick + 1; LLM_BUSY_PAINT(snap); } catch (e) { } } }); // 直接改 DOM 上的节点,绕过 Vue 的静态节点优化 // 注意:面板挂在 top.document(见 ensureAskPanel 的 hostDoc),不是当前 iframe 的 document function LLM_BUSY_PAINT(snap) { try { if (!snap || !snap.active) return; let doc = document; try { if (typeof _unsafeWindow !== "undefined" && _unsafeWindow && _unsafeWindow.top && _unsafeWindow.top.document) doc = _unsafeWindow.top.document; } catch (e2) { } const el = doc.getElementById("cx-llm-elapsed"); if (el) el.textContent = snap.elapsed; const bar = doc.getElementById("cx-llm-busy-bar"); if (bar) bar.className = "cx-llm-busy" + (snap.slow ? " slow" : ""); } catch (e) { } } try { const pageWin = (typeof unsafeWindow !== "undefined" && unsafeWindow) ? unsafeWindow : _unsafeWindow; if (pageWin) { pageWin.__cxAskStore = askUI; try { if (pageWin.top) pageWin.top.__cxAskStore = askUI; } catch (e1) { } } if (document.documentElement) document.documentElement.__cxAskStore = askUI; } catch (e) { } const _sfc_main = vue.defineComponent({ setup() { const askstore = ensureAskPanel(); const tick = vue.computed(() => askstore.tick); const task = vue.computed(() => { void tick.value; return askstore.task; }); const dialogVisible = vue.computed({ get: () => askstore.dialogVisible, set: (v) => { askstore.dialogVisible = v; } }); const count = vue.computed(() => askstore.count); const questionList = vue.computed(() => askstore.task.work.questionList); // askActiveName 已移除:tab 状态改由 askUI.askTab 管理(reactive 才能触发重渲染) const msg = vue.ref("

本脚本仅用于学习交流,请24h内删除


禁止用于各种非法用途,否则后果自负


本脚本题库接口均来源于网络以及用户反馈添加,不对题库准确率以及可用性负责,请自行判断、评估是否使用。

"); return { count, dialogVisible, questionList, task, tick, msg, Aim: aim_default, handleClick: (e) => { askstore.select(e); } }; } }); const Ask = _export_sfc(_sfc_main, [["render", function (_ctx, _cache, $props, $setup, $data, $options) { const S = askUI; const qlist = S.task.work.questionList.slice(); const hasQ = qlist.length > 0; const hasVideo = !!(S.task.video && S.task.video.status); // hasTask 已移除:面板与悬浮按钮均不再依赖它(对齐老版:出现条件只看是否在章节页) // 面板出现只取决于「是否展开」,与有没有检测到任务无关(对齐老版:URL 在章节页就常驻) const show = !!S.dialogVisible; const inx = S.task.work.inx; const viewInx = (S.task.work.viewInx != null) ? S.task.work.viewInx : inx; const cur = hasQ ? qlist[viewInx] : null; const progressText = hasQ ? ((inx + 1) + "/" + qlist.length) : ""; // viewingOther 已随「回到最新」按钮一并移除 // 默认居中(交给 CSS);只有用户拖拽过才用内联定位覆盖 const panelStyle = (S.panelLeft != null || S.panelTop != null) ? { display: show ? "flex" : "none", left: (S.panelLeft != null ? S.panelLeft + "px" : "50%"), top: (S.panelTop != null ? S.panelTop + "px" : "50%"), right: "auto" } : { display: show ? "flex" : "none" }; const fabStyle = { // 常驻显示:展开时作为左侧状态条,收起后作为重新打开的入口 display: "flex" }; const text = (s) => vue.createTextVNode(String(s == null ? "" : s)); return vue.createElementVNode("div", { id: "cx-ask-root" }, [ vue.createElementVNode("button", { id: "cx-ask-fab", class: "cx-fab", style: fabStyle, title: "打开答题控制台", // 老版行为:点按钮切换整个面板的显隐(收起后只剩左侧按钮) onClick: _cache[3] || (_cache[3] = ($event) => { S.dialogVisible = !S.dialogVisible; }) }, [text((() => { if (S.paused) return "⏸ 已暂停"; // 面板收起时,状态条是用户唯一能看到脚本在等什么的地方 if (S.task.status) return "◉ " + S.task.status; if (hasQ) return "◉ 进度 " + progressText; const _n = S.task.name || ""; if (!_n || _n === "暂未加载") return "◉ 等待任务加载"; return "◉ " + _n; })())]), vue.createElementVNode("div", { id: "cx-ask-panel", class: "cx-ask-panel", style: panelStyle }, [ vue.createElementVNode("div", { class: "cx-drag-bar", onMousedown: _cache[2] || (_cache[2] = function (e) { if (e.button !== 0) return; if (e.target && e.target.closest && e.target.closest("button")) return; // 面板挂在 top.document,必须去那里找,否则跨 iframe 时拖不动 let _doc = document; try { if (_unsafeWindow && _unsafeWindow.top && _unsafeWindow.top.document) _doc = _unsafeWindow.top.document; } catch (e1) { } const panel = _doc.getElementById("cx-ask-panel"); if (!panel) return; const startX = e.clientX, startY = e.clientY; const rect = panel.getBoundingClientRect(); const startLeft = rect.left, startTop = rect.top; panel.style.right = "auto"; // 清掉居中用的负 margin,否则拖动位置会偏 panel.style.marginLeft = "0"; panel.style.marginTop = "0"; panel.style.left = startLeft + "px"; panel.style.top = startTop + "px"; const onMove = function (ev) { const nl = Math.max(0, startLeft + ev.clientX - startX); const nt = Math.max(0, startTop + ev.clientY - startY); panel.style.left = nl + "px"; panel.style.top = nt + "px"; S.panelLeft = nl; S.panelTop = nt; }; const onUp = function () { _doc.removeEventListener("mousemove", onMove); _doc.removeEventListener("mouseup", onUp); }; _doc.addEventListener("mousemove", onMove); _doc.addEventListener("mouseup", onUp); e.preventDefault(); }) }, [ // 左侧:暂停 + 状态(不挤占标题) vue.createElementVNode("span", { class: "cx-header-left" }, [ vue.createElementVNode("button", { class: "cx-panel-toggle pause", title: S.paused ? "继续答题" : "暂停答题", onClick: _cache[5] || (_cache[5] = ($event) => { S.togglePause(); }) }, [text(S.paused ? "▶" : "⏸")]), hasQ ? vue.createElementVNode("span", { class: "cx-badge" }, [text(progressText)]) : vue.createCommentVNode("", true), // CX_AUDIT_UI_V1:task.status 原来只写不读,用户看不到「未开启自动切换」这类关键提示 S.task.status ? vue.createElementVNode("span", { class: "cx-status-badge" }, [text(S.task.status)]) : vue.createCommentVNode("", true) ]), // 中间:固定标题,视觉居中 vue.createElementVNode("span", { class: "cx-drag-title" }, [text("超星学习通满分助手")]), // 右侧:关闭 vue.createElementVNode("button", { class: "cx-panel-close", title: "收起", onClick: _cache[1] || (_cache[1] = ($event) => { S.dialogVisible = false; }) }, [text("×")]) ]), S.llmBusy && S.llmBusy.active ? (vue.openBlock(), vue.createElementBlock("div", { key: "llm-busy", class: vue.normalizeClass(["cx-llm-busy", S.llmBusy.slow ? "slow" : ""]), id: "cx-llm-busy-bar" }, [ vue.createElementVNode("i", { class: "cx-llm-dot" }), vue.createElementVNode("span", { class: "cx-llm-elapsed", id: "cx-llm-elapsed" }, vue.toDisplayString(S.llmBusy.elapsed), 1), vue.createElementVNode("span", { class: "cx-llm-label" }, vue.toDisplayString((S.llmBusy.questionText ? S.llmBusy.questionText + " · " : "") + S.llmBusy.label), 1), S.llmBusy.slow ? vue.createElementVNode("span", { class: "cx-llm-slowtip" }, "仍在等待,可继续挂机", 1) : vue.createCommentVNode("", true) ], 4)) : vue.createCommentVNode("", true), // 顶部切换:运行框 / 运行日志(单列显示,避免两列挤压) vue.createElementVNode("div", { class: "cx-ask-tabbar" }, [ vue.createElementVNode("button", { class: vue.normalizeClass(["cx-ask-tab", S.askTab === "first" ? "active" : ""]), onClick: () => { S.askTab = "first"; S.tick++; } }, [text("运行框")]), vue.createElementVNode("button", { class: vue.normalizeClass(["cx-ask-tab", S.askTab === "second" ? "active" : ""]), onClick: () => { S.askTab = "second"; S.tick++; } }, [text("运行日志")]) ]), vue.createElementVNode("div", { class: "cx-panel-body" }, [ // 运行框无题时的占位提示(避免切过去一片空白) (S.askTab === "first" && !hasQ && !hasVideo && !(S.task.jobs && S.task.jobs.length)) ? vue.createElementVNode("div", { class: "cx-empty-hint" }, "暂无任务,等待识别…") : vue.createCommentVNode("", true), // 运行日志无记录时的占位提示 (S.askTab === "second" && (!S.task.log || !S.task.log.length)) ? vue.createElementVNode("div", { class: "cx-empty-hint" }, "暂无日志") : vue.createCommentVNode("", true), vue.createElementVNode("div", { class: "cx-video-tip", style: { display: hasVideo ? "block" : "none" } }, [text("正在完成视频任务")]), vue.createElementVNode("div", { class: "cx-q-block", style: { display: (S.askTab === "first" && hasQ) ? "block" : "none" } }, [ vue.createElementVNode("div", { class: "cx-q-title" }, [text((inx + 1) + ". " + ((cur && cur.question) || ""))]), vue.createElementVNode("pre", { class: "cx-question-answer", style: { display: (cur && cur.answer) ? "block" : "none" } }, [text((cur && cur.answer) || "")]), vue.createElementVNode("div", { class: "cx-q-nav" }, qlist.map((item, index) => vue.createElementVNode("button", { key: index, class: vue.normalizeClass(["question_btn", item.status || "info", index === viewInx ? "active" : ""]), onClick: () => _ctx.handleClick(index) }, [text(index + 1)])) ), // CX_AUDIT_UI_V1:点过历史题后 follow 变 false 就再无恢复入口,这里补回来 (S.task.work.follow === false) ? vue.createElementVNode("button", { class: "cx-follow-btn", onClick: () => { S.followLatest(); } }, [text("回到最新")]) : vue.createCommentVNode("", true), vue.createElementVNode("div", { class: "cx-source-block", style: { display: (S.askTab === "first" && cur && cur.allAnswer && cur.allAnswer.length) ? "block" : "none" } }, [ vue.createElementVNode("div", { class: "cx-log-title" }, [text("运行框 · 接口返回")]), vue.createElementVNode("div", { class: "cx-source-list" }, ((cur && cur.allAnswer) || []).map((item, index) => vue.createElementVNode("div", { key: index, class: "cx-source-item" }, [ vue.createElementVNode("div", { class: "cx-source-header" }, [ vue.createElementVNode("span", { class: "cx-source-name" }, [text(item.form || ("来源" + index))]), vue.createElementVNode("span", { class: vue.normalizeClass(["cx-source-tag", item.status === "hit" || (item.answer && item.answer.length) ? "ok" : "no"]) }, [text(TIKU_BANK_STATUS_LABEL(item))]) ]), vue.createElementVNode("div", { class: "cx-source-answer", innerHTML: item.answer || (item.note ? "" : "暂无答案") }), item.note ? vue.createElementVNode("div", { class: "cx-source-note" }, vue.toDisplayString(item.note), 1) : vue.createCommentVNode("", true) ])) ) ]) ]), vue.createElementVNode("div", { class: "cx-job-block", style: { display: (S.askTab === "first" && S.task.jobs && S.task.jobs.length) ? "block" : "none" } }, [ vue.createElementVNode("div", { class: "cx-log-title" }, [text("本页任务点 " + (S.task.jobs || []).length)]), vue.createElementVNode("div", { class: "cx-job-list" }, (S.task.jobs || []).map((j, i) => vue.createElementVNode("div", { key: i, class: "cx-job-item" }, [ vue.createElementVNode("span", { class: vue.normalizeClass(["cx-job-dot", j.status || "info"]) }), vue.createElementVNode("span", { class: "cx-job-name" }, [text(j.name || j.type || "任务")]), vue.createElementVNode("span", { class: "cx-job-state" }, [text(j.statusText || "待处理")]) ])) ) ]), vue.createElementVNode("div", { class: "cx-log-block", style: { display: (S.askTab === "second" && S.task.log && S.task.log.length) ? "block" : "none" } }, [ vue.createElementVNode("div", { class: "cx-log-title" }, [text("运行日志")]), vue.createElementVNode("div", { class: "cx-log-list" }, (S.task.log || []).slice(-8).map((item, index) => vue.createElementVNode("div", { key: index, class: "cx-log-item" }, [ vue.createElementVNode("span", { class: vue.normalizeClass(["cx-log-msg", item.type]) }, [text(item.msg)]) ])) ) ]) ]) ]) ]); }], ["__scopeId", "data-v-c3c6b09f"]]); function ensureAskPanel() { try { if (_unsafeWindow && _unsafeWindow.top) _unsafeWindow.top.__cxAskStore = askUI; if (typeof window !== "undefined" && window.top) window.top.__cxAskStore = askUI; } catch (e) { } let hostWin = null; try { hostWin = _unsafeWindow.top; } catch (e) { hostWin = _unsafeWindow; } if (!hostWin) hostWin = _unsafeWindow; if (hostWin.__cxAskApp) return askUI; try { hostWin.__cxAskApp = true; const hostDoc = hostWin.document || document; try { hostDoc.querySelectorAll("#zeokdjg, #xxxxzx").forEach((el) => el.remove()); } catch (e) { } const askApp = vue.createApp(Ask).use(ElementPlus).use(pinia); askApp.mount((() => { const div = hostDoc.createElement("div"); div.id = "xxxxzx"; hostDoc.body.append(div); return div; })()); hostWin.__cxAskApp = askApp; } catch (e) { try { hostWin.__cxAskApp = false; } catch (e2) { } console.error("[满分助手] 运行面板挂载失败", e); } return askUI; } class Cx { constructor() { __publicField(this, "app"); __publicField(this, "askStore"); __publicField(this, "ServerApi"); __publicField(this, "defaultConfig"); // CX_AUDIT_JUMP_V1:本代运行号。用户手动切章时被置为 -1, // 让 video/audio 这类长任务循环能立刻知道「这一代已经作废」。 __publicField(this, "__runEpoch"); this.askStore = ensureAskPanel(), this.ServerApi = new ServerApi(), this.defaultConfig = getConfig(); } innerbook() { } async audio(iframeWindow) { this.askStore.reset(), this.askStore.task.name = "视频音频"; const audio = (iframeWindow && iframeWindow.document) ? iframeWindow.document.getElementById("audio_html5_api") : null; // 元素缺失时原实现会在 audio.muted 处直接抛错,整轮任务静默放弃 if (!audio) { this.askStore.log("[音频] 未找到播放器,跳过本任务点", "error"); return; } audio.muted = true, audio.autoplay = true, audio.volume = 0; try { audio.play().then(function () { console.log("播放成功"); }).catch(function (error) { "NotAllowedError" === error.name ? ElementPlus.ElMessageBox.alert("由于自动播放需要用户点击过浏览器,请确认即可", "温馨提示", { confirmButtonText: "确认", callback: () => { try { audio.play(); } catch (e) { } } }) : console.error("视频播放失败,原因:", error); }); } catch (e) { } await new Promise((resolve) => { const _store = this.askStore; const _self2 = this; const _epoch = this.__runEpoch; let intervalId = null, _guard = null; const _finish = () => { if (intervalId) { clearInterval(intervalId); intervalId = null; } if (_guard) { clearTimeout(_guard); _guard = null; } try { resolve(); } catch (e) { } }; intervalId = setInterval(() => { // 用户已切到别的章节:本代作废 if (_self2.__runEpoch !== _epoch) { _finish(); return; } // 暂停期间不续播、不判定完成(原实现 audio.paused && audio.play() 会强行续播) if (_store.paused) { try { if (!audio.paused) audio.pause(); } catch (e) { } return; } try { if (audio.ended) { log("监听到音频已完成", "success"); _finish(); return; } if (audio.paused) { const p = audio.play(); if (p && p.catch) p.catch(() => { }); } } catch (e) { _finish(); } }, 1e3); // 兜底:音频 404 或播放器不派发 ended 时不能永久挂起(整锁不释放会卡死后续所有章节) const _dur = Number(audio.duration); const _limit = (isFinite(_dur) && _dur > 0 ? _dur * 1000 : 1800000) + 60000; _guard = setTimeout(() => { log("[音频] 超时未结束,跳过本任务点", "error"); _finish(); }, _limit); try { audio.addEventListener("error", () => { log("[音频] 播放出错,跳过本任务点", "error"); _finish(); }, { once: true }); } catch (e) { } try { audio.addEventListener("ended", function () { log("监听到音频已完成1", "success"); try { audio.pause(); } catch (e) { } _finish(); }, { once: true }); } catch (e) { } }); } async video(iframeWindow) { this.askStore.reset(), this.askStore.task.name = "视频", this.askStore.task.video.status = 1; await waitElementLoaded(iframeWindow, "#video_html5_api"); // 15 秒兜底放行后播放器可能还没准备好,直接解引用会抛 TypeError 中断整轮且不重试 if (!iframeWindow || typeof iframeWindow.videojs !== "function") { this.askStore.log("[视频] 播放器脚本未就绪,跳过本任务点", "error"); return; } let player = null; try { player = iframeWindow.videojs("video_html5_api"); } catch (e) { player = null; } if (!player || typeof player.playbackRate !== "function") { this.askStore.log("[视频] 未找到视频播放器,跳过本任务点", "error"); return; } const playerButton = iframeWindow.document.querySelector(".vjs-big-play-button"); // ===== CX_VIDEO_RATE_V3 ===== // 语义:脚本优先设定倍速;用户手动改过后永久让位。 // V2 用同步标志 _selfSetting 过滤自己触发的 ratechange,但 ratechange 是异步派发的, // 事件到达时标志早已复位 → 脚本自己设速被误判成用户操作,倍速静默失效并打假日志。 // V3 改为「记录脚本最后写入的值」,ratechange 时数值相同即认定是自己写的。 // 状态挂在 player 上,重复进入 video() 不会让监听器累积、也不会丢状态。 const _rate = Number(this.defaultConfig.videoRate) || 1; // 已 clamp 到 Chrome 上限 16 const _st = player.__cxRateState || (player.__cxRateState = { userTouched: false, lastApplied: null, store: this.askStore }); _st.store = this.askStore; const _self = this; const _applyRate = (r) => { try { const cur = player.playbackRate(); _st.lastApplied = r; if (cur !== r) player.playbackRate(r); } catch (e) { } }; if (!player.__cxRateBound) { player.__cxRateBound = true; try { if (typeof player.on === "function") player.on("ratechange", () => { try { const cur = player.playbackRate(); if (_st.lastApplied != null && Math.abs(cur - _st.lastApplied) < 1e-6) return; // 自己写的 if (_st.userTouched) return; _st.userTouched = true; _st.store && _st.store.log("[视频] 检测到手动调整倍速,脚本停止干预", "info"); } catch (e) { } }); } catch (e) { } } try { player.muted(true); } catch (e) { } _applyRate(_rate); try { player.play(); } catch (e) { } await new Promise((resolve) => { const pauseBase = player.pause; const _epoch = _self.__runEpoch; // 进入本任务时的代次 let intervalId = null, _settled = false; // 关键:原实现覆写 pause 后从不还原,也不调用原 pause → 面板暂停键对视频完全无效, // 且视频播完后这个播放器再也暂停不了。这里统一在结束路径还原。 const _restorePause = () => { try { player.pause = pauseBase; } catch (e) { } }; const _finish = () => { if (_settled) return; _settled = true; if (intervalId) { clearInterval(intervalId); intervalId = null; } _restorePause(); try { resolve(); } catch (e) { } }; intervalId = setInterval(() => { // 用户已切到别的章节:本代作废,立刻收手,别再把新页面翻走 if (_self.__runEpoch !== _epoch) { _finish(); return; } // 暂停键生效:暂停期间不续播,也不当作已完成 if (_self.askStore.paused) { try { if (!player.paused()) player.pause(); } catch (e) { } return; } // 用户未接管时,若播放器自己把速率重置了(例如切片/续播),再纠正回来; // 用户已接管则完全不再干预。 if (!_st.userTouched) { try { if (player.playbackRate() !== _rate) _applyRate(_rate); } catch (e) { } } let _unFinished = false; try { _unFinished = ("isUnFinishJob" in iframeWindow) && iframeWindow.isUnFinishJob(); } catch (e) { _unFinished = false; } if (_unFinished) { try { if (player.paused() && playerButton) playerButton.click(); } catch (e) { } } else { _finish(); } }, 1e3); player.pause = function () { // 先真正暂停,再判断是否播完(原实现只判完成,从不暂停) try { if (typeof pauseBase === "function") pauseBase.call(player); } catch (e) { } try { if (player.currentTime() >= player.duration()) { console.log("视频播放完成"); _finish(); } } catch (e) { } }; try { if (typeof player.on === "function") player.on("ended", () => { console.log("视频播放完成1"); _finish(); }); } catch (e) { } }), console.log("任务点完成"); } // CX_AUDIT_TASK_V1:原实现是 new Promise(async (resolve) => …),内部 await 抛错时 // resolve 永远不会被调用 → 整轮静默挂起、锁不释放。改为纯 async,异常自然冒泡到 startWork。 async work(iframeWindow) { if (!iframeWindow || !iframeWindow.document) return; decode(iframeWindow); const Timu = iframeWindow.document.querySelectorAll(".TiMu"); // querySelectorAll 永远返回 NodeList,原 `if (!Timu)` 是恒假死代码;真正要判的是长度 if (!Timu.length) { this.askStore.log("未解析到章节测验题目,跳过", "error"); return; } let ques = [], succ = 0; for (let i = 0; i < Timu.length; i++) { let data = getQuestion("1", Timu[i]); console.log(data), ques.push(data); } this.askStore.reset(), this.askStore.count = ques.length, this.askStore.task.name = "章节测验"; // 记住本次答题会话;reset() 推进 session 后本循环即为作废 const _sess = this.askStore.session; const _stale = () => this.askStore.session !== _sess; for (let i = 0; i < ques.length; i++) { if (_stale()) return; await this.askStore.waitIfPaused(); if (_stale()) return; await sleep(this.defaultConfig.answerInterval); if (_stale()) return; this.askStore.insert(ques[i]), this.askStore.task.work.inx = i; if (this.askStore.task.work.follow !== false) this.askStore.task.work.viewInx = i; let data = await getAnswers(ques[i], iframeWindow); if (_stale()) return; this.askStore.patch(i, { allAnswer: data }); let tmp = fillAnswer(data, ques[i], Timu[i], iframeWindow); if (!tmp && this.defaultConfig.llmEnabled && this.defaultConfig.llmApiKey && this.defaultConfig.llmBaseUrl) { const questionType = ques[i].type; if (this.defaultConfig.llmType && Array.isArray(this.defaultConfig.llmType) && this.defaultConfig.llmType.includes(questionType)) { LLM_BUSY.begin("probe", "准备请求", { index: i, total: ques.length }); let llmResult; try { llmResult = await this.ServerApi.getAnswerByLLM(ques[i]); } finally { LLM_BUSY.end(); } data.push(llmResult); tmp = fillAnswer([llmResult], ques[i], Timu[i], iframeWindow); } } if (_stale()) return; tmp ? (this.askStore.patch(i, { status: "primary", answer: tmp }), succ++) : (this.askStore.patch(i, { status: "danger", answer: "暂无答案" })), this.askStore.patch(i, { dom: Timu[i] }); } // 用户已经切走:绝不能拿旧题单去点提交 if (_stale()) return; // 原实现只在 autoSubmit 为 true 的分支里 resolve(),关掉「自动提交」后整轮永久挂起 if (this.defaultConfig.autoSubmit) { if (succ / ques.length < this.defaultConfig.minAccuracy) { this.askStore.log("章节测验正确率不足,暂存", "error"); try { iframeWindow.alert = function (e) { console.log("alert 方法被阻止", e); }; iframeWindow.noSubmit(); } catch (e) { this.askStore.log("暂存失败: " + ((e && e.message) || e), "error"); } } else { try { iframeWindow.btnBlueSubmit(); await sleep(3); iframeWindow.submitCheckTimes(); this.askStore.log("章节测验已完成", "success"); } catch (e) { this.askStore.log("提交失败: " + ((e && e.message) || e), "error"); } } this.askStore.task.status = `章节测验已完成,等待切换,正确率:${succ}/${ques.length}`; } else { this.askStore.log("已完成答题,未开启自动提交,等待手动提交中", "success"); this.askStore.task.status = `正在等待手动提交,正确率:${succ}/${ques.length}`; } } async homework() { const Timu = _unsafeWindow.document.querySelectorAll(".questionLi"); if (!Timu.length) { this.askStore.log("未解析到作业题目,跳过", "error"); return; } let ques = []; for (let i = 0; i < Timu.length; i++) { let data = getQuestion("2", Timu[i]); ques.push(data); } this.askStore.reset(), this.askStore.count = ques.length, this.askStore.task.name = "作业"; const _sess = this.askStore.session; const _stale = () => this.askStore.session !== _sess; for (let i = 0; i < ques.length; i++) { if (_stale()) return; await this.askStore.waitIfPaused(); if (_stale()) return; await sleep(this.defaultConfig.answerInterval); if (_stale()) return; this.askStore.insert(ques[i]), this.askStore.task.work.inx = i; if (this.askStore.task.work.follow !== false) this.askStore.task.work.viewInx = i; let data = await getAnswers(ques[i]); if (_stale()) return; this.askStore.patch(i, { allAnswer: data }); let tmp = fillAnswer(data, ques[i], Timu[i], _unsafeWindow); if (!tmp && this.defaultConfig.llmEnabled && this.defaultConfig.llmApiKey && this.defaultConfig.llmBaseUrl) { const questionType = ques[i].type; if (this.defaultConfig.llmType && Array.isArray(this.defaultConfig.llmType) && this.defaultConfig.llmType.includes(questionType)) { LLM_BUSY.begin("probe", "准备请求", { index: i, total: ques.length }); let llmResult; try { llmResult = await this.ServerApi.getAnswerByLLM(ques[i]); } finally { LLM_BUSY.end(); } data.push(llmResult); tmp = fillAnswer([llmResult], ques[i], Timu[i], _unsafeWindow); } } if (_stale()) return; tmp ? (this.askStore.patch(i, { status: "primary", answer: tmp })) : (this.askStore.patch(i, { status: "danger", answer: "暂无答案" })), this.askStore.patch(i, { dom: Timu[i] }); } } // CX_AUDIT_TASK_V1:原实现全函数没有任何 resolve() 调用,考试页 await 永不返回 async exam() { { this.askStore.reset(), this.askStore.count = 1, this.askStore.task.name = "考试"; const _sess = this.askStore.session; const _stale = () => this.askStore.session !== _sess; let data = getQuestion("3", _unsafeWindow.document.body); this.askStore.insert(data), this.askStore.task.work.inx = 0; if (this.askStore.task.work.follow !== false) this.askStore.task.work.viewInx = 0; let data1 = await getAnswers(data); if (_stale()) return; this.askStore.patch(0, { allAnswer: data1 }); let tmp = fillAnswer(data1, data, document.getElementsByClassName("mark_table")[0], _unsafeWindow); if (!tmp && this.defaultConfig.llmEnabled && this.defaultConfig.llmApiKey && this.defaultConfig.llmBaseUrl) { const questionType = data.type; if (this.defaultConfig.llmType && Array.isArray(this.defaultConfig.llmType) && this.defaultConfig.llmType.includes(questionType)) { LLM_BUSY.begin("probe", "准备请求", { index: 0, total: 1 }); let llmResult; try { llmResult = await this.ServerApi.getAnswerByLLM(data); } finally { LLM_BUSY.end(); } data1.push(llmResult); tmp = fillAnswer([llmResult], data, document.getElementsByClassName("mark_table")[0], _unsafeWindow); } } if (tmp ? (this.askStore.patch(0, { status: "primary", answer: tmp })) : (this.askStore.patch(0, { status: "danger", answer: "暂无答案" })), this.defaultConfig.autoExam) { await this.askStore.waitIfPaused(); await sleep(this.defaultConfig.answerInterval); const nextButton = $('.nextDiv .jb_btn:contains("下一题")'); // jQuery 对象恒为真,空选择集也会走 click 分支 → 必须判 .length (nextButton && nextButton.length) ? nextButton.click() : (this.askStore.log("已完成答题,请自行检查答案填写后自行提交", "success"), this.askStore.task.status = "已完成答题,请自行检查答案填写后自行提交"); } else this.askStore.task.status = "未开启自动切换,等待手动切换"; } } async pdf(iframeWindow) { // 原实现直接解引用 #panView.contentWindow,文档未加载时抛 TypeError 中断整轮 const pv = iframeWindow && iframeWindow.document && iframeWindow.document.querySelector("#panView"); const cw = pv && pv.contentWindow; if (!cw || !cw.document || !cw.document.body) { this.askStore.log("[文档] 未加载,跳过本任务点", "info"); return; } try { cw.scrollTo(0, cw.document.body.scrollHeight); } catch (e) { } } async s(iframeWindow) { if (!iframeWindow || !iframeWindow.document) return; const questionList = $(iframeWindow.document).find(".TiMu").map(function (index, element) { try { let questionHtml, questionText, questionType$1, questionAnswer, questionOption = [], questionAnalysis = ""; switch (questionHtml = $(element).find(".Zy_TItle .clearfix"), questionText = removeHtml(questionHtml[0].innerHTML), questionType$1 = questionText.match(/^\【(.+?)\】/)[1], questionText = questionText.replace(questionText.match(/^\【(.+?)\】/)[0], ""), questionType$1) { case "单选题": case "多选题": return questionOption = $(element).find("ul>li").map(function (inx, item) { return removeHtml($(item).find("a").html()); }).get(), null; case "判断题": if (questionAnalysis = removeHtml($(element).find(".Py_addpy:eq(0)").html() || ""), element.innerHTML.includes("正确答案")) questionAnswer = removeHtml($(element).find(".Py_answer.clearfix>span").html()); else { const match = $(element).find(".Py_answer.clearfix").html().match(/^(.*?)(?=<\/i>)/s), result = match ? match[1] : ""; questionAnswer = removeHtml(result); } if (questionAnswer.includes("正确答案")) questionAnswer = questionAnswer.replace("正确答案:", "").trim(); else if ($(element).find(".fr.dui").length > 0) questionAnswer = questionAnswer.replace("我的答案:", "").trim(); else { if (!questionAnswer.replace("我的答案:", "").trim().includes("√") && !questionAnswer.replace("我的答案:", "").trim().includes("×")) return null; questionAnswer = "√" == questionAnswer.replace("我的答案:", "").trim() ? "×" : "√"; } break; case "填空题": if (questionAnswer = $("span.font14", $(element)).map(function (inx, item) { return removeHtml($(item).html()).replace(/^第.空:/, "").trim(); }).get(), 0 == questionAnswer.length) { if (questionAnswer = $(element).find(".Py_answer.clearfix>div>div[class='font14']"), !(questionAnswer.length = $(element).find(".Py_answer.clearfix>div>div[class='font14']>>.fr.dui").length)) return null; questionAnswer = questionAnswer.map(function (inx, item) { return removeHtml($(item).html()).replace(/^第.空:/, "").trim(); }).get(); } break; default: return null; } return { question: questionText, options: questionOption, type: questionType[questionType$1], answer: questionAnswer }; } catch { return null; } }).get(); try { const pageHref = (iframeWindow && iframeWindow.location && iframeWindow.location.href) || (typeof _unsafeWindow !== "undefined" && _unsafeWindow.location && _unsafeWindow.location.href) || ""; await this.ServerApi.s(questionList, pageHref); } catch (e) { console.error("[满分助手] s() 失败", e); } } } const pinia = pinia$1.createPinia(), app = vue.createApp(App).use(ElementPlus).use(pinia), _self = _unsafeWindow, top = _self.top, formStore = useformStore(); app.component('TikuBankList', TIKU_BANK_LIST_COMPONENT); var iframeCom = null; switch ((() => { try { if (top.__cxConfigApp) return; top.__cxConfigApp = true; const div = top.document.createElement("div"); div.id = "cccxapp"; var old = top.document.getElementById("cccxapp"); if (old) old.remove(); top.document.querySelectorAll("#csbutton").forEach((el) => el.remove()); top.document.body.append(div); app.mount(div); top.__cxConfigApp = app; } catch (e) { try { top.__cxConfigApp = false; } catch (e2) { } log(e, "error"); } })(), // 面板不再无条件挂载:只在 Cx 构造函数里(章节学习页/作业页/考试页)创建 (() => { document.body.oncopy = null, document.body.oncut = null, document.body.onpaste = null, document.body.onselectstart = null, document.body.ondragstart = null; const style = document.createElement("style"); style.innerHTML = "\n * {\n -webkit-user-select: auto !important;\n -moz-user-select: auto !important;\n -o-user-select: auto !important;\n user-select: auto !important;\n }\n ", document.head.appendChild(style); })(), _self.location.pathname) { case "/work/doHomeWorkNew": case "/mooc-ans/work/doHomeWorkNew": case "/mooc2-ans/work/doHomeWorkNew": if (location.href.includes("mooc2=1")) { location.href = location.href.replace(/&mooc2=1/g, ""); break; } if (_self !== top) break; { const cxHw = new Cx(); const llmHw = getConfig(); cxHw.askStore.log("脚本初始化成功!", "success"); if (llmHw.llmEnabled) cxHw.askStore.log("[LLM] 已启用,模型: " + llmHw.llmModel, "success"); else cxHw.askStore.log("[LLM] 未启用,请在配置中开启", "info"); cxHw.askStore.msg("正在答题"); await (cxHw.homework()); } break; case "/mycourse/studentstudy": case "/mooc-ans/mycourse/studentstudy": case "/mooc2-ans/mycourse/studentstudy": if (_self !== top) break; if (!_self.location.href.match(/mooc2=1/)) { ElementPlus.ElNotification({ title: "Auto Ask", message: "暂不支持旧版章节,尝试切换至新版", type: "error" }), _self.location.href = _self.location.href + "&mooc2=1"; break; } const cxModel = new Cx(); const llmConfig = getConfig(); console.log("[LLM] 初始化配置检查:", JSON.stringify({ llmEnabled: llmConfig.llmEnabled, llmApiKey: llmConfig.llmApiKey ? "***" + llmConfig.llmApiKey.slice(-4) : "未设置", llmBaseUrl: llmConfig.llmBaseUrl, llmModel: llmConfig.llmModel, llmType: llmConfig.llmType }, null, 2)); cxModel.askStore.log("脚本初始化成功!", "success"); if (llmConfig.llmEnabled) { cxModel.askStore.log("[LLM] 已启用,模型: " + llmConfig.llmModel, "success"); } else { cxModel.askStore.log("[LLM] 未启用,请在配置中开启", "info"); } // ===== 任务循环防重入 ===== // 原实现由 2s 轮询 href 变化触发,用户手动切换任务会重跑整个 startWork, // 而 startWork 末尾无条件 autoJump,导致「手动切一个任务却跳到下一个」。 const __WORK_LOCK = { running: false, runId: 0 }; // 脚本自己点「下一页/下一章」前记下来源地址;轮询看到 href 与它不同即认为是脚本跳的。 // 原实现记录的是点击后的 href 再与之比较,二者永不相等 → 每次自动跳转都被当成用户手动切页。 let __SCRIPT_JUMP_FROM = null; // 旧循环还在跑时用户手动切章:记一笔,等旧循环收尾后补扫一次 let __pendingRescan = false; const startWork = async () => { var _a, _b, _c, _d, _e; if (__WORK_LOCK.running) { // 原实现直接 return,而轮询已先把 iframeCom 更新成新 href → 新章节一次都不会被扫描, // 旧循环还会拿着旧 jobList 把用户切到的这一章直接翻走。这里记为待补扫。 __pendingRescan = true; cxModel.askStore.log("已有任务正在执行,稍后补扫当前章节", "info"); return; } const __myRun = ++__WORK_LOCK.runId; __WORK_LOCK.running = true; cxModel.__runEpoch = __myRun; // 长任务循环据此判断自己是否已作废 // 语义修正:原「本轮有没有完成过任务点」会把「无需再做」和「识别失败」混为一谈, // 导致「全部已完成」「autoVideo 关闭」也永久停住。改为记录「是否有处理失败的任务点」。 let __pending = false; let __didComplete = false; // 保留:仅用于日志与统计 try { await waitElementLoaded(_self, "#iframe"); const cardsIframe = _self.document.querySelector("#iframe"); await waitIframeLoaded(cardsIframe); const _self1 = cardsIframe && cardsIframe.contentWindow; if (!_self1) return; try { top.scroll2Job(); } catch (e) { } let jobList = __collectJobItems(_self1.document); if (!jobList.length) { cxModel.askStore.log("本页未发现任务点,直接切换下一章", "info"); // 无任务点不应阻塞跳转:当作「已无待做」处理 __pending = false; } else { cxModel.askStore.log("发现 " + jobList.length + " 个任务点", "info"); } // 任务点概览:无论后续处理成功与否,先把本页有什么写进面板 try { const _jobView = jobList.map((it) => { const _h = it.host || it; const _ifr = _h.querySelector && _h.querySelector("iframe"); const _src = (_ifr && _ifr.src) || ""; let _type = "课件"; if (_src.indexOf('/ananas/modules/video/') >= 0) _type = "视频"; else if (_src.indexOf('/ananas/modules/work/') >= 0) _type = "作业"; else if (_src.indexOf('/ananas/modules/audio/') >= 0) _type = "音频"; else if (_src.indexOf('/ananas/modules/pdf/') >= 0) _type = "文档"; let _nm = _type; try { const _d = _ifr && _ifr.getAttribute("data"); if (_d) { const _o = JSON.parse(_d); _nm = _o.name || _o.title || _type; } } catch (e) { } const _fin = __isJobFinished(_h); return { name: _nm, type: _type, status: _fin ? "success" : "info", statusText: _fin ? "已完成" : "待处理" }; }); cxModel.askStore.task.jobs = _jobView; if (!_jobView.length) cxModel.askStore.task.name = "本页无任务点"; } catch (e) { } for (let i = 0; i < jobList.length; i++) { if (__WORK_LOCK.runId !== __myRun) return; await cxModel.askStore.waitIfPaused(); const item = jobList[i]; const __host = item.host || item; if (__isJobFinished(__host)) { const iframe = __host.querySelector("iframe"); if (iframe == null ? void 0 : iframe.src.match(/\/ananas\/modules\/work\/index.html/)) { await waitIframeLoaded(iframe); const workIframe = (_c = iframe.contentWindow) == null ? void 0 : _c.document.querySelector("iframe"); workIframe && (await waitIframeLoaded(workIframe), cxModel.s(workIframe.contentWindow)); } console.log(iframe ? iframe.src : "(无 iframe)", "已完成"), cxModel.askStore.log("已完成的任务点,跳过"); } else { const iframe = __host.querySelector("iframe"); if (iframe) await waitIframeLoaded(iframe); // 无 iframe 的纯内嵌课件不等待 // data 属性可能不存在或不是合法 JSON,任何情况都不能中断整轮 let otherInfo = {}; try { const _d2 = iframe && iframe.getAttribute("data"); if (_d2) otherInfo = JSON.parse(_d2) || {}; } catch (e) { otherInfo = {}; } if (cxModel.askStore.log(`正在完成任务:${otherInfo.name || otherInfo.title}`), iframe == null ? void 0 : iframe.src.match(/\/ananas\/modules\/video\/index\.html/)) { if (!formStore.forminput.autoVideo) { cxModel.askStore.log("视频任务已跳过", "success"); continue; } { await cxModel.video(iframe.contentWindow); // 代次已变说明用户切走了,这个任务点并没有真正完成 if (cxModel.__runEpoch === __myRun) { __didComplete = true; cxModel.askStore.log("视频任务已完成", "success"); } else { cxModel.askStore.log("视频任务被中断(已切换章节)", "info"); } } } else if (iframe == null ? void 0 : iframe.src.match(/\/ananas\/modules\/work\/index.html/)) { cxModel.askStore.log("即将开始做作业", "info"); __didComplete = true; const workIframe = (_e = iframe.contentWindow) == null ? void 0 : _e.document.querySelector("iframe"); if (workIframe) { await waitIframeLoaded(workIframe); await cxModel.work(workIframe.contentWindow); // 会话已变说明用户切走了,这个任务点并没有真正做完 if (cxModel.__runEpoch === __myRun) cxModel.askStore.log("作业任务已完成", "success"); else cxModel.askStore.log("作业任务被中断(已切换章节)", "info"); } } else if (iframe == null ? void 0 : iframe.src.match(/\/ananas\/modules\/audio\/index.html/)) { if (log("音频", "error"), !formStore.forminput.autoVideo) { cxModel.askStore.log("音频任务已跳过", "success"); continue; } iframe && (await waitIframeLoaded(iframe), await cxModel.audio(iframe.contentWindow), __didComplete = true, cxModel.askStore.log("音频任务已完成", "success")); } else if (iframe == null ? void 0 : iframe.src.match(/\/ananas\/modules\/pdf\/index.html/)) { log("文档", "error"); if (iframe) { await waitIframeLoaded(iframe); await cxModel.pdf(iframe.contentWindow); } __didComplete = true; cxModel.askStore.log("pdf任务已完成", "success"); } else { // 未知类型(课件/PPT/文档/阅读等):通用兜底——滚动 + 点击 + 等完成标记 const _src = iframe ? iframe.src : "(无 iframe)"; cxModel.askStore.log("非媒体任务点(" + _src + "),尝试通用处理", "info"); const _ok = await __handleGenericJob(__host, (m, t) => cxModel.askStore.log(m, t)); if (_ok) { __didComplete = true; const _done = __isJobFinished(__host); cxModel.askStore.log(_done ? "课件任务已完成" : "课件已尝试处理(未检测到完成标记,可能需要人工确认)", _done ? "success" : "info"); } else { __pending = true; cxModel.askStore.log("课件任务处理失败,已记录", "error"); } } } } await cxModel.askStore.waitIfPaused(); await sleep(formStore.forminput.interval); // 暂停中不推进 await cxModel.askStore.waitIfPaused(); if (__WORK_LOCK.runId !== __myRun) return; // 只有「确实有任务点没处理成功」才停下;全部已完成 / 用户主动关闭 / 无任务点 都应继续 if (__pending) { cxModel.askStore.log("存在未能处理的任务点,停留在当前页,请手动确认", "error"); return; } if (!__didComplete) cxModel.askStore.log("本页无待做任务点,继续切换", "info"); // 最后一道闸:任何情况下都不许把用户已经切到的章节再翻走 if (cxModel.__runEpoch !== __myRun) return; if (!formStore.forminput.autoJump) { cxModel.askStore.msg("由于未开启自动切换,请手动切换"); } else { const _detectSubTab = () => { try { const sels = ["#prev_tab > li", ".prev_ul > li", "#prevTabBox > li"]; for (const sel of sels) { const nodes = Array.from((top == null ? void 0 : top.document.querySelectorAll(sel)) || []); if (!nodes.length) continue; const ai = nodes.findIndex(n => n.classList && n.classList.contains("active")); if (ai === -1) continue; return { activeIndex: ai, total: nodes.length, hasNext: ai < nodes.length - 1, tabs: nodes }; } } catch (e) { } return null; }; const _sub = _detectSubTab(); // 记录本次自动跳转前的 href,轮询看到变化时用来区分「脚本自己跳」与「用户手动跳」 try { const _curIframe = _self.document.querySelector("#iframe"); __SCRIPT_JUMP_FROM = (_curIframe && _curIframe.contentWindow && _curIframe.contentWindow.location && _curIframe.contentWindow.location.href) || null; } catch (e) { __SCRIPT_JUMP_FROM = null; } if (_sub && _sub.hasNext) { cxModel.askStore.log(`当前课时存在未完成页面(${_sub.activeIndex + 1}/${_sub.total}),切换到下一页`, "info"); const _nextPageBtn = (top == null ? void 0 : top.document.querySelector("#mainid > .prev_next.next")); _nextPageBtn ? _nextPageBtn.click() : (function(){ try { const _n = top && top.document && top.document.querySelector(".nextChapter"); if (_n) _n.click(); else cxModel.askStore.log("未找到下一章按钮", "error"); } catch (e) { } })(); } else { (function(){ try { const _n = top && top.document && top.document.querySelector(".nextChapter"); if (_n) _n.click(); else cxModel.askStore.log("未找到下一章按钮", "error"); } catch (e) { } })(); } } } catch (e) { // 原来没有 catch:任何异常都变成未捕获 rejection,面板没有任何提示 cxModel.askStore.log("任务处理异常: " + ((e && e.message) || e), "error"); } finally { // 只有最新一代运行才释放锁,避免旧循环提前放开导致重入 if (__WORK_LOCK.runId === __myRun) __WORK_LOCK.running = false; if (__pendingRescan) { __pendingRescan = false; setTimeout(() => { startWork(); }, 0); } } }; setInterval(async () => { await waitElementLoaded(_self, "#iframe"); const cardsIframe = _self.document.querySelector("#iframe"); await waitIframeLoaded(cardsIframe); const _self1 = cardsIframe && cardsIframe.contentWindow; if (!_self1) return; try { const href = _self1.location && _self1.location.href; if (href && iframeCom != href) { iframeCom = href; // 脚本自己刚点过「下一章/下一页」:只更新缓存,不重跑,避免自激链 if (__SCRIPT_JUMP_FROM && href !== __SCRIPT_JUMP_FROM) { __SCRIPT_JUMP_FROM = null; cxModel.askStore.log("脚本自动跳转,跳过重复扫描", "info"); } else { // 用户手动切换任务。 // 关键:不能只是「记一笔待补扫」——那样旧循环的 runId 没变, // ``if (__WORK_LOCK.runId !== __myRun) return;`` 永远为假, // 旧循环会跑完这一轮并 autoJump,把用户刚切到的章节直接翻走。 // 这里立刻作废:推进 runId + 清 running + 作废长任务代次。 __SCRIPT_JUMP_FROM = null; cxModel.__runEpoch = -1; // video/audio 循环据此立刻收手 __WORK_LOCK.runId++; // 旧循环下一次代次检查即 return __WORK_LOCK.running = false; // 释放锁,让新一轮能立刻开始 __pendingRescan = false; cxModel.askStore.reset(); startWork(); } } } catch (e) { } }, 2e3); break; case "/mooc2-ans/mycourse/stu": case "/mooc-ans/mycourse/stu": case "/mycourse/stu": ElementPlus.ElNotification({ title: "Auto Ask", message: "此页面无任务,请自行进入章节页面", type: "error" }); break; case "/work/selectWorkQuestionYiPiYue": break; case "/knowledge/cards": if (_self !== top) break; { const cxCards = new Cx(); const llmCards = getConfig(); cxCards.askStore.log("脚本初始化成功!", "success"); if (llmCards.llmEnabled) cxCards.askStore.log("[LLM] 已启用,模型: " + llmCards.llmModel, "success"); else cxCards.askStore.log("[LLM] 未启用,请在配置中开启", "info"); const tiMu = _self.document.querySelectorAll(".TiMu"); const qLi = _self.document.querySelectorAll(".questionLi"); if (tiMu && tiMu.length) { cxCards.askStore.log("检测到章节测验,开始答题", "info"); cxCards.askStore.msg("章节测验"); await (cxCards.work(_unsafeWindow)); } else if (qLi && qLi.length) { cxCards.askStore.log("检测到作业题目,开始答题", "info"); cxCards.askStore.msg("作业"); await (cxCards.homework()); } else { cxCards.askStore.log("控制台已就绪,等待任务点…", "info"); } } break; case "/mooc2/work/dowork": case "/mooc-ans/mooc2/work/dowork": case "/mooc2-ans/mooc2/work/dowork": if (_self !== top) break; const cxModel1 = new Cx(); const llmConfig1 = getConfig(); console.log("[LLM] 作业页配置:", JSON.stringify({ enabled: llmConfig1.llmEnabled, model: llmConfig1.llmModel }, null, 2)); cxModel1.askStore.log("脚本初始化成功!", "success"); if (llmConfig1.llmEnabled) cxModel1.askStore.log("[LLM] 已启用", "success"); await (cxModel1.homework()); break; case "/exam-ans/exam/test/reVersionTestStartNew": if (_self !== top) break; const cxModel2 = new Cx(); const llmConfig2 = getConfig(); console.log("[LLM] 考试页配置:", JSON.stringify({ enabled: llmConfig2.llmEnabled, model: llmConfig2.llmModel }, null, 2)); cxModel2.askStore.log("脚本初始化成功!", "success"); if (llmConfig2.llmEnabled) cxModel2.askStore.log("[LLM] 已启用", "success"); await (cxModel2.exam()); break; default: if (_self === top) { try { const qEls = _self.document.querySelectorAll(".TiMu, .questionLi, .mark_table"); if (qEls && qEls.length) { const cxD = new Cx(); cxD.askStore.log("脚本初始化成功!", "success"); cxD.askStore.log("检测到答题页面,控制台已就绪", "info"); if (_self.document.querySelectorAll(".questionLi").length) { cxD.askStore.msg("作业"); await (cxD.homework()); } else if (_self.document.querySelectorAll(".mark_table").length) { cxD.askStore.msg("考试"); await (cxD.exam()); } else if (_self.document.querySelectorAll(".TiMu").length) { cxD.askStore.msg("章节测验"); await (cxD.work(_unsafeWindow)); } } } catch (e) { console.error("[满分助手] 兜底答题失败", e); } } } })(Vue, Pinia, ElementPlus, md5, $);