repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
siyuan-unlock
github_2023
appdev
typescript
winOnClose
const winOnClose = (close = false) => { exportLayout({ cb() { if (window.siyuan.config.appearance.closeButtonBehavior === 1 && !close) { // 最小化 if ("windows" === window.siyuan.config.system.os) { ipcRenderer.send(Constants.SIYUAN_CONFIG_TRAY, { languages: window.siyuan.languages["_trayMenu"], }); } else { ipcRenderer.send(Constants.SIYUAN_CMD, "closeButtonBehavior"); } } else { exitSiYuan(); } }, errorExit: true }); };
/// #if !BROWSER
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/boot/onGetConfig.ts#L115-L133
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
updateTab
const updateTab = () => { const indexList: number[] = []; const inputValue = inputElement.value; configIndex.map((item, index) => { item.map((subItem) => { if (!subItem) { console.warn("Search config miss language: ", item, index); } if (subItem && (inputValue.toLowerCase().indexOf(subItem.toLowerCase()) > -1 || subItem.toLowerCase().indexOf(inputValue.toLowerCase()) > -1)) { indexList.push(index); } }); }); let currentTabElement: HTMLElement; element.querySelectorAll(".b3-tab-bar li").forEach((item: HTMLElement, index) => { if (indexList.includes(index)) { if (!currentTabElement) { currentTabElement = item; } const type = item.getAttribute("data-name"); item.style.display = ""; if (["image", "bazaar", "account"].includes(type)) { return; } // 右侧面板过滤 const panelElement = element.querySelector(`.config__tab-container[data-name="${type}"]`); if (panelElement.innerHTML === "") { genItemPanel(type, panelElement, app); } if (type === "keymap") { const searchElement = keymap.element.querySelector("#keymapInput") as HTMLInputElement; const searchKeymapElement = keymap.element.querySelector("#searchByKey") as HTMLInputElement; searchElement.value = inputValue; searchKeymapElement.value = ""; keymap.search(searchElement.value, searchKeymapElement.value); } else { panelElement.querySelectorAll(`.config__tab-container[data-name="${type}"] .b3-label`).forEach((itemElement: HTMLElement) => { if (!itemElement.classList.contains("fn__none")) { const text = itemElement.textContent.toLowerCase(); if (text.indexOf(inputValue.toLowerCase()) > -1 || inputValue.toLowerCase().indexOf(text) > -1) { itemElement.style.display = ""; } else { itemElement.style.display = "none"; } } }); } } else { item.style.display = "none"; } }); const tabPanelElements = element.querySelectorAll(".config__tab-container"); if (currentTabElement) { currentTabElement.click(); } else { tabPanelElements.forEach((item) => { item.classList.add("fn__none"); }); } inputElement.focus(); };
/// #endif
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/config/search.ts#L110-L173
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
getUnInitTab
const getUnInitTab = (options: IOpenFileOptions) => { return getAllTabs().find(item => { const initData = item.headElement?.getAttribute("data-initdata"); if (initData) { const initObj = JSON.parse(initData); if (initObj.instance === "Editor" && (initObj.rootId === options.rootID || initObj.blockId === options.rootID)) { initObj.blockId = options.id; initObj.mode = options.mode; if (options.zoomIn) { initObj.action = [Constants.CB_GET_ALL, Constants.CB_GET_FOCUS]; } else { initObj.action = options.action; } item.headElement.setAttribute("data-initdata", JSON.stringify(initObj)); item.parent.switchTab(item.headElement); return true; } else if (initObj.instance === "Custom" && options.custom && objEquals(initObj.customModelData, options.custom.data)) { item.parent.switchTab(item.headElement); return true; } } }); };
// 没有初始化的页签无法检测到
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/editor/util.ts#L323-L346
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
importstdmd
const importstdmd = (label: string, isDoc?: boolean) => { return { id: isDoc ? "importMarkdownDoc" : "importMarkdownFolder", icon: isDoc ? "iconMarkdown" : "iconFolder", label, click: async () => { let filters: FileFilter[] = []; if (isDoc) { filters = [{name: "Markdown", extensions: ["md", "markdown"]}]; } const localPath = await ipcRenderer.invoke(Constants.SIYUAN_GET, { cmd: "showOpenDialog", defaultPath: window.siyuan.config.system.homeDir, filters, properties: [isDoc ? "openFile" : "openDirectory"], }); if (localPath.filePaths.length === 0) { return; } fetchPost("/api/import/importStdMd", { notebook: notebookId, localPath: localPath.filePaths[0], toPath: pathString, }, () => { reloadDocTree(); }); } }; };
/// #if !BROWSER
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/menus/navigation.ts#L732-L760
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
getModelByDockType
const getModelByDockType = (type: TDock | string) => { /// #if MOBILE return window.siyuan.mobile.docks[type]; /// #else return getDockByType(type).data[type]; /// #endif };
/// #endif
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/plugin/API.ts#L171-L177
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
Protyle.constructor
constructor(app: App, id: HTMLElement, options?: IProtyleOptions) { this.version = Constants.SIYUAN_VERSION; let pluginsOptions: IProtyleOptions = options; app.plugins.forEach(item => { if (item.protyleOptions) { pluginsOptions = merge(pluginsOptions, item.protyleOptions); } }); const getOptions = new Options(pluginsOptions); const mergedOptions = getOptions.merge(); this.protyle = { getInstance: () => this, app, transactionTime: new Date().getTime(), id: genUUID(), disabled: false, updated: false, element: id, options: mergedOptions, block: {}, highlight: { mark: isSupportCSSHL() ? new Highlight() : undefined, markHL: isSupportCSSHL() ? new Highlight() : undefined, ranges: [], rangeIndex: 0, styleElement: document.createElement("style"), } }; if (isSupportCSSHL()) { const styleId = genUUID(); this.protyle.highlight.styleElement.dataset.uuid = styleId; this.protyle.highlight.styleElement.textContent = `.protyle-wysiwyg::highlight(search-mark-${styleId}) {background-color: var(--b3-highlight-background);color: var(--b3-highlight-color);} .protyle-wysiwyg::highlight(search-mark-hl-${styleId}) {color: var(--b3-highlight-color);background-color: var(--b3-highlight-current-background)}`; } this.protyle.hint = new Hint(this.protyle); if (mergedOptions.render.breadcrumb) { this.protyle.breadcrumb = new Breadcrumb(this.protyle); } if (mergedOptions.render.title) { this.protyle.title = new Title(this.protyle); } if (mergedOptions.render.background) { this.protyle.background = new Background(this.protyle); } this.protyle.element.innerHTML = ""; this.protyle.element.classList.add("protyle"); if (mergedOptions.render.breadcrumb) { this.protyle.element.appendChild(this.protyle.breadcrumb.element.parentElement); } this.protyle.undo = new Undo(); this.protyle.wysiwyg = new WYSIWYG(this.protyle); this.protyle.toolbar = new Toolbar(this.protyle); this.protyle.scroll = new Scroll(this.protyle); // 不能使用 render.scroll 来判读是否初始化,除非重构后面用到的相关变量 if (this.protyle.options.render.gutter) { this.protyle.gutter = new Gutter(this.protyle); } if (mergedOptions.upload.url || mergedOptions.upload.handler) { this.protyle.upload = new Upload(); } this.init(); if (!mergedOptions.action.includes(Constants.CB_GET_HISTORY)) { this.protyle.ws = new Model({ app, id: this.protyle.id, type: "protyle", msgCallback: (data) => { switch (data.cmd) { case "reload": if (data.data === this.protyle.block.rootID) { reloadProtyle(this.protyle, false); } break; case "refreshAttributeView": Array.from(this.protyle.wysiwyg.element.querySelectorAll(`[data-av-id="${data.data.id}"]`)).forEach((item: HTMLElement) => { item.removeAttribute("data-render"); avRender(item, this.protyle); }); break; case "addLoading": if (data.data === this.protyle.block.rootID) { addLoading(this.protyle, data.msg); } break; case "transactions": data.data[0].doOperations.find((item: IOperation) => { if (!this.protyle.preview.element.classList.contains("fn__none") && item.action !== "updateAttrs" // 预览模式下点击只读 ) { this.protyle.preview.render(this.protyle); } else if (options.backlinkData && ["delete", "move"].includes(item.action)) { // 只对特定情况刷新,否则展开、编辑等操作刷新会频繁 getAllModels().backlink.find(backlinkItem => { if (backlinkItem.element.contains(this.protyle.element)) { backlinkItem.refresh(); return true; } }); return true; } else { onTransaction(this.protyle, item, false); } }); break; case "readonly": window.siyuan.config.editor.readOnly = data.data; setReadonlyByConfig(this.protyle, true); break; case "heading2doc": case "li2doc": if (this.protyle.block.rootID === data.data.srcRootBlockID) { if (this.protyle.block.showAll && data.cmd === "heading2doc" && !this.protyle.options.backlinkData) { fetchPost("/api/filetree/getDoc", { id: this.protyle.block.rootID, size: window.siyuan.config.editor.dynamicLoadBlocks, }, getResponse => { onGet({data: getResponse, protyle: this.protyle}); }); } else { reloadProtyle(this.protyle, false); } /// #if !MOBILE if (data.cmd === "heading2doc") { // 文档标题互转后,需更新大纲 updatePanelByEditor({ protyle: this.protyle, focus: false, pushBackStack: false, reload: true, resize: false }); } /// #endif } break; case "rename": if (this.protyle.path === data.data.path) { if (this.protyle.model) { this.protyle.model.parent.updateTitle(data.data.title); } if (this.protyle.background) { this.protyle.background.ial.title = data.data.title; } } if (this.protyle.options.render.title && this.protyle.block.parentID === data.data.id) { if (!document.body.classList.contains("body--blur") && getSelection().rangeCount > 0 && this.protyle.title.editElement?.contains(getSelection().getRangeAt(0).startContainer)) { // 标题编辑中的不用更新 https://github.com/siyuan-note/siyuan/issues/6565 } else { this.protyle.title.setTitle(data.data.title); } } // update ref this.protyle.wysiwyg.element.querySelectorAll(`[data-type~="block-ref"][data-id="${data.data.id}"]`).forEach(item => { if (item.getAttribute("data-subtype") === "d") { // 同 updateRef 一样处理 https://github.com/siyuan-note/siyuan/issues/10458 item.innerHTML = data.data.refText; } }); break; case "moveDoc": if (this.protyle.path === data.data.fromPath) { this.protyle.path = data.data.newPath; this.protyle.notebookId = data.data.toNotebook; } break; case "unmount": if (this.protyle.notebookId === data.data.box) { /// #if MOBILE setEmpty(app); /// #else if (this.protyle.model) { this.protyle.model.parent.parent.removeTab(this.protyle.model.parent.id, false); } /// #endif } break; case "removeDoc": if (data.data.ids.includes(this.protyle.block.rootID)) { /// #if MOBILE setEmpty(app); /// #else if (this.protyle.model) { this.protyle.model.parent.parent.removeTab(this.protyle.model.parent.id, false); } /// #endif delete window.siyuan.storage[Constants.LOCAL_FILEPOSITION][this.protyle.block.rootID]; setStorageVal(Constants.LOCAL_FILEPOSITION, window.siyuan.storage[Constants.LOCAL_FILEPOSITION]); } break; } } }); if (options.backlinkData) { this.protyle.block.rootID = options.blockId; renderBacklink(this.protyle, options.backlinkData); // 为了满足 eventPath0.style.paddingLeft 从而显示块标 https://github.com/siyuan-note/siyuan/issues/11578 this.protyle.wysiwyg.element.style.paddingLeft = "16px"; return; } if (!options.blockId) { // 搜索页签需提前初始化 removeLoading(this.protyle); return; } if (this.protyle.options.mode !== "preview" && options.rootId && window.siyuan.storage[Constants.LOCAL_FILEPOSITION][options.rootId] && ( mergedOptions.action.includes(Constants.CB_GET_SCROLL) || (mergedOptions.action.includes(Constants.CB_GET_ROOTSCROLL) && options.rootId === options.blockId) ) ) { getDocByScroll({ protyle: this.protyle, scrollAttr: window.siyuan.storage[Constants.LOCAL_FILEPOSITION][options.rootId], mergedOptions, cb: () => { this.afterOnGet(mergedOptions); } }); } else { this.getDoc(mergedOptions); } } else { this.protyle.contentElement.classList.add("protyle-content--transition"); } }
/** * @param id 要挂载 Protyle 的元素或者元素 ID。 * @param options Protyle 参数 */
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L57-L287
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
Protyle.focus
public focus() { this.protyle.wysiwyg.element.focus(); }
/** 聚焦到编辑器 */
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L378-L380
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
Protyle.isUploading
public isUploading() { return this.protyle.upload.isUploading; }
/** 上传是否还在进行中 */
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L383-L385
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
Protyle.clearStack
public clearStack() { this.protyle.undo.clear(); }
/** 清空 undo & redo 栈 */
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L388-L390
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
Protyle.destroy
public destroy() { destroy(this.protyle); }
/** 销毁编辑器 */
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L393-L395
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
Protyle.turnIntoOneTransaction
public turnIntoOneTransaction(selectsElement: Element[], type: TTurnIntoOne, subType?: TTurnIntoOneSub) { turnsIntoOneTransaction({ protyle: this.protyle, selectsElement, type, level: subType }); }
/** * 多个块转换为一个块 * @param {TTurnIntoOneSub} [subType] type 为 "BlocksMergeSuperBlock" 时必传 */
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L417-L424
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
Protyle.turnIntoTransaction
public turnIntoTransaction(nodeElement: Element, type: TTurnInto, subType?: number) { turnsIntoTransaction({ protyle: this.protyle, nodeElement, type, level: subType, }); }
/** * 多个块转换 * @param {Element} [nodeElement] 优先使用包含 protyle-wysiwyg--select 的块,否则使用 nodeElement 单块 * @param {number} [subType] type 为 "Blocks2Hs" 时必传 */
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/index.ts#L431-L438
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
renderPDF
const renderPDF = async (id: string) => { const localData = window.siyuan.storage[Constants.LOCAL_EXPORTPDF]; const servePath = window.location.protocol + "//" + window.location.host; const isDefault = (window.siyuan.config.appearance.mode === 1 && window.siyuan.config.appearance.themeDark === "midnight") || (window.siyuan.config.appearance.mode === 0 && window.siyuan.config.appearance.themeLight === "daylight"); let themeStyle = ""; if (!isDefault) { themeStyle = `<link rel="stylesheet" type="text/css" id="themeStyle" href="${servePath}/appearance/themes/${window.siyuan.config.appearance.themeLight}/theme.css?${Constants.SIYUAN_VERSION}"/>`; } const currentWindowId = await ipcRenderer.invoke(Constants.SIYUAN_GET, { cmd: "getContentsId", }); // data-theme-mode="light" https://github.com/siyuan-note/siyuan/issues/7379 const html = `<!DOCTYPE html> <html lang="${window.siyuan.config.appearance.lang}" data-theme-mode="light" data-light-theme="${window.siyuan.config.appearance.themeLight}" data-dark-theme="${window.siyuan.config.appearance.themeDark}"> <head> <base href="${servePath}/"> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"/> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <link rel="stylesheet" type="text/css" id="baseStyle" href="${servePath}/stage/build/export/base.css?v=${Constants.SIYUAN_VERSION}"/> <link rel="stylesheet" type="text/css" id="themeDefaultStyle" href="${servePath}/appearance/themes/daylight/theme.css?v=${Constants.SIYUAN_VERSION}"/> <script src="${servePath}/stage/protyle/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}"></script> ${themeStyle} <title>${window.siyuan.languages.export} PDF</title> <style> body { margin: 0; font-family: var(--b3-font-family); } #action { width: 232px; background: var(--b3-theme-surface); padding: 16px 0; position: fixed; right: 0; top: 0; overflow-y: auto; bottom: 0; overflow-x: hidden; z-index: 1; display: flex; flex-direction: column; } #preview { max-width: 800px; margin: 0 auto; position: absolute; right: 232px; left: 0; box-sizing: border-box; } #preview.exporting { position: inherit; max-width: none; } .b3-switch { margin-left: 14px; } .exporting::-webkit-scrollbar { width: 0; height: 0; } .protyle-wysiwyg { height: 100%; overflow: auto; box-sizing: border-box; } .b3-label { border-bottom: 1px solid var(--b3-theme-surface-lighter); display: block; color: var(--b3-theme-on-surface); padding-bottom: 16px; margin: 0 16px 16px 16px; } .b3-label:last-child { border-bottom: none; } ${await setInlineStyle(false)} ${document.getElementById("pluginsStyle").innerHTML} ${getSnippetCSS()} </style> </head> <body style="-webkit-print-color-adjust: exact;"> <div id="action"> <div style="flex: 1;overflow: auto;"> <div class="b3-label"> <div> ${window.siyuan.languages.exportPDF0} </div> <span class="fn__hr"></span> <select class="b3-select" id="pageSize"> <option ${localData.pageSize === "A3" ? "selected" : ""} value="A3">A3</option> <option ${localData.pageSize === "A4" ? "selected" : ""} value="A4">A4</option> <option ${localData.pageSize === "A5" ? "selected" : ""} value="A5">A5</option> <option ${localData.pageSize === "Legal" ? "selected" : ""} value="Legal">Legal</option> <option ${localData.pageSize === "Letter" ? "selected" : ""} value="Letter">Letter</option> <option ${localData.pageSize === "Tabloid" ? "selected" : ""} value="Tabloid">Tabloid</option> </select> </div> <div class="b3-label"> <div> ${window.siyuan.languages.exportPDF2} </div> <span class="fn__hr"></span> <select class="b3-select" id="marginsType"> <option ${localData.marginType === "default" ? "selected" : ""} value="default">${window.siyuan.languages.defaultMargin}</option> <option ${localData.marginType === "none" ? "selected" : ""} value="none">${window.siyuan.languages.noneMargin}</option> <option ${localData.marginType === "printableArea" ? "selected" : ""} value="printableArea">${window.siyuan.languages.minimalMargin}</option> <option ${localData.marginType === "custom" ? "selected" : ""} value="custom">${window.siyuan.languages.customMargin}</option> </select> <div class="${localData.marginType === "custom" ? "" : "fn__none"}"> <span class="fn__hr"></span> <div>${window.siyuan.languages.marginTop}</div> <input id="marginsTop" class="b3-text-field fn__block" value="${localData.marginTop || 0}" type="number" min="0" step="0.01"> <span class="fn__hr"></span> <div>${window.siyuan.languages.marginRight}</div> <input id="marginsRight" class="b3-text-field fn__block" value="${localData.marginRight || 0}" type="number" min="0" step="0.01"> <span class="fn__hr"></span> <div>${window.siyuan.languages.marginBottom}</div> <input id="marginsBottom" class="b3-text-field fn__block" value="${localData.marginBottom || 0}" type="number" min="0" step="0.01"> <span class="fn__hr"></span> <div>${window.siyuan.languages.marginLeft}</div> <input id="marginsLeft" class="b3-text-field fn__block" value="${localData.marginLeft || 0}" type="number" min="0" step="0.01"> </div> </div> <div class="b3-label"> <div> ${window.siyuan.languages.exportPDF3} <span id="scaleTip" style="float: right;color: var(--b3-theme-on-background);">${localData.scale || 1}</span> </div> <span class="fn__hr"></span> <input style="width: 192px" value="${localData.scale || 1}" id="scale" step="0.1" class="b3-slider" type="range" min="0.1" max="2"> </div> <label class="b3-label"> <div> ${window.siyuan.languages.exportPDF1} </div> <span class="fn__hr"></span> <input id="landscape" class="b3-switch" type="checkbox" ${localData.landscape ? "checked" : ""}> </label> <label class="b3-label"> <div> ${window.siyuan.languages.exportPDF4} </div> <span class="fn__hr"></span> <input id="removeAssets" class="b3-switch" type="checkbox" ${localData.removeAssets ? "checked" : ""}> </label> <label class="b3-label"> <div> ${window.siyuan.languages.exportPDF5} </div> <span class="fn__hr"></span> <input id="keepFold" class="b3-switch" type="checkbox" ${localData.keepFold ? "checked" : ""}> </label> <label class="b3-label"> <div> ${window.siyuan.languages.mergeSubdocs} </div> <span class="fn__hr"></span> <input id="mergeSubdocs" class="b3-switch" type="checkbox" ${localData.mergeSubdocs ? "checked" : ""}> </label> <label class="b3-label"> <div> ${window.siyuan.languages.export27} </div> <span class="fn__hr"></span> <input id="watermark" class="b3-switch" type="checkbox" ${localData.watermark ? "checked" : ""}> <div style="display:none;font-size: 12px;margin-top: 12px;color: var(--b3-theme-on-surface);">${window.siyuan.languages._kernel[214]}</div> </label> </div> <div class="fn__flex" style="padding: 0 16px"> <div class="fn__flex-1"></div> <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button> <div class="fn__space"></div> <button class="b3-button b3-button--text">${window.siyuan.languages.confirm}</button> </div> </div> <div style="zoom:${localData.scale || 1}" id="preview"> <div class="fn__loading" style="left:0;height:100vh"><img width="48px" src="${servePath}/stage/loading-pure.svg"></div> </div> <script src="${servePath}/appearance/icons/${window.siyuan.config.appearance.icon}/icon.js?${Constants.SIYUAN_VERSION}"></script> <script src="${servePath}/stage/build/export/protyle-method.js?${Constants.SIYUAN_VERSION}"></script> <script src="${servePath}/stage/protyle/js/lute/lute.min.js?${Constants.SIYUAN_VERSION}"></script> <script> const previewElement = document.getElementById('preview'); const fixBlockWidth = () => { const isLandscape = document.querySelector("#landscape").checked; let width = 800 switch (document.querySelector("#action #pageSize").value) { case "A3": width = isLandscape ? 1587.84 : 1122.24 break; case "A4": width = isLandscape ? 1122.24 : 793.92 break; case "A5": width = isLandscape ? 793.92 : 559.68 break; case "Legal": width = isLandscape ? 1344: 816 break; case "Letter": width = isLandscape ? 1056 : 816 break; case "Tabloid": width = isLandscape ? 1632 : 1056 break; } width = width / parseFloat(document.querySelector("#scale").value); previewElement.style.width = width + "px"; width = width - parseFloat(previewElement.style.paddingLeft) * 96 * 2; // 为保持代码块宽度一致,全部都进行宽度设定 https://github.com/siyuan-note/siyuan/issues/7692 previewElement.querySelectorAll('.hljs').forEach((item) => { // 强制换行 https://ld246.com/article/1679228783553 item.parentElement.setAttribute("linewrap", "true"); item.parentElement.style.width = ""; item.parentElement.style.boxSizing = "border-box"; item.parentElement.style.width = Math.min(item.parentElement.clientWidth, width) + "px"; item.removeAttribute('data-render'); }) Protyle.highlightRender(previewElement, "${servePath}/stage/protyle"); previewElement.querySelectorAll('[data-type="NodeMathBlock"]').forEach((item) => { item.style.width = ""; item.style.boxSizing = "border-box"; item.style.width = Math.min(item.clientWidth, width) + "px"; item.removeAttribute('data-render'); }) previewElement.querySelectorAll('[data-type="NodeCodeBlock"][data-subtype="mermaid"] svg').forEach((item) => { item.style.maxHeight = width * 1.414 + "px"; }) Protyle.mathRender(previewElement, "${servePath}/stage/protyle", true); previewElement.querySelectorAll("table").forEach(item => { if (item.clientWidth > item.parentElement.clientWidth) { item.style.zoom = (item.parentElement.clientWidth / item.clientWidth).toFixed(2) - 0.01; item.parentElement.style.overflow = "hidden"; } }) } const setPadding = () => { const isLandscape = document.querySelector("#landscape").checked; const topElement = document.querySelector("#marginsTop") const rightElement = document.querySelector("#marginsRight") const bottomElement = document.querySelector("#marginsBottom") const leftElement = document.querySelector("#marginsLeft") switch (document.querySelector("#marginsType").value) { case "default": if (isLandscape) { topElement.value = "0.42"; rightElement.value = "0.42"; bottomElement.value = "0.42"; leftElement.value = "0.42"; } else { topElement.value = "1"; rightElement.value = "0.54"; bottomElement.value = "1"; leftElement.value = "0.54"; } break; case "none": // none topElement.value = "0"; rightElement.value = "0"; bottomElement.value = "0"; leftElement.value = "0"; break; case "printableArea": // minimal if (isLandscape) { topElement.value = ".07"; rightElement.value = ".07"; bottomElement.value = ".07"; leftElement.value = ".07"; } else { topElement.value = "0.58"; rightElement.value = "0.1"; bottomElement.value = "0.58"; leftElement.value = "0.1"; } break; } document.getElementById('preview').style.padding = topElement.value + "in " + rightElement.value + "in " + bottomElement.value + "in " + leftElement.value + "in"; setTimeout(() => { fixBlockWidth(); }, 300); } const fetchPost = (url, data, cb) => { fetch("${servePath}" + url, { method: "POST", body: JSON.stringify(data) }).then((response) => { return response.json(); }).then((response) => { cb(response); }) } const renderPreview = (data) => { previewElement.innerHTML = '<div style="padding:6px 0 0 0" class="protyle-wysiwyg${window.siyuan.config.editor.displayBookmarkIcon ? " protyle-wysiwyg--attr" : ""}">' + data.content + '</div>'; const wysElement = previewElement.querySelector(".protyle-wysiwyg"); wysElement.setAttribute("data-doc-type", data.type || "NodeDocument"); if (data.attrs.memo) { wysElement.setAttribute("memo", data.attrs.memo); } if (data.attrs.name) { wysElement.setAttribute("name", data.attrs.name); } if (data.attrs.bookmark) { wysElement.setAttribute("bookmark", data.attrs.bookmark); } if (data.attrs.alias) { wysElement.setAttribute("alias", data.attrs.alias); } Protyle.mermaidRender(wysElement, "${servePath}/stage/protyle"); Protyle.flowchartRender(wysElement, "${servePath}/stage/protyle"); Protyle.graphvizRender(wysElement, "${servePath}/stage/protyle"); Protyle.chartRender(wysElement, "${servePath}/stage/protyle"); Protyle.mindmapRender(wysElement, "${servePath}/stage/protyle"); Protyle.abcRender(wysElement, "${servePath}/stage/protyle"); Protyle.htmlRender(wysElement); Protyle.plantumlRender(wysElement, "${servePath}/stage/protyle"); } fetchPost("/api/export/exportPreviewHTML", { id: "${id}", keepFold: ${localData.keepFold}, merge: ${localData.mergeSubdocs}, }, response => { if (response.code === 1) { alert(response.msg) return; } document.title = response.data.name window.siyuan = { config: { appearance: { mode: 0, codeBlockThemeDark: "${window.siyuan.config.appearance.codeBlockThemeDark}", codeBlockThemeLight: "${window.siyuan.config.appearance.codeBlockThemeLight}" }, editor: { allowHTMLBLockScript: ${window.siyuan.config.editor.allowHTMLBLockScript}, fontSize: ${window.siyuan.config.editor.fontSize}, codeLineWrap: true, codeLigatures: ${window.siyuan.config.editor.codeLigatures}, plantUMLServePath: "${window.siyuan.config.editor.plantUMLServePath}", codeSyntaxHighlightLineNum: ${window.siyuan.config.editor.codeSyntaxHighlightLineNum}, katexMacros: JSON.stringify(${window.siyuan.config.editor.katexMacros}), } }, languages: {copy:"${window.siyuan.languages.copy}"} }; previewElement.addEventListener("click", (event) => { let target = event.target; while (target && !target.isEqualNode(previewElement)) { if (target.tagName === "A") { const linkAddress = target.getAttribute("href"); if (linkAddress.startsWith("#")) { // 导出预览模式点击块引转换后的脚注跳转不正确 https://github.com/siyuan-note/siyuan/issues/5700 const hash = linkAddress.substring(1); previewElement.querySelector('[data-node-id="' + hash + '"], [id="' + hash + '"]').scrollIntoView(); event.stopPropagation(); event.preventDefault(); return; } } else if (target.classList.contains("protyle-action__copy")) { let text = target.parentElement.nextElementSibling.textContent.trimEnd(); text = text.replace(/\u00A0/g, " "); // Replace non-breaking spaces with normal spaces when copying https://github.com/siyuan-note/siyuan/issues/9382 navigator.clipboard.writeText(text); event.preventDefault(); event.stopPropagation(); break; } target = target.parentElement; } }); const actionElement = document.getElementById('action'); const keepFoldElement = actionElement.querySelector('#keepFold'); keepFoldElement.addEventListener('change', () => { refreshPreview(); }); const mergeSubdocsElement = actionElement.querySelector('#mergeSubdocs'); mergeSubdocsElement.addEventListener('change', () => { refreshPreview(); }); const watermarkElement = actionElement.querySelector('#watermark'); watermarkElement.addEventListener('change', () => { if (watermarkElement.checked && ${!isPaidUser()}) { watermarkElement.nextElementSibling.style.display = ""; watermarkElement.checked = false; } }); const refreshPreview = () => { previewElement.innerHTML = '<div class="fn__loading" style="left:0;height: 100vh"><img width="48px" src="${servePath}/stage/loading-pure.svg"></div>' fetchPost("/api/export/exportPreviewHTML", { id: "${id}", keepFold: keepFoldElement.checked, merge: mergeSubdocsElement.checked, }, response2 => { if (response2.code === 1) { alert(response2.msg) return; } setPadding(); renderPreview(response2.data); }) }; actionElement.querySelector("#scale").addEventListener("input", () => { const scale = actionElement.querySelector("#scale").value; actionElement.querySelector("#scaleTip").innerText = scale; previewElement.style.zoom = scale; fixBlockWidth(); }) actionElement.querySelector("#pageSize").addEventListener('change', () => { fixBlockWidth(); }); actionElement.querySelector("#marginsType").addEventListener('change', (event) => { setPadding(); if (event.target.value === "custom") { event.target.nextElementSibling.classList.remove("fn__none"); } else { event.target.nextElementSibling.classList.add("fn__none"); } }); actionElement.querySelector("#marginsTop").addEventListener('change', () => { setPadding(); }); actionElement.querySelector("#marginsRight").addEventListener('change', () => { setPadding(); }); actionElement.querySelector("#marginsBottom").addEventListener('change', () => { setPadding(); }); actionElement.querySelector("#marginsLeft").addEventListener('change', () => { setPadding(); }); actionElement.querySelector("#landscape").addEventListener('change', () => { setPadding(); }); actionElement.querySelector('.b3-button--cancel').addEventListener('click', () => { const {ipcRenderer} = require("electron"); ipcRenderer.send("${Constants.SIYUAN_CMD}", "destroy") }); actionElement.querySelector('.b3-button--text').addEventListener('click', () => { const {ipcRenderer} = require("electron"); ipcRenderer.send("${Constants.SIYUAN_EXPORT_PDF}", { title: "${window.siyuan.languages.export} PDF", pdfOptions:{ printBackground: true, landscape: actionElement.querySelector("#landscape").checked, marginType: actionElement.querySelector("#marginsType").value, margins: { top: parseFloat(document.querySelector("#marginsTop").value), bottom: parseFloat(document.querySelector("#marginsBottom").value), left: parseFloat(document.querySelector("#marginsLeft").value), right: parseFloat(document.querySelector("#marginsRight").value), }, scale: parseFloat(actionElement.querySelector("#scale").value), pageSize: actionElement.querySelector("#pageSize").value, }, keepFold: keepFoldElement.checked, mergeSubdocs: mergeSubdocsElement.checked, watermark: watermarkElement.checked, removeAssets: actionElement.querySelector("#removeAssets").checked, rootId: "${id}", rootTitle: response.data.name, parentWindowId: ${currentWindowId}, }) previewElement.classList.add("exporting"); previewElement.style.zoom = ""; previewElement.style.paddingTop = "6px"; previewElement.style.paddingBottom = "0"; fixBlockWidth(); actionElement.remove(); }); setPadding(); renderPreview(response.data); window.addEventListener("keydown", (event) => { if (event.key === "Escape") { const {ipcRenderer} = require("electron"); ipcRenderer.send("${Constants.SIYUAN_CMD}", "destroy") event.preventDefault(); } }) }); </script></body></html>`; fetchPost("/api/export/exportTempContent", {content: html}, (response) => { ipcRenderer.send(Constants.SIYUAN_EXPORT_NEWWINDOW, response.data.url); }); };
/// #if !BROWSER
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/export/index.ts#L83-L578
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
Gutter.genHeights
private genHeights(nodeElements: Element[], protyle: IProtyle) { const matchHeight = nodeElements.find(item => { if (!item.classList.contains("p") && !item.classList.contains("code-block") && !item.classList.contains("render-node")) { return true; } }); if (matchHeight) { return; } let rangeElement: HTMLInputElement; const firstElement = nodeElements[0] as HTMLElement; const styles: IMenu[] = [{ id: "heightInput", iconHTML: "", type: "readonly", label: `<div class="fn__flex-center"> <input class="b3-text-field" value="${firstElement.style.height.endsWith("px") ? parseInt(firstElement.style.height) : ""}" type="number" style="margin: 4px" placeholder="${window.siyuan.languages.height}"> px </div>`, bind: (element) => { const inputElement = element.querySelector("input"); inputElement.addEventListener("input", () => { nodeElements.forEach((item: HTMLElement) => { item.style.height = inputElement.value + "px"; item.style.flex = "none"; }); rangeElement.value = "0"; rangeElement.parentElement.setAttribute("aria-label", inputElement.value + "px"); }); this.updateNodeElements(nodeElements, protyle, inputElement); } }]; ["25%", "33%", "50%", "67%", "75%", "100%"].forEach((item) => { styles.push({ id: "height_" + item, iconHTML: "", label: item, click: () => { this.genClick(nodeElements, protyle, (e: HTMLElement) => { e.style.height = item; e.style.flex = "none"; }); } }); }); styles.push({ type: "separator" }); const height = firstElement.style.height.endsWith("%") ? parseInt(firstElement.style.height) : 0; window.siyuan.menus.menu.append(new MenuItem({ id: "heightDrag", label: window.siyuan.languages.height, submenu: styles.concat([{ iconHTML: "", type: "readonly", label: `<div style="margin: 4px 0;" aria-label="${firstElement.style.height.endsWith("px") ? firstElement.style.height : (firstElement.style.height || window.siyuan.languages.default)}" class="b3-tooltips b3-tooltips__n${isMobile() ? "" : " fn__size200"}"> <input style="box-sizing: border-box" value="${height}" class="b3-slider fn__block" max="100" min="1" step="1" type="range"> </div>`, bind: (element) => { rangeElement = element.querySelector("input"); rangeElement.addEventListener("input", () => { nodeElements.forEach((e: HTMLElement) => { e.style.height = rangeElement.value + "%"; e.style.flex = "none"; }); rangeElement.parentElement.setAttribute("aria-label", `${rangeElement.value}%`); }); this.updateNodeElements(nodeElements, protyle, rangeElement); } }, { type: "separator" }, { id: "default", iconHTML: "", label: window.siyuan.languages.default, click: () => { this.genClick(nodeElements, protyle, (e: HTMLElement) => { if (e.style.height) { e.style.height = ""; e.style.overflow = ""; } }); } }]), }).element); }
// TODO https://github.com/siyuan-note/siyuan/issues/11055
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/gutter/index.ts#L2163-L2247
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
getAbcParams
const getAbcParams = (abcString: string): any => { let params = { responsive: "resize", }; const firstLine = abcString.substring(0, abcString.indexOf("\n")); if (firstLine.startsWith(ABCJS_PARAMS_KEY)) { try { params = looseJsonParse(firstLine.substring(ABCJS_PARAMS_KEY.length)); } catch (e) { console.error(`Failed to parse ABCJS params: ${e}`); } } return params; };
// Read the abcjsParams from the content if it exists.
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/render/abcRender.ts#L12-L25
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
Scroll.constructor
constructor(protyle: IProtyle) { this.parentElement = document.createElement("div"); this.parentElement.classList.add("protyle-scroll"); this.parentElement.innerHTML = `<div class="protyle-scroll__up ariaLabel" data-position="right4top" aria-label="${updateHotkeyTip("⌘Home")}"> <svg><use xlink:href="#iconUp"></use></svg> </div> <div class="fn__none protyle-scroll__bar ariaLabel" data-position="right18bottom" aria-label="Blocks 1/1"> <input class="b3-slider" type="range" max="1" min="1" step="1" value="1" /> </div> <div class="protyle-scroll__down ariaLabel" data-position="right4bottom" aria-label="${updateHotkeyTip("⌘End")}"> <svg><use xlink:href="#iconDown"></use></svg> </div>`; this.element = this.parentElement.querySelector(".protyle-scroll__bar"); this.keepLazyLoad = false; if (!protyle.options.render.scroll) { this.parentElement.classList.add("fn__none"); } this.lastScrollTop = 0; this.inputElement = this.element.firstElementChild as HTMLInputElement; this.inputElement.addEventListener("input", () => { this.element.setAttribute("aria-label", `Blocks ${this.inputElement.value}/${protyle.block.blockCount}`); showTooltip(this.element.getAttribute("aria-label"), this.element); }); /// #if BROWSER this.inputElement.addEventListener("change", () => { this.setIndex(protyle); }); this.inputElement.addEventListener("touchend", () => { this.setIndex(protyle); }); /// #endif this.parentElement.addEventListener("click", (event) => { const target = event.target as HTMLElement; if (hasClosestByClassName(target, "protyle-scroll__up")) { goHome(protyle); } else if (hasClosestByClassName(target, "protyle-scroll__down")) { goEnd(protyle); } else if (target.classList.contains("b3-slider")) { this.setIndex(protyle); } }); }
// 保持加载内容
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/scroll/index.ts#L16-L58
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
Toolbar.mergeNode
private mergeNode(nodes: NodeListOf<ChildNode>) { for (let i = 0; i < nodes.length; i++) { if (nodes[i].nodeType !== 3 && (nodes[i] as HTMLElement).tagName === "WBR") { nodes[i].remove(); i--; } } for (let i = 0; i < nodes.length; i++) { if (nodes[i].nodeType === 3) { if (nodes[i].textContent === "") { nodes[i].remove(); i--; } else if (nodes[i + 1] && nodes[i + 1].nodeType === 3) { nodes[i].textContent = nodes[i].textContent + nodes[i + 1].textContent; nodes[i + 1].remove(); i--; } } } }
// 合并多个 text 为一个 text
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/toolbar/index.ts#L1681-L1700
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
RecordMedia.cloneChannelData
public cloneChannelData(leftChannelData: Float32List, rightChannelData: Float32List) { this.leftChannel.push(new Float32Array(leftChannelData)); this.rightChannel.push(new Float32Array(rightChannelData)); this.recordingLength += 2048; }
// Publicly accessible methods:
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/util/RecordMedia.ts#L50-L54
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
goPreviousCell
const goPreviousCell = (cellElement: HTMLElement, range: Range, isSelected = true) => { let previousElement = cellElement.previousElementSibling; if (!previousElement) { if (cellElement.parentElement.previousElementSibling) { previousElement = cellElement.parentElement.previousElementSibling.lastElementChild; } else if (cellElement.parentElement.parentElement.tagName === "TBODY" && cellElement.parentElement.parentElement.previousElementSibling) { previousElement = cellElement.parentElement .parentElement.previousElementSibling.lastElementChild.lastElementChild; } else { previousElement = null; } } if (previousElement) { range.selectNodeContents(previousElement); if (!isSelected) { range.collapse(false); } focusByRange(range); } return previousElement; };
// 光标设置到前一个表格中
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/util/table.ts#L36-L57
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
WYSIWYG.escapeInline
private escapeInline(protyle: IProtyle, range: Range, event: InputEvent) { if (!event.data && event.inputType !== "insertLineBreak") { return; } const inputData = event.data; protyle.toolbar.range = range; const inlineElement = range.startContainer.parentElement; const currentTypes = protyle.toolbar.getCurrentType(); // https://github.com/siyuan-note/siyuan/issues/11766 if (event.inputType === "insertLineBreak") { if (currentTypes.length > 0 && range.toString() === "" && inlineElement.tagName === "SPAN" && inlineElement.textContent.startsWith("\n") && range.startContainer.previousSibling && range.startContainer.previousSibling.textContent === "\n") { inlineElement.before(range.startContainer.previousSibling); } return; } let dataLength = inputData.length; if (inputData === "<" || inputData === ">") { // 使用 inlineElement.innerHTML 会出现 https://ld246.com/article/1627185027423 中的第2个问题 dataLength = 4; } else if (inputData === "&") { // https://github.com/siyuan-note/siyuan/issues/12239 dataLength = 5; } // https://github.com/siyuan-note/siyuan/issues/5924 if (currentTypes.length > 0 && range.toString() === "" && range.startOffset === inputData.length && inlineElement.tagName === "SPAN" && inlineElement.textContent.replace(Constants.ZWSP, "") !== inputData && inlineElement.textContent.replace(Constants.ZWSP, "").length >= inputData.length && !hasPreviousSibling(range.startContainer) && !hasPreviousSibling(inlineElement)) { const html = inlineElement.innerHTML.replace(Constants.ZWSP, ""); inlineElement.innerHTML = html.substr(dataLength); const textNode = document.createTextNode(inputData); inlineElement.before(textNode); range.selectNodeContents(textNode); range.collapse(false); return; } if (// 表格行内公式之前无法插入文字 https://github.com/siyuan-note/siyuan/issues/3908 inlineElement.tagName === "SPAN" && inlineElement.textContent !== inputData && !currentTypes.includes("search-mark") && // https://github.com/siyuan-note/siyuan/issues/7586 range.toString() === "" && range.startContainer.nodeType === 3 && (currentTypes.includes("inline-memo") || currentTypes.includes("text") || currentTypes.includes("block-ref") || currentTypes.includes("file-annotation-ref") || currentTypes.includes("a")) && !hasNextSibling(range.startContainer) && range.startContainer.textContent.length === range.startOffset && inlineElement.textContent.length > inputData.length ) { const position = getSelectionOffset(inlineElement, protyle.wysiwyg.element, range); const html = inlineElement.innerHTML; if (position.start === inlineElement.textContent.length) { // 使用 inlineElement.textContent **$a$b** 中数学公式消失 inlineElement.innerHTML = html.substr(0, html.length - dataLength); const textNode = document.createTextNode(inputData); inlineElement.after(textNode); range.selectNodeContents(textNode); range.collapse(false); } } }
// text block-ref file-annotation-ref a 结尾处打字应为普通文本
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/wysiwyg/index.ts#L158-L220
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
promiseTransaction
const promiseTransaction = () => { if (window.siyuan.transactions.length === 0) { return; } const protyle = window.siyuan.transactions[0].protyle; const doOperations = window.siyuan.transactions[0].doOperations; const undoOperations = window.siyuan.transactions[0].undoOperations; // 1. * ;2. * ;3. a // 第一步请求没有返回前在 transaction 中会合并1、2步,此时第一步请求返回将被以下代码删除,在输入a时,就会出现 block not found,因此以下代码不能放入请求回调中 window.siyuan.transactions.splice(0, 1); fetchPost("/api/transactions", { session: protyle.id, app: Constants.SIYUAN_APPID, transactions: [{ doOperations, undoOperations // 目前用于 ws 推送更新大纲 }] }, (response) => { if (window.siyuan.transactions.length === 0) { countBlockWord([], protyle.block.rootID, true); } else { promiseTransaction(); } /// #if MOBILE if (((0 !== window.siyuan.config.sync.provider && isPaidUser()) || (0 === window.siyuan.config.sync.provider && !needSubscribe(""))) && window.siyuan.config.repo.key && window.siyuan.config.sync.enabled) { document.getElementById("toolbarSync").classList.remove("fn__none"); } /// #endif let range: Range; if (getSelection().rangeCount > 0) { range = getSelection().getRangeAt(0); } response.data[0].doOperations.forEach((operation: IOperation) => { if (operation.action === "unfoldHeading" || operation.action === "foldHeading") { processFold(operation, protyle); return; } if (operation.action === "update") { if (protyle.options.backlinkData) { // 反链中有多个相同块的情况 Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => { if (!isInEmbedBlock(item)) { if (range && (item.isSameNode(range.startContainer) || item.contains(range.startContainer))) { // 正在编辑的块不能进行更新 } else { item.outerHTML = operation.data.replace("<wbr>", ""); } } }); processRender(protyle.wysiwyg.element); highlightRender(protyle.wysiwyg.element); avRender(protyle.wysiwyg.element, protyle); blockRender(protyle, protyle.wysiwyg.element); } // 当前编辑器中更新嵌入块 updateEmbed(protyle, operation); return; } if (operation.action === "delete" || operation.action === "append") { if (protyle.options.backlinkData) { Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => { if (!isInEmbedBlock(item)) { item.remove(); } }); } // 更新嵌入块 protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => { if (item.querySelector(`[data-node-id="${operation.id}"]`)) { item.removeAttribute("data-render"); blockRender(protyle, item); } }); hideElements(["gutter"], protyle); return; } if (operation.action === "move") { if (protyle.options.backlinkData) { const updateElements: Element[] = []; Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.id}"]`)).forEach(item => { if (!isInEmbedBlock(item)) { updateElements.push(item); return; } }); let hasFind = false; if (operation.previousID && updateElements.length > 0) { Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`)).forEach(item => { if (!isInEmbedBlock(item)) { item.after(processClonePHElement(updateElements[0].cloneNode(true) as Element)); hasFind = true; } }); } else if (updateElements.length > 0) { Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`)).forEach(item => { if (!isInEmbedBlock(item)) { // 列表特殊处理 if (item.firstElementChild?.classList.contains("protyle-action")) { item.firstElementChild.after(processClonePHElement(updateElements[0].cloneNode(true) as Element)); } else { item.prepend(processClonePHElement(updateElements[0].cloneNode(true) as Element)); } hasFind = true; } }); } updateElements.forEach(item => { if (hasFind) { item.remove(); } else if (!hasFind && item.parentElement) { removeTopElement(item, protyle); } }); } // 更新嵌入块 protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => { if (item.querySelector(`[data-node-id="${operation.id}"]`)) { item.removeAttribute("data-render"); blockRender(protyle, item); } }); return; } if (operation.action === "insert") { // insert if (protyle.options.backlinkData) { const cursorElements: Element[] = []; if (operation.previousID) { Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.previousID}"]`)).forEach(item => { if (item.nextElementSibling?.getAttribute("data-node-id") !== operation.id && !hasClosestByAttribute(item, "data-node-id", operation.id) && // 段落转列表会在段落后插入新列表 !isInEmbedBlock(item)) { item.insertAdjacentHTML("afterend", operation.data); cursorElements.push(item.nextElementSibling); } }); } else { Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id="${operation.parentID}"]`)).forEach(item => { if (!isInEmbedBlock(item)) { // 列表特殊处理 if (item.firstElementChild && item.firstElementChild.classList.contains("protyle-action") && item.firstElementChild.nextElementSibling.getAttribute("data-node-id") !== operation.id) { item.firstElementChild.insertAdjacentHTML("afterend", operation.data); cursorElements.push(item.firstElementChild.nextElementSibling); } else if (item.firstElementChild && item.firstElementChild.getAttribute("data-node-id") !== operation.id) { item.insertAdjacentHTML("afterbegin", operation.data); cursorElements.push(item.firstElementChild); } } }); } // https://github.com/siyuan-note/siyuan/issues/4420 protyle.wysiwyg.element.querySelectorAll('[data-type="NodeHeading"]').forEach(item => { if (item.lastElementChild.getAttribute("spin") === "1") { item.lastElementChild.remove(); } }); cursorElements.forEach(item => { processRender(item); highlightRender(item); avRender(item, protyle); blockRender(protyle, item); const wbrElement = item.querySelector("wbr"); if (wbrElement) { wbrElement.remove(); } }); } // 不更新嵌入块:在快速删除时重新渲染嵌入块会导致滚动条产生滚动从而触发 getDoc 请求,此时删除的块还没有写库,会把已删除的块 append 到文档底部,最终导致查询块失败、光标丢失 // protyle.wysiwyg.element.querySelectorAll('[data-type="NodeBlockQueryEmbed"]').forEach((item) => { // if (item.getAttribute("data-node-id") === operation.id) { // item.removeAttribute("data-render"); // blockRender(protyle, item); // } // }); } }); // 删除仅有的折叠标题后展开内容为空 if (protyle.wysiwyg.element.childElementCount === 0 && // 聚焦时不需要新增块,否则会导致 https://github.com/siyuan-note/siyuan/issues/12326 第一点 !protyle.block.showAll) { const newID = Lute.NewNodeID(); const emptyElement = genEmptyElement(false, true, newID); protyle.wysiwyg.element.insertAdjacentElement("afterbegin", emptyElement); transaction(protyle, [{ action: "insert", data: emptyElement.outerHTML, id: newID, parentID: protyle.block.parentID }]); // 不能撤销,否则就无限循环了 focusByWbr(emptyElement, range); } }); };
// 用于执行操作,外加处理当前编辑器中块引用、嵌入块的更新
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/protyle/wysiwyg/transaction.ts#L63-L260
d6bf65b650165c80c1feadb9c6e19fe01a26105d
siyuan-unlock
github_2023
appdev
typescript
inputEvent
const inputEvent = (event?: InputEvent) => { if (event && event.isComposing) { return; } if (inputElement.value.trim() === "") { searchListElement.classList.add("fn__none"); searchTreeElement.classList.remove("fn__none"); return; } searchTreeElement.classList.add("fn__none"); searchListElement.classList.remove("fn__none"); searchListElement.scrollTo(0, 0); fetchPost("/api/filetree/searchDocs", { k: inputElement.value, flashcard, }, (data) => { let fileHTML = ""; data.data.forEach((item: { boxIcon: string, box: string, hPath: string, path: string, newFlashcardCount: string, dueFlashcardCount: string, flashcardCount: string }) => { let countHTML = ""; if (flashcard) { countHTML = `<span class="fn__flex-1"></span> <span class="counter counter--right b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.flashcardNewCard}">${item.newFlashcardCount}</span> <span class="counter counter--right b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.flashcardDueCard}">${item.dueFlashcardCount}</span> <span class="counter counter--right b3-tooltips b3-tooltips__w" aria-label="${window.siyuan.languages.flashcardCard}">${item.flashcardCount}</span>`; } fileHTML += `<li class="b3-list-item${fileHTML === "" ? " b3-list-item--focus" : ""}" data-path="${item.path}" data-box="${item.box}"> ${unicode2Emoji(item.boxIcon || window.siyuan.storage[Constants.LOCAL_IMAGES].note, "b3-list-item__graphic", true)} <span class="b3-list-item__showall" style="padding: 4px 0">${escapeHtml(item.hPath)}</span> ${countHTML} </li>`; }); searchListElement.innerHTML = fileHTML; }); };
/// #endif
https://github.com/appdev/siyuan-unlock/blob/d6bf65b650165c80c1feadb9c6e19fe01a26105d/app/src/util/pathName.ts#L221-L262
d6bf65b650165c80c1feadb9c6e19fe01a26105d
bce-qianfan-sdk
github_2023
baidubce
typescript
main
async function main() { const stream = await client.chat({ messages: [ { role: 'user', content: '等额本金和等额本息有什么区别?', }, ], stream: true, }, 'ERNIE-Bot-turbo'); console.log('流式返回结果'); for await (const chunk of stream as AsyncIterableIterator<any>) { console.log(chunk); } }
// 手动传AK/SK 测试
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/chatCompletion.ts#L30-L44
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
main
async function main() { const stream = await client.completions({ prompt: 'Introduce the city Beijing', stream: true, }, 'SQLCoder-7B'); console.log('流式返回结果'); for await (const chunk of stream as AsyncIterableIterator<any>) { console.log(chunk); } }
// 手动传AK/SK 测试
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/completiont.ts#L39-L48
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
main
async function main() { const resp = await client.embedding({ input: ['Introduce the city Beijing'], }, 'Embedding-V1'); console.log('返回结果'); console.log(resp.data); }
// 手动传AK/SK 测试
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/embedding.ts#L30-L36
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
main
async function main() { const resp = await client.image2Text({ prompt: '分析一下图片画了什么', image: '图片的base64编码', }); console.log(resp); }
// 手动传AK/SK 测试
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/image2text.ts#L33-L39
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
weatherMain
async function weatherMain() { const resp = await client.plugins({ query: '深圳今天天气如何', plugins: [ 'uuid-weatherforecast', ], }); console.log('返回结果'); console.log(resp); }
// 手动传AK/SK 测试
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/plugins.ts#L35-L44
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
weatherStreamMain
async function weatherStreamMain() { const stream = await client.plugins({ query: '深圳今天天气如何', plugins: [ 'uuid-weatherforecast', ], stream: true, verbose: false, }); console.log('返回结果'); for await (const chunk of stream as AsyncIterableIterator<any>) { console.log(chunk); } }
// weatherMain();
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/plugins.ts#L49-L62
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
main
async function main() { const stream = await client.plugins({ query: '请解析这张图片, 告诉我怎么画这张图的简笔画', plugins: [ 'uuid-chatocr', ], stream: true, fileurl: 'https://xxx.bcebos.com/xxx/xxx.jpeg', }); for await (const chunk of stream as AsyncIterableIterator<any>) { console.log(chunk); } // console.log('返回结果'); // console.log(resp); }
// 智慧图问插件 测试
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/plugins.ts#L65-L79
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
streamYiYanMain
async function streamYiYanMain() { const resp = await client.plugins({ messages: [ { 'role': 'user', 'content': '<file>浅谈牛奶的营养与消费趋势.docx</file><url>https://xxx/xxx/xxx.docx</url>', }, ], plugins: ['ImageAI'], stream: false, }); for await (const chunk of resp as AsyncIterableIterator<any>) { console.log(chunk); } }
// weatherStreamMain();
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/plugins.ts#L139-L153
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
yiYanMain
async function yiYanMain() { const resp = await client.plugins({ messages: [ {'role': 'user', 'content': '<file>浅谈牛奶的营养与消费趋势.docx</file><url>https://xxx/xxx/xxx.docx</url>'}, // eslint-disable-next-line max-len {'role': 'assistant', 'content': '以下是该文档的关键内容:\n牛奶作为一种营养丰富、易消化吸收的天然食品,受到广泛欢迎。其价值主要表现在营养成分和医学价值两个方面。在营养成分方面,牛奶含有多种必需的营养成分,如脂肪、蛋白质、乳糖、矿物质和水分等,比例适中,易于消化吸收。在医学价值方面,牛奶具有促进生长发育、维持健康水平的作用,对于儿童长高也有积极影响。此外,牛奶还具有极高的市场前景,消费者关注度持续上升,消费心理和市场需求也在不断变化。为了更好地发挥牛奶的营养价值,我们应该注意健康饮用牛奶的方式,适量饮用,并根据自身情况选择合适的牛奶产品。综上所述,牛奶作为一种理想的天然食品,不仅具有丰富的营养成分,还具有极高的医学价值和市场前景。我们应该充分认识牛奶的价值,科学饮用,让牛奶为我们的健康发挥更大的作用。'}, {'role': 'user', 'content': '牛奶的营养成本有哪些'}, ], plugins: ['ChatFile'], stream: false, }); console.log('返回结果'); console.log(resp); }
// ChatFile测试
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/plugins.ts#L156-L169
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
main
async function main() { const resp = await client.reranker({ query: '上海天气', documents: ['上海气候', '北京美食'], }); console.log('返回结果'); console.log(resp); }
// 手动传AK/SK 测试
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/reranker.ts#L30-L37
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
main
async function main() { const resp = await client.text2Image({ prompt: '生成爱莎公主的图片', size: '768x768', n: 1, steps: 20, sampler_index: 'Euler a', }, 'Stable-Diffusion-XL'); console.log(resp); const base64Image = resp.data[0].b64_image; // 创建一个简单的服务器 const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/html'}); let html = `<html><body><img src="data:image/jpeg;base64,${base64Image}" /><br/></body></html>`; res.end(html); }); const port = 3001; server.listen(port, () => { console.log(`服务器运行在 http://localhost:${port}`); }); }
// 手动传AK/SK 测试
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/examples/test2image.ts#L31-L52
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
BaseClient.getAccessToken
private async getAccessToken(): Promise<AccessTokenResp> { const url = getAccessTokenUrl(this.qianfanAk, this.qianfanSk, this.qianfanBaseUrl); try { const resp = await this.fetchInstance.makeRequest(url, { headers: this.headers, method: 'POST', }); this.access_token = resp.access_token ?? ''; this.expires_in = resp.expires_in + Date.now() / 1000; return { access_token: resp.access_token, expires_in: resp.expires_in, }; } catch (error) { const error_msg = `Failed to get access token: ${error && error.message}`; throw new Error(error_msg); } }
/** * 使用 AK,SK 生成鉴权签名(Access Token) * @return string 鉴权签名信息(Access Token) */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Base/index.ts#L99-L117
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
BaseClient.getIAMPath
private async getIAMPath(type, model) { if (this.qianfanBaseUrl.includes('aip.baidubce.com')) { throw new Error('请设置proxy的baseUrl'); } const dynamicModelEndpoint = new DynamicModelEndpoint( null, this.qianfanConsoleApiBaseUrl, this.qianfanBaseUrl ); return await dynamicModelEndpoint.getEndpoint(type, model); }
/** * 获取 IAM 路径 (配置proxy情况下) * * @param type 路径类型 * @param model 模型名称 * @returns 返回 IAM 路径 * @throws 当 qianfanBaseUrl 包含 'aip.baidubce.com' 时,抛出错误提示设置 proxy 的 baseUrl * @throws 当 qianfanConsoleApiBaseUrl 未设置时,抛出错误提示未设置 qianfanConsoleApiBaseUrl * @throws 当 Endpoint 未设置且 qianfanConsoleApiBaseUrl 不包含 'qianfan.baidubce.com' 时,抛出错误提示未设置 Endpoint */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Base/index.ts#L129-L139
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
ChatCompletion.chat
public async chat(body: ChatBody, model = 'ERNIE-Lite-8K'): Promise<Resp | AsyncIterable<Resp>> { const stream = body.stream ?? false; const modelKey = model.toLowerCase(); const typeMap = getTypeMap(typeModelEndpointMap, type) ?? new Map(); const endPoint = typeMap.get(modelKey) || ''; const {AKPath, requestBody} = getPathAndBody({ baseUrl: this.qianfanBaseUrl, body, endpoint: this.Endpoint ?? endPoint, type, }); return this.sendRequest(type, model, AKPath, requestBody, stream); }
/** * chat * @param body 聊天请求体 * @param model 聊天模型,默认为 'ERNIE-Bot-turbo' * @param stream 是否开启流模式,默认为 false * @returns Promise<ChatResp | AsyncIterable<ChatResp>> */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/ChatCompletion/index.ts#L30-L42
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Completions.completions
public async completions( body: CompletionBody, model = 'ERNIE-Bot-turbo' ): Promise<Resp | AsyncIterable<Resp>> { const stream = body.stream ?? false; const {modelInfoMapUppercase, modelUppercase} = getUpperCaseModelAndModelMap(model, modelInfoMap); // 兼容Chat模型 const required_keys = modelInfoMapUppercase[modelUppercase]?.required_keys; let reqBody: CompletionBody | ChatBody; const type = ModelType.COMPLETIONS; if (required_keys.includes('messages') && isCompletionBody(body)) { const {prompt, ...restOfBody} = body; reqBody = { ...restOfBody, // 保留除prompt之外的所有属性 messages: [ { role: 'user', content: prompt, }, ], }; } else { reqBody = body; } const modelKey = model.toLowerCase(); const typeMap = getTypeMap(typeModelEndpointMap, type) ?? new Map(); const endPoint = typeMap.get(modelKey) || ''; const {AKPath, requestBody} = getPathAndBody({ model: modelUppercase, modelInfoMap: modelInfoMapUppercase, baseUrl: this.qianfanBaseUrl, body: reqBody, endpoint: this.Endpoint ?? endPoint, type, }); return this.sendRequest(type, model, AKPath, requestBody, stream); }
/** * 续写 * @param body 续写请求体 * @param model 续写模型,默认为 'ERNIE-Bot-turbo' * @returns 返回 Promise 对象,异步获取续写结果 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Completions/index.ts#L29-L66
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
DynamicModelEndpoint.getEndpoint
public async getEndpoint(type: string, model?: string): Promise<string> { const mutex = new Mutex(); const release = await mutex.acquire(); // 等待获取互斥锁 try { if (!DYNAMIC_INVALID.includes(type) && this.isDynamicMapExpired()) { await this.updateDynamicModelEndpoint(type); // 等待动态更新完成 this.dynamicMapExpireAt = Date.now() / 1000 + this.DYNAMIC_MAP_REFRESH_INTERVAL; } } catch (error) { console.log('Failed to update dynamic model endpoint map', error); } finally { release(); // 释放互斥锁 const getEndpointUrl = (typeMap :Map<string, string>) => { const modelKey = (model || '').toLowerCase(); const rawEndPoint = typeMap.get(modelKey) || ''; let endPoint = type === 'plugin' ? rawEndPoint : rawEndPoint.split('/').pop() || ''; return endPoint ? getPath({ Authentication: 'IAM', api_base: this.qianfanBaseUrl, endpoint: endPoint, type, }) : ''; }; const dynamicTypeMap = getTypeMap(this.dynamicTypeModelEndpointMap, type); let url = dynamicTypeMap ? getEndpointUrl(dynamicTypeMap) : ''; if (url) { return url; } // 如果动态映射中没有找到,尝试从静态映射中获取 const typeMap = getTypeMap(typeModelEndpointMap, type); return typeMap ? getEndpointUrl(typeMap) : ''; // 返回从静态映射中获取的URL } }
/** * 获取终端节点 * * @param type 类型 * @param model 模型(可选) * @param endpoint 终端节点(可选) * @returns 终端节点 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/DynamicModelEndpoint/index.ts#L40-L74
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
getEndpointUrl
const getEndpointUrl = (typeMap :Map<string, string>) => { const modelKey = (model || '').toLowerCase(); const rawEndPoint = typeMap.get(modelKey) || ''; let endPoint = type === 'plugin' ? rawEndPoint : rawEndPoint.split('/').pop() || ''; return endPoint ? getPath({ Authentication: 'IAM', api_base: this.qianfanBaseUrl, endpoint: endPoint, type, }) : ''; };
// 释放互斥锁
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/DynamicModelEndpoint/index.ts#L54-L64
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
DynamicModelEndpoint.isDynamicMapExpired
private isDynamicMapExpired() { // 获取当前时间戳(以秒为单位) const now = Date.now() / 1000; // 比较当前时间戳和动态映射过期时间戳 return now > this.dynamicMapExpireAt; }
/** * 判断动态映射是否已过期 * * @return 如果动态映射已过期,返回true;否则返回false */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/DynamicModelEndpoint/index.ts#L80-L85
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
DynamicModelEndpoint.updateDynamicModelEndpoint
async updateDynamicModelEndpoint(type: string) { const url = `${this.qianfanConsoleApiBaseUrl}${SERVER_LIST_API}`; let fetchOption = {}; // 设置默认的请求选项 const defaultOptions = { body: JSON.stringify({ apiTypefilter: [type], }), headers: { ...DEFAULT_HEADERS, }, }; // 如果有node环境,则获取签名 if (this.client !== null) { fetchOption = await this.client.getSignature({ ...defaultOptions, httpMethod: 'POST', path: url, }); } // 浏览器环境下走proxy代理,不需要签名 else { fetchOption = { ...defaultOptions, method: 'POST', url, }; } try { const res = await this.fetchInstance.makeRequest(url, fetchOption); const commonServerList = res?.result?.common ?? []; const newMap = new Map<string, string>(); this.dynamicTypeModelEndpointMap.set(type, newMap); if (commonServerList.length) { commonServerList.forEach(item => { let modelMap = this.dynamicTypeModelEndpointMap.get(item.apiType); if (!modelMap) { modelMap = new Map<string, string>(); this.dynamicTypeModelEndpointMap.set(item.apiType, modelMap); } modelMap.set(item.name.toLowerCase(), item.url); }); } } catch (error) { // console.log('Failed to update dynamic model endpoint map', error); } }
/** * 更新动态模型端点 * * @param qianfanConsoleApiBaseUrl Qianfan控制台API基础URL * @param apiTypefilter API类型过滤器数组 * @param headers HTTP请求头 * @returns 返回异步操作结果 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/DynamicModelEndpoint/index.ts#L94-L142
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Eembedding.embedding
public async embedding(body: EmbeddingBody, model = 'Embedding-V1'): Promise<EmbeddingResp> { const type = ModelType.EMBEDDINGS; const modelKey = model.toLowerCase(); const typeMap = getTypeMap(typeModelEndpointMap, type) ?? new Map(); const endPoint = typeMap.get(modelKey) || ''; const {AKPath, requestBody} = getPathAndBody({ baseUrl: this.qianfanBaseUrl, body, endpoint: this.Endpoint ?? endPoint, type, }); const resp = await this.sendRequest(type, model, AKPath, requestBody); return resp as EmbeddingResp; }
/** * 向量化 * @param body 请求体 * @param model 向量化模型,默认为'Embedding-V1' * @returns Promise<Resp | AsyncIterable<Resp>> */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Embedding/index.ts#L28-L41
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.constructor
constructor({ maxRetries = 3, timeout = 600000, backoffFactor = 0, retryMaxWaitInterval = 120000, }: { maxRetries?: number | undefined; timeout?: number | undefined; backoffFactor?: number | undefined; retryMaxWaitInterval?: number | undefined; } = {}) { this.maxRetries = validatePositiveInteger('maxRetries', maxRetries); this.timeout = validatePositiveInteger('timeout', timeout); this.backoffFactor = backoffFactor; this.retryMaxWaitInterval = retryMaxWaitInterval; }
/** * 使用带有超时的 fetch 请求获取资源 * @returns 返回 Promise<Response>,表示获取到的响应 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L110-L125
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.makeRequest
async makeRequest(url: string, options: RequestOptions, retriesRemaining?: number): Promise<Response | any> { if (!retriesRemaining && retriesRemaining !== 0) { retriesRemaining = options.maxRetries ?? this.maxRetries; } if (options.signal?.aborted) { throw new Error('Request was aborted.'); } const timeout = options.timeout ?? this.timeout; const controller = new AbortController(); const response = await this.fetchWithTimeout(url, options, timeout, controller).catch(castToError); if (response instanceof Error) { if (options.signal?.aborted) { throw new Error('Request was aborted.'); } if (response.name === 'AbortError') { throw new Error('Request timed out.'); } throw new Error('Request timed out.' + response.message); } if (!response.ok) { if (retriesRemaining && this.shouldRetry(response)) { const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; console.log(retryMessage); return this.retryRequest(url, options, retriesRemaining, response.headers as any); } const retryMessage = retriesRemaining ? '(error; no more retries left)' : '(error; not retryable)'; throw new Error(retryMessage); } const res = await handleResponse({response, options, controller}); if (typeof res === 'object' && res !== null && 'error_code' in res) { const resWithError = res as {error_code: number; error_description?: string}; // 如果存在错误码且不需要重试,则直接抛出错误 if (!RETRY_CODE.includes(resWithError.error_code)) { throw new Error(JSON.stringify(res)); } // 网络正常的情况下API 336100(ServerHighLoad)、18 (QPSIimit)、336501(RPMLimitReached)、336502(TPMLimitReached)进行重试 if (retriesRemaining && this.shouldRetryWithErrorCode(resWithError)) { return this.retryRequest(url, options, retriesRemaining, response.headers as any); } } // 流式 if (options.stream && res instanceof Readable) { const [stream1, stream2] = (res as any).tee(); return stream2; } return res; }
/** * 发起请求并处理响应 * * @param options 请求选项 * @param retriesRemaining 剩余重试次数,可以为 null * @returns Promise<APIResponseProps> 响应对象,包含响应信息、请求选项和 AbortController 实例 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L162-L210
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.shouldRetry
private shouldRetry(response: Response): boolean { const shouldRetryHeader = response.headers.get('x-should-retry'); if (shouldRetryHeader === 'true') { return true; } if (shouldRetryHeader === 'false') { return false; } if (response.status === 408) { return true; } if (response.status === 409) { return true; } if (response.status === 429) { return true; } if (response.status >= 500) { return true; } return false; }
/** * 判断是否应该重试请求 * * @param response HTTP响应对象 * @returns 返回布尔值,表示是否应该重试请求 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L218-L239
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.shouldRetryWithErrorCode
private shouldRetryWithErrorCode(data: {error_code?: number; error_description?: string}): boolean { // 对于已识别为可重试的错误码继续重试 return RETRY_CODE.includes(data?.error_code ?? 0); }
/** * 判断是否应该根据错误码进行重试 * * @param data 包含错误码和错误描述的对象 * @returns 如果错误码在可重试的错误码列表中,则返回true,否则返回false */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L247-L250
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.retryRequest
private async retryRequest( url: string, options: RequestOptions, retriesRemaining: number, responseHeaders?: Headers | undefined ): Promise<Response | any> { let timeoutMillis: number | undefined; const retryAfterMillisHeader = responseHeaders?.['retry-after-ms']; if (retryAfterMillisHeader) { const timeoutMs = parseFloat(retryAfterMillisHeader); if (!Number.isNaN(timeoutMs)) { timeoutMillis = timeoutMs; } } // Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After const retryAfterHeader = responseHeaders?.['retry-after']; if (retryAfterHeader && !timeoutMillis) { const timeoutSeconds = parseFloat(retryAfterHeader); if (!Number.isNaN(timeoutSeconds)) { timeoutMillis = timeoutSeconds * 1000; } else { timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); } } if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { const maxRetries = options.maxRetries ?? this.maxRetries; timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries ?? 0); } await sleep(timeoutMillis); return this.makeRequest(url, options, retriesRemaining - 1); }
/** * 重试请求 * * @param options 请求选项 * @param retriesRemaining 剩余重试次数 * @param responseHeaders 响应头,可选 * @returns 返回 API 响应属性 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L260-L291
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.calculateDefaultRetryTimeoutMillis
private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number { // 计算当前尝试的次数 const attempt = maxRetries - retriesRemaining; // 应用指数退避算法,并确保不超过最大值 const sleepSeconds = Math.min(this.retryMaxWaitInterval, this.backoffFactor * Math.pow(2, attempt)); // 应用一些抖动,最多占用重试时间的25% const jitter = 1 - Math.random() * 0.25; // 返回重试间隔的毫秒值 return sleepSeconds * jitter * 1000; }
/** * 计算默认的重试超时时间(毫秒) * * @param retriesRemaining 剩余重试次数 * @param maxRetries 最大重试次数 * @returns 返回重试超时时间(毫秒) */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/browserFetch.ts#L300-L309
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.constructor
constructor({ maxRetries = 3, timeout = 600000, backoffFactor = 0, retryMaxWaitInterval = 120000 }: { maxRetries?: number | undefined; timeout?: number | undefined; backoffFactor?: number | undefined; retryMaxWaitInterval?: number | undefined; } = {}) { this.maxRetries = validatePositiveInteger('maxRetries', maxRetries); this.timeout = validatePositiveInteger('timeout', timeout); this.backoffFactor = backoffFactor; this.retryMaxWaitInterval = retryMaxWaitInterval; this.rateLimiter = new RateLimiter(); this.tokenLimiter = new TokenLimiter(); }
/** * 使用带有超时的 fetch 请求获取资源 * @returns 返回 Promise<Response>,表示获取到的响应 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L115-L132
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.getTpmHeader
getTpmHeader(headers: any): void { const val = headers.get('x-ratelimit-limit-tokens') ?? '0'; this.tokenLimiter.resetTokens(val); return val; }
/** * 获取TPM头部信息 * * @param headers HTTP请求头对象 * @returns 返回字符串类型的令牌限制数量 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L172-L176
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.makeRequest
async makeRequest(url: string, options: RequestOptions, retriesRemaining?: number): Promise<Response | any> { if (!retriesRemaining && retriesRemaining !== 0) { retriesRemaining = options.maxRetries ?? this.maxRetries; } if (options.signal?.aborted) { throw new Error('Request was aborted.'); } const timeout = options.timeout ?? this.timeout; const controller = new AbortController(); // 计算请求token const tokens = this.tokenLimiter.calculateTokens((options.body as string) ?? ''); const hasToken = await this.tokenLimiter.acquireTokens(tokens); if (hasToken) { const response = await this.fetchWithTimeout(url, options, timeout, controller).catch(castToError); let usedTokens = 0; if (response instanceof Error) { if (response.name === 'AbortError') { throw new Error('Request timed out.'); } throw new Error('Request timed out.' + (response?.message || response)); } if (!response.ok) { if (retriesRemaining && this.shouldRetry(response)) { const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; console.log(retryMessage); return this.retryRequest(url, options, retriesRemaining, response.headers as any); } const retryMessage = retriesRemaining ? '(error; no more retries left)' : '(error; not retryable)'; throw new Error(retryMessage); } const res = await handleResponse({response, options, controller}); if (typeof res === 'object' && res !== null && 'error_code' in res) { const resWithError = res as {error_code: number; error_description?: string}; // 如果存在错误码且不需要重试,则直接抛出错误 if (!RETRY_CODE.includes(resWithError.error_code)) { throw new Error(JSON.stringify(res)); } // 网络正常的情况下API 336100(ServerHighLoad)、18 (QPSIimit)、336501(RPMLimitReached)、336502(TPMLimitReached)进行重试 if (retriesRemaining && this.shouldRetryWithErrorCode(resWithError)) { return this.retryRequest(url, options, retriesRemaining, response.headers as any); } } const rpm = response?.headers?.get('x-ratelimit-limit-requests'); const tmp = response?.headers?.get('x-ratelimit-limit-tokens') ?? '0'; if (rpm) { this.rateLimiter.updateLimits(Number(rpm)); } if (tmp) { this.tokenLimiter.resetTokens(Number(tmp)); } const val = this.getTpmHeader(response.headers); // 流式 if (options.stream && res instanceof Readable) { const [stream1, stream2] = (res as any).tee(); if (isOpenTpm(val)) { const updateTokensAsync = async () => { for await (const data of stream1 as unknown as AsyncIterableType) { const typedData = data as RespBase; if (typedData.is_end) { usedTokens = typedData?.usage?.total_tokens; await this.tokenLimiter.acquireTokens(usedTokens - tokens); break; } } }; setTimeout(updateTokensAsync, 0); } return stream2; } return res; } }
/** * 发起请求并处理响应 * * @param options 请求选项 * @param retriesRemaining 剩余重试次数,可以为 null * @returns Promise<APIResponseProps> 响应对象,包含响应信息、请求选项和 AbortController 实例 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L190-L265
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.shouldRetry
private shouldRetry(response: Response): boolean { const shouldRetryHeader = response.headers.get('x-should-retry'); if (shouldRetryHeader === 'true') { return true; } if (shouldRetryHeader === 'false') { return false; } if (response.status === 408) { return true; } if (response.status === 409) { return true; } if (response.status === 429) { return true; } if (response.status >= 500) { return true; } return false; }
/** * 判断是否应该重试请求 * * @param response HTTP响应对象 * @returns 返回布尔值,表示是否应该重试请求 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L273-L294
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.shouldRetryWithErrorCode
private shouldRetryWithErrorCode(data: {error_code?: number; error_description?: string}): boolean { // 对于已识别为可重试的错误码继续重试 return RETRY_CODE.includes(data?.error_code); }
/** * 判断是否应该根据错误码进行重试 * * @param data 包含错误码和错误描述的对象 * @returns 如果错误码在可重试的错误码列表中,则返回true,否则返回false */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L302-L305
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.retryRequest
private async retryRequest( url: string, options: RequestOptions, retriesRemaining: number, responseHeaders?: Headers | undefined ): Promise<Response | any> { let timeoutMillis: number | undefined; const retryAfterMillisHeader = responseHeaders?.['retry-after-ms']; if (retryAfterMillisHeader) { const timeoutMs = parseFloat(retryAfterMillisHeader); if (!Number.isNaN(timeoutMs)) { timeoutMillis = timeoutMs; } } // Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After const retryAfterHeader = responseHeaders?.['retry-after']; if (retryAfterHeader && !timeoutMillis) { const timeoutSeconds = parseFloat(retryAfterHeader); if (!Number.isNaN(timeoutSeconds)) { timeoutMillis = timeoutSeconds * 1000; } else { timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); } } if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { const maxRetries = options.maxRetries ?? this.maxRetries; timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); } await sleep(timeoutMillis); return this.makeRequest(url, options, retriesRemaining - 1); }
/** * 重试请求 * * @param options 请求选项 * @param retriesRemaining 剩余重试次数 * @param responseHeaders 响应头,可选 * @returns 返回 API 响应属性 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L315-L345
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Fetch.calculateDefaultRetryTimeoutMillis
private calculateDefaultRetryTimeoutMillis(retriesRemaining: number, maxRetries: number): number { // 计算当前尝试的次数 const attempt = maxRetries - retriesRemaining; // 应用指数退避算法,并确保不超过最大值 const sleepSeconds = Math.min(this.retryMaxWaitInterval, this.backoffFactor * Math.pow(2, attempt)); // 应用一些抖动,最多占用重试时间的25% const jitter = 1 - Math.random() * 0.25; // 返回重试间隔的毫秒值 return sleepSeconds * jitter * 1000; }
/** * 计算默认的重试超时时间(毫秒) * * @param retriesRemaining 剩余重试次数 * @param maxRetries 最大重试次数 * @returns 返回重试超时时间(毫秒) */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Fetch/nodeFetch.ts#L354-L363
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
HttpClient.getSignature
async getSignature(config): Promise<any> { const {httpMethod, path, body, headers, params, signFunction} = config; const method = httpMethod.toUpperCase(); const requestUrl = this._getRequestUrl(path); const _headers = Object.assign({}, this.defaultHeaders, headers); if (!_headers.hasOwnProperty(H.CONTENT_LENGTH)) { let contentLength = this._guessContentLength(body); if (!(contentLength === 0 && /GET|HEAD/i.test(method))) { _headers[H.CONTENT_LENGTH] = contentLength; } } const url = new URLClass(requestUrl) as any; _headers[H.HOST] = url.host; const options = urlObjectToPlainObject(url, method, _headers); const reqHeaders = await this.setAuthorizationHeader(signFunction, _headers, options, params); const fetchOptions = { url: options.href, method: options.method, headers: reqHeaders, body, }; return fetchOptions; }
/** * 获取签名 * * @param config 请求配置对象 * @returns 返回包含签名信息的 fetchOptions 对象 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/HttpClient/index.ts#L43-L65
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
HttpClient._guessContentLength
private _guessContentLength(data: string | Buffer | Blob | ArrayBuffer | any): number { if (data == null) { return 0; } else if (typeof data === 'string') { return new TextEncoder().encode(data).length; } else if (typeof data === 'object') { if (data instanceof Blob) { return data.size; } if (data instanceof ArrayBuffer) { return data.byteLength; } if (Buffer.isBuffer(data)) { return data.length; } if (typeof data === 'object') { const keys = Object.keys(data); return keys.length; } } throw new Error('No Content-Length is specified.'); }
/** * 猜测数据长度 * * @param data 数据,可以是字符串、Buffer、可读流 * @returns 返回数据长度 * @throws {Error} 当没有指定 Content-Length 时抛出异常 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/HttpClient/index.ts#L129-L153
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Image2Text.image2Text
public async image2Text( body: Image2TextBody, model = 'Fuyu-8B' ): Promise<RespBase> { const type = ModelType.IMAGE_2_TEXT; const modelKey = model.toLowerCase(); const typeMap = getTypeMap(typeModelEndpointMap, type) ?? new Map(); const endPoint = typeMap.get(modelKey) || ''; const {AKPath, requestBody} = getPathAndBody({ baseUrl: this.qianfanBaseUrl, body, endpoint: this.Endpoint ?? endPoint, type, }); const resp = await this.sendRequest(type, model, AKPath, requestBody); return resp as RespBase; }
/** * 图生文 * @param body 请求体 * @returns 返回图像转文本 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Images/image2text.ts#L27-L43
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Text2Image.text2Image
public async text2Image( body: Text2ImageBody, model = 'Stable-Diffusion-XL' ): Promise<Text2ImageResp> { const type = ModelType.TEXT_2_IMAGE; const modelKey = model.toLowerCase(); const typeMap = getTypeMap(typeModelEndpointMap, type) ?? new Map(); const endPoint = typeMap.get(modelKey) || ''; const {AKPath, requestBody} = getPathAndBody({ baseUrl: this.qianfanBaseUrl, body, endpoint: this.Endpoint ?? endPoint, type, }); const resp = await this.sendRequest(type, model, AKPath, requestBody); return resp as Text2ImageResp; }
/** * 文生图 * @param body 续写请求体 * @param model 续写模型,默认为 'ERNIE-Bot-turbo' * @returns 返回 Promise 对象,异步获取续写结果 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Images/text2image.ts#L29-L45
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
RateLimiter.schedule
async schedule<T>(func: () => Promise<T>): Promise<T> { return this.limiter.schedule(func); }
/** * 使用限流器调度函数执行 * * @param func 要调度的函数,返回一个Promise<T> * @returns 返回Promise<T>类型的调度结果 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/RateLimiter/index.ts#L72-L74
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
RateLimiter.updateLimits
async updateLimits(requestPerMinute: number): Promise<void> { let release: () => void; try { // 使用hasReset检查是否已经进行过更新 if (this.hasReset) { return; } release = await this.mutex.acquire(); // 防止多个任务同时更新限制 if (this.hasReset) { return; } if (requestPerMinute <= 0) { throw new Error('请求次数必须为正数'); } if (this.rpm === requestPerMinute) { return; } this.rpm = this.safeParseInt(requestPerMinute, 'QIANFAN_RPM_LIMIT') ?? this.rpm; this.initializeLimiter(); this.hasReset = true; // 确保只有第一个调用能够更新,并阻止后续调用 } catch (error) { console.error('更新限制失败:', error); } finally { if (release) { release(); } } }
/** * 更新限制 * * @param requestPerMinute 每分钟请求次数,可选参数 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/RateLimiter/index.ts#L81-L111
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
RateLimiter.safeParseInt
private safeParseInt(value?: number | string, envVarName?: string): number | undefined { if (!value) { return; } const parsedValue = Number.parseInt(String(value), 10); if (isNaN(parsedValue) || parsedValue < 0) { console.warn(`Invalid value for ${envVarName}: ${value}. Using undefined.`); return undefined; } return parsedValue; }
/** * 安全解析整数 * * @param value 要解析的值,可以是数字或字符串 * @param envVarName 环境变量名,用于输出警告信息 * @returns 解析后的整数,若解析失败则返回 undefined */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/RateLimiter/index.ts#L120-L130
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
TokenLimiter.getTimeAtLastMinute
private getTimeAtLastMinute(): number { return Math.floor(this.currentTime().getTime() / 60000) * 60000; }
/** * 获取当前时间所在分钟的开始时间戳 * @returns {number} 返回当前时间所在分钟的开始时间戳(毫秒) */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L51-L53
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
TokenLimiter.refreshTokens
private async refreshTokens(): Promise<void> { const nowAtMinute = this.getTimeAtLastMinute(); if (nowAtMinute !== this.lastRefreshTime.getTime()) { this.tokens = this.maxTokens; this.lastRefreshTime = new Date(nowAtMinute); } }
/** * 整分刷新令牌 * @returns Promise<void> */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L59-L65
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
TokenLimiter.timeUntilNextMinute
private timeUntilNextMinute(): number { const now = this.currentTime(); const nextMinute = new Date(now); nextMinute.setMinutes(now.getMinutes() + 1); nextMinute.setSeconds(0); nextMinute.setMilliseconds(0); return nextMinute.getTime() - now.getTime(); }
/** * 当前时间开始到下一分钟开始所需等待的时间(以毫秒为单位) * 如果在一个时间窗口(例如一分钟)内可用的令牌已经用完,需要等待直到下一个时间窗口开始才能再次填充令牌 * @returns 等待时间 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L72-L79
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
TokenLimiter.acquireTokens
public async acquireTokens(tokenCount: number): Promise<boolean> { if (this.maxTokens <= 0) { return true; } let release: () => void; try { release = await this.mutex.acquire(); await this.refreshTokens(); if (this.tokens >= tokenCount) { this.tokens -= tokenCount; return true; } await new Promise(resolve => setTimeout(resolve, this.timeUntilNextMinute())); return false; } catch (error) { console.error('Error acquiring tokens:', error); return false; } finally { if (release) { release(); } } }
/** * 当前是否有指定数量的可用令牌 * 如果当前令牌数不足,它将计算等待时间直到下一分钟开始,并尝试再次刷新令牌。 * @param tokenCount 令牌数量 * @returns 返回Promise<boolean>类型,如果成功获取令牌,则返回true;否则返回false */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L87-L112
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
TokenLimiter.resetTokens
public async resetTokens(totalTokens: number): Promise<void> { let release: () => void; try { if (this.hasReset) { return; } release = await this.mutex.acquire(); if (this.hasReset) { return; } // 检查如果传入的totalTokens与当前最大令牌数一致,则不做改变 if (this.initialMaxTokens === totalTokens) { return; } // 之前设置过token if (this.maxTokens > 0) { totalTokens = Math.min(this.maxTokens, totalTokens); } const originalTokenCurrent = this.tokens; const originalTokenMax = this.maxTokens; const diff = originalTokenMax - originalTokenCurrent; // 重新设置最大令牌数,同时考虑缓冲区比率 this.maxTokens = Math.floor(totalTokens * (1 - this.bufferRatio)); this.tokens = Math.max(this.maxTokens - diff, 0); this.lastRefreshTime = new Date(); this.hasReset = true; } catch (error) { console.error('Error resetting tokens:', error); } finally { if (release) { release(); } } }
/** * 重置令牌 * * @param totalTokens 总的令牌数量 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L119-L154
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
TokenLimiter.calculateTokens
public calculateTokens(text: string): number { const chineseCharactersCount = text.match(/[\u4e00-\u9fa5]/g)?.length || 0; const englishWordCount = text.match(/\b[a-zA-Z]+\b/g)?.length || 0; return chineseCharactersCount * 0.625 + englishWordCount; }
/** * 计算文本中的 Token 数量 * * @param text 要计算 Token 的文本 * @returns 返回计算出的 Token 数量 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Limiter/TokenLimiter/index.ts#L162-L166
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
Plugin.plugins
public async plugins( body: PluginsBody | YiYanPluginBody, model = 'EBPluginV2' ): Promise<PluginsResp | AsyncIterable<PluginsResp>> { const stream = body.stream ?? false; const type = ModelType.PLUGIN; const modelKey = model.toLowerCase(); const typeMap = getTypeMap(typeModelEndpointMap, type) ?? new Map(); const endPoint = typeMap.get(modelKey) || ''; const {AKPath, requestBody} = getPathAndBody({ baseUrl: this.qianfanBaseUrl, endpoint: endPoint, body, type, }); console.log(AKPath); return (await this.sendRequest(type, model, AKPath, requestBody, stream)) as | PluginsResp | AsyncIterable<PluginsResp>; }
/** * 插件 * @param body 请求体 * @param model 续写模型,默认为 'ERNIE-Bot-turbo' * @returns 返回 Promise 对象,异步获取续写结果 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/Plugin/index.ts#L28-L47
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
concatUint8Arrays
function concatUint8Arrays(a: Uint8Array, b: Uint8Array): Uint8Array { const result = new Uint8Array(a.length + b.length); result.set(a, 0); result.set(b, a.length); return result; }
// 合并两个 Uint8Array
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/streaming/index.ts#L330-L335
96135c9bfa9cfc8178725fc303f966774f31b693
bce-qianfan-sdk
github_2023
baidubce
typescript
splitUint8Array
function splitUint8Array(array: Uint8Array, delimiter: number): [Uint8Array[], Uint8Array] { const result: Uint8Array[] = []; let start = 0; for (let i = 0; i < array.length; i++) { if (array[i] === delimiter) { result.push(array.subarray(start, i)); start = i + 1; // 跳过 delimiter } } // 返回分割后的数组和剩余的部分 return [result, array.subarray(start)]; }
/** * 使用指定的分隔符将 Uint8Array 数组拆分为多个子数组和剩余部分。 * * @param array 要拆分的 Uint8Array 数组。 * @param delimiter 分隔符的数值。 * @returns 包含拆分后的多个子数组和剩余部分的数组。 * 第一个元素是拆分后的子数组列表,类型为 Uint8Array[]。 * 第二个元素是剩余部分的 Uint8Array 数组。 */
https://github.com/baidubce/bce-qianfan-sdk/blob/96135c9bfa9cfc8178725fc303f966774f31b693/javascript/src/streaming/index.ts#L385-L398
96135c9bfa9cfc8178725fc303f966774f31b693
powerpipe
github_2023
turbot
typescript
nodesAndEdgesToTree
const nodesAndEdgesToTree = ( nodesAndEdges: NodesAndEdges, namedThemeColors, ): TreeItem[] => { // const rootParentIds = { "": true }; // the resulting unflattened tree // const rootItems: TreeItem[] = []; // stores all already processed items with their ids as key so we can easily look them up const lookup: { [id: string]: TreeItem } = {}; // stores all item ids that have not been added to the resulting unflattened tree yet // this is an opt-in property, since it has a slight runtime overhead // const orphanIds: null | Set<string | number> = new Set(); let colorIndex = 0; // Add in the nodes to the lookup for (const node of nodesAndEdges.nodes) { // look whether item already exists in the lookup table if (!lookup[node.id]) { // item is not yet there, so add a preliminary item (its data will be added later) lookup[node.id] = { children: [] }; } let color; if (node.category && nodesAndEdges.categories[node.category]) { const categoryOverrides = nodesAndEdges.categories[node.category]; if (categoryOverrides.color) { color = categoryOverrides.color; colorIndex++; } else { color = namedThemeColors.charts[colorIndex++]; } } lookup[node.id] = { ...node, name: node.title, itemStyle: { color, }, children: lookup[node.id].children, }; } // Fill in the children with the edge relationships for (const edge of nodesAndEdges.edges) { const childId = edge.to_id; const parentId = edge.from_id; // look whether the parent already exists in the lookup table if (!lookup[parentId]) { // parent is not yet there, so add a preliminary parent (its data will be added later) lookup[parentId] = { children: [] }; } const childItem = lookup[childId]; // add the current item to the parent lookup[parentId].children.push(childItem); } return Object.values(lookup).filter( (node) => nodesAndEdges.root_nodes[node.id], ); };
// Taken from https://github.com/philipstanislaus/performant-array-to-tree
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/common/index.ts#L976-L1041
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
generateColors
const generateColors = () => { // echarts vintage // return [ // "#d87c7c", // "#919e8b", // "#d7ab82", // "#6e7074", // "#61a0a8", // "#efa18d", // "#787464", // "#cc7e63", // "#724e58", // "#4b565b", // ]; // tableau.Tableau20 return [ "#4E79A7", "#A0CBE8", "#F28E2B", "#FFBE7D", "#59A14F", "#8CD17D", "#B6992D", "#F1CE63", "#499894", "#86BCB6", "#E15759", "#FF9D9A", "#79706E", "#BAB0AC", "#D37295", "#FABFD2", "#B07AA1", "#D4A6C8", "#9D7660", "#D7B5A6", ]; };
// TODO color scheme - need to find something better?
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/common/index.ts#L1054-L1091
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
getChartColors
const getChartColors = (theme: Theme) => { if (theme.name === ThemeNames.STEAMPIPE_DARK) { return [ "#486de8", "#e07f9d", "#018977", "#b088f5", "#c55305", "#8ea9ff", "#ffb0c8", "#40bfa9", ]; } else { return [ "#688ae8", "#c33d69", "#2ea597", "#8456ce", "#e07941", "#3759ce", "#962249", "#096f64", ]; } };
// Taken from https://cloudscape.design/foundation/visual-foundation/data-vis-colors/
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/common/index.ts#L1094-L1118
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
getNodeAndEdgeDataFormat
const getNodeAndEdgeDataFormat = ( properties: NodeAndEdgeProperties | undefined, ): NodeAndEdgeDataFormat => { if (!properties) { return "LEGACY"; } if (!properties.nodes && !properties.edges) { return "LEGACY"; } if ( (properties.nodes && properties.nodes.length > 0) || (properties.edges && properties.edges.length > 0) ) { return "NODE_AND_EDGE"; } return "LEGACY"; };
// Categories may be sourced from a node, an edge, a flow, a graph or a hierarchy
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/common/useNodeAndEdgeData.ts#L33-L52
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
useNodeAndEdgeData
const useNodeAndEdgeData = ( data: NodeAndEdgeData | undefined, properties: NodeAndEdgeProperties | undefined, status: DashboardRunState, ) => { const { panelsMap } = useDashboardState(); const themeColors = useChartThemeColors(); const dataFormat = getNodeAndEdgeDataFormat(properties); const panels = useMemo(() => { if (dataFormat === "LEGACY") { return emptyPanels; } return panelsMap; }, [panelsMap, dataFormat]); return useMemo(() => { if (dataFormat === "LEGACY") { if (status === "complete") { const categories: CategoryMap = {}; // Set defaults on categories for (const [name, category] of Object.entries( properties?.categories || {}, )) { categories[name] = populateCategoryWithDefaults( category, themeColors, ); } return data ? { categories, data, dataFormat, properties } : null; } return null; } // We've now established that it's a NODE_AND_EDGE format data set, so let's build // what we need from the component parts let columns: NodeAndEdgeDataColumn[] = []; let rows: NodeAndEdgeDataRow[] = []; const categories: CategoryMap = {}; const withNameLookup: KeyValueStringPairs = {}; // Add flow/graph/hierarchy level categories for (const [name, category] of Object.entries( properties?.categories || {}, )) { categories[name] = populateCategoryWithDefaults(category, themeColors); } const missingNodes = {}; const missingEdges = {}; const nodeAndEdgeStatus: NodeAndEdgeStatus = { withs: {}, nodes: [], edges: [], }; const nodeIdLookup = {}; // Loop over all the node names and check out their respective panel in the panels map for (const nodePanelName of properties?.nodes || []) { const panel = panels[nodePanelName]; // Capture missing panels - we'll deal with that after if (!panel) { missingNodes[nodePanelName] = true; continue; } // Capture the status of any with blocks that this node depends on addPanelWithsStatus( panels, panel.dependencies, withNameLookup, nodeAndEdgeStatus.withs, ); const typedPanelData = (panel.data || {}) as NodeAndEdgeData; columns = addColumnsForResource(columns, typedPanelData); const nodeProperties = (panel.properties || {}) as NodeProperties; const nodeDataRows = typedPanelData.rows || []; // Capture the status of this node resource nodeAndEdgeStatus.nodes.push({ id: panel.title || nodeProperties.name, state: panel.status || "initialized", category: nodeProperties.category, error: panel.error, title: panel.title, dependencies: panel.dependencies, }); let nodeCategory: Category | null = null; let nodeCategoryId: string = ""; if (nodeProperties.category) { nodeCategory = populateCategoryWithDefaults( nodeProperties.category, themeColors, ); nodeCategoryId = `node.${nodePanelName}.${nodeCategory.name}`; categories[nodeCategoryId] = nodeCategory; } // Loop over each row and ensure we have the correct category information set for it for (const row of nodeDataRows) { // Ensure each row has an id if (row.id === null || row.id === undefined) { continue; } const updatedRow = { ...row }; // Ensure the row has a title and populate from the node if not set if (!updatedRow.title && panel.title) { updatedRow.title = panel.title; } // Capture the ID of each row nodeIdLookup[row.id.toString()] = row; // If the row specifies a category and it's the same now as the node specified, // then update the category to the artificial node category ID if (updatedRow.category && nodeCategory?.name === updatedRow.category) { updatedRow.category = nodeCategoryId; } // Else if the row has a category, but we don't know about it, clear it else if (updatedRow.category && !categories[updatedRow.category]) { updatedRow.category = undefined; } else if (!updatedRow.category && nodeCategoryId) { updatedRow.category = nodeCategoryId; } rows.push(updatedRow); } } // Loop over all the edge names and check out their respective panel in the panels map for (const edgePanelName of properties?.edges || []) { const panel = panels[edgePanelName]; // Capture missing panels - we'll deal with that after if (!panel) { missingEdges[edgePanelName] = true; continue; } // Capture the status of any with blocks that this edge depends on addPanelWithsStatus( panels, panel.dependencies, withNameLookup, nodeAndEdgeStatus.withs, ); const typedPanelData = (panel.data || {}) as NodeAndEdgeData; columns = addColumnsForResource(columns, typedPanelData); const edgeProperties = (panel.properties || {}) as EdgeProperties; // Capture the status of this edge resource nodeAndEdgeStatus.edges.push({ id: panel.title || edgeProperties.name, state: panel.status || "initialized", category: edgeProperties.category, error: panel.error, title: panel.title, dependencies: panel.dependencies, }); let edgeCategory: Category | null = null; let edgeCategoryId: string = ""; if (edgeProperties.category) { edgeCategory = populateCategoryWithDefaults( edgeProperties.category, themeColors, ); edgeCategoryId = `edge.${edgePanelName}.${edgeCategory.name}`; categories[edgeCategoryId] = edgeCategory; } for (const row of typedPanelData.rows || []) { // Ensure the node this edge points to exists in the data set // @ts-ignore const from_id = has(row, "from_id") && row.from_id !== null && row.from_id !== undefined ? row.from_id.toString() : null; // @ts-ignore const to_id = has(row, "to_id") && row.to_id !== null && row.to_id !== undefined ? row.to_id.toString() : null; if ( !from_id || !to_id || !nodeIdLookup[from_id] || !nodeIdLookup[to_id] ) { continue; } const updatedRow = { ...row }; // Ensure the row has a title and populate from the edge if not set if (!updatedRow.title && panel.title) { updatedRow.title = panel.title; } // If the row specifies a category and it's the same now as the edge specified, // then update the category to the artificial edge category ID if (updatedRow.category && edgeCategory?.name === updatedRow.category) { updatedRow.category = edgeCategoryId; } // Else if the row has a category, but we don't know about it, clear it else if (updatedRow.category && !categories[updatedRow.category]) { updatedRow.category = undefined; } else if (!updatedRow.category && edgeCategoryId) { updatedRow.category = edgeCategoryId; } rows.push(updatedRow); } } return { categories, data: { columns, rows }, dataFormat, properties, status: nodeAndEdgeStatus, }; }, [data, dataFormat, panels, properties, status, themeColors]); };
// This function will normalise both the legacy and node/edge data formats into a data table.
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/common/useNodeAndEdgeData.ts#L126-L357
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
getNodeIntersection
function getNodeIntersection(intersectionNode, targetNode) { // https://math.stackexchange.com/questions/1724792/an-algorithm-for-finding-the-intersection-point-between-a-center-of-vision-and-a const { width: intersectionNodeWidth, position: intersectionNodePosition } = intersectionNode; const targetPosition = targetNode.position; const w = intersectionNodeWidth / 2; //const h = intersectionNodeHeight / 2; const h = CIRCLE_SIZE / 2; const x2 = intersectionNodePosition.x + w; const y2 = intersectionNodePosition.y + h; const x1 = targetPosition.x + w; const y1 = targetPosition.y + h; // Algorithm from https://stackoverflow.com/a/18009621.1, const padding = 5; const r = CIRCLE_SIZE / 2 + padding; const phi = Math.atan2(y1 - y2, x1 - x2); const x = x2 + r * Math.cos(phi); const y = y2 + r * Math.sin(phi); return { x, y }; /* // Use linear algebra for slope and intercept: y = mx + b const m = (y2 - y1) / (x2 - x1) const b = y1 - (m * x1) // Now, use pythagoras theorem for x and y difference. We have a circle out // from (x2, y2) with radius r. So, the intercept point (xi, yi) must be // subject to a delta from x2 to xi of xd and from y2 to yi of yd, and: // r^2 = xd^2 + yd^2. // // But we also know yd = m*xd + b // // So: // r^2 = xd^2 + (m*xd + b)^2 // // // x = // const gap = Math.Sqrt(50^2 / 2) let x = x2 let y = y2 if (x1 < return { x: x2, y: y2 }; */ /* const xx1 = (x1 - x2) / (2 * w) - (y1 - y2) / (2 * h); const yy1 = (x1 - x2) / (2 * w) + (y1 - y2) / (2 * h); const a = 1 / (Math.abs(xx1) + Math.abs(yy1)); const xx3 = a * xx1; const yy3 = a * yy1; const x = w * (xx3 + yy3) + x2; const y = h * (-xx3 + yy3) + y2; return { x, y } */ }
// this helper function returns the intersection point
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/graphs/Graph/utils.ts#L7-L70
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
getEdgePosition
function getEdgePosition(node, intersectionPoint) { const n = { ...node.position, ...node }; const nx = Math.round(n.x); const ny = Math.round(n.y); const px = Math.round(intersectionPoint.x); const py = Math.round(intersectionPoint.y); if (px <= nx + 1) { return Position.Left; } if (px >= nx + n.width - 1) { return Position.Right; } if (py <= ny + 1) { return Position.Top; } if (py >= n.y + n.height - 1) { return Position.Bottom; } return Position.Top; }
// returns the position (top,right,bottom or right) passed node compared to the intersection point
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/graphs/Graph/utils.ts#L73-L94
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
circleGetControlWithCurvature
function circleGetControlWithCurvature({ x1, y1, x2, y2, c }) { let ctX; let ctY; if (x1 > x2) { ctX = x1 - calculateControlOffset(x2 - x1, c); } else { ctX = x1 + calculateControlOffset(x1 - x2, c); } if (y1 > y2) { ctY = y1 - calculateControlOffset(y2 - y1, c); } else { ctY = y1 + calculateControlOffset(y1 - y2, c); } return [ctX, ctY]; }
/* export function createNodesAndEdges() { const nodes = []; const edges = []; const center = { x: window.innerWidth / 2, y: window.innerHeight / 2 }; nodes.push({ id: "target", data: { label: "Target" }, position: center }); for (let i = 0; i < 8; i++) { const degrees = i * (360 / 8); const radians = degrees * (Math.PI / 180); const x = 250 * Math.cos(radians) + center.x; const y = 250 * Math.sin(radians) + center.y; nodes.push({ id: `${i}`, data: { label: "Source" }, position: { x, y } }); edges.push({ id: `edge-${i}`, target: "target", source: `${i}`, type: "floating", markerEnd: { type: MarkerType.Arrow, }, }); } return { nodes, edges }; } */
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/graphs/Graph/utils.ts#L154-L171
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
runTestCases
function runTestCases( testCases: TestCase[], validationFunction: (input: any) => boolean, ) { testCases.forEach((testCase) => { it(`should return ${testCase.expected} for ${testCase.name}`, () => { const result = validationFunction(testCase.input); expect(result).toBe(testCase.expected); }); }); }
// const orFilterTestCases: TestCase[] = [
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/grouping/FilterEditor/index.test.ts#L103-L113
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
DatetimeInput
const DatetimeInput = (props: InputProps) => { // return <Foo />; return ( <Date name={props.name} display_type="datetime" properties={props.properties} /> ); };
// const Foo = () => {
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/components/dashboards/inputs/DatetimeInput/index.tsx#L12-L21
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
getCheckGroupingKey
const getCheckGroupingKey = ( checkResult: CheckResult, group: CheckDisplayGroup, ) => { switch (group.type) { case "dimension": return getCheckDimensionGroupingKey(group.value, checkResult.dimensions); case "control_tag": return getCheckTagGroupingKey(group.value, checkResult.tags); case "reason": return getCheckReasonGroupingKey(checkResult.reason); case "resource": return getCheckResourceGroupingKey(checkResult.resource); // case "result": // return getCheckResultGroupingKey(checkResult); case "severity": return getCheckSeverityGroupingKey(checkResult.control.severity); case "status": return getCheckStatusGroupingKey(checkResult.status); case "benchmark": if (checkResult.benchmark_trunk.length <= 1) { return null; } return checkResult.benchmark_trunk[checkResult.benchmark_trunk.length - 1] .name; case "control": return checkResult.control.name; default: return "Other"; } };
// const getCheckResultGroupingKey = (checkResult: CheckResult): string => {
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/hooks/useBenchmarkGrouping.tsx#L244-L274
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
handleResize
function handleResize() { // Set window width/height to state // @ts-ignore setDimensions(ref.current.getBoundingClientRect().toJSON()); }
// Handler to call on window resize
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/hooks/useDimensions.ts#L14-L18
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
useWindowSize
const useWindowSize = (): readonly [number, number] => { // @ts-ignore const [size, setSize] = useState( typeof window !== "undefined" ? ([window.innerWidth, window.innerHeight] as const) : ([0, 0] as const), ); useEffect(() => { const updateSize = () => { setSize([window.innerWidth, window.innerHeight]); }; window.addEventListener("resize", updateSize); return () => window.removeEventListener("resize", updateSize); }, []); return size; };
// https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/hooks/useWindowSize.ts#L4-L19
e500c48d5bc38a63c694007f80a13c42b3da0d17
powerpipe
github_2023
turbot
typescript
getResponsivePanelWidthClass
const getResponsivePanelWidthClass = (width: number | undefined): string => { switch (width) { case 0: // Hide anything with no width return "hidden"; case 1: return "md:col-span-3 lg:col-span-1"; case 2: return "md:col-span-3 lg:col-span-2"; case 3: return "md:col-span-3"; case 4: return "md:col-span-6 lg:col-span-4"; case 5: return "md:col-span-6 lg:col-span-5"; case 6: return "md:col-span-6"; case 7: return "md:col-span-7"; case 8: return "md:col-span-8"; case 9: return "md:col-span-9"; case 10: return "md:col-span-10"; case 11: return "md:col-span-11"; default: // 12 or anything else returns empty string // and accepts our default grid behaviour return ""; } };
// Needs to be a single unbroken string so that the tailwind content purging
https://github.com/turbot/powerpipe/blob/e500c48d5bc38a63c694007f80a13c42b3da0d17/ui/dashboard/src/utils/layout.ts#L4-L36
e500c48d5bc38a63c694007f80a13c42b3da0d17
gadget
github_2023
tangle-network
typescript
signAndSend
async function signAndSend( signer: AddressOrPair, tx: SubmittableExtrinsic<"promise">, waitTillFinallized: boolean = false, ): Promise<void> { // Sign and send the transaction and wait for it to be included. await new Promise(async (resolve, reject) => { const unsub = await tx.signAndSend( signer, async ({ events = [], status, dispatchError }) => { if (dispatchError) { if (dispatchError.isModule) { // for module errors, we have the section indexed, lookup const decoded = api.registry.findMetaError(dispatchError.asModule); const { docs, name, section } = decoded; console.log(`|--- ${section}.${name}: ${docs.join(" ")}`); reject(`${section}.${name}`); } } if (status.isInBlock && !waitTillFinallized) { console.log("|--- Events:"); events.forEach(({ event: { data, method, section } }) => { console.log(`|---- ${section}.${method}:: ${data}`); }); unsub(); resolve(void 0); } if (status.isFinalized && waitTillFinallized) { console.log("|--- Events:"); events.forEach(({ event: { data, method, section } }) => { console.log(`|---- ${section}.${method}:: ${data}`); }); unsub(); resolve(void 0); } }, ); }); }
// *** --- Helper Functions --- ***
https://github.com/tangle-network/gadget/blob/06ebab91cbb0fd361b2397a6221c2020173ebbf3/blueprints/incredible-squaring/deploy.ts#L148-L187
06ebab91cbb0fd361b2397a6221c2020173ebbf3
react-native-vercel-ai
github_2023
bidah
typescript
createChunkDecoder
function createChunkDecoder(complex?: boolean) { const decoder = new TextDecoder(); if (!complex) { return function (chunk: Uint8Array | undefined): string { if (!chunk) return ''; return decoder.decode(chunk, { stream: true }); }; } return function (chunk: Uint8Array | undefined) { const decoded = decoder.decode(chunk, { stream: true }).split('\n'); return decoded.map(getStreamStringTypeAndValue).filter(Boolean) as any; }; }
// Type overloads
https://github.com/bidah/react-native-vercel-ai/blob/3b5441140f61b5f480e112e2588dd2883ed35ad1/src/shared/utils.ts#L23-L37
3b5441140f61b5f480e112e2588dd2883ed35ad1
javavscode
github_2023
oracle
typescript
matchTemplate
function matchTemplate(str1: string, str2: string): boolean { const regexp = /\{[^\{\}]*\}/g; const params1 = new Set([...str1.matchAll(regexp)].map((value) => value[0])); const params2 = new Set([...str2.matchAll(regexp)].map((value) => value[0])); return setEqual(params1, params2); }
/** * * @param str1 * @param str2 * @returns Checks if the placeholders specified as {placeholder} match for str1 and str2 */
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L500-L505
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
placeholderMatch
function placeholderMatch(targetString: string, placeholders: Set<string>): boolean { const regexp = /\{([^\{\}]*)\}/g; const params1 = new Set([...targetString.matchAll(regexp)].map((value) => value[1])); return setEqual(params1, placeholders); }
/** * * @param targetString String containing placeholder in form of {placeholder} * @param placeholders Set of required placeholders in the target string * @returns Whether the placeholders present in the targetString and in the placeholders set are same */
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L520-L524
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
getPlaceholders
function getPlaceholders(dictString: string): Set<string> { const placeholders = new Set<string>(); const cleanedDictString = dictString.replace(/"[^"]*"/g, "SOME_STRING_VALUE").replace(/'[^']*'/g, "SOME_STRING_VALUE"); for (const keyVal of cleanedDictString.split(',')) { // improve this so that if value has key:"," that doesn't get picked up placeholders.add(keyVal.split(':')[0].trim()); } return placeholders; }
/** * * @param dictString String having key value pairs {key1:value1,key2:value2...} * @returns Set of keys used in the dictString */
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L533-L541
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
checkL10nUsageInFile
function checkL10nUsageInFile(filePath: string, pattern: RegExp, validKeyValues: any): boolean { const fileContent: string = fs.readFileSync(filePath, 'utf8'); const matches = fileContent.matchAll(pattern); const keys = new Set(Object.keys(validKeyValues)); let result = true; for (const matchArr of matches) { const context: string = matchArr[0]; const key: string = matchArr[1]; const placeholders: undefined | Set<string> = matchArr.length === 3 ? getPlaceholders(matchArr[2]) : undefined; if (!keys.has(key)) { console.log(`Found invalid localisation key in file:'${filePath.replace(".js", ".ts")}'.Here is the expression used in file with invalid key '${context}'`); result = false; continue; } if (placeholders != undefined) { if (!placeholderMatch(validKeyValues[key], placeholders)) { console.log(placeholders); result = false; console.log(`Wrong placeholder map for a localisation key in file:'${filePath.replace(".js", ".ts")}'.Here is the expression used in file with wrong placeholder map '${context}'. Here is the bundle value '${validKeyValues[key]}'`); } } else { if (!matchTemplate("", validKeyValues[key])) { result = false; console.log(`Placeholder map not provided for a localisation key in file:'${filePath.replace(".js", ".ts")}'.Here is the expression used in file without the placeholder '${context}'. Here is the bundle value '${validKeyValues[key]}'`); } } } return result; }
/** * * @param filePath * @param pattern To extract the keys and the placeholder map used when calling l10n.value * @param validKeyValues From the bundle.en.json filee * @returns All usage of l10n.value according to the pattern is having valid keys and placeholder map */
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L550-L579
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
isLocalizedVal
function isLocalizedVal(value: string): boolean { return value.length > 2 && value[0] === '%' && value[0] === value[value.length - 1]; }
/** * * @param value string to be checked * @returns value of the form %key% where key is some string containing alphanumeric characters */
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L586-L588
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
getlocalizingKey
function getlocalizingKey(str: string): string { const length = str.length; return str.substring(1, length - 1); }
/** * * @param str localised value of the form %key% * @returns key */
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L596-L599
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
isLocalizedObj
function isLocalizedObj(obj: any, localisableFields: any, id: string, category: string, validKeys: Set<string>): boolean { let localized: boolean = true; let fieldVals: any; let localizingKey: string; for (const field of localisableFields) { fieldVals = obj[field]; if (fieldVals === undefined) continue; if (!Array.isArray(fieldVals)) fieldVals = [fieldVals]; for (const fieldVal of fieldVals) { localizingKey = getlocalizingKey(fieldVal); if (!isLocalizedVal(fieldVal)) { console.log(`${category} object with id ${id} has a unlocalized field field:'${field}'`); localized = false; } else if (!validKeys.has(localizingKey)) { console.log(`${category} object of id '${id}' has a invalid localizing key for the field:'${field}' key:'${localizingKey}'`); localized = false; } } } return localized; }
/** * * @param obj * @param localisableFields Array or Scalar fields which are to be tested for localisation * @param id * @param category * @param validKeys Keys present in the package.nls.json * @returns Whether the object given has the required fields localised by some valid key */
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/integration/testutils.ts#L610-L630
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
_schemeFix
function _schemeFix(scheme: string, _strict: boolean): string { if (_strict || _throwOnMissingSchema) { return scheme || _empty; } if (!scheme) { console.trace('BAD uri lacks scheme, falling back to file-scheme.'); scheme = 'file'; } return scheme; }
// for a while we allowed uris *without* schemes and this is the migration
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L102-L111
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
_referenceResolution
function _referenceResolution(scheme: string, path: string): string { // the slash-character is our 'default base' as we don't // support constructing URIs relative to other URIs. This // also means that we alter and potentially break paths. // see https://tools.ietf.org/html/rfc3986#section-5.1.4 switch (scheme) { case 'https': case 'http': case 'file': if (!path) { path = _slash; } else if (path[0] !== _slash) { path = _slash + path; } break; default: break; } return path; }
// implements a bit of https://tools.ietf.org/html/rfc3986#section-5
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L114-L133
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
URI.constructor
protected constructor( schemeOrData: string | UriComponents, authority?: string, path?: string, query?: string, fragment?: string, _strict = false, ) { if (typeof schemeOrData === 'object') { this.scheme = schemeOrData.scheme || _empty; this.authority = schemeOrData.authority || _empty; this.path = schemeOrData.path || _empty; this.query = schemeOrData.query || _empty; this.fragment = schemeOrData.fragment || _empty; // no validation because it's this URI // that creates uri components. // _validateUri(this); } else { this.scheme = _schemeFix(schemeOrData, _strict); this.authority = authority || _empty; this.path = _referenceResolution(this.scheme, path || _empty); this.query = query || _empty; this.fragment = fragment || _empty; _validateUri(this, _strict); } }
/** * @internal */
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L217-L243
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
URI.fsPath
get fsPath(): string { // if (this.scheme !== 'file') { // console.warn(`[UriError] calling fsPath with scheme ${this.scheme}`); // } return _makeFsPath(this); }
/** * Returns a string representing the corresponding file system path of this URI. * Will handle UNC paths, normalizes windows drive letters to lower-case, and uses the * platform specific path separator. * * * Will *not* validate the path for invalid characters and semantics. * * Will *not* look at the scheme of this URI. * * The result shall *not* be used for display purposes but for accessing a file on disk. * * * The *difference* to `URI#path` is the use of the platform specific separator and the handling * of UNC paths. See the below sample of a file-uri with an authority (UNC path). * * ```ts const u = URI.parse('file://server/c$/folder/file.txt') u.authority === 'server' u.path === '/shares/c$/file.txt' u.fsPath === '\\server\c$\folder\file.txt' ``` * * Using `URI#path` to read a file (using fs-apis) would not be enough because parts of the path, * namely the server name, would be missing. Therefore `URI#fsPath` exists - it's sugar to ease working * with URIs that represent files on disk (`file` scheme). */
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L271-L276
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
URI.with
with(change: { scheme?: string; authority?: string | null; path?: string | null; query?: string | null; fragment?: string | null; }): URI { if (!change) { return this; } let { scheme, authority, path, query, fragment } = change; if (scheme === undefined) { scheme = this.scheme; } else if (scheme === null) { scheme = _empty; } if (authority === undefined) { authority = this.authority; } else if (authority === null) { authority = _empty; } if (path === undefined) { path = this.path; } else if (path === null) { path = _empty; } if (query === undefined) { query = this.query; } else if (query === null) { query = _empty; } if (fragment === undefined) { fragment = this.fragment; } else if (fragment === null) { fragment = _empty; } if ( scheme === this.scheme && authority === this.authority && path === this.path && query === this.query && fragment === this.fragment ) { return this; } // eslint-disable-next-line @typescript-eslint/no-use-before-define return new _URI(scheme, authority, path, query, fragment); }
// ---- modify to new -------------------------
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L280-L330
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9
javavscode
github_2023
oracle
typescript
URI.parse
static parse(value: string, _strict = false): URI { const match = _regexp.exec(value); if (!match) { // eslint-disable-next-line @typescript-eslint/no-use-before-define return new _URI(_empty, _empty, _empty, _empty, _empty); } // eslint-disable-next-line @typescript-eslint/no-use-before-define return new _URI( match[2] || _empty, decodeURIComponent(match[4] || _empty), decodeURIComponent(match[5] || _empty), decodeURIComponent(match[7] || _empty), decodeURIComponent(match[9] || _empty), _strict, ); }
/** * Creates a new URI from a string, e.g. `http://www.msft.com/some/path`, * `file:///usr/home`, or `scheme:with/path`. * * @param value A string which represents an URI (see `URI#toString`). * @param {boolean} [_strict=false] */
https://github.com/oracle/javavscode/blob/40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9/vscode/src/test/unit/mocks/vscode/uri.ts#L341-L356
40d9fe288a4f2a3117be5be3ef2b53fc8f53c4e9