repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
MaxKB
github_2023
1Panel-dev
typescript
getProfile
const getProfile: (loading?: Ref<boolean>) => Promise<Result<any>> = (loading) => { return get('/profile', undefined, loading) }
/** * 获取profile */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/user.ts#L135-L137
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
getValid
const getValid: ( valid_type: string, valid_count: number, loading?: Ref<boolean> ) => Promise<Result<any>> = (valid_type, valid_count, loading) => { return get(`/valid/${valid_type}/${valid_count}`, undefined, loading) }
/** * 获取校验 * @param valid_type 校验类型: application|dataset|user * @param valid_count 校验数量: 5 | 50 | 2 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/user.ts#L144-L150
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
getAuthType
const getAuthType: (loading?: Ref<boolean>) => Promise<Result<any>> = (loading) => { return get('auth/types', undefined, loading) }
/** * 获取登录方式 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/user.ts#L154-L156
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
getQrType
const getQrType: (loading?: Ref<boolean>) => Promise<Result<any>> = (loading) => { return get('qr_type', undefined, loading) }
/** * 获取二维码类型 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/user.ts#L161-L163
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
postLanguage
const postLanguage: (data: any, loading?: Ref<boolean>) => Promise<Result<User>> = ( data, loading ) => { return post('/user/language', data, undefined, loading) }
/** * 设置语言 * data: { * "language": "string" * } */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/user.ts#L185-L190
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
ChatManagement.write
static write(chatRecordId: string) { const chatRecord = this.chatMessageContainer[chatRecordId] if (chatRecord) { chatRecord.write() } }
/** * 持续从缓存区 写出数据 * @param chatRecordId 对话记录id */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/type/application.ts#L434-L439
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
ChatManagement.close
static close(chatRecordId: string) { const chatRecord = this.chatMessageContainer[chatRecordId] if (chatRecord) { chatRecord.close() } }
/** * 等待所有数据输出完毕后 才会关闭流 * @param chatRecordId 对话记录id * @returns boolean */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/type/application.ts#L445-L450
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
ChatManagement.stop
static stop(chatRecordId: string) { const chatRecord = this.chatMessageContainer[chatRecordId] if (chatRecord) { chatRecord.stop() } }
/** * 停止输出 立即关闭定时任务输出 * @param chatRecordId 对话记录id * @returns boolean */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/type/application.ts#L456-L461
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
ChatManagement.isClose
static isClose(chatRecordId: string) { const chatRecord = this.chatMessageContainer[chatRecordId] return chatRecord ? chatRecord.is_close && chatRecord.write_ed : false }
/** * 判断是否输出完成 * @param chatRecordId 对话记录id * @returns boolean */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/type/application.ts#L467-L470
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
ChatManagement.isStop
static isStop(chatRecordId: string) { const chatRecord = this.chatMessageContainer[chatRecordId] return chatRecord ? chatRecord.is_stop : false }
/** * 判断是否停止输出 * @param chatRecordId 对话记录id * @returns */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/type/application.ts#L476-L479
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
ChatManagement.clean
static clean() { for (const key in Object.keys(this.chatMessageContainer)) { if (this.chatMessageContainer[key].is_close) { delete this.chatMessageContainer[key] } } }
/** * 清除无用数据 也就是被close掉的和stop的数据 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/api/type/application.ts#L483-L489
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
generateLangModuleMap
const generateLangModuleMap = () => { const fullPaths = Object.keys(langModules) fullPaths.forEach((fullPath) => { const k = fullPath.replace('./lang', '') const startIndex = 1 const lastIndex = k.lastIndexOf('/') const code = k.substring(startIndex, lastIndex) langCode.push(code) langModule...
// 生成语言模块列表
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/locales/index.ts#L34-L44
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
promise
const promise: ( request: Promise<any>, loading?: NProgress | Ref<boolean> | WritableComputedRef<boolean> ) => Promise<Result<any>> = (request, loading = ref(false)) => { return new Promise((resolve, reject) => { if ((loading as NProgress).start) { ;(loading as NProgress).start() } else { ;(lo...
/* 简化请求方法,统一处理返回结果,并增加loading处理,这里以{success,data,message}格式的返回值为例,具体项目根据实际需求修改 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/request/index.ts#L90-L120
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
hasPermissionChild
const hasPermissionChild = (permission: Role | string | Permission | ComplexPermission) => { const { user } = useStore(); const permissions = user.getPermissions() const role = user.getRole() if (!permission) { return true } if (permission instanceof Role) { return role === permission.role } if ...
/** * 是否包含当前权限 * @param permission 当前权限 * @returns True 包含 false 不包含 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/utils/permission/index.ts#L8-L31
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
AppNodeModel.getAnchorStyle
getAnchorStyle(anchorInfo: any) { const style = super.getAnchorStyle(anchorInfo) if (anchorInfo.type === 'left') { style.fill = 'red' style.hover.fill = 'transparent' style.hover.stroke = 'transpanrent' style.className = 'lf-hide-default' } else { style.fill = 'green' } ...
// 如果不用修改锚地形状,可以重写颜色相关样式
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/app-node.ts#L307-L318
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
CustomEdge2.renderVueComponent
protected renderVueComponent(root: any) { this.unmountVueComponent() this.root = root const { graphModel } = this.props if (root) { if (isActive()) { connect( this.targetId(), CustomLine, root, this.props.model, graphModel, (node:...
/** * 渲染vue组件 * @param root */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/edge.ts#L36-L59
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
CustomEdge2.componentWillUnmount
componentWillUnmount() { if (super.componentWillUnmount) { super.componentWillUnmount() } if (isActive()) { disconnect(this.targetId()) } this.unmountVueComponent() }
/** * 组件即将卸载勾子 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/edge.ts#L66-L74
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
CustomEdge2.unmountVueComponent
protected unmountVueComponent() { if (this.customLineApp) { this.customLineApp.unmount() this.customLineApp = null } if (this.root) { this.root.innerHTML = '' } return this.root }
/** * 卸载vue * @returns */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/edge.ts#L79-L88
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
CustomEdgeModel2.getData
getData() { const data: any = super.getData() if (data) { data.sourceAnchorId = this.sourceAnchorId data.targetAnchorId = this.targetAnchorId } return data }
/** * 重写此方法,使保存数据是能带上锚点数据。 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/edge.ts#L192-L199
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
CustomEdgeModel2.updatePathByAnchor
updatePathByAnchor() { // TODO const sourceNodeModel = this.graphModel.getNodeModelById(this.sourceNodeId) const sourceAnchor = sourceNodeModel .getDefaultAnchor() .find((anchor: any) => anchor.id === this.sourceAnchorId) const targetNodeModel = this.graphModel.getNodeModelById(this.targetN...
/** * 给边自定义方案,使其支持基于锚点的位置更新边的路径 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/edge.ts#L203-L231
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
WorkFlowInstance.is_valid_start_node
private is_valid_start_node() { const start_node_list = this.nodes.filter((item) => item.id === WorkflowType.Start) if (start_node_list.length == 0) { throw t('views.applicationWorkflow.validate.startNodeRequired') } else if (start_node_list.length > 1) { throw t('views.applicationWorkflow.valid...
/** * 校验开始节点 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/validate.ts#L27-L34
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
WorkFlowInstance.is_valid_base_node
private is_valid_base_node() { const start_node_list = this.nodes.filter((item) => item.id === WorkflowType.Base) if (start_node_list.length == 0) { throw t('views.applicationWorkflow.validate.baseNodeRequired') } else if (start_node_list.length > 1) { throw t('views.applicationWorkflow.validate...
/** * 校验基本信息节点 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/validate.ts#L38-L45
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
WorkFlowInstance.is_valid
is_valid() { this.is_valid_start_node() this.is_valid_base_node() this.is_valid_work_flow() this.is_valid_nodes() }
/** * 校验节点 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/validate.ts#L49-L54
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
WorkFlowInstance.get_start_node
get_start_node() { const start_node_list = this.nodes.filter((item) => item.id === WorkflowType.Start) return start_node_list[0] }
/** * 获取开始节点 * @returns */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/validate.ts#L60-L63
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
WorkFlowInstance.get_base_node
get_base_node() { const base_node_list = this.nodes.filter((item) => item.id === WorkflowType.Base) return base_node_list[0] }
/** * 获取基本节点 * @returns 基本节点 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/validate.ts#L68-L71
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
WorkFlowInstance._is_valid_work_flow
private _is_valid_work_flow(up_node?: any) { if (!up_node) { up_node = this.get_start_node() } this.workFlowNodes.push(up_node) this.is_valid_node(up_node) const next_nodes = this.get_next_nodes(up_node) for (const next_node of next_nodes) { this._is_valid_work_flow(next_node) } ...
/** * 校验工作流 * @param up_node 上一个节点 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/validate.ts#L77-L87
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
WorkFlowInstance.get_next_nodes
private get_next_nodes(node: any) { const edge_list = this.edges.filter((edge) => edge.sourceNodeId == node.id) const node_list = edge_list .map((edge) => this.nodes.filter((node) => node.id == edge.targetNodeId)) .reduce((x, y) => [...x, ...y], []) if (node_list.length == 0 && !end_nodes.includ...
/** * 获取流程下一个节点列表 * @param node 节点 * @returns 节点列表 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/validate.ts#L104-L113
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
WorkFlowInstance.is_valid_node
private is_valid_node(node: any) { if (node.properties.status && node.properties.status === 500) { throw `${node.properties.stepName} ${t('views.applicationWorkflow.validate.nodeUnavailable')}` } if (node.type === WorkflowType.Condition) { const branch_list = node.properties.node_data.branch ...
/** * 校验节点 * @param node 节点 */
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/common/validate.ts#L127-L149
a1fca58864ba09b49e87bff186d4d428aaa45b72
MaxKB
github_2023
1Panel-dev
typescript
Dagre.layout
layout(option = {}) { const { nodes, edges, gridSize } = this.lf.graphModel // 为了保证生成的节点在girdSize上,需要处理一下。 let nodesep = 40 let ranksep = 40 if (gridSize > 20) { nodesep = gridSize * 2 ranksep = gridSize * 2 } this.option = { type: 'dagre', rankdir: 'LR', // ali...
/** * option: { * rankdir: "TB", // layout 方向, 可选 TB, BT, LR, RL * align: undefined, // 节点对齐方式,可选 UL, UR, DL, DR * nodeSize: undefined, // 节点大小 * nodesepFunc: undefined, // 节点水平间距(px) * ranksepFunc: undefined, // 每一层节点之间间距 * nodesep: 40, // 节点水平间距(px) 注意:如果有grid,需要保证nodesep为grid的偶数倍 ...
https://github.com/1Panel-dev/MaxKB/blob/a1fca58864ba09b49e87bff186d4d428aaa45b72/ui/src/workflow/plugins/dagre.ts#L25-L68
a1fca58864ba09b49e87bff186d4d428aaa45b72
invoify
github_2023
al1abb
typescript
returnButtonVariant
const returnButtonVariant = (step: WizardStepType) => { if (!step.isValid) { return "destructive"; } if (step.id === activeStep) { return "default"; } else { return "outline"; } };
/** * Determines the button variant based on the given WizardStepType. * * @param {WizardStepType} step - The wizard step object * @returns The button variant ("destructive", "default", or "outline") based on the step's validity and active status. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/app/components/invoice/form/wizard/WizardProgress.tsx#L54-L63
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
stepPassed
const stepPassed = (currentStep: WizardStepType) => { if (currentStep.isValid) { return activeStep > currentStep.id ? true : false; } };
/** * Checks whether the given WizardStepType has been passed or not. * * @param {WizardStepType} currentStep - The WizardStepType object * @returns `true` if the step has been passed, `false` if it hasn't, or `undefined` if the step is not valid. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/app/components/invoice/form/wizard/WizardProgress.tsx#L71-L75
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
calculateTotal
const calculateTotal = () => { // Here Number(item.total) fixes a bug where an extra zero appears // at the beginning of subTotal caused by toFixed(2) in item.total in single item // Reason: toFixed(2) returns string, not a number instance const totalSum: number = itemsArray.reduce( ...
/** * Calculates the subtotal, total, and the total amount in words on the invoice. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/ChargesContext.tsx#L173-L242
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
onFormSubmit
const onFormSubmit = (data: InvoiceType) => { console.log("VALUE"); console.log(data); // Call generate pdf method generatePdf(data); };
/** * Handles form submission. * * @param {InvoiceType} data - The form values used to generate the PDF. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L115-L121
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
newInvoice
const newInvoice = () => { reset(FORM_DEFAULT_VALUES); setInvoicePdf(new Blob()); router.refresh(); // Toast newInvoiceSuccess(); };
/** * Generates a new invoice. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L126-L134
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
removeFinalPdf
const removeFinalPdf = () => { setInvoicePdf(new Blob()); };
/** * Removes the final PDF file and switches to Live Preview */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L169-L171
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
previewPdfInTab
const previewPdfInTab = () => { if (invoicePdf) { const url = window.URL.createObjectURL(invoicePdf); window.open(url, "_blank"); } };
/** * Generates a preview of a PDF file and opens it in a new browser tab. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L176-L181
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
downloadPdf
const downloadPdf = () => { // Only download if there is an invoice if (invoicePdf instanceof Blob && invoicePdf.size > 0) { // Create a blob URL to trigger the download const url = window.URL.createObjectURL(invoicePdf); // Create an anchor element to initiate the download const a = do...
/** * Downloads a PDF file. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L186-L204
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
printPdf
const printPdf = () => { if (invoicePdf) { const pdfUrl = URL.createObjectURL(invoicePdf); const printWindow = window.open(pdfUrl, "_blank"); if (printWindow) { printWindow.onload = () => { printWindow.print(); }; } } };
/** * Prints a PDF file. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L209-L219
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
saveInvoice
const saveInvoice = () => { if (invoicePdf) { // If get values function is provided, allow to save the invoice if (getValues) { // Retrieve the existing array from local storage or initialize an empty array const savedInvoicesJSON = localStorage.getItem("savedInvoices"); const sa...
// TODO: Change function name. (saveInvoiceData maybe?)
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L225-L274
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
deleteInvoice
const deleteInvoice = (index: number) => { if (index >= 0 && index < savedInvoices.length) { const updatedInvoices = [...savedInvoices]; updatedInvoices.splice(index, 1); setSavedInvoices(updatedInvoices); const updatedInvoicesJSON = JSON.stringify(updatedInvoices); localStorage.setI...
// TODO: Change function name. (deleteInvoiceData maybe?)
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L282-L292
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
sendPdfToMail
const sendPdfToMail = (email: string) => { const fd = new FormData(); fd.append("email", email); fd.append("invoicePdf", invoicePdf, "invoice.pdf"); fd.append("invoiceNumber", getValues().details.invoiceNumber); return fetch(SEND_PDF_API, { method: "POST", body: fd, }) .then((...
/** * Send the invoice PDF to the specified email address. * * @param {string} email - The email address to which the Invoice PDF will be sent. * @returns {Promise<void>} A promise that resolves once the email is successfully sent. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L300-L325
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
exportInvoiceAs
const exportInvoiceAs = (exportAs: ExportTypes) => { const formValues = getValues(); // Service to export invoice with given parameters exportInvoice(exportAs, formValues); };
/** * Export an invoice in the specified format using the provided form values. * * This function initiates the export process with the chosen export format and the form data. * * @param {ExportTypes} exportAs - The format in which to export the invoice. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L334-L339
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
importInvoice
const importInvoice = (file: File) => { const reader = new FileReader(); reader.onload = (event) => { try { const importedData = JSON.parse(event.target?.result as string); // Parse the dates if (importedData.details) { if (importedData.details.invoiceDate) { ...
/** * Import an invoice from a JSON file. * * @param {File} file - The JSON file to import. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/InvoiceContext.tsx#L346-L374
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
handleColorButtonClick
const handleColorButtonClick = (color: string) => { setSelectedColor(color); };
/** * Sets selected signature color * * @param {string} color - Color to be selected as string. Ex: "red" */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/SignatureContext.tsx#L87-L89
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
calculateFontSize
const calculateFontSize = (text: string) => { const initialFontSize = 100; const canvasWidth = 300; let fontSize = initialFontSize; const textWidth = text.length * (initialFontSize / 2); // Adjust as needed for font width if (textWidth > canvasWidth - 20) { // Gradua...
/** * Font size calculator for typed signature * * @param {string} text - Text in signature input * @returns {number} Font size that should be used */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/SignatureContext.tsx#L138-L150
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
clearTypedSignature
const clearTypedSignature = () => { setTypedSignature(""); setValue("details.signature", ""); };
/** * Clears typed signature */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/SignatureContext.tsx#L163-L166
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
handleUploadSignatureChange
const handleUploadSignatureChange = ( e: React.ChangeEvent<HTMLInputElement> ) => { const file = e.target.files![0]; if (file) { const reader = new FileReader(); reader.onload = (event) => { const base64String = event.target!.result as string; ...
/** * Function that fires every time signature file input changes * @param e - Event object from file input */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/SignatureContext.tsx#L178-L190
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
handleRemoveUploadedSignature
const handleRemoveUploadedSignature = () => { setUploadSignatureImg(""); if (uploadSignatureRef.current) { uploadSignatureRef.current.value = ""; } };
/** * Function that removes uploaded signature */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/contexts/SignatureContext.tsx#L195-L201
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
fetchCurrencies
const fetchCurrencies = async () => { setCurrenciesLoading(true); try { const response = await fetch(`${CURRENCIES_API}`); const data = await response.json(); const currencyOptions = Object.keys(data).map((currencyCode) => { const currencyName = data...
/** * Fetches all the currencies asynchronously. * * @return {Promise<void>} Promise that resolves when the currencies are fetched. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/hooks/useCurrencies.tsx#L18-L36
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
formatNumberWithCommas
const formatNumberWithCommas = (number: number) => { return number.toLocaleString("en-US", { style: "decimal", minimumFractionDigits: 2, maximumFractionDigits: 2, }); };
/** * Formats a number with commas and decimal places * * @param {number} number - Number to format * @returns {string} A styled number to be displayed on the invoice */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/lib/helpers.ts#L17-L23
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
fetchCurrencyDetails
const fetchCurrencyDetails = (currency: string): CurrencyDetails | null => { const data = currenciesDetails as Record<string, CurrencyDetails>; const currencyDetails = data[currency]; return currencyDetails || null; };
/** * @param {string} currency - The currency that is currently selected * @returns {Object} - An object containing the currency details as * ``` * { "currency": "United Arab Emirates Dirham", "decimals": 2, "beforeDecimal": "Dirham", "afterDecimal": "Fils" } */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/lib/helpers.ts#L36-L40
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
formatPriceToString
const formatPriceToString = (price: number, currency: string): string => { // Initialize variables let decimals : number; let beforeDecimal: string | null = null; let afterDecimal: string | null = null; const currencyDetails = fetchCurrencyDetails(currency); // If currencyDetails is availa...
/** * Turns a number into words for invoices * * @param {number} price - Number to format * @returns {string} Number in words */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/lib/helpers.ts#L49-L114
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
flattenObject
const flattenObject = <T>( obj: Record<string, T>, parentKey = "" ): Record<string, T> => { const result: Record<string, T> = {}; for (const key in obj) { if (typeof obj[key] === "object" && !Array.isArray(obj[key])) { const flattened = flattenObject( obj[key] as Rec...
/** * This method flattens a nested object. It is used for xlsx export * * @param {Record<string, T>} obj - A nested object to flatten * @param {string} parentKey - The parent key * @returns {Record<string, T>} A flattened object */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/lib/helpers.ts#L123-L144
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
isValidEmail
const isValidEmail = (email: string) => { // Regular expression for a simple email pattern const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i; return emailRegex.test(email); };
/** * A method to validate an email address * * @param {string} email - Email to validate * @returns {boolean} A boolean indicating if the email is valid */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/lib/helpers.ts#L152-L156
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
isDataUrl
const isDataUrl = (str: string) => str.startsWith("data:");
/** * A method to check if a string is a data URL * * @param {string} str - String to check * @returns {boolean} Boolean indicating if the string is a data URL */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/lib/helpers.ts#L164-L164
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
getInvoiceTemplate
const getInvoiceTemplate = async (templateId: number) => { // Dynamic template component name const componentName = `InvoiceTemplate${templateId}`; try { const module = await import( `@/app/components/templates/invoice-pdf/${componentName}` ); return module.default; ...
/** * Dynamically imports and retrieves an invoice template React component based on the provided template ID. * * @param {number} templateId - The ID of the invoice template. * @returns {Promise<React.ComponentType<any> | null>} A promise that resolves to the invoice template component or null if not found. * @th...
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/lib/helpers.ts#L173-L188
ecc710f67122303040a40b38d8c0ef6c0d72cc19
invoify
github_2023
al1abb
typescript
fileToBuffer
const fileToBuffer = async (file: File) => { // Convert Blob to ArrayBuffer const arrayBuffer = await new NextResponse(file).arrayBuffer(); // Convert ArrayBuffer to Buffer const pdfBuffer = Buffer.from(arrayBuffer); return pdfBuffer; };
/** * Convert a file to a buffer. Used for sending invoice as email attachment. * @param {File} file - The file to convert to a buffer. * @returns {Promise<Buffer>} A promise that resolves to a buffer. */
https://github.com/al1abb/invoify/blob/ecc710f67122303040a40b38d8c0ef6c0d72cc19/lib/helpers.ts#L195-L203
ecc710f67122303040a40b38d8c0ef6c0d72cc19
ACE_Framework
github_2023
daveshap
typescript
fetchInitialLayerState
async function fetchInitialLayerState() { try { const response = await fetch(`${backendUrl}/layer_state/${layerId}/`); console.log("response", response); const initialState = await response.json(); console.log("response.json", initialState); ...
// Fetch the initial layerState
https://github.com/daveshap/ACE_Framework/blob/c6693ee2ff547d63675f938a3714165050fd0126/CORE_DEMOS/stacey/frontend/components/layerStateComponent.tsx#L37-L57
c6693ee2ff547d63675f938a3714165050fd0126
ACE_Framework
github_2023
daveshap
typescript
handleKeyPress
const handleKeyPress = async (e: React.KeyboardEvent) => { if (e.key === 'Enter') { e.preventDefault(); const newMessage = createChatMessage(userName, input); const updatedMessages = [...messages, newMessage]; setMessages(updatedMessages); setLoading(t...
// Empty dependency array means this useEffect runs once, similar to componentDidMount
https://github.com/daveshap/ACE_Framework/blob/c6693ee2ff547d63675f938a3714165050fd0126/CORE_DEMOS/stacey/frontend/pages/chat.tsx#L62-L87
c6693ee2ff547d63675f938a3714165050fd0126
pattycake
github_2023
aidenybai
typescript
hirCodegenPatternThen
function hirCodegenPatternThen( hc: HirCodegen, expr: Expr, then: Expr, ): b.BlockStatement { // Try to inline function expressions if (then.type === 'ArrowFunctionExpression') { if (then.params.some((p) => p.type !== 'Identifier')) { throw new Error(`only identifier param types supported now`); ...
// TODO: here is where we would also do the captures from P.select()
https://github.com/aidenybai/pattycake/blob/fac748174aadeab4e3404e5e70392e9c4cef085c/src/codegen.ts#L236-L280
fac748174aadeab4e3404e5e70392e9c4cef085c
pattycake
github_2023
aidenybai
typescript
hirCodegenOutput
function hirCodegenOutput(hc: HirCodegen, value: Expr): b.Statement[] { switch (hc.kind) { case 'iife': { return [b.returnStatement(value)]; } case 'block': { return [ b.expressionStatement(b.assignmentExpression('=', hc.outVar, value)), b.breakStatement(hc.outLabel), ]; ...
/** * When `hc.kind` is "iife", it will emit a return statement * When `hc.kind` is "block", it will emit an assignment statement and a break statement * */
https://github.com/aidenybai/pattycake/blob/fac748174aadeab4e3404e5e70392e9c4cef085c/src/codegen.ts#L286-L298
fac748174aadeab4e3404e5e70392e9c4cef085c
pattycake
github_2023
aidenybai
typescript
hirCodegenConstructSelectionExpr
function hirCodegenConstructSelectionExpr( selections: BranchCtxSelections, ): b.Expression { if (selections.type === 'anonymous') return selections.expr; const properties = selections.selections.map(([pattern, expr]) => b.objectProperty(pattern.name, expr, true), ); return b.objectExpression(properties...
/** * Returns an expression that represents the selection of the branch: * - anonymous selection => the expression referencing the match expr * - named selection => an object literal with keys being the names, and values being referencing the match expr * * Anonymous selection: * ```typescript * match(foo).with(...
https://github.com/aidenybai/pattycake/blob/fac748174aadeab4e3404e5e70392e9c4cef085c/src/codegen.ts#L318-L328
fac748174aadeab4e3404e5e70392e9c4cef085c
pattycake
github_2023
aidenybai
typescript
concatConditionals
function concatConditionals(conds_: Array<b.Expression>): b.Expression { // `true` is redundant so we can get rid of it const conds = conds_.filter( (cond) => !(b.isBooleanLiteral(cond) && cond.value === true), ); if (conds.length === 0) return b.booleanLiteral(true); if (conds.length === 1) return conds[...
/** * Turn an array of conditionals (expressions that return a boolean) into a single expression chained by multiple '&&' **/
https://github.com/aidenybai/pattycake/blob/fac748174aadeab4e3404e5e70392e9c4cef085c/src/codegen.ts#L590-L609
fac748174aadeab4e3404e5e70392e9c4cef085c
pattycake
github_2023
aidenybai
typescript
isInexpensiveExpr
function isInexpensiveExpr(expr: b.Expression): boolean { if (b.isIdentifier(expr)) return true; return false; }
// TODO: expressions like arr[0], 'literal', 123, foo.bar
https://github.com/aidenybai/pattycake/blob/fac748174aadeab4e3404e5e70392e9c4cef085c/src/codegen.ts#L612-L615
fac748174aadeab4e3404e5e70392e9c4cef085c
pattycake
github_2023
aidenybai
typescript
hirPatternMatchTopDownCallExprs
function hirPatternMatchTopDownCallExprs( ht: HirTransform, expr: b.CallExpression, buf: Array<b.CallExpression>, i: number, ) { if (!b.isExpression(expr.callee)) return; if (b.isIdentifier(expr.callee) && expr.callee.name == ht.matchIdentifier) { buf[0] = expr; return; } if (b.isMemberExpressi...
/** * The AST of a ts-pattern match expression is a nested * tree of CallExpressions, which is cumbersome and also upside-down for our purposes. This * functions converts this upside down tree into a flat array in the correct * order (the first CallExpression represents the initial `match()` call, the * next ...
https://github.com/aidenybai/pattycake/blob/fac748174aadeab4e3404e5e70392e9c4cef085c/src/hir.ts#L186-L211
fac748174aadeab4e3404e5e70392e9c4cef085c
pattycake
github_2023
aidenybai
typescript
transformToPatternMatchBranch
function transformToPatternMatchBranch( ht: HirTransform, args: b.CallExpression['arguments'], ): PatternMatchBranch { if (args.length < 2) { throw new Error(`Invalid amount of args: ${args.length}`); } // 2nd arg can possibly a guard function, see: https://github.com/gvergnaud/ts-pattern/tree/main#pwhen-...
// function isPatternMatchExpr(val: b.Node | null | undefined): val is Expr {
https://github.com/aidenybai/pattycake/blob/fac748174aadeab4e3404e5e70392e9c4cef085c/src/hir.ts#L244-L297
fac748174aadeab4e3404e5e70392e9c4cef085c
pattycake
github_2023
aidenybai
typescript
transformToSimpleTsPattern
function transformToSimpleTsPattern( ht: HirTransform, expr: b.Identifier, ): Pattern { switch (expr.name) { case 'string': return { type: 'string' }; case 'number': return { type: 'number' }; case 'boolean': return { type: 'boolean' }; case 'nullish': return { type: 'nulli...
/** * These are simple patterns from ts-pattern: * P.number, P.string, etc. **/
https://github.com/aidenybai/pattycake/blob/fac748174aadeab4e3404e5e70392e9c4cef085c/src/hir.ts#L419-L444
fac748174aadeab4e3404e5e70392e9c4cef085c
pattycake
github_2023
aidenybai
typescript
terminatesMatchExpression
function terminatesMatchExpression( ht: HirTransform, callExpr: NodePath<b.CallExpression>, ): boolean { const callExprs = callExpressionsFlat(ht, callExpr.node); if (callExprs === undefined) return false; const last = callExprs[callExprs.length - 1]!; if (!b.isMemberExpression(last.callee)) return false; ...
/** * Determines if this nested tree of call expressions is a complete ts-pattern match expression * * This is done simply by looking at the last call expression, and checking if the callee is a function that * terminates the match expression (.otherwise(), .run(), .exhaustive()) * * Without this, the compiler wi...
https://github.com/aidenybai/pattycake/blob/fac748174aadeab4e3404e5e70392e9c4cef085c/src/pattycake.ts#L133-L150
fac748174aadeab4e3404e5e70392e9c4cef085c
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.constructor
protected constructor(data: ChatHistoryData, mutable: boolean) { super(data, mutable); }
/** * Don't use this constructor directly. * * - To create an empty chat history, use `ChatHistory.createEmpty()`. * - To create a chat history with existing data, use `ChatHistory.from()`. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L51-L53
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.createEmpty
public static createEmpty() { return new ChatHistory({ messages: [] }, true); }
/** * Creates an empty mutable chat history. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L58-L60
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.from
public static from(initializer: ChatHistoryLike) { const stack = getCurrentStack(1); sharedValidator.validateMethodParamOrThrow( "ChatHistory", "from", "initializer", chatHistoryLikeSchema, initializer, stack, ); if (initializer instanceof ChatHistory) { // Chat...
/** * Quickly create a mutable chat history with something that can be converted to a chat history. * * The created chat history will be a mutable copy of the input. * * @example * ```ts * const history = ChatHistory.from([ * { role: "user", content: "Hello" }, * { role: "assistant", cont...
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L76-L109
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.createRaw
public static createRaw(data: ChatHistoryData, mutable: boolean) { return new ChatHistory(data, mutable); }
/** * Creates a chat history with raw data. This method is intended for internal use only. * * If mutable is set to false, you MUST ensure that the data is not mutated. * * @internal */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L118-L120
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.getRaw
public getRaw() { return this.data; }
/** * Gets the raw data of this message. This method is intended for internal use only. * * If mutable is set to false, you MUST ensure that the data is not mutated. * * @internal */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L129-L131
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.getLength
public getLength() { return this.data.messages.length; }
/** * Get the number of messages in the history. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L182-L184
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.length
public get length() { return this.getLength(); }
/** * Get the number of messages in the history. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L189-L191
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.pop
public pop(): ChatMessage { this.guardMutable(); if (this.data.messages.length === 0) { throw new Error("Tried to pop from an empty history."); } const popped = this.data.messages.pop()!; return ChatMessage.createRaw(popped, true); }
/** * Remove the last message from the history. If the history is empty, this method will throw. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L196-L203
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.getAllFiles
public getAllFiles(client: LMStudioClient): Array<FileHandle> { return this.data.messages .flatMap( message => message.content.filter(part => part.type === "file") as Array<ChatMessagePartFileData>, ) .map( part => new FileHandle(client.files, part.identifier, p...
/** * Gets all files contained in this history. * * @param client - LMStudio client */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L210-L220
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.files
public *files(client: LMStudioClient): Generator<FileHandle> { for (const message of this.data.messages) { for (const part of message.content) { if (part.type === "file") { yield new FileHandle( client.files, part.identifier, part.fileType, par...
/** * Allows iterating over the files in the history. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L225-L239
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.hasFiles
public hasFiles() { return this.data.messages.some(message => message.content.some(part => part.type === "file")); }
/** * Returns true if this history contains any files. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L244-L246
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.at
public at(index: number) { let actualIndex = index; if (index < 0) { actualIndex = this.data.messages.length + index; } if (actualIndex < 0 || actualIndex >= this.data.messages.length) { throw new Error(text` Tried to access the message at index ${index}, but the history only has ...
/** * Gets the message at the given index. If the index is negative, it will be counted from the end. * * If the index is out of bounds, this method will throw as oppose to returning undefined. This is * to help catch bugs early. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L254-L266
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.consumeFiles
public consumeFiles(client: LMStudioClient, predicate: (file: FileHandle) => boolean) { this.guardMutable(); const consumedFiles: Array<FileHandle> = []; for (const message of this.data.messages) { consumedFiles.push(...ChatMessage.createRaw(message, true).consumeFiles(client, predicate)); } r...
/** * Given a predicate, the predicate is called for each file in the history. * * - If the predicate returns true, the file is removed from the history and is collected into the * returned array. * - If the predicate returns false, the file is kept in the history. * * This method is useful if yo...
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L293-L300
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatHistory.consumeFilesAsync
public async consumeFilesAsync( client: LMStudioClient, predicate: (file: FileHandle) => Promise<boolean>, ) { this.guardMutable(); const consumedFiles: Array<FileHandle> = []; for (const message of this.data.messages) { consumedFiles.push( ...(await ChatMessage.createRaw(message, tr...
/** * Given an async predicate, the predicate is called for each file in the history. * * - If the predicate returns true, the file is removed from the history and is collected into the * returned array. * - If the predicate returns false, the file is kept in the history. * * This method is useful...
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L318-L330
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.create
public static create(role: ChatMessageRoleData, content: string) { return new ChatMessage( chatMessageDataSchema.parse({ role, content: [{ type: "text", text: content }], }), true, ); }
/** * Create a mutable text only message. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L413-L421
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.from
public static from(initializer: ChatMessageLike) { const stack = getCurrentStack(1); sharedValidator.validateMethodParamOrThrow( "ChatMessage", "from", "initializer", chatMessageLikeSchema, initializer, stack, ); if (initializer instanceof ChatMessage) { // Chat...
/** * Quickly create a mutable message with something that can be converted to a message. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L426-L456
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.createRaw
public static createRaw(data: ChatMessageData, mutable: boolean) { return new ChatMessage(data, mutable); }
/** * Creates a chat history with raw data. This method is intended for internal use only. * * If mutable is set to false, you MUST ensure that the data is not mutated. * * @internal */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L465-L467
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.getText
public getText() { return this.data.content .filter(part => part.type === "text") .map(part => (part as ChatMessagePartTextData).text) .join(" "); }
/** * Gets all text contained in this message. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L496-L501
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.getFiles
public getFiles(client: LMStudioClient) { return this.getFileParts().map( part => new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name), ); }
/** * Gets all files contained in this message. * * @param client - LMStudio client */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L508-L513
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.files
public *files(client: LMStudioClient): Generator<FileHandle> { for (const part of this.getFileParts()) { yield new FileHandle(client.files, part.identifier, part.fileType, part.sizeBytes, part.name); } }
/** * Allows iterating over the files in the message. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L518-L522
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.consumeFiles
public consumeFiles(client: LMStudioClient, predicate: (file: FileHandle) => boolean) { this.guardMutable(); const consumedFiles: Array<FileHandle> = []; const partIndexesToRemove = new Set<number>(); for (const [index, part] of this.data.content.entries()) { if (part.type !== "file") { co...
/** * Given a predicate, the predicate is called for each file in the message. * * - If the predicate returns true, the file is removed from the message and is collected into the * returned array. * - If the predicate returns false, the file is kept in the message. * * This method is useful if yo...
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L540-L564
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.consumeFilesAsync
public async consumeFilesAsync( client: LMStudioClient, predicate: (file: FileHandle) => Promise<boolean>, ) { this.guardMutable(); const consumedFiles: Array<FileHandle> = []; const partIndexesToRemove = new Set<number>(); for (const [index, part] of this.data.content.entries()) { if (p...
/** * Given an async predicate, the predicate is called for each file in the message. * * - If the predicate returns true, the file is removed from the message and is collected into the * returned array. * - If the predicate returns false, the file is kept in the message. * * This method is useful...
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L582-L609
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.hasFiles
public hasFiles(): boolean { return this.data.content.some(part => part.type === "file"); }
/** * Returns true if this message contains any files. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L614-L616
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.appendText
public appendText(text: string) { this.guardMutable(); switch (this.data.role) { case "assistant": case "user": case "system": this.data.content.push({ type: "text", text, }); break; case "tool": throw new Error(`Cannot append text to a...
/** * Append text to the message. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L621-L639
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.appendFile
public appendFile(file: FileHandle) { this.guardMutable(); switch (this.data.role) { case "assistant": case "user": case "system": this.data.content.push({ type: "file", name: file.name, identifier: file.identifier, sizeBytes: file.sizeBytes, ...
/** * Append a file to the message. Takes in a FileHandle. You can obtain a FileHandle from * `client.files.prepareImage`. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L645-L666
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
ChatMessage.replaceText
public replaceText(text: string) { this.guardMutable(); switch (this.data.role) { case "assistant": case "user": case "system": this.data.content = [ { type: "text", text }, ...this.data.content.filter(part => part.type !== "text"), ]; break; c...
/** * Replaces all text in the messages. * * If the message contains other components (such as files), they will kept. The replaced text * will be inserted to the beginning of the message. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/ChatHistory.ts#L674-L692
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
LMStudioClient.validateBaseUrlOrThrow
private validateBaseUrlOrThrow(baseUrl: string) { let url: URL; try { url = new URL(baseUrl); } catch (e) { this.logger.throw(text` Failed to construct LMStudioClient. The baseUrl passed in is invalid. Received: ${baseUrl} `); } if (!["ws:", "wss:"].includes(url.protocol)) ...
/** @internal */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/LMStudioClient.ts#L160-L199
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
LMStudioClient.guessBaseUrl
private async guessBaseUrl(stack?: string): Promise<string> { if (getHostedEnv() !== null) { return Promise.resolve("Using hosted env"); } // On browser, those apiServerPorts are not accessible anyway. We will just try to see if we can // reach the server on 127.0.0.1:1234 (the default port). ...
/** * Guess the base URL of the LM Studio server by visiting localhost on various default ports. */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/LMStudioClient.ts#L216-L271
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
DiagnosticsNamespace.constructor
public constructor( private readonly diagnosticsPort: DiagnosticsPort, private readonly validator: Validator, parentLogger: LoggerInterface, ) { this.logger = new SimpleLogger("Diagnostics", parentLogger); }
/** @internal */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/diagnostics/DiagnosticsNamespace.ts#L16-L22
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
DiagnosticsNamespace.unstable_streamLogs
public unstable_streamLogs(listener: (logEvent: DiagnosticsLogEvent) => void): () => void { const stack = getCurrentStack(1); this.validator.validateMethodParamOrThrow( "client.diagnostics", "unstable_streamLogs", "listener", z.function(), listener, stack, ); const ch...
/** * Register a callback to receive log events. Return a function to stop receiving log events. * * This method is in alpha. Do not use this method in production yet. * @alpha */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/diagnostics/DiagnosticsNamespace.ts#L30-L54
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
EmbeddingDynamicHandle.constructor
public constructor( /** @internal */ port: EmbeddingPort, /** @internal */ specifier: ModelSpecifier, /** @internal */ private readonly validator: Validator, /** @internal */ private readonly logger: SimpleLogger = new SimpleLogger(`EmbeddingModel`), ) { super(port, specifier); }
/** * Don't construct this on your own. Use {@link EmbeddingNamespace#get} or * {@link EmbeddingNamespace#load} * instead. * * @internal */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/embedding/EmbeddingDynamicHandle.ts#L31-L42
22f2871aa123f65384f3b4ee2b9e3aae924f4e09
lmstudio.js
github_2023
lmstudio-ai
typescript
EmbeddingModel.constructor
public constructor( embeddingPort: EmbeddingPort, instanceReference: string, descriptor: ModelDescriptor, validator: Validator, logger: SimpleLogger = new SimpleLogger(`EmbeddingModel`), ) { const specifier: ModelSpecifier = { type: "instanceReference", instanceReference, }; ...
/** @internal */
https://github.com/lmstudio-ai/lmstudio.js/blob/22f2871aa123f65384f3b4ee2b9e3aae924f4e09/packages/lms-client/src/embedding/EmbeddingModel.ts#L22-L36
22f2871aa123f65384f3b4ee2b9e3aae924f4e09