repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
freechat
github_2023
freechat-fun
typescript
PromisePromptApi.searchPromptSummaryWithHttpInfo
public searchPromptSummaryWithHttpInfo(promptQueryDTO: PromptQueryDTO, _options?: Configuration): Promise<HttpInfo<Array<PromptSummaryDTO>>> { const result = this.api.searchPromptSummaryWithHttpInfo(promptQueryDTO, _options); return result.toPromise(); }
/** * Search prompts: - Specifiable query fields, and relationship: - Scope: private, public_org or public. Private can only search this account. - Username: exact match, only valid when searching public, public_org. If not specified, search all users. - Tags: exact match (support and, or logic). - Model type: exact match (support and, or logic). - Name: left match. - Type, exact match: string (default) | chat. - Language, exact match. - General: name, description, template, example, fuzzy match, one hit is enough; public scope + all user\'s general search does not guarantee timeliness. - A certain sorting rule can be specified, such as view count, reference count, rating, time, descending or ascending. - The search result is the prompt summary content. - Support pagination. * Search Prompt Summary * @param promptQueryDTO Query conditions */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4014-L4017
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptApi.searchPromptSummary
public searchPromptSummary(promptQueryDTO: PromptQueryDTO, _options?: Configuration): Promise<Array<PromptSummaryDTO>> { const result = this.api.searchPromptSummary(promptQueryDTO, _options); return result.toPromise(); }
/** * Search prompts: - Specifiable query fields, and relationship: - Scope: private, public_org or public. Private can only search this account. - Username: exact match, only valid when searching public, public_org. If not specified, search all users. - Tags: exact match (support and, or logic). - Model type: exact match (support and, or logic). - Name: left match. - Type, exact match: string (default) | chat. - Language, exact match. - General: name, description, template, example, fuzzy match, one hit is enough; public scope + all user\'s general search does not guarantee timeliness. - A certain sorting rule can be specified, such as view count, reference count, rating, time, descending or ascending. - The search result is the prompt summary content. - Support pagination. * Search Prompt Summary * @param promptQueryDTO Query conditions */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4024-L4027
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptApi.searchPublicPromptSummaryWithHttpInfo
public searchPublicPromptSummaryWithHttpInfo(promptQueryDTO: PromptQueryDTO, _options?: Configuration): Promise<HttpInfo<Array<PromptSummaryDTO>>> { const result = this.api.searchPublicPromptSummaryWithHttpInfo(promptQueryDTO, _options); return result.toPromise(); }
/** * Search prompts: - Specifiable query fields, and relationship: - Scope: public(fixed). - Username: exact match. If not specified, search all users. - Tags: exact match (support and, or logic). - Model type: exact match (support and, or logic). - Name: left match. - Type, exact match: string (default) | chat. - Language, exact match. - General: name, description, template, example, fuzzy match, one hit is enough; public scope + all user\'s general search does not guarantee timeliness. - A certain sorting rule can be specified, such as view count, reference count, rating, time, descending or ascending. - The search result is the prompt summary content. - Support pagination. * Search Public Prompt Summary * @param promptQueryDTO Query conditions */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4034-L4037
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptApi.searchPublicPromptSummary
public searchPublicPromptSummary(promptQueryDTO: PromptQueryDTO, _options?: Configuration): Promise<Array<PromptSummaryDTO>> { const result = this.api.searchPublicPromptSummary(promptQueryDTO, _options); return result.toPromise(); }
/** * Search prompts: - Specifiable query fields, and relationship: - Scope: public(fixed). - Username: exact match. If not specified, search all users. - Tags: exact match (support and, or logic). - Model type: exact match (support and, or logic). - Name: left match. - Type, exact match: string (default) | chat. - Language, exact match. - General: name, description, template, example, fuzzy match, one hit is enough; public scope + all user\'s general search does not guarantee timeliness. - A certain sorting rule can be specified, such as view count, reference count, rating, time, descending or ascending. - The search result is the prompt summary content. - Support pagination. * Search Public Prompt Summary * @param promptQueryDTO Query conditions */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4044-L4047
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptApi.sendPromptWithHttpInfo
public sendPromptWithHttpInfo(promptAiParamDTO: PromptAiParamDTO, _options?: Configuration): Promise<HttpInfo<LlmResultDTO>> { const result = this.api.sendPromptWithHttpInfo(promptAiParamDTO, _options); return result.toPromise(); }
/** * Send the prompt to the AI service. Note that if the embedding model is called, the return is an embedding array, placed in the details field of the result; the original text is in the text field of the result. * Send Prompt * @param promptAiParamDTO Call parameters */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4054-L4057
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptApi.sendPrompt
public sendPrompt(promptAiParamDTO: PromptAiParamDTO, _options?: Configuration): Promise<LlmResultDTO> { const result = this.api.sendPrompt(promptAiParamDTO, _options); return result.toPromise(); }
/** * Send the prompt to the AI service. Note that if the embedding model is called, the return is an embedding array, placed in the details field of the result; the original text is in the text field of the result. * Send Prompt * @param promptAiParamDTO Call parameters */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4064-L4067
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptApi.streamSendPromptWithHttpInfo
public streamSendPromptWithHttpInfo(promptAiParamDTO: PromptAiParamDTO, _options?: Configuration): Promise<HttpInfo<SseEmitter>> { const result = this.api.streamSendPromptWithHttpInfo(promptAiParamDTO, _options); return result.toPromise(); }
/** * Refer to /api/v2/prompt/send, stream back chunks of the response. * Send Prompt by Streaming Back * @param promptAiParamDTO Call parameters */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4074-L4077
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptApi.streamSendPrompt
public streamSendPrompt(promptAiParamDTO: PromptAiParamDTO, _options?: Configuration): Promise<SseEmitter> { const result = this.api.streamSendPrompt(promptAiParamDTO, _options); return result.toPromise(); }
/** * Refer to /api/v2/prompt/send, stream back chunks of the response. * Send Prompt by Streaming Back * @param promptAiParamDTO Call parameters */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4084-L4087
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptApi.updatePromptWithHttpInfo
public updatePromptWithHttpInfo(promptId: number, promptUpdateDTO: PromptUpdateDTO, _options?: Configuration): Promise<HttpInfo<boolean>> { const result = this.api.updatePromptWithHttpInfo(promptId, promptUpdateDTO, _options); return result.toPromise(); }
/** * Update prompt, refer to /api/v2/prompt/create, required field: promptId. Returns success or failure. * Update Prompt * @param promptId The promptId to be updated * @param promptUpdateDTO The prompt information to be updated */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4095-L4098
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptApi.updatePrompt
public updatePrompt(promptId: number, promptUpdateDTO: PromptUpdateDTO, _options?: Configuration): Promise<boolean> { const result = this.api.updatePrompt(promptId, promptUpdateDTO, _options); return result.toPromise(); }
/** * Update prompt, refer to /api/v2/prompt/create, required field: promptId. Returns success or failure. * Update Prompt * @param promptId The promptId to be updated * @param promptUpdateDTO The prompt information to be updated */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4106-L4109
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptTaskApi.createPromptTaskWithHttpInfo
public createPromptTaskWithHttpInfo(promptTaskDTO: PromptTaskDTO, _options?: Configuration): Promise<HttpInfo<string>> { const result = this.api.createPromptTaskWithHttpInfo(promptTaskDTO, _options); return result.toPromise(); }
/** * Create a prompt task. * Create Prompt Task * @param promptTaskDTO The prompt task to be added */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4135-L4138
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptTaskApi.createPromptTask
public createPromptTask(promptTaskDTO: PromptTaskDTO, _options?: Configuration): Promise<string> { const result = this.api.createPromptTask(promptTaskDTO, _options); return result.toPromise(); }
/** * Create a prompt task. * Create Prompt Task * @param promptTaskDTO The prompt task to be added */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4145-L4148
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptTaskApi.deletePromptTaskWithHttpInfo
public deletePromptTaskWithHttpInfo(promptTaskId: string, _options?: Configuration): Promise<HttpInfo<boolean>> { const result = this.api.deletePromptTaskWithHttpInfo(promptTaskId, _options); return result.toPromise(); }
/** * Delete a prompt task. * Delete Prompt Task * @param promptTaskId The promptTaskId to be deleted */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4155-L4158
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptTaskApi.deletePromptTask
public deletePromptTask(promptTaskId: string, _options?: Configuration): Promise<boolean> { const result = this.api.deletePromptTask(promptTaskId, _options); return result.toPromise(); }
/** * Delete a prompt task. * Delete Prompt Task * @param promptTaskId The promptTaskId to be deleted */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4165-L4168
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptTaskApi.getPromptTaskWithHttpInfo
public getPromptTaskWithHttpInfo(promptTaskId: string, _options?: Configuration): Promise<HttpInfo<PromptTaskDetailsDTO>> { const result = this.api.getPromptTaskWithHttpInfo(promptTaskId, _options); return result.toPromise(); }
/** * Get the prompt task details. * Get Prompt Task * @param promptTaskId The promptTaskId to be queried */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4175-L4178
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptTaskApi.getPromptTask
public getPromptTask(promptTaskId: string, _options?: Configuration): Promise<PromptTaskDetailsDTO> { const result = this.api.getPromptTask(promptTaskId, _options); return result.toPromise(); }
/** * Get the prompt task details. * Get Prompt Task * @param promptTaskId The promptTaskId to be queried */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4185-L4188
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptTaskApi.updatePromptTaskWithHttpInfo
public updatePromptTaskWithHttpInfo(promptTaskId: string, promptTaskDTO: PromptTaskDTO, _options?: Configuration): Promise<HttpInfo<boolean>> { const result = this.api.updatePromptTaskWithHttpInfo(promptTaskId, promptTaskDTO, _options); return result.toPromise(); }
/** * Update a prompt task. * Update Prompt Task * @param promptTaskId The promptTaskId to be updated * @param promptTaskDTO The prompt task info to be updated */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4196-L4199
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromisePromptTaskApi.updatePromptTask
public updatePromptTask(promptTaskId: string, promptTaskDTO: PromptTaskDTO, _options?: Configuration): Promise<boolean> { const result = this.api.updatePromptTask(promptTaskId, promptTaskDTO, _options); return result.toPromise(); }
/** * Update a prompt task. * Update Prompt Task * @param promptTaskId The promptTaskId to be updated * @param promptTaskDTO The prompt task info to be updated */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4207-L4210
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.cancelRagTaskWithHttpInfo
public cancelRagTaskWithHttpInfo(taskId: number, _options?: Configuration): Promise<HttpInfo<boolean>> { const result = this.api.cancelRagTaskWithHttpInfo(taskId, _options); return result.toPromise(); }
/** * Cancel a RAG task. * Cancel RAG Task * @param taskId The taskId to be canceled */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4236-L4239
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.cancelRagTask
public cancelRagTask(taskId: number, _options?: Configuration): Promise<boolean> { const result = this.api.cancelRagTask(taskId, _options); return result.toPromise(); }
/** * Cancel a RAG task. * Cancel RAG Task * @param taskId The taskId to be canceled */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4246-L4249
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.createRagTaskWithHttpInfo
public createRagTaskWithHttpInfo(characterUid: string, ragTaskDTO: RagTaskDTO, _options?: Configuration): Promise<HttpInfo<number>> { const result = this.api.createRagTaskWithHttpInfo(characterUid, ragTaskDTO, _options); return result.toPromise(); }
/** * Create a RAG task. * Create RAG Task * @param characterUid The characterUid to be added a RAG task * @param ragTaskDTO The RAG task to be added */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4257-L4260
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.createRagTask
public createRagTask(characterUid: string, ragTaskDTO: RagTaskDTO, _options?: Configuration): Promise<number> { const result = this.api.createRagTask(characterUid, ragTaskDTO, _options); return result.toPromise(); }
/** * Create a RAG task. * Create RAG Task * @param characterUid The characterUid to be added a RAG task * @param ragTaskDTO The RAG task to be added */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4268-L4271
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.deleteRagTaskWithHttpInfo
public deleteRagTaskWithHttpInfo(taskId: number, _options?: Configuration): Promise<HttpInfo<boolean>> { const result = this.api.deleteRagTaskWithHttpInfo(taskId, _options); return result.toPromise(); }
/** * Delete a RAG task. * Delete RAG Task * @param taskId The taskId to be deleted */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4278-L4281
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.deleteRagTask
public deleteRagTask(taskId: number, _options?: Configuration): Promise<boolean> { const result = this.api.deleteRagTask(taskId, _options); return result.toPromise(); }
/** * Delete a RAG task. * Delete RAG Task * @param taskId The taskId to be deleted */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4288-L4291
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.getRagTaskWithHttpInfo
public getRagTaskWithHttpInfo(taskId: number, _options?: Configuration): Promise<HttpInfo<RagTaskDetailsDTO>> { const result = this.api.getRagTaskWithHttpInfo(taskId, _options); return result.toPromise(); }
/** * Get the RAG task details. * Get RAG Task * @param taskId The taskId to be queried */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4298-L4301
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.getRagTask
public getRagTask(taskId: number, _options?: Configuration): Promise<RagTaskDetailsDTO> { const result = this.api.getRagTask(taskId, _options); return result.toPromise(); }
/** * Get the RAG task details. * Get RAG Task * @param taskId The taskId to be queried */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4308-L4311
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.getRagTaskStatusWithHttpInfo
public getRagTaskStatusWithHttpInfo(taskId: number, _options?: Configuration): Promise<HttpInfo<string>> { const result = this.api.getRagTaskStatusWithHttpInfo(taskId, _options); return result.toPromise(); }
/** * Get the RAG task execution status: pending | running | succeeded | failed | canceled. * Get RAG Task Status * @param taskId The taskId to be queried status */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4318-L4321
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.getRagTaskStatus
public getRagTaskStatus(taskId: number, _options?: Configuration): Promise<string> { const result = this.api.getRagTaskStatus(taskId, _options); return result.toPromise(); }
/** * Get the RAG task execution status: pending | running | succeeded | failed | canceled. * Get RAG Task Status * @param taskId The taskId to be queried status */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4328-L4331
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.listRagTasksWithHttpInfo
public listRagTasksWithHttpInfo(characterUid: string, _options?: Configuration): Promise<HttpInfo<Array<RagTaskDetailsDTO>>> { const result = this.api.listRagTasksWithHttpInfo(characterUid, _options); return result.toPromise(); }
/** * List the RAG tasks by characterId. * List RAG Tasks * @param characterUid The characterUid to be queried */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4338-L4341
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.listRagTasks
public listRagTasks(characterUid: string, _options?: Configuration): Promise<Array<RagTaskDetailsDTO>> { const result = this.api.listRagTasks(characterUid, _options); return result.toPromise(); }
/** * List the RAG tasks by characterId. * List RAG Tasks * @param characterUid The characterUid to be queried */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4348-L4351
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.startRagTaskWithHttpInfo
public startRagTaskWithHttpInfo(taskId: number, _options?: Configuration): Promise<HttpInfo<boolean>> { const result = this.api.startRagTaskWithHttpInfo(taskId, _options); return result.toPromise(); }
/** * Start a RAG task. * Start RAG Task * @param taskId The taskId to be started */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4358-L4361
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.startRagTask
public startRagTask(taskId: number, _options?: Configuration): Promise<boolean> { const result = this.api.startRagTask(taskId, _options); return result.toPromise(); }
/** * Start a RAG task. * Start RAG Task * @param taskId The taskId to be started */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4368-L4371
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.updateRagTaskWithHttpInfo
public updateRagTaskWithHttpInfo(taskId: number, ragTaskDTO: RagTaskDTO, _options?: Configuration): Promise<HttpInfo<boolean>> { const result = this.api.updateRagTaskWithHttpInfo(taskId, ragTaskDTO, _options); return result.toPromise(); }
/** * Update a RAG task. * Update RAG Task * @param taskId The taskId to be updated * @param ragTaskDTO The prompt task info to be updated */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4379-L4382
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseRagApi.updateRagTask
public updateRagTask(taskId: number, ragTaskDTO: RagTaskDTO, _options?: Configuration): Promise<boolean> { const result = this.api.updateRagTask(taskId, ragTaskDTO, _options); return result.toPromise(); }
/** * Update a RAG task. * Update RAG Task * @param taskId The taskId to be updated * @param ragTaskDTO The prompt task info to be updated */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4390-L4393
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseTTSServiceApi.listTtsBuiltinSpeakersWithHttpInfo
public listTtsBuiltinSpeakersWithHttpInfo(_options?: Configuration): Promise<HttpInfo<Array<string>>> { const result = this.api.listTtsBuiltinSpeakersWithHttpInfo(_options); return result.toPromise(); }
/** * Return builtin TTS speakers. * List Builtin Speakers */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4418-L4421
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseTTSServiceApi.listTtsBuiltinSpeakers
public listTtsBuiltinSpeakers(_options?: Configuration): Promise<Array<string>> { const result = this.api.listTtsBuiltinSpeakers(_options); return result.toPromise(); }
/** * Return builtin TTS speakers. * List Builtin Speakers */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4427-L4430
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseTTSServiceApi.playSampleWithHttpInfo
public playSampleWithHttpInfo(speakerType: string, speaker: string, _options?: Configuration): Promise<HttpInfo<any>> { const result = this.api.playSampleWithHttpInfo(speakerType, speaker, _options); return result.toPromise(); }
/** * Play TTS sample audio of the builtin/custom speaker. * Play Sample Audio * @param speakerType The speaker type * @param speaker The speaker */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4438-L4441
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseTTSServiceApi.playSample
public playSample(speakerType: string, speaker: string, _options?: Configuration): Promise<any> { const result = this.api.playSample(speakerType, speaker, _options); return result.toPromise(); }
/** * Play TTS sample audio of the builtin/custom speaker. * Play Sample Audio * @param speakerType The speaker type * @param speaker The speaker */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4449-L4452
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseTTSServiceApi.speakMessageWithHttpInfo
public speakMessageWithHttpInfo(messageId: number, _options?: Configuration): Promise<HttpInfo<any>> { const result = this.api.speakMessageWithHttpInfo(messageId, _options); return result.toPromise(); }
/** * Read out the message. * Speak Message * @param messageId The message id */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4459-L4462
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseTTSServiceApi.speakMessage
public speakMessage(messageId: number, _options?: Configuration): Promise<any> { const result = this.api.speakMessage(messageId, _options); return result.toPromise(); }
/** * Read out the message. * Speak Message * @param messageId The message id */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4469-L4472
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseTagManagerForBizAdminApi.createTagWithHttpInfo
public createTagWithHttpInfo(referType: string, referId: string, tag: string, _options?: Configuration): Promise<HttpInfo<boolean>> { const result = this.api.createTagWithHttpInfo(referType, referId, tag, _options); return result.toPromise(); }
/** * Create a tag, tags created by the administrator cannot be deleted by ordinary users. * Create Tag * @param referType Tag type (prompt, agent, plugin...) * @param referId Resource identifier of the tag * @param tag Tag content */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4500-L4503
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseTagManagerForBizAdminApi.createTag
public createTag(referType: string, referId: string, tag: string, _options?: Configuration): Promise<boolean> { const result = this.api.createTag(referType, referId, tag, _options); return result.toPromise(); }
/** * Create a tag, tags created by the administrator cannot be deleted by ordinary users. * Create Tag * @param referType Tag type (prompt, agent, plugin...) * @param referId Resource identifier of the tag * @param tag Tag content */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4512-L4515
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseTagManagerForBizAdminApi.deleteTagWithHttpInfo
public deleteTagWithHttpInfo(referType: string, referId: string, tag: string, _options?: Configuration): Promise<HttpInfo<boolean>> { const result = this.api.deleteTagWithHttpInfo(referType, referId, tag, _options); return result.toPromise(); }
/** * Delete a tag, any tag created by anyone can be deleted. * Delete Tag * @param referType Tag type (prompt, agent, plugin...) * @param referId Resource identifier of the tag * @param tag Tag content */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4524-L4527
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
freechat
github_2023
freechat-fun
typescript
PromiseTagManagerForBizAdminApi.deleteTag
public deleteTag(referType: string, referId: string, tag: string, _options?: Configuration): Promise<boolean> { const result = this.api.deleteTag(referType, referId, tag, _options); return result.toPromise(); }
/** * Delete a tag, any tag created by anyone can be deleted. * Delete Tag * @param referType Tag type (prompt, agent, plugin...) * @param referId Resource identifier of the tag * @param tag Tag content */
https://github.com/freechat-fun/freechat/blob/cb80c3708b85cf52c02a91bdc0c9e9ddc14856db/freechat-sdk/typescript/types/PromiseAPI.ts#L4536-L4539
cb80c3708b85cf52c02a91bdc0c9e9ddc14856db
Aria-Docs
github_2023
nisabmohd
typescript
parseMdx
async function parseMdx<Frontmatter>(rawMdx: string) { return await compileMDX<Frontmatter>({ source: rawMdx, options: { parseFrontmatter: true, mdxOptions: { rehypePlugins: [ preProcess, rehypeCodeTitles, rehypePrism, rehypeSlug, rehypeAutolinkHeadings, postProcess, ], remarkPlugins: [remarkGfm], }, }, components, }); }
// can be used for other pages like blogs, Guides etc
https://github.com/nisabmohd/Aria-Docs/blob/29630f770db190999faa03adbf61034677ace4c1/lib/markdown.ts#L38-L57
29630f770db190999faa03adbf61034677ace4c1
Aria-Docs
github_2023
nisabmohd
typescript
preProcess
const preProcess = () => (tree: any) => { visit(tree, (node) => { if (node?.type === "element" && node?.tagName === "pre") { const [codeEl] = node.children; if (codeEl.tagName !== "code") return; node.raw = codeEl.children?.[0].value; } }); };
// for copying the code in pre
https://github.com/nisabmohd/Aria-Docs/blob/29630f770db190999faa03adbf61034677ace4c1/lib/markdown.ts#L150-L158
29630f770db190999faa03adbf61034677ace4c1
Aria-Docs
github_2023
nisabmohd
typescript
postProcess
const postProcess = () => (tree: any) => { visit(tree, "element", (node) => { if (node?.type === "element" && node?.tagName === "pre") { node.properties["raw"] = node.raw; } }); };
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/nisabmohd/Aria-Docs/blob/29630f770db190999faa03adbf61034677ace4c1/lib/markdown.ts#L161-L167
29630f770db190999faa03adbf61034677ace4c1
veloxi
github_2023
TahaSh
typescript
Plugin.update
update(ts: number, dt: number) {}
// @ts-ignore
https://github.com/TahaSh/veloxi/blob/2eb89939dfdbc063b7a42d98b4a07cd9ba477d31/src/core/Plugin.ts#L359-L359
2eb89939dfdbc063b7a42d98b4a07cd9ba477d31
veloxi
github_2023
TahaSh
typescript
CoreView.overlapsWith
overlapsWith(view: View): boolean { const viewScaledWidth = (view as CoreView)._localWidth * view.scale.x const viewScaledHeight = (view as CoreView)._localHeight * view.scale.y const scaledWidth = this._localWidth * this.scale.x const scaledHeight = this._localHeight * this.scale.y return ( this.position.x < view.position.x + viewScaledWidth && this.position.x + scaledWidth > view.position.x && this.position.y < view.position.y + viewScaledHeight && this.position.y + scaledHeight > view.position.y ) }
// Using AABB collision detection
https://github.com/TahaSh/veloxi/blob/2eb89939dfdbc063b7a42d98b4a07cd9ba477d31/src/core/View.ts#L389-L401
2eb89939dfdbc063b7a42d98b4a07cd9ba477d31
Protofy
github_2023
Protofy-xyz
typescript
handleFilesRequest
const handleFilesRequest = async (req, res) => { const name = req.params.path || ''; const isDownload = req.query.download const filepath = path.join(getRoot(req), name); if (! await fileExists(filepath)) { res.status(404).send('No such file or directory: ' + filepath) return } if (((await fs.stat(filepath)).isDirectory())) { if (isDownload) { try { // TODO compressDirectory is not working, it should be fixed // compressDirectory({ sourcePath: filepath, outputPath: path.basename(filepath) }) const archive = archiver('zip', { zlib: { level: 9 } }); res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(filepath) + '.zip'); res.setHeader('Content-Type', 'application/zip'); archive.on('error', (err) => { throw err; }); await archive.pipe(res); await archive.directory(filepath, false); await archive.finalize(); } catch (e) { console.error('Error, could not ZIP file', e) } } try { const fileList = await fs.readdir(filepath); res.send(await Promise.all(fileList.map(async (f) => { const filePath = path.join(filepath, f); const stats = await fs.stat(filePath); return { id: uuidv4(), path: `${name}/${f}`, isHidden: f.startsWith('.'), name: f, size: stats.size, modDate: stats.mtime, isDir: stats.isDirectory() }; }))); } catch (e) { res.status(501).send(`The path '${name}' is not a directory`); } } else { // Serving the file: try { // // Using 'mime' package to determine content type based on file extension // const contentType = mime.lookup(filepath) // if (contentType) { // res.setHeader('Content-Type', contentType); // } logger.debug({ filepath, resolvedPath: path.resolve(filepath) }, `send file: ${filepath} ${path.resolve(filepath)}`) if (isDownload) { // Establece el encabezado para forzar la descarga res.setHeader('Content-Disposition', 'attachment; filename='+name); } res.status(200).sendFile(path.resolve(filepath), { dotfiles: 'allow' }, (error) => { if (error) { logger.error({ error }, "Error sending file"); res.status(error.status || 500).send("Error sending file") } }); } catch (error) { logger.error({ error }, "Error reading file") res.status(500).send(`Failed to serve the file at path '${name}'`); } } };
// Handler function to avoid repeating the same code for both routes
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/apps/core/src/api/files.ts#L47-L122
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
handleFilesWriteRequest
const handleFilesWriteRequest = async (req, res, session) => { const name = req.params.path || ''; const filepath = path.join(getRoot(req), name); if (req.body && req.body.hasOwnProperty && req.body.hasOwnProperty("content")) { await fs.writeFile(filepath, req.body.content) } generateEvent({ path: 'files/write/file', //event type: / separated event category: files/create/file, files/create/dir, devices/device/online from: 'core', // system entity where the event was generated (next, api, cmd...) user: session.user.id, // the original user that generates the action, 'system' if the event originated in the system itself payload: {'path': name} // event payload, event-specific data }, getServiceToken()) res.status(200).send({result: "uploaded"}); };
//received post requests and creates directories or write files, dependeing on query string param
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/apps/core/src/api/files.ts#L128-L142
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
ProtoSchema.getFieldDefinition
getFieldDefinition(field: string) { return this.shape[field] ? this.shape[field]._def : undefined }
//get field definition
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protobase/src/ProtoSchema.ts#L17-L19
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
ProtoSchema.apply
async apply(eventName: string, data: any, transformers: any, prevData?: any) { let newData = { ...data } const withEvents = this.is('events') const keys = Object.keys(withEvents.shape) for (var i = 0; i < keys.length; i++) { const key = keys[i] const currField: any = withEvents.shape[key] const isNode = typeof process !== 'undefined' && process.versions && process.versions.node const events = currField._def.events.filter(e => e.eventName == eventName && (!e.eventContext || (e.eventContext == 'client' && !isNode) || (e.eventContext == 'server' && isNode))) for (var x = 0; x < events.length; x++) { const e = events[x] if (transformers[e.eventHandler]) { newData = await transformers[e.eventHandler](key, e, newData, prevData) } } } return newData }
//apply generative schema to data
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protobase/src/ProtoSchema.ts#L36-L54
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
ProtoSchema.load
static load(schema: Zod.ZodObject<any>) { return new ProtoSchema(schema.shape) }
//generate a protoSchema from a extended zodSchema
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protobase/src/ProtoSchema.ts#L171-L173
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
CapacitiveSoilMoistureSensor.attach
attach(pin) { return {componentName: 'sensor',payload: ` - platform: ${this.platform} pin: ${pin} id: ${this.name} name: ${this.name} update_interval: ${this.updateInterval} attenuation: ${this.attenuation} ` } }
//
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/device/CapacitiveSoilMoistureSensor.ts#L15-L25
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
ISOutput.setMqttTopicPrefix
setMqttTopicPrefix(setMqttTopicPrefix){ this.mqttTopicPrefix= setMqttTopicPrefix; }
/*mqtt: broker: 192.168.0.45 topic_prefix: protofy-seed/mydevice on_json_message: topic: protofy-seed/mydevice/output/pwm1/command then: - lambda: |- if (x.containsKey("pwmLevel")) { id(pwm1SetLevel).execute(x['pwmLevel']); } script: - id: pwm1SetLevel parameters: level: int then: - lambda: !lambda id(pwm1).set_level(level/100); */
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/device/ISOutput.ts#L31-L33
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
NFCReader.attach
attach(pin, deviceComponents) { const componentObjects = [ { name: this.type, config: { id: this.name, i2c_id: this.i2cBusId, update_interval: this.updateInterval, on_tag: { then: [ {'mqtt.publish': { topic: `devices/${deviceComponents.esphome.name}/sensor/${this.name}/state`, payload: '@!lambda return x;@', }, }, ] }, on_tag_removed: { then: [ {'mqtt.publish': { topic: `devices/${deviceComponents.esphome.name}/sensor/${this.name}/state`, payload: '@!lambda return "none";@', }, }, ] }, }, subsystem: this.getSubsystem() }, // ( // name: 'binary_sensor' // ) ] componentObjects.forEach((element, j) => { if (!deviceComponents[element.name]) { deviceComponents[element.name] = element.config } else { if (!Array.isArray(deviceComponents[element.name])) { deviceComponents[element.name] = [deviceComponents[element.name]] } deviceComponents[element.name] = [...deviceComponents[element.name], element.config] } }) return deviceComponents }
// }
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/device/NFCReader.ts#L47-L95
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
PulseCounter.attach
attach(pin) { return {componentName: 'sensor',payload: ` - platform: ${this.platform} pin: ${pin} id: ${this.name} name: ${this.name} ` } }
//
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/device/PulseCounter.ts#L11-L19
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
Transport.constructor
constructor(public device: SerialPort) {}
//@ts-ignore
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/device/esptool-js/webserial.ts#L7-L7
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
Transport.slip_reader
slip_reader(data: Uint8Array) { let i = 0; let data_start = 0, data_end = 0; let state = "init"; while (i < data.length) { if (state === "init" && data[i] == 0xc0) { data_start = i + 1; state = "valid_data"; i++; continue; } if (state === "valid_data" && data[i] == 0xc0) { data_end = i - 1; state = "packet_complete"; break; } i++; } if (state !== "packet_complete") { this.left_over = data; return new Uint8Array(0); } this.left_over = data.slice(data_end + 2); const temp_pkt = new Uint8Array(data_end - data_start + 1); let j = 0; for (i = data_start; i <= data_end; i++, j++) { if (data[i] === 0xdb && data[i + 1] === 0xdc) { temp_pkt[j] = 0xc0; i++; continue; } if (data[i] === 0xdb && data[i + 1] === 0xdd) { temp_pkt[j] = 0xdb; i++; continue; } temp_pkt[j] = data[i]; } const packet = temp_pkt.slice(0, j); /* Remove unused bytes due to escape seq */ return packet; }
/* this function expects complete packet (hence reader reads for atleast 8 bytes. This function is * stateless and returns the first wellformed packet only after replacing escape sequence */
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/device/esptool-js/webserial.ts#L70-L112
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
GPIOSwitch
const GPIOSwitch = ({ node = {}, nodeData = {}, children, color }: any) => { const nodeParams: Field[] = [ { label: 'Name', static: true, field: 'param-1', type: 'input' }, { label: 'Restore Mode', static: true, field: 'param-2', type: 'select', data: ["ALWAYS_ON", "ALWAYS_OFF"] } ] as Field[] return ( <Node node={node} isPreview={!node.id} title='GPIO Switch' color={color} id={node.id} skipCustom={true} disableInput disableOutput> <NodeParams id={node.id} params={nodeParams} /> {/* <div style={{marginTop: "10px", marginBottom: "10px"}}> {subsystem(subsystemData, nodeData, type)} </div> */} </Node> ) }
// import subsystem from "./utils/subsystem";
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/nodes/GPIOSwitch.tsx#L5-L20
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
NFCReader
const NFCReader = ({node = {}, nodeData = {}, children, color}: any) => { const [name, setName] = React.useState(nodeData['param-1']) const nameErrorMsg = 'Reserved name' const intervalErrorMsg = 'Add units h/m/s/ms' const nodeParams: Field[] = [ { label: 'Name', static: true, field: 'param-1', type: 'input', onBlur: () => { setName(nodeData['param-1']) }, error: nodeData['param-1']?.value?.replace(/['"]+/g, '') == 'nfcreader' ? nameErrorMsg : null }, { label: 'i2cBus', static: true, field: 'param-2', type: 'input', }, { label: 'updateInterval', static: true, field: 'param-3', type: 'input', },] return ( <Node node={node} isPreview={!node.id} title='NFCReader' color={color} id={node.id} skipCustom={true} > <NodeParams id={node.id} params={nodeParams} /> </Node> ) }
// import { Position } from "reactflow";
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/nodes/NFCReader.tsx#L7-L27
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
Relay
const Relay = ({ node = {}, nodeData = {}, children, color }: any) => { const nodeParams: Field[] = [ { label: 'Name', static: true, field: 'param-1', type: 'input' }, { label: 'Restore Mode', static: true, field: 'param-2', type: 'select', data: ["ALWAYS_ON", "ALWAYS_OFF"] } ] as Field[] return ( <Node node={node} isPreview={!node.id} title='Relay' color={color} id={node.id} skipCustom={true} disableInput disableOutput> <NodeParams id={node.id} params={nodeParams} /> {/* <div style={{marginTop: "10px", marginBottom: "10px"}}> {subsystem(subsystemData, nodeData, type)} </div> */} </Node> ) }
// import subsystem from "./utils/subsystem";
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/nodes/Relay.tsx#L5-L20
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
SCD4X
const SCD4X = ({node = {}, nodeData = {}, children, color}: any) => { const [name, setName] = React.useState(nodeData['param-1']) const nameErrorMsg = 'Reserved name' const intervalErrorMsg = 'Add units h/m/s/ms' const nodeParams: Field[] = [ { label: 'Name', static: true, field: 'param-1', type: 'input', onBlur: () => { setName(nodeData['param-1']) }, error: nodeData['param-1']?.value?.replace(/['"]+/g, '') == 'nfcreader' ? nameErrorMsg : null }, { label: 'i2cBus', static: true, field: 'param-2', type: 'input', }, { label: 'Update Interval', static: true, field: 'param-3', type: 'input', error: !/^\d+[hms]$/.test(nodeData['param-3']?.value) ? intervalErrorMsg : null } ] return ( <Node node={node} isPreview={!node.id} title='SCD4X' color={color} id={node.id} skipCustom={true} > <NodeParams id={node.id} params={nodeParams} /> </Node> ) }
// import { Position } from "reactflow";
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/nodes/SCD4X.tsx#L7-L29
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
TempHumidity
const TempHumidity = ({ node = {}, nodeData = {}, children, color }: any) => { const transitionErrorMsg = 'Add units s/ms' const nodeParams: Field[] = [ { label: 'Name', static: true, field: 'param-1', type: 'input' }, { label: 'Model', static: true, field: 'param-2', type: 'select', data: ["DHT11", "DHT22", "DHT22_TYPE2", "AM2302", "RHT03", "SI7021"] }, { label: 'Update Interval', static: true, field: 'param-3', type: 'input', error: !['s', 'ms'].includes(nodeData['param-3']?.value?.replace(/['"0-9]+/g, '')) ? transitionErrorMsg : null } ] as Field[] return ( <Node node={node} isPreview={!node.id} title='Temperature & Humidity' color={color} id={node.id} skipCustom={true} disableInput disableOutput> <NodeParams id={node.id} params={nodeParams} /> </Node> ) }
// import { Node, Field, HandleOutput, NodeParams } from '../../flowslib';
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/nodes/TempHumidity.tsx#L7-L26
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
getEnvVars
const getEnvVars = ()=>{ return {apiUrl: "http://localhost",imagesUrl: "test"} }
/* MIT License Copyright (c) 2022-present, PROTOFY.XYZ, S.L. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protodevice/src/oldThings/settings.ts#L26-L28
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
flatten
const flatten = (nodes) => { const total = [] const toFlow = (node, graph, parentNode) => { const obj = { ...node } delete obj.children if (parentNode) obj.parentNode = parentNode total.push(obj) if (node.children && node.children.length) { const link = edges.find((e) => e.source == node.children[0].id) if(link) { const newLink = JSON.parse(JSON.stringify(link)) newLink.source = node.id newLink.sourceHandle = node.id + '-output' edges.push(newLink) } node.children.forEach((childNode) => toFlow(childNode, graph, node.id)) } } nodes.forEach((node) => toFlow(node, graph, null)) return total }
// console.log('before toFlow: ', nodes)
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protoflow/src/diagram/layouts/ElkLayout.tsx#L45-L68
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
computeZoomFactor
function computeZoomFactor(currentZoom, b = 4.5, q = 8, x0 = 0.99, maxFactor = 12.5) { if (currentZoom >= 1) { return 1; // This means no change in the font, it's at its base size. } const a = -maxFactor; const c = maxFactor; // Exponential function const exponential = a * (1 - Math.exp(-b * currentZoom)) + c; // Quadratic function const quadratic = -q * Math.pow(currentZoom - 1, 2) + 1; // Weight based on sigmoidal function const w = 1 / (1 + Math.exp(-20 * (currentZoom - x0))); // Combine the functions const combinedFactor = w * quadratic + (1 - w) * exponential; // Ensure the factor is never less than 1 return Math.max(combinedFactor, 1); }
/** * Compute the zoom factor based on the current zoom level. * * @param {number} currentZoom - The current zoom level (0 to 2). * @param {number} [b=2] - Controls the steepness of the exponential curve. * Higher values make the exponential curve steeper. * @param {number} [q=8.33] - Controls the curvature of the quadratic function. * Higher values will make the curve sharper. * @param {number} [x0=0.7] - Determines the point of inflection for the weight function * (the point where the transition between quadratic and exponential is most noticeable). * @param {number} [maxFactor=12.5] - Determines the maximum factor by which the font size can grow. * * @returns {number} The font size multiplier based on the current zoom level. */
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protoflow/src/lib/ZoomMath.ts#L22-L48
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
createDateObject
function createDateObject(time, day, monthName, year): Date { const monthMap = { january: 0, february: 1, march: 2, april: 3, may: 4, june: 5, july: 6, august: 7, september: 8, october: 9, november: 10, december: 11 }; const [hour, minute] = time.split(':').map(num => parseInt(num, 10)); const monthIndex = monthMap[monthName.toString()]; if (monthIndex === undefined) { console.log({ time, day, monthName, year }, monthMap[monthName.toString()]) return null } return new Date(year, monthIndex, day, hour, minute); }
//1 marzo 2023
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protolib/src/bundles/automations/schedule.ts#L23-L49
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
flatten
const flatten = (nodes) => { const total = [] const toFlow = (node, parentNode) => { const obj = { ...node, data: {...node.data} } delete obj.children if (parentNode) obj.parentNode = parentNode total.push(obj) if (node.children && node.children.length) { const link = edges.find((e) => e.source == node.children[0].id) if(link) { const newLink = JSON.parse(JSON.stringify(link)) newLink.source = node.id newLink.sourceHandle = node.id + '-output' edges.push(newLink) } node.children.forEach((childNode) => toFlow(childNode, node.id)) } } nodes.forEach((node) => toFlow(node, null)) return total }
// console.log('before toFlow: ', nodes)
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protolib/src/bundles/devices/deviceDefinitions/DeviceLayout.tsx#L88-L111
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
filter
const filter = (cmd) => (cmd.name != commandName)
// WIP: Not working
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protolib/src/bundles/discord/context/index.ts#L157-L157
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
phpApisAbsolutePath
const phpApisAbsolutePath = (root, file) => fspath.join(process.cwd(), phpApisRoot(getRoot(root)), file)
// fix: here file var could be populated with ../../../ and it will be a path traversing
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protolib/src/bundles/php/phpApi.ts#L10-L10
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
fail
const fail = (returnUrl?) => { if (returnUrl.includes('_next/data/development/')) { const basePath = returnUrl.split('_next/data/development')[1].split('.json')[0]; returnUrl = basePath } if (returnUrl == "/") returnUrl = undefined const encodedReturn = encodeURIComponent(returnUrl); return { redirect: { permanent: false, destination: "/auth/login" + (returnUrl ? "?return=" + encodedReturn : "") } } }
//utility functions for nextjs pages
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protolib/src/lib/Session.ts#L72-L85
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
generateEvent
const generateEvent = async (event, token='') => { try { await API.post('/api/core/v1/events?token='+token, event, undefined, true) } catch(e) { //console.error("Failed to send event: ", e) } }
/* modelName: name of the model, used to generate api urls. for example, if model name is 'test' and prefix is '/api/v1/', then to read an item is: /api/v1/test the separation from prefix is to allow less parameters for the default scenario (so you dont to write /api/v1/ all the time) modelType: a class to interact with the data returned by the storage dir: the directory where your api is located. Used to load initialData.json if it exists prefix: exaplined in modelName dbName: name of the database, used by the storage engine transformers: a key->value object with transformations, invocable from the schema. See protolib/bundles/users _connectDB: function used by the api to preconnect the database. Its optional, used to provide your own database implementation _getDB: function used by the api to retrieve the database object to interact with the database. Its optional, used to provide your own database implementation (json...) operations: list of provided operations, by default ['create', 'read', 'update', 'delete', 'list'] single: most apis are used to expose a list of things. Single means a single entity, not a list of things. So /api/v1/test returns the entity, not a list of things */
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protonode/src/lib/generateApi.ts#L24-L30
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
ProtoLevelDB.getGroupIndexOptions
async getGroupIndexOptions(groupKey, limit = 100) { try { const indexTable = sublevel(this.rootDb, 'indexTable') const groupIndexes = JSON.parse(await indexTable.get('groupIndexes')) const index = groupIndexes.find(gi => gi.key == groupKey) if (index) { const groupSubLevelOptions = sublevel(this.rootDb, 'group_' + index.key + '_options_' + this.tableVersion) const keys = [] for await (const [key] of groupSubLevelOptions.iterator({ limit })) { keys.push(key.split('_').slice(1).join('_')) } return keys } else { return [] } } catch (e) { //logger.error({ db: this.location }, 'Error reading group indexes for database: ' + this.location) } }
//given a groupkey, like 'city', return all possible values for that group
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/protonode/src/lib/dbproviders/leveldb.ts#L217-L235
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
sizeToSpace
function sizeToSpace(v: number) { if (v === 0) return 0 if (v === 2) return 0.5 if (v === 4) return 1 if (v === 8) return 1.5 if (v <= 16) return Math.round(v * 0.333) return Math.floor(v * 0.7 - 12) }
// a bit odd but keeping backward compat for values >8 while fixing below
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/ui/src/tokens/index.tsx#L76-L83
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
cleanHtml
const cleanHtml = (html) => { const tempDiv = document.createElement('div'); tempDiv.innerHTML = html; return tempDiv.textContent || tempDiv.innerText || ''; };
// Clean html is necessawy when copy & paste from other websites or apps (contains metadata).
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/visualui/src/components/EditorLayout.tsx#L123-L127
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
handleEvent
const handleEvent = (e) => { if (enableClickEventsRef.current) return e.preventDefault(); e.stopPropagation(); }
// Prevents click events to interact inside editor-layout
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/visualui/src/components/UIEditor.tsx#L287-L291
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
useFlowsComms
function useFlowsComms({ edges, nodeData, nodes, setEdges, setNodesData, deleteNodes, setNodes, createNode, setNodeData, _customComponents, onSaveNodes, flowId, data }) { if (experimentalComms()) { const { lastEvent } = useVisualUi(props.contextAtom) useEffect(() => { if (lastEvent) { switch (lastEvent.action) { case "add-nodes": { break; }; case "edit-node": { var editedNodeData const field = lastEvent.field const newValue = lastEvent.value const nodeId = lastEvent.nodeId if (lastEvent.type == 'prop') { editedNodeData = { ["prop-" + field]: { ...nodeData[nodeId]["prop-" + field], value: newValue, key: field, kind: getKindName(newValue) } } } else {// edit node child editedNodeData = { "child-1": newValue } } var newNodesData = { ...nodeData, [nodeId]: { ...nodeData[nodeId], ...editedNodeData } } setNodesData(newNodesData) break; }; case "delete-node": { break; } default: { throw new Error("useVisualUi(...): Unhandled event type"); } } } }, [lastEvent]) } else { // TODO: JOIN DATA TOPIC USE EFFECTS useEffect(() => { const uiData = data[flowId + '/ui'] if (!uiData) return var nodeId = uiData.nodeId let newEdges switch (uiData.action) { case 'delete-node': var nodesToDelete = uiData.deletedNodes ?? [] var parentId = uiData.parent const { updatedEdges, newNodeData } = deleteNodes(nodesToDelete, parentId, nodeId, edges, nodeData) setEdges(updatedEdges) setNodesData(newNodeData) setNodes(nds => nds.filter(n => !nodesToDelete.includes(n.id))) break; case 'add-nodes': const parentData = uiData.parentData var newNodesData = uiData.newNodesData const newNodes = newNodesData.map(nd => createNode([0, 0], "JsxElement", nd.id, nd.data, true, {}, {})).flat() setNodes(nd => nd.concat(newNodes)); var newData = newNodesData?.reduce((ndData, node) => { const childs = node.childrens.reduce((total, child, index) => { return { ...total, ["child-" + (index + 1)]: "" } }, {}) return { ...ndData, [node.id]: { ...getNodePropsData(node.name, node.props, node.data), ...childs } } }, { ...nodeData, [parentData.id]: { ...addChildNodeDataAndReorder(nodeData[parentData.id], parentData.childrenPos + 1, '') } }) setNodesData(newData) newEdges = newNodesData.reduce((total, curr) => { var childPos = (newNodesData.find(n => n.childrens.includes(curr.id))?.childrens?.findIndex(c => c == curr.id) ?? parentData.childrenPos) + 1 return addEdgeChildAndReorder(total, curr.id, curr.parent, childPos) }, edges) setEdges(newEdges) break case 'edit-node': var editedNodeData const field = uiData.field const newValue = uiData.value if (uiData.type == 'prop') { editedNodeData = { ["prop-" + field]: { ...nodeData[nodeId]["prop-" + field], value: newValue, key: field, kind: getKindName(newValue) } } } else {// edit node child editedNodeData = { "child-1": newValue } } var newNodesData = { ...nodeData, [nodeId]: { ...nodeData[nodeId], ...editedNodeData } } setNodesData(newNodesData) break; case 'move-node': const isSameParent = uiData.isSameParent if (isSameParent) { let parent = uiData.parent; let childrenIndexes = uiData.childrenIndexes; let offset = Math.min(...childrenIndexes); let prevParentNodeData = { ...nodeData[parent] }; // const newParentNodeData = { ...prevParentNodeData } const newParentNodeData = reorderDataChilds(prevParentNodeData, childrenIndexes, offset) setNodeData(parent, newParentNodeData) const newEdges = reorderEdgeChilds(edges, parent, offset, childrenIndexes) setEdges(newEdges) return } else { // start-remove child from old parent const oldParentId = uiData.oldParentId; const oldChildPos = uiData.oldPos + 1; const oldParentNodeData = nodeData[oldParentId] const { data: new_oldParentNodeData, deletedElementData: movedElementData } = removeDataChildAndReorder(oldParentNodeData, oldChildPos) // end-remove child from old parent // start-add child to new parent const newParentId = uiData.newParentId; const newParentNodeData = nodeData[newParentId] if (!newParentNodeData) return const numChilds = Object.keys(newParentNodeData).filter(k => k.startsWith('child-')).length; const newChildPos = uiData.newPos == -1 ? (numChilds + 1) : (uiData.newPos + 1); const new_newParentNodeData = addChildNodeDataAndReorder(newParentNodeData, newChildPos, movedElementData) // end-add child to new parent setNodesData({ ...nodeData, [oldParentId]: new_oldParentNodeData, [newParentId]: new_newParentNodeData }) const newEdges = moveEdgeChildAndReorder(edges, nodeId, oldParentId, oldChildPos, newParentId, newChildPos) setEdges(newEdges) } break; } }, [data[flowId + '/ui']]) useEffect(() => { // Send response if (data["savenodes"]?.value) { onSaveNodes() } }, [data["savenodes"]]) } }
// flows comms custom hook
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/visualui/src/components/VisualUiFlows.tsx#L36-L199
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
Source.parse
static parse(source: string, metadata = {}): Source { const project = new Project({ useInMemoryFileSystem: true, manipulationSettings: { indentationText: IndentationText.Tab }, compilerOptions: { target: ScriptTarget.Latest, scriptKind: ScriptKind.TSX, languageVariant: LanguageVariant.JSX }, }) return new Source(project.createSourceFile('_temp2.tsx', source, { overwrite: true }), metadata) }
// sourceCode -> Ast
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/visualui/src/models/Source.ts#L17-L28
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
Protofy
github_2023
Protofy-xyz
typescript
Source.data
data(customIdentifier?: () => string | number): any { // Gets craftJS nodes if (customIdentifier) { this.identifyElements(customIdentifier) } const content = this.getContent(); let craftNodes = this.toCraftNodes(content) craftNodes = this.addCustomProps(craftNodes) // Adds imports return craftNodes; }
// Ast -> craftNodes
https://github.com/Protofy-xyz/Protofy/blob/636bcc1b2b5089fa7e9835cd531497cdc73ac83f/packages/visualui/src/models/Source.ts#L31-L39
636bcc1b2b5089fa7e9835cd531497cdc73ac83f
wga
github_2023
blackfyre
typescript
initViewer
function initViewer() { const elements = document.querySelectorAll("[data-viewer]"); if (elements.length > 0) { elements.forEach((element) => { const e = element as HTMLElement; new Viewer(e, { toolbar: { zoomIn: 1, zoomOut: 1, oneToOne: 1, reset: 1, prev: 1, play: { show: 1, size: "large", }, next: 1, rotateLeft: 1, rotateRight: 1, flipHorizontal: 0, flipVertical: 0, }, }); }); } }
/** * Initializes the Viewer plugin on all elements with the `data-viewer` attribute. * @function * @returns {void} */
https://github.com/blackfyre/wga/blob/79a8556130d2edd109a4a720cfac31036f52a7a5/resources/js/app.ts#L66-L91
79a8556130d2edd109a4a720cfac31036f52a7a5
wga
github_2023
blackfyre
typescript
InitEventListeners
function InitEventListeners() { document.body.addEventListener("notification:toast", function (evt) { const event = evt as ToastEvent; if (event.detail.closeDialog) { wgaInternal.els.dialog?.close(); } createToast(event.detail.message, event.detail.type); }); document.body.addEventListener("htmx:load", function (evt) { initViewer(); initCloner(); }); document.body.addEventListener("htmx:swapError", function (evt) { console.error(evt); // TODO: show error toast: An error occurred while processing your request. createToast("An error occurred while processing your request.", "danger"); }); document.body.addEventListener("htmx:targetError", function (evt) { console.error(evt); // TODO: show error toast: An error occurred while processing your request. createToast("An error occurred while processing your request.", "danger"); }); document.body.addEventListener("htmx:timeout", function (evt) { console.error(evt); // TODO: show error toast: Request timed out. createToast("Request timed out!", "danger"); }); // document.body.addEventListener("htmx:configRequest", (event) => { // const evt = event as CustomEvent; // //get the value of the _csrf cookie // const rawCookies: string = document.cookie; // const cookieList: string[] = rawCookies.split("; "); // if (cookieList.length === 0) { // return; // } // let csrf_token = ""; // for (let i = 0; i < cookieList.length; i++) { // const cookie = cookieList[i]; // if (cookie.startsWith("_csrf=")) { // csrf_token = cookie.split("=")[1]; // break; // } // } // evt.detail.headers["X-XSRF-TOKEN"] = csrf_token; // }); //! This is a workaround, has to be removed when htmx fixes the issue addEventListener("htmx:beforeHistorySave", () => { document.querySelectorAll(":disabled").forEach((el) => { const e = el as HTMLInputElement; e.disabled = false; }); }); document.addEventListener("trix-before-initialize", () => { Trix.config.toolbar.getDefaultHTML = () => { return ` <div class="trix-button-row"> <span class="trix-button-group trix-button-group--text-tools" data-trix-button-group="text-tools"> <button type="button" class="trix-button trix-button--icon trix-button--icon-bold btn-neutral" data-trix-attribute="bold" data-trix-key="b" title="Bold" tabindex="-1">Bold</button> <button type="button" class="trix-button trix-button--icon trix-button--icon-italic btn-neutral" data-trix-attribute="italic" data-trix-key="i" title="Italic" tabindex="-1">Italic</button> <button type="button" class="trix-button trix-button--icon trix-button--icon-strike btn-neutral" data-trix-attribute="strike" title="Strike" tabindex="-1">Strike</button> </span> <span class="trix-button-group trix-button-group--block-tools" data-trix-button-group="block-tools"> <button type="button" class="trix-button trix-button--icon trix-button--icon-heading-1 btn-neutral" data-trix-attribute="heading1" title="Heading 1" tabindex="-1">Heading 1</button> <button type="button" class="trix-button trix-button--icon trix-button--icon-quote btn-neutral" data-trix-attribute="quote" title="Quote" tabindex="-1">Quote</button> </span> </div>`; }; // Change Trix.config if you need }); }
/** * Initializes event listeners for the postcard dialog success and error events, as well as the htmx:load event and the trix-before-initialize event. * @function * @name InitEventListeners * @returns {void} */
https://github.com/blackfyre/wga/blob/79a8556130d2edd109a4a720cfac31036f52a7a5/resources/js/app.ts#L156-L239
79a8556130d2edd109a4a720cfac31036f52a7a5
wga
github_2023
blackfyre
typescript
initJumpToTop
function initJumpToTop() { const jumpToTop = document.querySelector(".jump.back-to-top"); if (jumpToTop) { jumpToTop.addEventListener("click", () => { window.scrollTo({ top: 0, behavior: "smooth" }); }); } }
/** * Initializes the "Jump to Top" functionality. * @function * @name initJumpToTop * @returns {void} */
https://github.com/blackfyre/wga/blob/79a8556130d2edd109a4a720cfac31036f52a7a5/resources/js/app.ts#L247-L254
79a8556130d2edd109a4a720cfac31036f52a7a5
datalens-ui
github_2023
datalens-tech
typescript
resolveEntryByLink
async function resolveEntryByLink({ originalUrl, ctx, getEntryMeta, }: ResolveEntryByLinkComponentArgs): Promise<ResolveEntryByLinkComponentResponse> { try { const url = new URL(originalUrl, 'http://stub'); const idOrKeyOrReport = url.pathname .replace(/^\/navigation\//, '') .replace(/^\/navigate\//, '') .replace(/^\/wizard\/preview\//, '') .replace( /^(\/(ChartPreview|preview))?(\/(ChartWizard|wizard|ChartEditor|editor))?\/?/, '', ) || url.searchParams.get('name'); if (!idOrKeyOrReport) { throw new AppError("Url doesn't contain a valid entry identificator", { code: ErrorCode.IncorrectURL, }); } const params = parse(url.searchParams.toString()) as StringParams; let entry: GetEntryMetaResponse | GetEntryByKeyResponse; const {extractEntryId} = registry.common.functions.getAll(); const possibleEntryId = extractEntryId(idOrKeyOrReport); if (possibleEntryId) { entry = await getEntryMeta({entryId: possibleEntryId}); } else { throw new AppError('Incorrect entry identificator', { code: ErrorCode.IncorrectURL, }); } ctx.log('RESOLVE_ENTRY_BY_LINK_SUCCESS', {originalUrl, entryId: entry.entryId, params}); return { entry, params, }; } catch (error) { ctx.logError('RESOLVE_ENTRY_BY_LINK_FAILED', error, {originalUrl}); if (typeof error === 'object' && error !== null) { if (error instanceof AppError || ('error' in error && Boolean(error.error))) { throw error; } else if ('response' in error && error.response) { const response = error.response; if (typeof response === 'object' && response !== null && 'status' in response) { if (response.status === 403) { throw AppError.wrap(error as unknown as Error, { code: ErrorCode.Forbidden, }); } if (response.status === 404) { throw AppError.wrap(error as unknown as Error, { code: ErrorCode.NotFound, }); } } } } throw AppError.wrap(error as Error, {code: ErrorCode.Unknown}); } }
// eslint-disable-next-line complexity
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/components/resolve-entry-by-link.ts#L22-L94
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
emptyStep
const emptyStep = (name: string) => async (options: {params: StringParams}) => { const {params} = options; const timeStart = process.hrtime(); const context = getChartApiContext({ name, shared, params, actionParams: {} as Record<string, string | string[]>, userLang: null, }); return { exports: {}, executionTiming: process.hrtime(timeStart), name, runtimeMetadata: context.__runtimeMetadata, }; };
// Nothing happens here - just for compatibility with the editor
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/components/charts-engine/components/processor/control-builder.ts#L24-L41
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
DataFetcher.getSourceConfig
static getSourceConfig({ sourcesConfig, sourcePath, isEmbed, }: { sourcesConfig: ChartsEngine['sources']; sourcePath: string; isEmbed?: boolean; }) { let sourceName = DataFetcher.getSourceName(sourcePath); // Temporary hack for embed endpoints if (isEmbed && sourceName === 'bi_datasets') { sourceName = 'bi_datasets_embed'; } if (isEmbed && sourceName === 'bi_connections') { sourceName = 'bi_connections_embed'; } const resultSourceType = Object.keys(sourcesConfig).find((sourceType) => { if (sourceName === sourceType) { return true; } const aliases = sourcesConfig[sourceType].aliases; if (aliases) { return aliases.has(sourceName); } return false; }); if (resultSourceType) { const sourceConfig = sourcesConfig[resultSourceType]; sourceConfig.sourceType = resultSourceType; // Temporary hack for embed endpoints if (isEmbed && resultSourceType === 'bi_datasets_embed') { sourceConfig.sourceType = 'bi_datasets'; } if (isEmbed && resultSourceType === 'bi_connections_embed') { sourceConfig.sourceType = 'bi_connections'; } return sourceConfig; } else { return null; } }
/** * @param {String} chartsEngine * @param {String} sourcePath requested source * * @returns {Object} source configuration */
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/components/charts-engine/components/processor/data-fetcher.ts#L370-L420
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
DataFetcher.getChartKitSources
static getChartKitSources({ sourcesConfig, lang = 'en', }: { sourcesConfig: ChartsEngine['sources']; lang: 'en' | 'ru'; }) { const sources = sourcesConfig; const chartkitSources: Record<string, ChartkitSource> = {}; Object.keys(sources).forEach((sourceType) => { const chartkitSource: ChartkitSource = {}; const source = sources[sourceType]; if (source.description) { const chartkitSourceDescription: ChartkitSourceDecription = {}; const description = source.description; if (description.title) { chartkitSourceDescription.title = description.title[lang]; } chartkitSource.description = chartkitSourceDescription; } if (source.uiEndpoint) { chartkitSource.uiEndpoint = source.uiEndpoint; } if (source.dataEndpoint) { chartkitSource.dataEndpoint = source.dataEndpoint; } chartkitSources[sourceType] = chartkitSource; if (source.aliases) { [...source.aliases].forEach((alias) => { chartkitSources[alias] = chartkitSource; }); } }); return chartkitSources; }
/** * @param {String} sourcesConfig * @param {String} lang target lang * * @returns {Object} config for all sources */
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/components/charts-engine/components/processor/data-fetcher.ts#L428-L472
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
DataFetcher.isStat
static isStat({ sourcesConfig, sourcePath, }: { sourcesConfig: ChartsEngine['sources']; sourcePath: string; }) { return DataFetcher.getSourceConfig({sourcesConfig, sourcePath}) === null; }
/** * @param {String} sourcePath requested source * * @returns {Boolean} check is source stat or not */
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/components/charts-engine/components/processor/data-fetcher.ts#L479-L487
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
Processor.process
static async process({ subrequestHeaders, paramsOverride = {}, widgetConfig = {}, configOverride, useUnreleasedConfig, userLang, userLogin, userId = null, iamToken = null, responseOptions = {}, uiOnly = false, isEditMode, configResolving, ctx, workbookId, builder, forbiddenFields, disableJSONFnByCookie, configName, configId, isEmbed, zitadelParams, authParams, originalReqHeaders, adapterContext, hooksContext, telemetryCallbacks, cacheClient, hooks, sourcesConfig, }: ProcessorParams): Promise< ProcessorSuccessResponse | ProcessorErrorResponse | {error: string} > { const requestId = ctx.get(REQUEST_ID_PARAM_NAME) || ''; const logs: ProcessorLogs = { modules: [], }; let processedModules: Record<string, ChartBuilderResult> = {}; let modulesLogsCollected = false; let resolvedSources: Record<string, DataFetcherResult> | undefined; let config: ResolvedConfig; let params: Record<string, string | string[]> | StringParams; let actionParams: Record<string, string | string[]>; let usedParams: Record<string, string | string[]>; const timings: { configResolving: number; dataFetching: null | number; jsExecution: null | number; } = { configResolving, dataFetching: null, jsExecution: null, }; const onCodeExecuted = telemetryCallbacks.onCodeExecuted || (() => {}); const onTabsExecuted = telemetryCallbacks.onTabsExecuted || (() => {}); function injectConfigAndParams({target}: {target: ProcessorSuccessResponse}) { let responseConfig; const useChartsEngineResponseConfig = Boolean( isEnabledServerFeature(ctx, Feature.UseChartsEngineResponseConfig), ); if (useChartsEngineResponseConfig && responseOptions.includeConfig && config) { responseConfig = config; } else { responseConfig = { type: config.type, meta: config.meta, entryId: config.entryId, key: config.key, }; } responseConfig.key = config.key || configName; responseConfig.entryId = config.entryId || configId; target._confStorageConfig = responseConfig; target.key = responseConfig.key; target.id = responseConfig.entryId; target.type = responseConfig.type; if (params) { target.params = params; } if (actionParams) { target.actionParams = actionParams; } return target; } function stringifyLogs(localLogs: ProcessorLogs, localHooks: ProcessorHooks) { try { const formatter = localHooks.getLogsFormatter(); return JSON.stringify(localLogs, (_, value: string | number) => { if (typeof value === 'number' && isNaN(value)) { return '__special_value__NaN'; } if (value === Infinity) { return '__special_value__Infinity'; } if (value === -Infinity) { return '__special_value__-Infinity'; } return formatter ? formatter(value) : value; }); } catch (e) { ctx.logError('Error during formatting logs', e); return ''; } } function injectLogs({ target, }: { target: ProcessorSuccessResponse | Partial<ProcessorErrorResponse>; }) { if (responseOptions.includeLogs) { target.logs_v2 = stringifyLogs(logs, hooks); } } try { let hrStart = process.hrtime(); try { config = (configOverride as ResolvedConfig) || (await Storage.resolveConfig(ctx, { unreleased: useUnreleasedConfig, key: configName, headers: {...subrequestHeaders}, workbookId, })); } catch (e) { return { error: { code: CONFIG_LOADING_ERROR, debug: { message: getMessageFromUnknownError(e), }, }, }; } const type = config.meta.stype; config.type = type; ctx.log('EditorEngine::ConfigResolved', {duration: getDuration(hrStart)}); const resultHooksInit = await hooks.init({ config: { ...config, entryId: config.entryId || configId, }, isEditMode, ctx, hooksContext, }); if (resultHooksInit.status === ProcessorHooks.STATUS.FAILED) { const {hookError, error} = resultHooksInit; if (hookError) { return { error: { code: HOOKS_ERROR, ...hookError, }, }; } else { return { error: { code: HOOKS_ERROR, message: 'Unhandled error init hooks', debug: { message: getMessageFromUnknownError(error), }, }, }; } } hrStart = process.hrtime(); try { processedModules = await builder.buildModules({ ctx, subrequestHeaders, onModuleBuild: ({executionTiming, filename}) => { logSandboxDuration(executionTiming, filename, ctx); }, }); } catch (error) { ctx.logError('DEPS_RESOLVE_ERROR', error); if (!isObject(error)) { return { error: { code: DEPS_RESOLVE_ERROR, details: { stackTrace: 'Error resolving required modules: internal error', }, debug: {}, }, }; } let reason = ('stackTrace' in error && error.stackTrace) || 'internal error'; if ('status' in error) { if (error.status === 403) { reason = 'access denied'; } else if (error.status === 404) { reason = 'not found'; } } const sandboxErrorFilename = 'executionResult' in error && isObject(error.executionResult) && 'filename' in error.executionResult ? error.executionResult?.filename : null; const axiosErrorFileName = error instanceof AxiosError && 'description' in error ? error.description : null; const filename = sandboxErrorFilename || axiosErrorFileName || 'required modules'; const stackTraceText = 'description' in error ? error.description : `module (${filename}): ${reason}`; return { error: { code: DEPS_RESOLVE_ERROR, details: { stackTrace: `Error resolving ${stackTraceText}`, }, statusCode: 'status' in error && isNumber(error.status) ? error.status : undefined, debug: { message: getMessageFromUnknownError(error), }, }, }; } ctx.log('EditorEngine::DepsResolved', {duration: getDuration(hrStart)}); hrStart = process.hrtime(); ctx.log('EditorEngine::DepsProcessed', {duration: getDuration(hrStart)}); try { await builder.buildShared(); } catch (error) { ctx.logError('Error during shared tab parsing', error); logs.Shared = [[{type: 'string', value: 'Invalid JSON in Shared tab'}]]; const failedResponse = { error: { code: RUNTIME_ERROR, details: { description: 'Invalid JSON in Shared tab', }, debug: { message: getMessageFromUnknownError(error), }, }, }; injectLogs({target: failedResponse}); return failedResponse; } const {params: normalizedParamsOverride, actionParams: normalizedActionParamsOverride} = normalizeParams(paramsOverride); hrStart = process.hrtime(); usedParams = {}; const paramsTabResults = await builder.buildParams({ params: normalizedParamsOverride, usedParams: usedParams, actionParams: normalizedActionParamsOverride, hooks, }); logSandboxDuration(paramsTabResults.executionTiming, paramsTabResults.name, ctx); const paramsTabError = paramsTabResults.runtimeMetadata.error; if (paramsTabError) { throw paramsTabError; } ctx.log('EditorEngine::Params', {duration: getDuration(hrStart)}); usedParams = { ...(paramsTabResults.exports as Record<string, string | string[]>), ...usedParams, }; // Merge used to be here. Merge in this situation does not work as it should for arrays, so assign. params = Object.assign({}, usedParams, normalizedParamsOverride); actionParams = Object.assign({}, {}, normalizedActionParamsOverride); Object.keys(params).forEach((paramName) => { const param = params[paramName]; if (!Array.isArray(param)) { params[paramName] = [param]; } }); // take values from params in usedParams there are always only defaults exported from the Params tab // and in params new passed parameters Object.keys(usedParams).forEach((paramName) => { usedParams[paramName] = params[paramName]; }); // ChartEditor.updateParams() has the highest priority, // therefore, now we take the parameters set through this method updateParams({ userParamsOverride: paramsTabResults.runtimeMetadata.userParamsOverride, params, usedParams, }); actionParams = updateActionParams({ userActionParamsOverride: paramsTabResults.runtimeMetadata.userActionParamsOverride, actionParams, }); if (paramsTabResults.logs) { logs.Params = paramsTabResults.logs; } resolveParams(params as Record<string, string[]>); hrStart = process.hrtime(); const sourcesTabResults = await builder.buildUrls({ params, actionParams: normalizedActionParamsOverride, hooks, }); logSandboxDuration(sourcesTabResults.executionTiming, sourcesTabResults.name, ctx); ctx.log('EditorEngine::Urls', {duration: getDuration(hrStart)}); logs.Urls = sourcesTabResults.logs; try { hrStart = process.hrtime(); const sourcesTabError = sourcesTabResults.runtimeMetadata.error; if (sourcesTabError) { throw sourcesTabError; } let sources = sourcesTabResults.exports as Record<string, Source>; if (uiOnly) { const filteredSources: Record<string, Source> = {}; Object.keys(sources).forEach((key) => { const source = sources[key]; if (isObject(source) && source.ui) { filteredSources[key] = source; } }); sources = filteredSources; } if (configOverride?.entryId || configId) { let dlContext: Record<string, string> = {}; if (subrequestHeaders[DL_CONTEXT_HEADER]) { const dlContextHeader = subrequestHeaders[DL_CONTEXT_HEADER]; dlContext = JSON.parse( dlContextHeader && !Array.isArray(dlContextHeader) ? dlContextHeader : '', ); } dlContext.chartId = configOverride?.entryId || configId; if (subrequestHeaders['x-chart-kind']) { dlContext.chartKind = subrequestHeaders['x-chart-kind']; } subrequestHeaders[DL_CONTEXT_HEADER] = JSON.stringify(dlContext); } resolvedSources = await DataFetcher.fetch({ sources, ctx, iamToken, subrequestHeaders, userId, userLogin, workbookId, isEmbed, zitadelParams, authParams, originalReqHeaders, adapterContext, telemetryCallbacks, cacheClient, sourcesConfig, }); if (Object.keys(resolvedSources).length) { timings.dataFetching = getDuration(hrStart); } ctx.log('EditorEngine::DataFetched', {duration: getDuration(hrStart)}); } catch (error) { logFetchingError(ctx, error); if (!modulesLogsCollected) { collectModulesLogs({logsStorage: logs, processedModules}); } if (!isObject(error)) { return {error: 'Internal fetching error'}; } const response: ProcessorErrorResponse = { error: { code: DATA_FETCHING_ERROR, debug: { message: getMessageFromUnknownError(error), ...('debug' in error && error.debug ? error.debug : {}), }, }, }; if ('status' in error) { if (error.status === 403) { response.error.code = 'ENTRY_FORBIDDEN'; } else if (error.status === 404) { response.error.code = 'ENTRY_NOT_FOUND'; } } injectLogs({target: response}); if (error instanceof Error) { return {error: 'Internal fetching error'}; } else if (!response.error.details) { response.error.details = { sources: error, }; let maybe400 = false; let maybe500 = false; let requestSizeLimitExceeded = false; Object.values(error).forEach((sourceResult) => { const possibleStatus = sourceResult && sourceResult.status; if (399 < possibleStatus && possibleStatus < 500) { maybe400 = true; } else { maybe500 = true; } if ( sourceResult.code === REQUEST_SIZE_LIMIT_EXCEEDED || sourceResult.code === ALL_REQUESTS_SIZE_LIMIT_EXCEEDED ) { requestSizeLimitExceeded = true; } }); if (maybe400 && !maybe500) { response.error.statusCode = DEFAULT_SOURCE_FETCHING_ERROR_STATUS_400; } else if (requestSizeLimitExceeded) { response.error.statusCode = DEFAULT_SOURCE_FETCHING_LIMIT_EXCEEDED_STATUS; } else { response.error.statusCode = DEFAULT_SOURCE_FETCHING_ERROR_STATUS_500; } } return response; } const data = Object.keys(resolvedSources).reduce< Record<string, DataFetcherResult['body']> >((acc, sourceName) => { if (resolvedSources) { acc[sourceName] = resolvedSources[sourceName].body; // @ts-ignore body not optional; delete resolvedSources[sourceName].body; } return acc; }, {}); hrStart = process.hrtime(); const libraryTabResult = await builder.buildChartLibraryConfig({ data, params, actionParams: normalizedActionParamsOverride, hooks, }); ctx.log('EditorEngine::HighCharts', {duration: getDuration(hrStart)}); let libraryConfig; if (libraryTabResult) { logSandboxDuration(libraryTabResult.executionTiming, libraryTabResult.name, ctx); libraryConfig = libraryTabResult.exports || {}; logs.Highcharts = libraryTabResult.logs; const libraryError = libraryTabResult.runtimeMetadata.error; if (libraryError) { throw libraryTabResult.runtimeMetadata.error; } } else { libraryConfig = {}; } let userConfig: UserConfig = {}; let processedData; let jsTabResults; if (!uiOnly) { hrStart = process.hrtime(); const configTabResults = await builder.buildChartConfig({ data, params, actionParams: normalizedActionParamsOverride, hooks, }); logSandboxDuration(configTabResults.executionTiming, configTabResults.name, ctx); ctx.log('EditorEngine::Config', {duration: getDuration(hrStart)}); logs.Config = configTabResults.logs; userConfig = configTabResults.exports as UserConfig; hrStart = process.hrtime(); jsTabResults = await builder.buildChart({ data, sources: resolvedSources, params, usedParams, actionParams: normalizedActionParamsOverride, hooks, }); logSandboxDuration(jsTabResults.executionTiming, jsTabResults.name, ctx); timings.jsExecution = getDuration(hrStart); const hrEnd = process.hrtime(); const hrDuration = [hrEnd[0] - hrStart[0], hrEnd[1] - hrStart[1]]; onCodeExecuted({ id: `${config.entryId || configId}:${config.key || configName}`, requestId, latency: (hrDuration[0] * 1e9 + hrDuration[1]) / 1e6, }); ctx.log('EditorEngine::JS', {duration: getDuration(hrStart)}); processedData = jsTabResults.exports; logs.JavaScript = jsTabResults.logs; const jsError = jsTabResults.runtimeMetadata.error; if (jsError) { throw jsError; } // ChartEditor.updateParams() has the highest priority, // so now we take the parameters set through this method updateParams({ userParamsOverride: jsTabResults.runtimeMetadata.userParamsOverride, params, usedParams, }); } const uiTabResults = await builder.buildUI({ data, params, usedParams, actionParams: normalizedActionParamsOverride, hooks, }); logSandboxDuration(uiTabResults.executionTiming, uiTabResults.name, ctx); const uiTabExports = uiTabResults.exports; let uiScheme: UiTabExports | null = null; if ( uiTabExports && (Array.isArray(uiTabExports) || (isObject(uiTabExports) && 'controls' in uiTabExports && Array.isArray(uiTabExports.controls))) ) { uiScheme = uiTabExports as UiTabExports; } logs.UI = uiTabResults.logs; ctx.log('EditorEngine::UI', {duration: getDuration(hrStart)}); // ChartEditor.updateParams() has the highest priority, // so now we take the parameters set through this method updateParams({ userParamsOverride: uiTabResults.runtimeMetadata.userParamsOverride, params, usedParams, }); if (uiScheme && userConfig && !userConfig.overlayControls) { userConfig.notOverlayControls = true; } collectModulesLogs({processedModules, logsStorage: logs}); modulesLogsCollected = true; const normalizedDefaultParams = normalizeParams( paramsTabResults.exports as ProcessorSuccessResponse['defaultParams'], ); const result: ProcessorSuccessResponse = { sources: resolvedSources, uiScheme, params: {...params, ...transformParamsToActionParams(actionParams)}, usedParams, actionParams, widgetConfig, defaultParams: normalizedDefaultParams.params, extra: {}, timings, }; injectLogs({target: result}); if (!uiOnly && jsTabResults) { result.data = processedData as ProcessorSuccessResponse['data']; let resultConfig = merge( {}, userConfig, jsTabResults.runtimeMetadata.userConfigOverride, ); let resultLibraryConfig = mergeWith( {}, libraryConfig, jsTabResults.runtimeMetadata.libraryConfigOverride, (a, b) => { return mergeArrayWithObject(a, b) || mergeArrayWithObject(b, a); }, ); onTabsExecuted({ result: { config: resultConfig, highchartsConfig: resultLibraryConfig, processedData, sources: resolvedSources, sourceData: data, }, entryId: config.entryId || configId, }); const disableFnAndHtml = isEnabledServerFeature(ctx, Feature.DisableFnAndHtml); if ( disableFnAndHtml || !isChartWithJSAndHtmlAllowed({createdAt: config.createdAt}) ) { resultConfig.enableJsAndHtml = false; } const enableJsAndHtml = get(resultConfig, 'enableJsAndHtml', false); const disableJSONFn = isEnabledServerFeature(ctx, Feature.NoJsonFn) || disableJSONFnByCookie || enableJsAndHtml === false; const stringify = disableJSONFn ? JSON.stringify : JSONfn.stringify; if (builder.type === 'CHART_EDITOR' && disableJSONFn) { resultConfig = cleanJSONFn(resultConfig); resultLibraryConfig = cleanJSONFn(resultLibraryConfig); } result.config = stringify(resultConfig); result.publicAuthor = config.publicAuthor; result.highchartsConfig = stringify(resultLibraryConfig); result.extra = jsTabResults.runtimeMetadata.extra || {}; result.extra.chartsInsights = jsTabResults.runtimeMetadata.chartsInsights; result.extra.sideMarkdown = jsTabResults.runtimeMetadata.sideMarkdown; result.sources = merge( resolvedSources, jsTabResults.runtimeMetadata.dataSourcesInfos, ); if (jsTabResults.runtimeMetadata.exportFilename) { result.extra.exportFilename = jsTabResults.runtimeMetadata.exportFilename; } ctx.log('EditorEngine::Postprocessing', {duration: getDuration(hrStart)}); if ( ctx.config.chartsEngineConfig.flags?.chartComments && (type === CONFIG_TYPE.GRAPH_NODE || type === CONFIG_TYPE.GRAPH_WIZARD_NODE || type === CONFIG_TYPE.GRAPH_QL_NODE) ) { try { const chartName = type === CONFIG_TYPE.GRAPH_NODE || type === CONFIG_TYPE.GRAPH_QL_NODE ? configName : configId; hrStart = process.hrtime(); result.comments = await CommentsFetcher.prepareComments( { chartName, config: resultConfig.comments, data: result.data as CommentsFetcherPrepareCommentsParams['data'], params, }, subrequestHeaders, ctx, ); ctx.log('EditorEngine::Comments', {duration: getDuration(hrStart)}); } catch (error) { ctx.logError('Error preparing comments', error); } } if (type === CONFIG_TYPE.MARKDOWN_NODE) { try { if (!(result.data?.markdown || result.data?.html)) { throw Error('Empty markdown or html'); } const markdown = result.data.markdown || result.data.html; const html = renderHTML({ text: markdown || '', lang: userLang || '', plugins: registry.getYfmPlugins(), }); delete result.data.markdown; result.data.html = html.result; result.data.meta = html.meta; } catch (error) { ctx.logError('Error render markdown', error); } } } injectConfigAndParams({target: result}); if (forbiddenFields) { forbiddenFields.forEach((field) => { if (result[field]) { delete result[field]; } }); } return result; } catch (error) { ctx.logError('Run failed', error); const isError = (error: unknown): error is SandboxError => { return isObject(error); }; if (!isError(error)) { throw error; } const executionResult: { filename?: string; logs?: LogItem[][]; stackTrace?: string; stack?: string; executionTiming?: [number, number]; } = error.executionResult || {}; if (!modulesLogsCollected) { collectModulesLogs({logsStorage: logs, processedModules}); } const failedLogs = executionResult.logs; if (failedLogs) { logs[(executionResult.filename as ProcessorFiles) || 'failed'] = failedLogs; } const result: Partial<ProcessorErrorResponse> = {}; injectLogs({target: result}); switch (error.code) { case CONFIG_LOADING_ERROR: case DEPS_RESOLVE_ERROR: case DATA_FETCHING_ERROR: result.error = error; break; case ROWS_NUMBER_OVERSIZE: case SEGMENTS_OVERSIZE: case TABLE_OVERSIZE: result.error = { code: error.code, details: error.details, statusCode: DEFAULT_OVERSIZE_ERROR_STATUS, }; break; case RUNTIME_ERROR: executionResult.stackTrace = executionResult.stackTrace || executionResult.stack; if (resolvedSources) { result.sources = resolvedSources; } result.error = { code: RUNTIME_ERROR, details: { stackTrace: executionResult.stackTrace ? StackTracePreparer.prepare(executionResult.stackTrace) : '', tabName: error.executionResult ? error.executionResult.filename : '', }, statusCode: DEFAULT_RUNTIME_ERROR_STATUS, }; break; case RUNTIME_TIMEOUT_ERROR: result.error = { code: RUNTIME_TIMEOUT_ERROR, statusCode: DEFAULT_RUNTIME_TIMEOUT_STATUS, }; onCodeExecuted({ id: `${configId}:${configName}`, requestId, latency: executionResult.executionTiming ? (executionResult.executionTiming[0] * 1e9 + executionResult.executionTiming[1]) / 1e6 : 0, }); break; default: throw error; } const tabName = (error.executionResult && error.executionResult.filename) || 'script'; const message = `EXECUTION_ERROR Error processing ${tabName}\n${error.stackTrace}`; ctx.log(message, { stackTrace: error.stackTrace, tabName, }); return { error: result.error, logs_v2: result.logs_v2, sources: result.sources, }; } finally { builder.dispose(); } }
// eslint-disable-next-line complexity
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/components/charts-engine/components/processor/index.ts#L188-L1055
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
emptyStep
const emptyStep = (name: string) => async (options: {params: StringParams; actionParams: StringParams}) => { const {params, actionParams} = options; const timeStart = process.hrtime(); const context = getChartApiContext({ name, shared, params, actionParams, widgetConfig, userLang, }); return { exports: {}, executionTiming: process.hrtime(timeStart), name, runtimeMetadata: context.__runtimeMetadata, }; };
// Nothing happens here - just for compatibility with the editor
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/components/charts-engine/components/processor/worker-chart-builder.ts#L45-L64
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
formatPassedHeaders
function formatPassedHeaders( headers: Request['headers'], ctx: AppContext, extraAllowedHeaders?: string[], ) { const headersNew: Request['headers'] = {}; const {headersMap} = ctx.config; const passedHeaders = [ ...PASSED_HEADERS, headersMap.folderId, headersMap.subjectToken, PROJECT_ID_HEADER, TENANT_ID_HEADER, SERVICE_USER_ACCESS_TOKEN_HEADER, ...(extraAllowedHeaders || []), ]; if (headers) { passedHeaders.forEach((name) => { if (headers[name]) { headersNew[name] = headers[name]; } }); } return headersNew; }
// 100 MB
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/components/charts-engine/components/storage/united-storage/provider.ts#L125-L154
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
prepareSingleResult
function prepareSingleResult({ resultData, fields, notifications, visualization, shared, idToTitle, idToDataType, ChartEditor, datasetsIds, loadedColorPalettes, layerChartMeta, usedColors, palettes, features, }: PrepareSingleResultArgs) { const isVisualizationWithLayers = Boolean( (visualization as ServerVisualizationLayer).layerSettings, ); const commonPlaceholders = (visualization as ServerVisualizationLayer).commonPlaceholders; preprocessHierarchies({ visualizationId: visualization.id, placeholders: visualization.placeholders, params: ChartEditor.getParams(), sharedData: shared.sharedData, colors: isVisualizationWithLayers ? commonPlaceholders.colors : shared.colors, shapes: (isVisualizationWithLayers ? commonPlaceholders.shapes : shared.shapes) || [], segments: shared.segments || [], }); const { sharedData: {drillDownData}, } = shared; let rowsLength: undefined | number; let cellsCount: number | undefined; let columnsCount: number | undefined; if ((resultData as any)?.pivot_data) { const pivotData = (resultData as any).pivot_data as PivotData; const rows = pivotData.rows || []; const columns = pivotData.columns || []; const rowsValues = rows[0]?.values || []; cellsCount = rows.length * rowsValues.length; columnsCount = columns.length; } else { rowsLength = resultData.data && resultData.data.length; } if (notifications.length) { notifications = prepareNotifications(notifications, visualization); ChartEditor.setChartsInsights(notifications); } if (drillDownData) { const currentDrillDownField = drillDownData.fields[drillDownData.level]; ChartEditor.updateConfig({ drillDown: { breadcrumbs: drillDownData.breadcrumbs, dateFormat: getServerDateFormat(currentDrillDownField?.data_type || ''), }, }); ChartEditor.updateParams({ drillDownLevel: drillDownData.level, drillDownFilters: drillDownData.filters, isColorDrillDown: drillDownData.isColorDrillDown, }); } if (rowsLength === 0) { return {}; } let prepare; let rowsLimit: number | undefined; let cellsLimit: number | undefined; let columnsLimit: number | undefined; let shapes: ServerShape[] = []; let shapesConfig; const segments: ServerField[] = shared.segments || []; switch (visualization.id) { case 'line': case 'area': case 'area100p': { if (visualization.id === 'line') { shapes = shared.shapes || []; shapesConfig = shared.shapesConfig; } prepare = prepareHighchartsLine; rowsLimit = 75000; break; } case WizardVisualizationId.Bar: case WizardVisualizationId.Bar100p: { prepare = prepareHighchartsBarY; rowsLimit = 75000; break; } case WizardVisualizationId.BarYD3: case WizardVisualizationId.BarY100pD3: { prepare = prepareD3BarY; rowsLimit = 75000; break; } case WizardVisualizationId.LineD3: { shapes = shared.shapes || []; shapesConfig = shared.shapesConfig; prepare = prepareD3Line; rowsLimit = 75000; break; } case 'column': case 'column100p': { prepare = prepareHighchartsBarX; rowsLimit = 75000; break; } case 'bar-x-d3': { prepare = prepareD3BarX; rowsLimit = 75000; break; } case 'scatter': shapes = shared.shapes || []; shapesConfig = shared.shapesConfig; prepare = prepareHighchartsScatter; rowsLimit = 75000; break; case 'scatter-d3': shapes = shared.shapes || []; shapesConfig = shared.shapesConfig; prepare = prepareD3Scatter; rowsLimit = 75000; break; case 'pie': case 'donut': prepare = prepareHighchartsPie; rowsLimit = 1000; break; case WizardVisualizationId.PieD3: case WizardVisualizationId.DonutD3: prepare = prepareD3Pie; rowsLimit = 1000; break; case 'metric': prepare = prepareMetricData; rowsLimit = 1000; break; case 'treemap': prepare = prepareHighchartsTreemap; rowsLimit = 800; break; case WizardVisualizationId.TreemapD3: prepare = prepareD3Treemap; rowsLimit = 800; break; case 'flatTable': prepare = prepareFlatTableData; rowsLimit = 100000; break; case 'pivotTable': { const pivotFallbackEnabled = shared.extraSettings?.pivotFallback === 'on'; if (pivotFallbackEnabled) { prepare = preparePivotTableData; rowsLimit = 40000; } else { prepare = prepareBackendPivotTableData; cellsLimit = 100000; columnsLimit = 800; } break; } case 'geopoint': prepare = prepareGeopointData; rowsLimit = 40000; break; case 'geopoint-with-cluster': prepare = prepareGeopointWithClusterData; rowsLimit = 40000; break; case 'geopolygon': prepare = prepareGeopolygonData; rowsLimit = 40000; break; case 'heatmap': prepare = prepareHeatmapData; rowsLimit = 40000; break; case 'polyline': prepare = preparePolylineData; rowsLimit = 40000; break; } const oversize = isDefaultOversizeError(rowsLength, rowsLimit); const backendPivotCellsOversize = isBackendPivotCellsOversizeError(cellsCount, cellsLimit); const backendPivotColumnsOversize = isBackendPivotColumnsOversizeError( columnsCount, columnsLimit, ); const {segmentsOversize, segmentsNumber} = isSegmentsOversizeError({ segments, idToTitle, order: resultData.order, data: resultData.data, }); const isChartOversizeError = oversize || backendPivotCellsOversize || backendPivotColumnsOversize || segmentsOversize; if (isChartOversizeError) { let errorType; let limit; let current; if (backendPivotColumnsOversize) { errorType = OversizeErrorType.PivotTableColumns; limit = columnsLimit!; current = columnsCount!; } else if (backendPivotCellsOversize) { errorType = OversizeErrorType.PivotTableCells; limit = cellsLimit!; current = cellsCount; } else if (segmentsOversize) { errorType = OversizeErrorType.SegmentsNumber; limit = MAX_SEGMENTS_NUMBER; current = segmentsNumber; } else { errorType = OversizeErrorType.Default; limit = rowsLimit!; current = rowsLength!; } const oversizeError = getOversizeError({ type: errorType, limit, current: current!, }); ChartEditor._setError(oversizeError); return {}; } let { colors = [], colorsConfig, labels = [], tooltips = [], tooltipConfig, geopointsConfig, sort = [], } = shared; if ((visualization as ServerVisualizationLayer).layerSettings) { ({ geopointsConfig, colors, colorsConfig = {}, labels, tooltips, sort, shapes = [], shapesConfig = {}, tooltipConfig, } = (visualization as ServerVisualizationLayer).commonPlaceholders); } const chartColorsConfig = getChartColorsConfig({ loadedColorPalettes, colorsConfig, availablePalettes: palettes, }); const prepareFunctionArgs: PrepareFunctionArgs = { placeholders: visualization.placeholders, colors, colorsConfig: chartColorsConfig, geopointsConfig, sort, visualizationId: visualization.id, layerSettings: (visualization as ServerVisualizationLayer).layerSettings, labels, tooltips, tooltipConfig, datasets: datasetsIds, resultData, fields, idToTitle, idToDataType, shared, ChartEditor, shapes, shapesConfig, segments, layerChartMeta, usedColors, features, }; return (prepare as PrepareFunction)(prepareFunctionArgs); }
// eslint-disable-next-line complexity
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/js/js.ts#L389-L719
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
prepareGeopolygon
function prepareGeopolygon(options: PrepareFunctionArgs) { const DEFAULT_COLOR = 'rgb(77, 162, 241)'; const { colors, colorsConfig, tooltips, tooltipConfig, placeholders, resultData: {data, order}, idToTitle, shared, idToDataType, ChartEditor, } = options; const widgetConfig = ChartEditor.getWidgetConfig(); const isActionParamsEnabled = widgetConfig?.actionParams?.enable; const layerSettings = (options.layerSettings || {}) as VisualizationLayerShared['visualization']['layerSettings']; const allPolygons: Record<string, GeopolygonConfig[]> = {}; const hashTable: Record<string, string[] | {[x: string]: string}[]> = {}; const color = colors[0]; const colorFieldDataType = color ? idToDataType[color.guid] : null; const coordinates = placeholders[0].items; const gradientMode = color && colorFieldDataType && isGradientMode({colorField: color, colorFieldDataType, colorsConfig}); let colorizedResult: | ReturnType<typeof colorizeGeoByGradient> | ReturnType<typeof colorizeGeoByPalette>; let colorData = {}, leftBot: Coordinate | undefined, rightTop: Coordinate | undefined; let colorDictionary: Record<string, string> = {}; const getPolygonConfig = ({ coordinates, colorData, columnIndex, key, }: { coordinates: Coordinate[][]; colorData: SomeColorData; columnIndex: number; key: string; }): GeopolygonConfig => { const options: GeopolygonConfig['options'] = {}; const properties: {colorIndex?: number | null; rawText?: boolean} = {}; options.strokeColor = '#FFF'; options.zIndex = GEO_MAP_LAYERS_LEVEL.POLYGON; if (colorData && colorData[key]) { if (gradientMode) { options.fillColor = colorData[key].backgroundColor; options.fillColorDefault = colorData[key].backgroundColor; properties.colorIndex = (colorData as MeasureColorData)[key].value; } else { const {r, g, b} = hexToRgb((colorData as MeasureColorData)[key].backgroundColor); options.fillColor = `rgb(${r}, ${g}, ${b})`; options.fillColorDefault = `rgb(${r}, ${g}, ${b})`; properties.colorIndex = (colorData as DimensionColorData)[key].colorIndex; } if (colorsConfig.polygonBorders === 'hide') { options.strokeWidth = 0; } options.iconColor = colorData[key] ? colorData[key].backgroundColor : DEFAULT_COLOR; } return { geometry: { type: 'Polygon', coordinates, }, properties, options, columnIndex, }; }; const setPolygonTooltip = ({ polygon, text, tooltipIndex, }: { polygon: GeopolygonConfig | undefined; text: string; tooltipIndex: number; }) => { if (!polygon) { return; } const tooltip = tooltips[tooltipIndex]; const formattedText = prepareFormattedValue({ dataType: tooltip.data_type, formatting: tooltip.formatting, value: text, }); const shouldUseFieldTitle = tooltipConfig?.fieldTitle !== 'off'; const itemTitle = shouldUseFieldTitle ? getFakeTitleOrTitle(tooltip as ServerField) : ''; const tooltipText = itemTitle ? `${itemTitle}: ${formattedText}` : formattedText; const isMarkupField = tooltip?.data_type === DATASET_FIELD_TYPES.MARKUP; const useHtml = isHtmlField(tooltip); if (isMarkupField || isMarkdownField(tooltip) || useHtml) { polygon.properties.rawText = true; } if (useHtml) { ChartEditor.updateConfig({useHtml: true}); } let tooltipData; if (isMarkupField) { tooltipData = {key: itemTitle, value: formattedText}; } else if (tooltip?.markupType === MARKUP_TYPE.markdown) { tooltipData = {[WRAPPED_MARKDOWN_KEY]: tooltipText}; } else if (tooltip?.markupType === MARKUP_TYPE.html) { tooltipData = {text: wrapHtml(tooltipText)}; } else { tooltipData = {text: tooltipText}; } if (gradientMode) { if (!polygon.properties.data) { polygon.properties.data = []; } if ( !polygon.properties.data.some( (entry: {text?: string}) => entry.text === tooltipText, ) ) { polygon.properties.data[tooltipIndex] = { ...tooltipData, }; } } else { if (!polygon.properties.data) { polygon.properties.data = []; } polygon.properties.data[tooltipIndex] = { ...tooltipData, }; } }; if (color) { data.forEach((values, valuesIndex) => { hashTable[`polygons-${valuesIndex}`] = []; values.forEach((columnData, columnIndex) => { if (columnData === 'null' || columnData === null) { return; } const dataTitle = getTitleInOrder(order, columnIndex, coordinates); if (coordinates.findIndex(({title}) => title === dataTitle) !== -1) { (hashTable[`polygons-${valuesIndex}`] as string[]).push(columnData); } if (color.title === dataTitle) { hashTable[`polygons-${valuesIndex}`] = ( hashTable[`polygons-${valuesIndex}`] as string[] ).map((_coord: string, coordIndex: number) => { return {[`polygons-${valuesIndex}-${coordIndex}`]: columnData}; }); } }); }); if (gradientMode) { colorizedResult = colorizeGeoByGradient(hashTable, colorsConfig); colorData = colorizedResult.colorData; } else { colorizedResult = colorizeGeoByPalette(hashTable, colorsConfig, color.guid); colorData = colorizedResult.colorData; colorDictionary = colorizedResult.colorDictionary; } } const getTooltipIndex = ({ tooltips, dataTitle, }: { tooltips: ServerTooltip[]; dataTitle: string; }) => { if (!tooltips || tooltips.length === 0) { return -1; } return tooltips.findIndex((tooltip) => tooltip.title === dataTitle); }; data.forEach((values, valuesIndex) => { allPolygons[`polygons-${valuesIndex}`] = []; const polygons = allPolygons[`polygons-${valuesIndex}`]; const actionParams: StringParams = {}; values.forEach((columnData, columnIndex) => { if (columnData === 'null' || columnData === null) { return; } const dataTitle = getTitleInOrder(order, columnIndex, coordinates); if (coordinates.findIndex(({title}) => title === dataTitle) !== -1) { const polygonCoordinates: Coordinate[][] = JSON.parse(columnData); const flattenCoordinates = getFlattenCoordinates( polygonCoordinates, ) as Coordinate[]; // we go through the points of the polygon and adjust the boundaries of the map flattenCoordinates.forEach((current: Coordinate) => { [leftBot, rightTop] = getMapBounds({leftBot, rightTop, current}); }); polygons.push( getPolygonConfig({ colorData, columnIndex, coordinates: polygonCoordinates, key: `polygons-${valuesIndex}-${columnIndex}`, }), ); } const tooltipIndex = getTooltipIndex({tooltips, dataTitle}); const tooltipField = tooltips[tooltipIndex]; if (tooltipIndex !== -1 && polygons?.length && tooltipField) { polygons.forEach((polygon) => { setPolygonTooltip({ polygon, text: columnData, tooltipIndex, }); }); if (tooltipIndex === 0 && tooltipConfig?.color !== 'off') { polygons[0]!.properties!.data![0].color = polygons[0].options.iconColor || DEFAULT_COLOR; } addActionParamValue(actionParams, tooltipField as ServerField, columnData); } }); if (isActionParamsEnabled) { polygons.forEach((polygon) => { if (polygon) { set(polygon, 'properties.custom.actionParams', actionParams); } }); } }); const polygons = { type: 'FeatureCollection', features: getFlattenCoordinates(Object.values(allPolygons)).map((item) => { (item as GeopolygonConfig).type = 'Feature'; return item; }), }; const fillOpacity = getLayerAlpha(layerSettings); let fillOpacityHover = fillOpacity + 0.1; fillOpacityHover = fillOpacityHover > 1 ? 1 : fillOpacityHover; let mapOptions: GeopolygonMapOptions = { fillOpacity, fillOpacityHover, fillColorEmptyPolygon: DEFAULT_COLOR, strokeColorHover: '#FFF', strokeWidthHover: 2, showCustomLegend: true, }; if (shared.extraSettings && shared.extraSettings.legendMode === 'hide') { mapOptions.showLegend = false; mapOptions.showCustomLegend = false; } if (layerSettings.id) { mapOptions.geoObjectId = layerSettings.id; } mapOptions.layerTitle = layerSettings.name || options.ChartEditor.getTranslation('wizard.prepares', 'label_new-layer'); if (colorsConfig.polygonBorders === 'hide') { mapOptions.strokeWidth = 0; } if (gradientMode) { const colorTitle = color.fakeTitle || idToTitle[color.guid] || color.title; mapOptions = { ...mapOptions, ...getGradientMapOptions( colorsConfig, colorTitle, colorizedResult! as ReturnType<typeof colorizeGeoByGradient>, ), }; return [ { polygonmap: { polygons, }, options: mapOptions, bounds: [leftBot, rightTop], }, ]; } else { if (color) { mapOptions = { ...mapOptions, colorDictionary, mode: 'dictionary', colorTitle: color.fakeTitle || idToTitle[color.guid] || color.title, }; } return [ { polygonmap: { polygons, }, options: mapOptions, bounds: [leftBot, rightTop], }, ]; } }
// eslint-disable-next-line complexity
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/preparers/geopolygon.ts#L135-L486
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
getHighchartsConfig
function getHighchartsConfig(args: PrepareFunctionArgs & {graphs: any[]}) { const { placeholders, colors, colorsConfig, sort, visualizationId, shared, graphs, idToDataType, } = args; // for some reason, the vertical axis for the horizontal bar is considered the X axis const xPlaceholder = placeholders.find((p) => p.id === PlaceholderId.Y); const yPlaceholder = placeholders.find((p) => p.id === PlaceholderId.X); const xPlaceholderSettings = xPlaceholder?.settings; const x: ServerField | undefined = xPlaceholder?.items[0]; const isXDiscrete = getAxisMode(xPlaceholderSettings, x?.guid) === AxisMode.Discrete; const ySectionItems = yPlaceholder?.items || []; const colorItem = colors[0]; const chartConfig = getConfigWithActualFieldTypes({config: shared, idToDataType}); const xAxisMode = getXAxisMode({config: chartConfig}) ?? AxisMode.Discrete; const customConfig: any = { xAxis: { type: getAxisType({ field: x, settings: xPlaceholder?.settings, axisMode: xAxisMode, }), reversed: isXAxisReversed(x, sort, visualizationId as WizardVisualizationId), labels: { formatter: isDateField(x) && isXDiscrete ? ChartkitHandlers.WizardXAxisFormatter : undefined, useHTML: isHtmlField(x), }, }, axesFormatting: { yAxis: yPlaceholder?.settings?.axisFormatMode === AxisLabelFormatMode.ByField ? [getAxisFormattingByField(yPlaceholder, visualizationId)] : [], xAxis: [], }, exporting: { csv: { custom: { categoryHeader: getFieldExportingOptions(x), }, columnHeaderFormatter: ChartkitHandlers.WizardExportColumnNamesFormatter, }, }, }; if (ySectionItems.length) { if (shouldUseGradientLegend(colorItem, colorsConfig, shared)) { customConfig.colorAxis = getHighchartsColorAxis(graphs, colorsConfig); customConfig.legend = { title: { text: getFakeTitleOrTitle(colorItem), }, enabled: isLegendEnabled(shared.extraSettings), symbolWidth: null, }; } if (getIsNavigatorEnabled(shared)) { customConfig.xAxis.ordinal = isXDiscrete; } if (shared.extraSettings) { const {tooltipSum} = shared.extraSettings; if (typeof tooltipSum === 'undefined' || tooltipSum === 'on') { customConfig.enableSum = true; } } if (x && !isMeasureNameOrValue(x)) { customConfig.tooltipHeaderFormatter = getFakeTitleOrTitle(x); } const [layerYPlaceholder] = getYPlaceholders(args); if (layerYPlaceholder?.settings?.axisFormatMode === AxisLabelFormatMode.ByField) { customConfig.axesFormatting.xAxis.push( getAxisFormattingByField(layerYPlaceholder, visualizationId), ); } } const shouldUseHtmlForLegend = isHtmlField(colorItem); if (shouldUseHtmlForLegend) { set(customConfig, 'legend.useHTML', true); } return customConfig; }
// eslint-disable-next-line complexity
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/preparers/bar-y/highcharts.ts#L35-L135
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
prepareGeopoint
function prepareGeopoint(options: PrepareFunctionArgs, {isClusteredPoints = false} = {}) { const { colors, colorsConfig, tooltips, tooltipConfig, labels, placeholders, resultData: {data, order}, idToTitle, shared, idToDataType, features, ChartEditor, } = options; const widgetConfig = ChartEditor.getWidgetConfig(); const isActionParamsEnabled = widgetConfig?.actionParams?.enable; const geopointsConfig = (options.geopointsConfig || {}) as PointSizeConfig; const layerSettings = (options.layerSettings || {}) as VisualizationLayerShared['visualization']['layerSettings']; const ALPHA = getLayerAlpha(layerSettings); const allPoints: Record<string, GeopointPointConfig[]> = {}; const colorValues: number[] = []; const color = colors[0]; const colorFieldDataType = color ? idToDataType[color.guid] : null; const gradientMode = color && colorFieldDataType && isGradientMode({colorField: color, colorFieldDataType, colorsConfig}); const size = placeholders[1].items[0]; const coordinates = placeholders[0].items; const updatedTooltips = [...tooltips]; const shouldEscapeUserValue = features[Feature.EscapeUserHtmlInDefaultHcTooltip]; const label = labels[0]; let colorData: Record<string, string> = {}, gradientOptions: GradientOptions | null = null, sizeMinValue: number | undefined, sizeMaxValue: number | undefined, leftBot: Coordinate | undefined, rightTop: Coordinate | undefined; const colorDictionary: Record<string, string> = {}; const getTooltip = (dataTitle: string) => updatedTooltips.find((tooltip) => dataTitle === tooltip.title); // we get the min and max for the radius, as well as the gradient values if (size || color) { data.forEach((values) => { values.forEach((columnData, columnIndex) => { if (columnData === 'null' || columnData === null) { return; } const dataTitle = getTitleInOrder(order, columnIndex, coordinates); if (size && size.title === dataTitle) { const value = Number(columnData); [sizeMinValue, sizeMaxValue] = getExtremeValues({ min: sizeMinValue, max: sizeMaxValue, value, }); } if (color && color.title === dataTitle) { const colorValue = Number(columnData); if (!isNaN(colorValue)) { colorValues.push(colorValue); } } }); }); } if (gradientMode) { const gradientThresholdValues = getThresholdValues(colorsConfig, colorValues); const {min, rangeMiddle, max} = gradientThresholdValues; colorData = getColorsByMeasureField({ values: colorValues, colorsConfig, gradientThresholdValues, }); gradientOptions = { min: min, mid: min + rangeMiddle, max: max, }; } let colorIndex = -1; if (color) { const cTitle = idToTitle[color.guid]; colorIndex = findIndexInOrder(order, color, cTitle); } const colorsByValue = new Map<string, string>(); data.forEach((values, valuesIndex) => { // at each pass of the string, we collect the points into an array, assuming, // that there can be more than one pair of coordinates in a row allPoints[`points-${valuesIndex}`] = []; const actionParams: Record<string, any> = {}; // eslint-disable-next-line complexity values.forEach((columnData, columnIndex) => { if (columnData === 'null' || columnData === null) { return; } const dataTitle = getTitleInOrder(order, columnIndex, coordinates); if (coordinates.findIndex(({title}) => title === dataTitle) !== -1) { const current = JSON.parse(columnData); // adjusting the borders of the map [leftBot, rightTop] = getMapBounds({leftBot, rightTop, current}); allPoints[`points-${valuesIndex}`].push( getPointConfig({ columnIndex, stringifyedCoordinates: columnData, geopointsConfig, }), ); } if (size && size.title === dataTitle) { const radius = getPointRadius({ current: Number(columnData), min: sizeMinValue!, max: sizeMaxValue!, geopointsConfig, }); allPoints[`points-${valuesIndex}`].forEach((point) => setPointProperty({ point, propName: 'radius', propValue: radius, }), ); } if (label && label.title === dataTitle) { allPoints[`points-${valuesIndex}`].forEach((point) => setPointProperty({ point, propName: 'label', propValue: columnData, propType: label.data_type, formatting: label.formatting, }), ); } if (color && color.title === dataTitle) { const colorValue = escape(values[colorIndex] as string); let iconColor = DEFAULT_ICON_COLOR; if (colorValue) { if (gradientMode) { const key = isNaN(Number(colorValue)) ? colorValue : String(Number(colorValue)); if (colorData[key]) { iconColor = colorData[key]; } } else { let mountedColor = getMountedColor(colorsConfig, colorValue); if (!mountedColor || mountedColor === 'auto') { if (!colorsByValue.has(colorValue)) { const key = colorsConfig.colors[ colorsByValue.size % colorsConfig.colors.length ]; colorsByValue.set(colorValue, key); } mountedColor = colorsByValue.get(colorValue) || DEFAULT_ICON_COLOR; } iconColor = mountedColor; colorDictionary[colorValue] = mountedColor; } } allPoints[`points-${valuesIndex}`].forEach((point) => { point.options.iconColor = iconColor; }); } const tooltipField = tooltips.length ? (getTooltip(dataTitle) as ServerField) : undefined; if (tooltipField) { // Due to the fact that a field that already exists in another section can be installed in a section with a tooltip, // it (the field in the tooltip and other section) comes to the order array in a single instance, // which in turn can lead to an incorrect order of displaying fields in the tooltip. // Therefore, before installing the tooltip, we remember its correct index const index = updatedTooltips.findIndex((t) => t.title === dataTitle); const shouldUseFieldTitle = tooltipConfig?.fieldTitle !== 'off'; const itemTitle = shouldUseFieldTitle ? getFakeTitleOrTitle(tooltipField) : ''; const pointData: Record<string, unknown> = {}; if (isMarkupDataType(tooltipField.data_type)) { pointData.key = itemTitle; pointData.value = columnData; } else { const value = prepareValue( columnData, tooltipField.data_type, tooltipField.formatting, ); const text = itemTitle ? `${itemTitle}: ${value}` : value; switch (tooltipField?.markupType) { case MARKUP_TYPE.markdown: { pointData[WRAPPED_MARKDOWN_KEY] = text; break; } case MARKUP_TYPE.html: { pointData.text = wrapHtml(text); break; } default: { pointData.text = shouldEscapeUserValue ? escape(text) : text; break; } } } allPoints[`points-${valuesIndex}`].forEach((point: GeopointPointConfig) => { if (!point) { return; } if (!point.feature.properties.data) { point.feature.properties.data = []; } if (index === 0 && tooltipConfig?.color !== 'off') { pointData.color = point.options.iconColor; } point.feature.properties.data[index] = pointData; }); addActionParamValue(actionParams, tooltipField, columnData); } if (isActionParamsEnabled) { allPoints[`points-${valuesIndex}`].forEach((point: GeopointPointConfig) => { set(point, 'feature.properties.custom.actionParams', actionParams); }); } }); }); if (tooltips.some((item) => item.markupType === MARKUP_TYPE.markdown)) { ChartEditor.updateConfig({useMarkdown: true}); } if (tooltips.some((item) => item.markupType === MARKUP_TYPE.html)) { ChartEditor.updateConfig({useHtml: true}); } let mapOptions: GeopointMapOptions = { opacity: ALPHA, showCustomLegend: true, }; if (shared.extraSettings && shared.extraSettings.legendMode === 'hide') { mapOptions.showCustomLegend = false; } if (layerSettings.id) { mapOptions.geoObjectId = layerSettings.id; } mapOptions.layerTitle = layerSettings.name || ChartEditor.getTranslation('wizard.prepares', 'label_new-layer'); if (size) { mapOptions = { ...mapOptions, sizeMinValue, sizeMaxValue, sizeTitle: size.fakeTitle || idToTitle[size.guid] || size.title, }; } if (gradientOptions) { const colorTitle = color.fakeTitle || idToTitle[color.guid] || color.title; mapOptions = { ...mapOptions, ...getGradientMapOptions(colorsConfig, colorTitle, gradientOptions), }; return [ { collection: { children: getFlattenCoordinates(Object.values(allPoints)), }, options: mapOptions, bounds: [leftBot, rightTop], }, ]; } else { mapOptions = { ...mapOptions, }; if (color) { mapOptions.colorDictionary = colorDictionary; mapOptions.mode = 'dictionary'; mapOptions.colorTitle = color.fakeTitle || idToTitle[color.guid] || color.title; } } const resultData = { options: mapOptions, bounds: [leftBot, rightTop], }; const flatternCoordinates = getFlattenCoordinates(Object.values(allPoints)); if (isClusteredPoints) { return [ { ...resultData, clusterer: flatternCoordinates, options: { ...resultData.options, clusterIconLayout: 'default#pieChart', iconPieChartCoreRadius: 15, iconPieChartRadius: 20, iconPieChartStrokeWidth: 1, hasBalloon: false, margin: 20, }, }, ]; } return [ { ...resultData, collection: { children: flatternCoordinates, }, }, ]; }
// eslint-disable-next-line complexity
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/preparers/geopoint/index.ts#L114-L478
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
prepareLineTime
function prepareLineTime(options: PrepareFunctionArgs) { const {placeholders, resultData, colors, idToTitle, colorsConfig, shared, ChartEditor} = options; const {data, order} = resultData; const xField = placeholders[0].items[0]; if (!xField) { return {timeline: []}; } const xFieldDataType = xField.data_type; const xFieldIndex = findIndexInOrder(order, xField, idToTitle[xField.guid] || xField.title); const xFieldIsDate = isDateField(xField); const yPlaceholderSettings = placeholders[1]?.settings || {}; const yFields = placeholders[1].items; const yFieldIndexes = yFields.map((yField) => findIndexInOrder(order, yField, idToTitle[yField.guid] || yField.title), ); const colorIndexes = colors.map((color) => findIndexInOrder(order, color, idToTitle[color.guid] || color.title), ); const result: QLRenderResultYagr = {timeline: [], timeZone: 'UTC'}; if (yFields.length > 0 && xField) { let xValues: QLValue[] = []; let colorValues: QLValue[] = []; const dataMatrix: Record<string, number | null | Record<string | number, number | null>> = {}; data.forEach((row) => { let xValue: QLValue = row[xFieldIndex]; if (typeof xValue !== 'undefined' && xValue !== null && xFieldIsDate) { // CHARTS-6632 - revision/study of yagr is necessary, after that moment.utc(xValue) is possible.valueOf(); xValue = (getUtcDateTime(xValue)?.valueOf() || 0) / 1000; } else if (xFieldDataType === DATALENS_QL_TYPES.UNKNOWN) { xValue = formatUnknownTypeValue(xValue); } xValues.push(xValue); yFieldIndexes.forEach((yFieldIndex, i) => { const yValue = row[yFieldIndex]; if (colorIndexes.length > 0) { let colorValue = ''; colorIndexes.forEach((colorIndex, j) => { const colorValuePart: QLValue = colors[j].type === 'PSEUDO' ? yFields[i].title : row[colorIndex]; colorValue = getLineTimeDistinctValue(colorValuePart, colorValue); }); let dataCell = dataMatrix[String(xValue)] as Record< string | number, number | null >; if (typeof dataCell === 'undefined') { dataCell = dataMatrix[String(xValue)] = {}; } if (typeof dataCell === 'object' && dataCell !== null) { dataCell[String(colorValue)] = parseNumberValue(yValue); } colorValues.push(colorValue); } else { dataMatrix[String(xValue)] = parseNumberValue(yValue); } }); }); xValues = Array.from(new Set(xValues)).sort(); colorValues = Array.from(new Set(colorValues)).sort(); result.timeline = xValues.map((value) => Number(value)); if (colors.length > 0) { const graphs: QLRenderResultYagrGraph[] = colorValues.map((colorValue) => { return { id: renderValue(colorValue), name: renderValue(colorValue), colorValue: renderValue(colorValue), colorGuid: colors[0].guid || null, color: 'rgb(0,127,0)', data: [], }; }); xValues.forEach((xValue) => { const dataCell = dataMatrix[String(xValue)] as Record<string | number, number>; if (typeof dataCell === 'object' && dataCell !== null) { colorValues.forEach((colorValue: QLValue, i) => { if (typeof dataCell[String(colorValue)] === 'undefined') { if (yPlaceholderSettings.nulls === AxisNullsMode.AsZero) { graphs[i].data.push(0); } else { graphs[i].data.push(null); } } else { graphs[i].data.push(dataCell[String(colorValue)]); } }); } }); result.graphs = graphs; } else { result.graphs = []; yFields.forEach((y) => { const graph = { id: y.title, name: y.title, data: xValues.map((xValue) => { return dataMatrix[String(xValue)] as number; }), }; const formatting = y.formatting as CommonNumberFormattingOptions | undefined; const tooltipOptions = getFormatOptionsFromFieldFormatting(formatting, y.data_type); // TODO: add other options when they will be available in Chartkit // https://github.com/gravity-ui/chartkit/issues/476 ChartEditor.updateLibraryConfig({ tooltip: { precision: tooltipOptions.chartKitPrecision, }, }); result.graphs?.push(graph); }); } } else if (xField) { let xValues: QLValue[] = []; data.forEach((row) => { let xValue: QLValue = row[xFieldIndex]; if (typeof xValue !== 'undefined' && xValue !== null && xFieldIsDate) { // CHARTS-6632 - revision/study of yagr is necessary, after that moment.utc(xValue) is possible.valueOf(); xValue = (getUtcDateTime(xValue)?.valueOf() || 0).valueOf() / 1000; } else if (xFieldDataType === DATALENS_QL_TYPES.UNKNOWN) { xValue = formatUnknownTypeValue(xValue); } xValues.push(xValue); }); xValues = Array.from(new Set(xValues)).sort(); result.timeline = xValues.map((value) => Number(value)); result.graphs = [ { data: data.map(() => { return null; }), }, ]; return result; } else { result.graphs = []; return result; } result.graphs.sort((graph1, graph2) => { if (graph1.name && graph2.name) { return collator.compare(String(graph1.name), String(graph2.name)); } else { return 0; } }); const useColorizingWithPalettes = colorsConfig.mountedColors && Object.keys(colorsConfig.mountedColors).length > 0; if (useColorizingWithPalettes) { // Use usual colorizing with datalens palettes mapAndColorizeGraphsByPalette({ graphs: result.graphs as unknown as ExtendedSeriesLineOptions[], colorsConfig, isColorsItemExists: Boolean(colors), }); } else { // Else apply colorizing from YAGR for compatibility with Monitoring let colorData: string[]; if (shared.visualization.id === 'area' && result.graphs.length > 1) { colorData = getColorsForNames( result.graphs.map(({name}) => String(name)), {type: 'gradient'}, ); } else { colorData = getColorsForNames(result.graphs.map(({name}) => String(name))); } result.graphs.forEach((graph, i) => { graph.color = colorData[i]; graph.spanGaps = yPlaceholderSettings.nulls === AxisNullsMode.Connect; }); if (result.graphs.length > 1 && isLegendEnabled(shared.extraSettings)) { ChartEditor.updateLibraryConfig({ legend: { show: true, }, }); } } result.axes = [ { scale: 'x', plotLines: [ { width: 3, color: '#ffa0a0', }, ], }, ]; return result; }
// eslint-disable-next-line complexity
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/preparers/line-time/index.ts#L34-L267
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
getHighchartsConfig
function getHighchartsConfig(args: PrepareFunctionArgs & {graphs: any[]}) { const { placeholders, colors, colorsConfig, sort, visualizationId, shared, shapes, graphs, segments, idToDataType, } = args; const xPlaceholder = placeholders.find((p) => p.id === PlaceholderId.X); const xPlaceholderSettings = xPlaceholder?.settings; const x: ServerField | undefined = xPlaceholder?.items[0]; const isXDiscrete = getAxisMode(xPlaceholderSettings, x?.guid) === AxisMode.Discrete; const x2 = isVisualizationWithSeveralFieldsXPlaceholder(visualizationId) ? xPlaceholder?.items[1] : undefined; const yPlaceholder = placeholders.find((p) => p.id === PlaceholderId.Y); const y2Placeholder = placeholders.find((p) => p.id === PlaceholderId.Y2); const ySectionItems = yPlaceholder?.items || []; const y2SectionItems = y2Placeholder?.items || []; const mergedYSections = [...ySectionItems, ...y2SectionItems]; const colorItem = colors[0]; const shapeItem = shapes[0]; const segment = segments[0]; const segmentsMap = getSegmentMap(args); const xField = x ? ({guid: x.guid, data_type: idToDataType[x.guid]} as Field) : x; const chartConfig = getConfigWithActualFieldTypes({config: shared, idToDataType}); const xAxisMode = getXAxisMode({config: chartConfig}); const xAxisType = getAxisType({ field: xField, settings: xPlaceholder?.settings, axisMode: xAxisMode, }); const customConfig: any = { xAxis: { type: xAxisType, reversed: isXAxisReversed(x, sort, visualizationId as WizardVisualizationId), labels: { formatter: isDateField(x) && xAxisType === 'category' ? ChartkitHandlers.WizardXAxisFormatter : undefined, useHTML: isHtmlField(x), }, }, axesFormatting: { xAxis: xPlaceholder?.settings?.axisFormatMode === AxisLabelFormatMode.ByField ? [getAxisFormattingByField(xPlaceholder, visualizationId)] : [], yAxis: [], }, exporting: { csv: { custom: { categoryHeader: getFieldExportingOptions(x), }, columnHeaderFormatter: ChartkitHandlers.WizardExportColumnNamesFormatter, }, }, }; if (mergedYSections.length) { if (shouldUseGradientLegend(colorItem, colorsConfig, shared)) { customConfig.colorAxis = getHighchartsColorAxis(graphs, colorsConfig); customConfig.legend = { title: { text: getFakeTitleOrTitle(colorItem), }, enabled: isLegendEnabled(shared.extraSettings), symbolWidth: null, }; } if (getIsNavigatorEnabled(shared)) { customConfig.xAxis.ordinal = isXDiscrete; } if (shared.extraSettings) { const {tooltipSum} = shared.extraSettings; if (typeof tooltipSum === 'undefined' || tooltipSum === 'on') { customConfig.enableSum = true; } } if (x && !isMeasureNameOrValue(x)) { customConfig.tooltipHeaderFormatter = getFakeTitleOrTitle(x); } if (_isEmpty(segmentsMap)) { const [layerYPlaceholder, layerY2Placeholder] = getYPlaceholders(args); if (layerYPlaceholder?.settings?.axisFormatMode === AxisLabelFormatMode.ByField) { customConfig.axesFormatting.yAxis.push( getAxisFormattingByField(layerYPlaceholder, visualizationId), ); } if (layerY2Placeholder?.settings?.axisFormatMode === AxisLabelFormatMode.ByField) { if (customConfig.axesFormatting.yAxis.length === 0) { customConfig.axesFormatting.yAxis.push({}); } customConfig.axesFormatting.yAxis.push( getAxisFormattingByField(layerY2Placeholder, visualizationId), ); } } else { customConfig.legend = { enabled: Boolean( colorItem || shapeItem || x2 || ySectionItems.length > 1 || y2SectionItems.length > 1, ) && isLegendEnabled(shared.extraSettings), }; const {yAxisFormattings, yAxisSettings} = getSegmentsYAxis({ segment, segmentsMap, placeholders: { y: yPlaceholder, y2: y2Placeholder, }, visualizationId, }); customConfig.yAxis = yAxisSettings; customConfig.axesFormatting.yAxis = yAxisFormattings; } } const shouldUseHtmlForLegend = [colorItem, shapeItem].some(isHtmlField); if (shouldUseHtmlForLegend) { set(customConfig, 'legend.useHTML', true); } return customConfig; }
// eslint-disable-next-line complexity
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/preparers/line/highcharts.ts#L39-L185
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
preparePivotTable
function preparePivotTable({ placeholders, resultData, colors, sort, colorsConfig, idToTitle, idToDataType, ChartEditor, }: PrepareFunctionArgs) { const {data, order} = resultData; // Fields dragged into "columns" const c: any[] = placeholders[0].items; // Types of fields dragged into "columns" const cTypes = c.map((item) => idToDataType[item.guid] || item.data_type); // Fields dragged into "rows" const r: any[] = placeholders[1].items; // Types of fields dragged into "rows" const rTypes = r.map((item) => idToDataType[item.guid] || item.data_type); // Fields dragged into "indicators" const m = placeholders[2].items; // Types of fields dragged into "indicators" const mTypes = m.map((item) => idToDataType[item.guid] || item.data_type); // Fields dragged into "sorting" const s = sort; // Number of fields dragged into "columns" const cl = c.length; // Number of fields dragged into "rows" const rl = r.length; // Number of fields dragged into "indicators" const ml = m.length; // Number of fields dragged into "sorting" const sl = s.length; // Enumeration of unique values for the lowercase header by levels // The lowercase header is the vertical header on the left in the table const headRow: any[] = []; // Enumeration of unique values for columnar caps by levels // A columnar header is a horizontal header at the top of the table const headColumn: any[] = []; // Table "cell key (intersection of row and column)" - "value in cell" const hashTable: Record<string, any> = {}; // Table "cell key (intersection of row and column)" - "formatted value in cell" const hashTableFormatted: Record<string, any> = {}; // Table "cell key (intersection of row and column)" - "type of value in the cell" const typeTable: Record<string, any> = {}; // Table "cell key (intersection of row and column)" - "color of the value in the cell" const colorHashTable: Record<string, any> = {}; // Flag indicating that more than 1 metric is used let multimeasure = false; // Flag, meaning that the pseudo-field "Measure Names" in the lowercase header let measureNamesInRow = false; // Flag, meaning that the pseudo-field "Measure Names" in the columnar cap let measureNamesLevel: any = null; // Service flag telling data-table to use grouping const useGroup = rl > 1; // Array of displayed indicator names const measureNames = m.map((measureItem) => { return measureItem.fakeTitle || idToTitle[measureItem.guid]; }); if (ml > 1) { multimeasure = true; } // Flag indicating that the "Measure Names" pseudo field is present in the visualization let measureNamesExists = false; // Flag indicating that the "lowercase" header will not be displayed let hideHeadRows = false; // Table "displayed field name" - "its index in the back response" const indices: Record<string, any> = {}; // Table "columnar key" - "true/false" // (depending on whether there are values for this key) const hashTableCKeys: Record<string, any> = {}; const colorHashTableCKeys: Record<string, any> = {}; // Table "lowercase key" - "true/false" // (depending on whether there are values for this key) const hashTableRKeys: Record<string, any> = {}; const colorHashTableRKeys: Record<string, any> = {}; // Table "columnar key or part of it" - "true/false" // (depending on whether there are values for this key) // Auxiliary table to reduce the number of iterations // when generating a columnar header const auxHashTableCKeys: Record<string, any> = {}; // Table "lowercase key or part of it" - "true/false" // (depending on whether there are values for this key) // Auxiliary table to reduce the number of iterations // when generating a lowercase header const auxHashTableRKeys: Record<string | number, any> = {}; // Report point for debugging time metrics const startTime = new Date(); // Table "level - value - true/false" for columnar header // Auxiliary table to speed up the analysis of data from the backup // Previously, indexOf was used const headColumnMapping: Record<string | number, any> = {}; // Table "level - value - true/false" for the lowercase header // Auxiliary table to speed up the analysis of data from the backup // Previously, indexOf was used const headRowMapping: Record<string | number, any> = {}; // An object that stores the number of unique parts of lowercase keys for each level // Used to estimate the execution time const urcountbylvl: Record<string | number, any> = {}; // An object that stores the number of existing parts of lowercase keys for each level // Used to estimate the execution time const ercountbylvl: Record<string | number, any> = {}; // An object that stores the number of unique parts of columnar keys for each level // Used to estimate the execution time const uccountbylvl: Record<string | number, any> = {}; // An object that stores the number of existing parts of columnar keys for each level // Used to estimate the execution time const eccountbylvl: Record<string | number, any> = {}; // Determining where the "Measure Names" is located // "Measure Names" cannot be if there are no indicators if (ml > 0) { if ( r.some((item, level) => { if (item.type === 'PSEUDO') { measureNamesLevel = level; measureNamesExists = true; return true; } else { return false; } }) ) { measureNamesInRow = true; } else { c.some((item, level) => { if (item.type === 'PSEUDO') { measureNamesLevel = level; measureNamesExists = true; return true; } else { return false; } }); } } // We determine the lack of headers if (!rl && !cl) { if (ml) { c.push({ type: 'PSEUDO', title: 'Measure Names', }); measureNamesExists = true; } hideHeadRows = true; measureNamesLevel = measureNamesLevel || 0; } else if (!cl) { if (!measureNamesExists) { if (ml) { c.push({ type: 'PSEUDO', title: 'Measure Names', }); measureNamesExists = true; } measureNamesLevel = 0; } } else if (!rl) { if (!measureNamesExists) { if (ml) { r.push({ type: 'PSEUDO', title: 'Measure Names', }); measureNamesExists = true; measureNamesInRow = true; } measureNamesLevel = 0; } } // We begin a line-by-line analysis of the data from the backup data.forEach((values) => { // Array storing a columnar key const cPath: any[] = []; let replaceMeasureName = false; c.forEach((headColumnItem, level) => { if (headColumnItem.type === 'PSEUDO') { cPath.push('$measureName$'); const cKey = cPath.join(SPECIAL_DELIMITER); if (!auxHashTableCKeys[cKey]) { auxHashTableCKeys[cKey] = true; } measureNames.forEach((measureName) => { const customRKey = cKey.replace('$measureName$', measureName); if (!auxHashTableCKeys[customRKey]) { auxHashTableCKeys[customRKey] = true; } }); replaceMeasureName = true; if (!eccountbylvl[level]) { eccountbylvl[level] = measureNames.length; } if (!uccountbylvl[level]) { uccountbylvl[level] = measureNames.length; } return; } const actualTitle = idToTitle[headColumnItem.guid]; const actualDataType = idToDataType[headColumnItem.guid]; let i; if (typeof indices[actualTitle] === 'undefined') { i = indices[actualTitle] = findIndexInOrder(order, headColumnItem, actualTitle); } else { i = indices[actualTitle]; } let value = values[i]; let stringifiedValue = String(undefined); if (actualDataType === 'markup') { stringifiedValue = JSON.stringify(value); } if (!headColumnMapping[level]) { headColumnMapping[level] = {}; } if (Array.isArray(headColumn[level])) { const levelValues = headColumn[level]; if (actualDataType === 'markup') { if (!headColumnMapping[level][stringifiedValue]) { ++uccountbylvl[level]; levelValues.push(value); headColumnMapping[level][stringifiedValue] = true; } } else if (!headColumnMapping[level][String(value)]) { ++uccountbylvl[level]; levelValues.push(value); headColumnMapping[level][String(value)] = true; } } else { if (actualDataType === 'markup') { headColumnMapping[level] = {[stringifiedValue]: true}; } else { headColumnMapping[level] = {[String(value)]: true}; } uccountbylvl[level] = 1; headColumn[level] = [value]; } if (value === null) { value = '__null'; } else if (typeof value === 'undefined') { value = '__undefined'; } if (actualDataType === 'markup') { cPath.push(stringifiedValue); } else { cPath.push(value); } const cKey = cPath.join(SPECIAL_DELIMITER); if (!auxHashTableCKeys[cKey]) { auxHashTableCKeys[cKey] = true; if (replaceMeasureName) { measureNames.forEach((measureName) => { const customCKey = cKey.replace('$measureName$', measureName); if (!auxHashTableCKeys[customCKey]) { auxHashTableCKeys[customCKey] = true; } }); } if (eccountbylvl[level]) { ++eccountbylvl[level]; } else { eccountbylvl[level] = 1; } } }); const rPath: any[] = []; r.forEach((headRowItem, level) => { if (headRowItem.type === 'PSEUDO') { rPath.push('$measureName$'); const rKey = rPath.join(SPECIAL_DELIMITER); if (!auxHashTableRKeys[rKey]) { auxHashTableRKeys[rKey] = true; } measureNames.forEach((measureName) => { const customRKey = rKey.replace('$measureName$', measureName); if (!auxHashTableRKeys[customRKey]) { auxHashTableRKeys[customRKey] = true; } }); replaceMeasureName = true; if (!ercountbylvl[level]) { ercountbylvl[level] = measureNames.length; } if (!urcountbylvl[level]) { urcountbylvl[level] = measureNames.length; } return; } const actualTitle = idToTitle[headRowItem.guid]; const actualDataType = idToDataType[headRowItem.guid]; let i; if (typeof indices[actualTitle] === 'undefined') { i = indices[actualTitle] = findIndexInOrder(order, headRowItem, actualTitle); } else { i = indices[actualTitle]; } let value = values[i]; let stringifiedValue = String(undefined); if (actualDataType === 'markup') { stringifiedValue = JSON.stringify(value); } if (!headRowMapping[level]) { headRowMapping[level] = {}; } if (Array.isArray(headRow[level])) { const levelValues = headRow[level]; if (actualDataType === 'markup') { if (!headRowMapping[level][stringifiedValue]) { ++urcountbylvl[level]; levelValues.push(value); headRowMapping[level][stringifiedValue] = true; } } else if (!headRowMapping[level][String(value)]) { ++urcountbylvl[level]; levelValues.push(value); headRowMapping[level][String(value)] = true; } } else { if (actualDataType === 'markup') { headRowMapping[level] = {[stringifiedValue]: true}; } else { headRowMapping[level] = {[String(value)]: true}; } urcountbylvl[level] = 1; headRow[level] = [value]; } if (value === null) { value = '__null'; } else if (typeof value === 'undefined') { value = '__undefined'; } if (actualDataType === 'markup') { rPath.push(stringifiedValue); } else { rPath.push(value); } const rKey = rPath.join(SPECIAL_DELIMITER); if (!auxHashTableRKeys[rKey]) { auxHashTableRKeys[rKey] = true; if (replaceMeasureName) { measureNames.forEach((measureName) => { const customRKey = rKey.replace('$measureName$', measureName); if (!auxHashTableRKeys[customRKey]) { auxHashTableRKeys[customRKey] = true; } }); } if (ercountbylvl[level]) { ++ercountbylvl[level]; } else { ercountbylvl[level] = 1; } } }); const cKey = cPath.join(SPECIAL_DELIMITER); const rKey = rPath.join(SPECIAL_DELIMITER); // Getting the full key // The intersection of a line and a line is the union of a lowercase and columnar key const key = `${cKey};${rKey}`; // eslint-disable-next-line complexity m.forEach((measureItem) => { const actualTitle = idToTitle[measureItem.guid]; const {data_type: dataType} = measureItem; const shownTitle = measureItem.fakeTitle || idToTitle[measureItem.guid]; let i; if (typeof indices[actualTitle] === 'undefined') { i = indices[actualTitle] = findIndexInOrder(order, measureItem, actualTitle); } else { i = indices[actualTitle]; } let value: string | number | null = values[i]; let formattedValue = ''; if (value !== null) { if (isNumericalDataType(dataType)) { value = Number(value); formattedValue = chartKitFormatNumberWrapper(value, { lang: 'ru', ...(measureItem.formatting ?? { precision: isFloatDataType(dataType) ? MINIMUM_FRACTION_DIGITS : 0, }), }); } else if (isDateField(measureItem)) { value = getTimezoneOffsettedTime(new Date(value)); } } // If necessary, you need to supplement the key with a pseudo-field "Measure Names" if (measureNamesExists || !rl || !cl) { let rPathSpecial: any = [...rPath]; let cPathSpecial: any = [...cPath]; rPathSpecial = rPathSpecial.join(SPECIAL_DELIMITER); cPathSpecial = cPathSpecial.join(SPECIAL_DELIMITER); if (measureNamesInRow) { rPathSpecial = rPathSpecial.replace('$measureName$', shownTitle); } else { cPathSpecial = cPathSpecial.replace('$measureName$', shownTitle); } if (!hashTableRKeys[rPathSpecial]) { hashTableRKeys[rPathSpecial] = true; } if (!hashTableCKeys[cPathSpecial]) { hashTableCKeys[cPathSpecial] = true; } if (!auxHashTableRKeys[rPathSpecial]) { auxHashTableRKeys[rPathSpecial] = true; } if (!auxHashTableCKeys[cPathSpecial]) { auxHashTableCKeys[cPathSpecial] = true; } const specialKey = `${cPathSpecial};${rPathSpecial}`; hashTable[specialKey] = [value]; hashTableFormatted[specialKey] = [formattedValue]; typeTable[specialKey] = dataType; if (colors.length) { const actualColorTitle = idToTitle[colors[0].guid]; let j; if (typeof indices[actualColorTitle] === 'undefined') { j = indices[actualColorTitle] = findIndexInOrder( order, colors[0], actualColorTitle, ); } else { j = indices[actualColorTitle]; } colorHashTable[specialKey] = values[j]; } } else { hashTable[key] = [value]; hashTableFormatted[key] = [formattedValue]; typeTable[key] = dataType; const rKey = rPath.join(SPECIAL_DELIMITER); const cKey = cPath.join(SPECIAL_DELIMITER); if (!hashTableRKeys[rKey]) { hashTableRKeys[rKey] = true; } if (!hashTableCKeys[cKey]) { hashTableCKeys[cKey] = true; } } }); if (!multimeasure) { if (colors.length) { const actualColorTitle = idToTitle[colors[0].guid]; let i; if (typeof indices[actualColorTitle] === 'undefined') { i = indices[actualColorTitle] = findIndexInOrder( order, colors[0], actualColorTitle, ); } else { i = indices[actualColorTitle]; } const value = values[i]; colorHashTableCKeys[cKey] = true; colorHashTableRKeys[rKey] = true; colorHashTable[key] = value; } } }); if (sl) { s.forEach((sortItem) => { r.forEach((item, level) => { if (sortItem.guid === item.guid) { if (headRow[level]) { headRow[level].sort(sorter); if (sortItem.direction !== 'ASC') { headRow[level].reverse(); } } } }); c.forEach((item, level) => { if (sortItem.guid === item.guid) { if (headColumn[level]) { headColumn[level].sort(sorter); if (sortItem.direction !== 'ASC') { headColumn[level].reverse(); } } } }); }); } else { r.forEach((item, level) => { if (item.type !== 'PSEUDO') { if (headRow[level]) { headRow[level].sort(sorter); } } }); c.forEach((item, level) => { if (item.type !== 'PSEUDO') { if (headColumn[level]) { headColumn[level].sort(sorter); } } }); } // At this stage, after 0.5-1.5 seconds, we can cut off the execution, // if we understand that we will not meet the 10-second limit // The time for which the initial analysis of data from the backend occurred const initTime = (new Date() as unknown as number) - (startTime as unknown as number); logTiming('Inited', initTime); // "Predicted Head Row Iterations Count" // Number of iterations required to generate a lowercase header let phric = ercountbylvl[0] || 1; if (rl > 1) { for (let i = 1; i < rl; ++i) { phric += ercountbylvl[i - 1] * urcountbylvl[i]; } } // "Predicted Head Column Iterations Count" // The number of iterations that will be required to generate a columnar header let phcic = eccountbylvl[0] || 1; if (cl > 1) { for (let i = 1; i < cl; ++i) { phcic += eccountbylvl[i - 1] * uccountbylvl[i]; } } // Experiments have shown that each iteration of generating caps // takes ~0.0006-0.0015 ms // Therefore, we can say in advance how long it will take to generate these caps const TIME_FOR_HEAD_GENERATION_ITERATION = 0.0012; const thric = phric * TIME_FOR_HEAD_GENERATION_ITERATION; const thcic = phcic * TIME_FOR_HEAD_GENERATION_ITERATION; // A similar dependency with the execution of getPaths: const TIME_FOR_GET_PATHS_ITERATION = 0.003; const tpric = phric * TIME_FOR_GET_PATHS_ITERATION; const tpcic = phcic * TIME_FOR_GET_PATHS_ITERATION; // And a similar dependency with the last nested loop: const TIME_FOR_DATA_LOOP_ITERATION = 0.003; const flic = Object.keys(hashTableRKeys).length * Object.keys(hashTableCKeys).length * TIME_FOR_DATA_LOOP_ITERATION; // The allowed limit is 10 seconds // It's already been - "initTime" seconds // Also, probably, we don't want users to draw end-to-end under 10 seconds of the table // Let's take another buffer in 1 second const SECOND = 1000; const ALLOWED_EXECUTON_TIME = 10000; const estimatedResultTime = thric + thcic + tpric + tpcic + flic + initTime + SECOND; log('estimated result time:', estimatedResultTime); if (estimatedResultTime > ALLOWED_EXECUTON_TIME) { ChartEditor._setError({ code: 'ERR.CHARTS.ROWS_NUMBER_OVERSIZE', details: { estimatedResultTime, }, }); return {}; } // We determine in which header we put Measure Names if (ml) { if (measureNamesInRow) { headRow[measureNamesLevel] = measureNames; } else { headColumn[measureNamesLevel] = measureNames; } } // Lowercase header generation function function generateHeadRows() { function generateHeadRowLevel(level: any, accumulated: any): any[] { const localResult: any[] = []; accumulated.forEach((accumulatedRow: any) => { const keyPrefix = accumulatedRow.length ? accumulatedRow .map((cell: any) => { return cell.originalValue; }) .join(SPECIAL_DELIMITER) : null; headRow[level].forEach((headRowLevel: any) => { let value = headRowLevel; let formattedValue = ''; let originalValue = headRowLevel; if (originalValue === null) { originalValue = '__null'; } else if (typeof originalValue === 'undefined') { originalValue = '__undefined'; } if (rTypes[level] === 'markup') { originalValue = JSON.stringify(value); } const currentKey = keyPrefix === null ? originalValue : `${keyPrefix}${SPECIAL_DELIMITER}${originalValue}`; if (!auxHashTableRKeys[currentKey]) { return; } if (headRowLevel === null) { value = null; } else if (isDateField({data_type: rTypes[level]})) { value = formatDate({ valueType: rTypes[level], value: headRowLevel, format: r[level].format, }); } else if (isNumericalDataType(rTypes[level]) && r[level]?.formatting) { formattedValue = chartKitFormatNumberWrapper(Number(headRowLevel), { lang: 'ru', ...r[level].formatting, }); } const cell = { value, originalValue, formattedValue, key: currentKey, css: { fontSize: '13px', lineHeight: '15px', }, }; localResult.push([...accumulatedRow, cell]); }); }); if (headRow[level + 1]) { return generateHeadRowLevel(level + 1, localResult); } else { return localResult; } } let rows; if (headRow[0]) { rows = generateHeadRowLevel(0, [[]]); let rowId = 0; rows = rows.map((cells) => { const row = { cells, id: ++rowId, }; return row; }); } else { rows = [{cells: []}]; } return rows; } // Header cap generation function function generateHeadColumns() { let headerId = 0; function generateHeadColumnLevel(level: any, key?: any) { return ( headColumn[level] // eslint-disable-next-line complexity .map((entry: any, entryIndex: number) => { const cell: any = { id: ++headerId, type: 'text', }; let mType; let mItem; let value = entry; if (value === null) { value = '__null'; } if (typeof value === 'undefined') { value = '__undefined'; } const cType = cTypes[level]; if (cType === 'markup') { value = JSON.stringify(value); } if ( !measureNamesInRow && (measureNamesLevel === null || measureNamesLevel === level) ) { if (multimeasure) { mType = mTypes[entryIndex]; mItem = m[entryIndex]; } else { mType = mTypes[0]; mItem = m[0]; } if (isNumericalDataType(mType)) { cell.type = 'number'; cell.sortable = true; const mItemFormatting = mItem?.formatting as | CommonNumberFormattingOptions | undefined; if (mItemFormatting) { cell.formatter = { format: mItemFormatting.format, suffix: mItemFormatting.postfix, prefix: mItemFormatting.prefix, showRankDelimiter: mItemFormatting.showRankDelimiter, unit: mItemFormatting.unit, precision: mType === DATASET_FIELD_TYPES.FLOAT && typeof mItemFormatting.precision !== 'number' ? MINIMUM_FRACTION_DIGITS : mItemFormatting.precision, }; } else { cell.precision = mType === DATASET_FIELD_TYPES.FLOAT ? MINIMUM_FRACTION_DIGITS : 0; } } else if (isDateField({data_type: mType})) { cell.type = 'date'; cell.sortable = true; cell.format = mItem.format; } } if (isDateField({data_type: cType})) { cell.name = formatDate({ valueType: cType, value: entry, format: c[level].format, }); } else if (isMarkupField({data_type: cType})) { cell.name = markupToRawString(entry); cell.markup = entry; } else if (isNumericalDataType(cType) && c[level]?.formatting) { cell.name = entry === null ? 'null' : entry; cell.formattedName = chartKitFormatNumberWrapper(entry, { lang: 'ru', ...c[level].formatting, }); } else { cell.name = entry === null ? 'null' : entry; } const currentKey = typeof key === 'string' ? `${key}${SPECIAL_DELIMITER}${value}` : `${value}`; const nextLevel = headColumn[level + 1]; const noValues = !auxHashTableCKeys[currentKey]; if (noValues) { return null; } else if (nextLevel) { cell.sub = generateHeadColumnLevel(level + 1, currentKey); if (cell.sub.length === 0) { return null; } } return cell; }) .filter((entry: any) => entry !== null) ); } let result; if (headColumn[0]) { result = generateHeadColumnLevel(0); } else { result = [ { name: '', group: useGroup, autogroup: false, sortable: false, }, ]; } if (!hideHeadRows) { // How many levels are there in the headRow - so many need to insert an empty cell into the header headRow.forEach(() => { result.unshift({ name: '', group: useGroup, autogroup: false, sortable: false, }); }); } return result; } const rows = generateHeadRows(); logTiming( 'Generated rows', (new Date() as unknown as number) - (startTime as unknown as number), ); const head = generateHeadColumns(); logTiming( 'Generated head', (new Date() as unknown as number) - (startTime as unknown as number), ); let colorData: any; if (colors.length) { colorData = mapAndColorizeHashTableByGradient(colorHashTable, colorsConfig).colorData; logTiming( 'Map and colorize', (new Date() as unknown as number) - (startTime as unknown as number), ); } // The function of generating keys of existing data in the correct order function getPaths(structure: any, level: any, current: any, target: any, direction: any) { if (current.length) { if (direction === 'row' && !auxHashTableRKeys[current.join(SPECIAL_DELIMITER)]) { return; } else if ( direction === 'column' && !auxHashTableCKeys[current.join(SPECIAL_DELIMITER)] ) { return; } } if (structure[level + 1]) { structure[level].forEach((entry: any) => { let pathPart = entry; if (entry === null) { pathPart = '__null'; } else if (typeof entry === 'undefined') { pathPart = '__undefined'; } else if (typeof entry === 'object') { pathPart = JSON.stringify(pathPart); } getPaths(structure, level + 1, [...current, pathPart], target, direction); }); } else if (structure[level]) { structure[level].forEach((entry: any) => { let pathPart = entry; if (entry === null) { pathPart = '__null'; } else if (typeof entry === 'undefined') { pathPart = '__undefined'; } else if (typeof entry === 'object') { pathPart = JSON.stringify(pathPart); } target.push([...current, pathPart]); }); } } let headRowPaths: any[] = []; getPaths(headRow, 0, [], headRowPaths, 'row'); logTiming( 'getPaths headRow', (new Date() as unknown as number) - (startTime as unknown as number), ); if (headRowPaths.length === 0) { headRowPaths = [['']]; } let headColumnPaths: any[] = []; getPaths(headColumn, 0, [], headColumnPaths, 'column'); logTiming( 'getPaths headColumn', (new Date() as unknown as number) - (startTime as unknown as number), ); if (headColumnPaths.length === 0) { headColumnPaths = [['']]; } let cellId = 0; let rCounter = 0; // The final cycle - we fill the cells with data headRowPaths.forEach((headRowPath) => { const rKey = headRowPath.join(SPECIAL_DELIMITER); const rKeyExisting = hashTableRKeys[rKey] || colorHashTableRKeys[rKey]; if (!rKeyExisting) { return; } const dataCells: any[] = []; headColumnPaths.forEach((headColumnPath) => { const cKey = headColumnPath.join(SPECIAL_DELIMITER); const cKeyExisting = hashTableCKeys[cKey] || colorHashTableCKeys[cKey]; if (!cKeyExisting) { return; } const key = `${cKey};${rKey}`; const value = hashTable[key] && hashTable[key][0]; const formattedValue = hashTableFormatted[key] && hashTableFormatted[key][0]; const type = typeTable[key]; const cell: any = { value, id: ++cellId, }; if (type === 'markup') { cell.value = value; cell.type = 'markup'; } else if (type === 'float') { cell.precision = 2; cell.type = 'number'; cell.formattedValue = formattedValue; } else if (isNumericalDataType(type)) { cell.type = 'number'; cell.formattedValue = formattedValue; } else if (isDateField({data_type: type})) { cell.type = 'date'; if (type === 'datetime' || type === 'genericdatetime') { cell.format = 'DD.MM.YYYY HH:mm:ss'; } else { cell.format = 'DD.MM.YYYY'; } } if (colors.length && colorData && colorData[key]) { cell.css = colorData[key]; } if (!cell.css) { cell.css = {}; } Object.assign(cell.css, { fontSize: '13px', lineHeight: '15px', }); dataCells.push(cell); }); rows[rCounter].cells = [...rows[rCounter].cells, ...dataCells]; ++rCounter; }); logTiming('Result', (new Date() as unknown as number) - (startTime as unknown as number)); return {head, rows}; }
// The function that generates the structure,
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/preparers/old-pivot-table/old-pivot-table.ts#L39-L1152
c6c62518947d4384167d05e7c686eb880fef00f8
datalens-ui
github_2023
datalens-tech
typescript
generateHeadRows
function generateHeadRows() { function generateHeadRowLevel(level: any, accumulated: any): any[] { const localResult: any[] = []; accumulated.forEach((accumulatedRow: any) => { const keyPrefix = accumulatedRow.length ? accumulatedRow .map((cell: any) => { return cell.originalValue; }) .join(SPECIAL_DELIMITER) : null; headRow[level].forEach((headRowLevel: any) => { let value = headRowLevel; let formattedValue = ''; let originalValue = headRowLevel; if (originalValue === null) { originalValue = '__null'; } else if (typeof originalValue === 'undefined') { originalValue = '__undefined'; } if (rTypes[level] === 'markup') { originalValue = JSON.stringify(value); } const currentKey = keyPrefix === null ? originalValue : `${keyPrefix}${SPECIAL_DELIMITER}${originalValue}`; if (!auxHashTableRKeys[currentKey]) { return; } if (headRowLevel === null) { value = null; } else if (isDateField({data_type: rTypes[level]})) { value = formatDate({ valueType: rTypes[level], value: headRowLevel, format: r[level].format, }); } else if (isNumericalDataType(rTypes[level]) && r[level]?.formatting) { formattedValue = chartKitFormatNumberWrapper(Number(headRowLevel), { lang: 'ru', ...r[level].formatting, }); } const cell = { value, originalValue, formattedValue, key: currentKey, css: { fontSize: '13px', lineHeight: '15px', }, }; localResult.push([...accumulatedRow, cell]); }); }); if (headRow[level + 1]) { return generateHeadRowLevel(level + 1, localResult); } else { return localResult; } } let rows; if (headRow[0]) { rows = generateHeadRowLevel(0, [[]]); let rowId = 0; rows = rows.map((cells) => { const row = { cells, id: ++rowId, }; return row; }); } else { rows = [{cells: []}]; } return rows; }
// Lowercase header generation function
https://github.com/datalens-tech/datalens-ui/blob/c6c62518947d4384167d05e7c686eb880fef00f8/src/server/modes/charts/plugins/datalens/preparers/old-pivot-table/old-pivot-table.ts#L743-L835
c6c62518947d4384167d05e7c686eb880fef00f8