prefix
stringlengths
82
32.6k
middle
stringlengths
5
470
suffix
stringlengths
0
81.2k
file_path
stringlengths
6
168
repo_name
stringlengths
16
77
context
listlengths
5
5
lang
stringclasses
4 values
ground_truth
stringlengths
5
470
import BookModel from "../models/BookModel"; import Bucket from "../models/Bucket"; import Token from "../lib/GenerateToken"; import { ERROR, MAX_EPUB_SIZE_MB } from "../common/const"; import { TokStatus, Book } from "../common/types"; import { sendJsonResponse, parseSimplePostData, md5, uuid, } from "../common/utils"; import filetype from "file-type-cjs"; import fs from "node:fs"; import EPub from "epub"; import os from "node:os"; import path from "node:path"; import crypto from "node:crypto"; import { exec } from "node:child_process"; import http from "node:http"; async function getEpubCoverFromEpubFile_UNIX( epubFilepath: string ): Promise<[Buffer, string] | null> { let randomString = crypto.randomBytes(16).toString("hex"); let tempDir = path.join(os.tmpdir(), `tmp-${randomString}`); fs.mkdirSync(tempDir); let unzipCMD = `unzip -q ${epubFilepath} -d ${tempDir}`; let unzipCMDExec = new Promise((resolve, reject) => { exec(unzipCMD, (err: any, stdout: any, stderr: any) => { if (err) reject(err); resolve(stdout); }); }); try { await unzipCMDExec; } catch (err) { console.error(err); fs.rmSync(tempDir, { recursive: true }); // we r good boys! return null; } let findCMD = `find ${tempDir} -type f \\( -iname \\*.jpeg -o -iname \\*.jpg -o -iname \\*.png \\) | grep -Ei 'cover\\.|index-1_1'`; let findCMDExec: Promise<string> = new Promise((resolve, reject) => { exec(findCMD, (err: any, stdout: any, stderr: any) => { if (err) reject(err); resolve(stdout); }); }); let selectedFilePath: string; try { selectedFilePath = await findCMDExec; selectedFilePath = selectedFilePath.trim(); } catch (err) { console.error(err); fs.rmSync(tempDir, { recursive: true }); // we r good boys! return null; } let ret: [Buffer, string] = [ Buffer.from(fs.readFileSync(selectedFilePath)), selectedFilePath, ]; fs.rmSync(tempDir, { recursive: true }); // we r good boys! return ret; } export default async function ( req: http.IncomingMessage, res: http.ServerResponse ) { const BOOK_DB = new BookModel(); const BUCKET = new Bucket(); await BOOK_DB.init(); await BUCKET.init(); try { if (req.method === "GET") { try { let userBooks = await BOOK_DB.getBooks(); userBooks = userBooks.map((e) => { delete e.path; return e; }); sendJsonResponse(res, userBooks, 200); } catch (error) { console.error(error); sendJsonResponse(res, ERROR.internalErr); } } else if (req.method === "POST") { const authorization = req.headers?.authorization; const authToken = authorization?.split(" ")?.pop(); if (!authorization || !authToken) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } const token = new Token(); const tokenStatus: TokStatus = token.verify(authToken); if ( tokenStatus === TokStatus.INVALID || tokenStatus === TokStatus.INVALID_SIG ) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } const parsedAuthToken: any = token.UNSAFE_parse(authToken); let epubBuffer: Buffer; epubBuffer = await parseSimplePostData(req); let epubSizeInMB = Math.ceil(epubBuffer.length / 1e6); let bufferMime = await filetype.fromBuffer(epubBuffer); if (bufferMime.mime != "application/epub+zip") { sendJsonResponse(res, ERROR.invalidMimeForResource, 415); return; } if (epubSizeInMB > MAX_EPUB_SIZE_MB) { sendJsonResponse(res, ERROR.fileTooLarge, 400); return; } let randomString = crypto.randomBytes(16).toString("hex"); const tempEpubFilePath = path.join(os.tmpdir(), `tmp-${randomString}.epub`); fs.writeFileSync(tempEpubFilePath, epubBuffer); const epub: any = await new Promise((resolve, reject) => { const epub = new EPub(tempEpubFilePath); epub.on("end", () => resolve(epub)); epub.on("error", reject); epub.parse(); }); let epubCoverBuffer = await getEpubCoverFromEpubFile_UNIX(tempEpubFilePath); console.log(epubCoverBuffer); let epubSignature = md5(epubBuffer.toString("hex"));
let foundBook = await BOOK_DB.getBook("", epubSignature);
if (foundBook) { sendJsonResponse( res, { ...ERROR.resourceExists, data: { id: foundBook.id, }, }, 409 ); return; } let epubFilePermalink = await BUCKET.pushBufferWithName( epubBuffer, `${epubSignature}.epub` ); let epubCoverPermalink = null; if (epubCoverBuffer) { epubCoverPermalink = await BUCKET.pushBufferWithName( epubCoverBuffer[0], `${epubSignature}.${epubCoverBuffer[1].split(".").pop()}` ); } let epubID = uuid(); let epubEntry: Book = { id: epubID, userid: parsedAuthToken.id, title: epub.metadata?.title ?? epubID.split("-").pop(), author: epub.metadata?.creator ?? parsedAuthToken.email, path: epubFilePermalink, signature: epubSignature, cover: epubCoverPermalink, }; const pushed = await BOOK_DB.pushBook(epubEntry); if (!pushed) { sendJsonResponse(res, ERROR.internalErr, 500); return; } sendJsonResponse( res, { error: null, message: `successfully published a book of id ${epubEntry.id}`, data: { id: epubEntry.id, }, }, 201 ); } else if (req.method === "DELETE") { const authorization = req.headers?.authorization; const authToken = authorization?.split(" ")?.pop(); if (!authorization || !authToken) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } const token = new Token(); const tokenStatus: TokStatus = token.verify(authToken); if ( tokenStatus === TokStatus.INVALID || tokenStatus === TokStatus.INVALID_SIG ) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } const parsedAuthToken: any = token.UNSAFE_parse(authToken); let body: Buffer; body = await parseSimplePostData(req); let data: any; try { data = JSON.parse(body.toString()); } catch { sendJsonResponse(res, ERROR.invalidJSONData, 400); return; } if (!data.bookid) { sendJsonResponse(res, ERROR.badRequest, 400); return; } let bookDeleted = await BOOK_DB.deleteBook(data.bookid, parsedAuthToken.id); if (!bookDeleted) { sendJsonResponse(res, { error: "unable-to-delete-book", message: `was unable to delete book ${data.bookid}, perhaps the id was invalid?`, status: 404 }, 404) return; } sendJsonResponse(res, { error: null, message: `successfully deleted book of id ${data.bookid}`, status: 204, data: { id: data.bookid, } }, 204) } } finally { await BOOK_DB.close(); } }
src/routes/Books.ts
Aadv1k-quillia-52c5b34
[ { "filename": "src/routes/Issue.ts", "retrieved_chunk": " let targetBook = await BOOK_DB.getBook(requestedBook);\n if (!targetBook) {\n sendJsonResponse(res, ERROR.resourceNotExists, 404);\n return;\n }\n let epubResourcePath = targetBook.path;\n const response: Array<Buffer> = await new Promise((resolve, reject) => {\n https.get(epubResourcePath, (res) => {\n let data: Array<Buffer> = [];\n res.on(\"data\", (d: Buffer) => data.push(d));", "score": 0.7658327221870422 }, { "filename": "src/routes/Issue.ts", "retrieved_chunk": " res.on(\"end\", () => resolve(data));\n res.on(\"error\", (error) => reject(error));\n });\n });\n let epubBuffer = Buffer.concat(response);\n sendEpubResponse(res, epubBuffer);\n return;\n } else {\n let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id);\n if (!userIssues) {", "score": 0.7509286403656006 }, { "filename": "src/routes/Issue.ts", "retrieved_chunk": " let issueData: Issue;\n try {\n let issuePostData = await parseSimplePostData(req);\n issueData = JSON.parse(issuePostData.toString());\n } catch (error) {\n console.error(error);\n sendJsonResponse(res, ERROR.badRequest, 400);\n return;\n }\n if (!issueData.lenderid || !issueData.bookid) {", "score": 0.6907154321670532 }, { "filename": "src/routes/Issue.ts", "retrieved_chunk": " return;\n }\n await ISSUE_DB.init();\n await BOOK_DB.init();\n await USER_DB.init();\n const parsedAuthToken: any = token.UNSAFE_parse(authToken);\n if (req.method === \"GET\") {\n let URLParams = req.url.split(\"/\").slice(3);\n let requestedBook = URLParams?.[0];\n if (requestedBook) {", "score": 0.6839762926101685 }, { "filename": "src/lib/GenerateToken.ts", "retrieved_chunk": " }\n if (this.sign(`${head}.${body}`) !== signature) {\n return TokStatus.INVALID_SIG\n }\n let decodedBody = Buffer.from(body, \"base64\").toString(\"utf-8\");\n const curTime = Math.floor(Date.now() / 1000);\n if (JSON.parse(decodedBody)?.exp > curTime) {\n return TokStatus.EXPIRED;\n }\n return TokStatus.VALID", "score": 0.6725500822067261 } ]
typescript
let foundBook = await BOOK_DB.getBook("", epubSignature);
import { ObjectDiscovery } from "./object-discovery"; import { Condition, Constraint, Rule } from "../types/rule"; export class Evaluator { private _objectDiscovery: ObjectDiscovery = new ObjectDiscovery(); /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. */ evaluate(rule: Rule, criteria: object | object[]): boolean | any { // Cater for the case where the conditions property is not an array. const conditions = rule.conditions instanceof Array ? rule.conditions : [rule.conditions]; if (criteria instanceof Array) { const result = []; for (const c of criteria) { result.push(this.evaluateRule(conditions, c, rule?.default)); } return result; } return this.evaluateRule(conditions, criteria, rule?.default); } /** * Evaluates a rule against a set of criteria and returns the result. * @param conditions The conditions to evaluate. * @param criteria The criteria to evaluate the conditions against. * @param defaultResult The default result to return if no conditions pass. */ private evaluateRule(
conditions: Condition[], criteria: object, defaultResult?: any ): boolean | any {
// We should evaluate all conditions and return the result // of the first condition that passes. for (const condition of conditions) { const result = this.evaluateCondition(condition, criteria); if (result) { return condition?.result ?? true; } } // If no conditions pass, we should return the default result of // the rule or false if no default result is provided. return defaultResult ?? false; } /** * Evaluates a condition against a set of criteria and returns the result. * Uses recursion to evaluate nested conditions. * @param condition The condition to evaluate. * @param criteria The criteria to evaluate the condition against. */ private evaluateCondition(condition: Condition, criteria: object): boolean { // The condition must have an 'any' or 'all' property. const type = this._objectDiscovery.conditionType(condition); if (!type) { return false; } // If the type is 'all' or 'none', we should set the initial // result to true, otherwise we should set it to false. let result = ["all", "none"].includes(type); // Check each node in the condition. for (const node of condition[type]) { let fn; if (this._objectDiscovery.isCondition(node)) { fn = "evaluateCondition"; } if (this._objectDiscovery.isConstraint(node)) { fn = "checkConstraint"; } // Process the node switch (type) { case "any": result = result || this[fn](node, criteria); break; case "all": result = result && this[fn](node, criteria); break; case "none": result = result && !this[fn](node, criteria); } } return result; } /** * Checks a constraint against a set of criteria and returns true whenever the constraint passes. * @param constraint The constraint to evaluate. * @param criteria The criteria to evaluate the constraint with. */ private checkConstraint(constraint: Constraint, criteria: object): boolean { // If the value contains '.' we should assume it is a nested property const criterion = constraint.field.includes(".") ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria) : criteria[constraint.field]; // If the criteria object does not have the field // we are looking for, we should return false. if (!criterion) { return false; } switch (constraint.operator) { case "==": return criterion == constraint.value; case "!=": return criterion != constraint.value; case ">": return criterion > constraint.value; case ">=": return criterion >= constraint.value; case "<": return criterion < constraint.value; case "<=": return criterion <= constraint.value; case "in": return ( Array.isArray(constraint.value) && constraint.value.includes(criterion as never) ); case "not in": return ( !Array.isArray(constraint.value) || !constraint.value.includes(criterion as never) ); default: return false; } } }
src/services/evaluator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n * @param trustRule Set true to avoid validating the rule before evaluating it (faster).\n * @throws Error if the rule is invalid.\n */\n static async evaluate<T>(\n rule: Rule,\n criteria: object | object[],\n trustRule = false\n ): Promise<T> {", "score": 0.9489328265190125 }, { "filename": "src/services/mutator.ts", "retrieved_chunk": " * @param criteria The criteria to check.\n * @param result Whether a mutate-able property has been found.\n * @param parentPath The parent path to the current property.\n */\n private hasMutations(\n criteria: object,\n result: boolean = false,\n parentPath: string = \"\"\n ): boolean {\n // If we have already found a mutation, we can stop.", "score": 0.9375215172767639 }, { "filename": "src/services/mutator.ts", "retrieved_chunk": " return result;\n }\n /**\n * Recursively applies mutations to the criteria.\n * @param criteria The criteria to mutate.\n * @param parentPath The parent path to the current property.\n */\n private async applyMutations(\n criteria: object,\n parentPath: string = \"\"", "score": 0.9301265478134155 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " */\n static builder(): Builder {\n return this._rulePilot.builder();\n }\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * If the criteria is an array (indicating multiple criteria to test),\n * the rule will be evaluated against each item in the array and\n * an array of results will be returned.\n *", "score": 0.9253546595573425 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " }\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * If the criteria is an array (indicating multiple criteria to test),\n * the rule will be evaluated against each item in the array and\n * an array of results will be returned.\n *\n * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n * @param trustRule Set true to avoid validating the rule before evaluating it (faster).", "score": 0.9246373772621155 } ]
typescript
conditions: Condition[], criteria: object, defaultResult?: any ): boolean | any {
import IssueModel from "../models/IssueModel"; import BookModel from "../models/BookModel"; import UserModel from "../models/UserModel"; import Token from "../lib/GenerateToken"; import { ERROR } from "../common/const"; import { TokStatus, Issue } from "../common/types"; import { sendJsonResponse, sendEpubResponse, parseSimplePostData, uuid, getBufferFromRawURL, } from "../common/utils"; import http from "node:http"; import https from "node:https"; export default async function ( req: http.IncomingMessage, res: http.ServerResponse ) { const ISSUE_DB = new IssueModel(); const BOOK_DB = new BookModel(); const USER_DB = new UserModel(); const authorization = req.headers?.authorization; const authToken = authorization?.split(" ")?.pop()?.trim(); try { if (req.method === "OPTIONS") { sendJsonResponse(res, {}, 200); return; } if (!authorization || !authToken) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } const token = new Token(); const tokenStatus: TokStatus = token.verify(authToken); if ( tokenStatus === TokStatus.INVALID || tokenStatus === TokStatus.INVALID_SIG ) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } await ISSUE_DB.init(); await BOOK_DB.init(); await USER_DB.init(); const parsedAuthToken: any = token.UNSAFE_parse(authToken); if (req.method === "GET") { let URLParams = req.url.split("/").slice(3); let requestedBook = URLParams?.[0]; if (requestedBook) { let targetBook = await BOOK_DB.getBook(requestedBook); if (!targetBook) { sendJsonResponse(res, ERROR.resourceNotExists, 404); return; } let epubResourcePath = targetBook.path; const response: Array<Buffer> = await new Promise((resolve, reject) => { https.get(epubResourcePath, (res) => { let data: Array<Buffer> = []; res.on("data", (d: Buffer) => data.push(d)); res.on("end", () => resolve(data)); res.on("error", (error) => reject(error)); }); }); let epubBuffer = Buffer.concat(response); sendEpubResponse(res, epubBuffer); return; } else { let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id); if (!userIssues) { sendJsonResponse(res, ERROR.resourceNotExists, 404); } else { sendJsonResponse(res, userIssues, 200); } } } else if (req.method === "POST") { if (req.headers?.["content-type"] != "application/json") { sendJsonResponse(res, ERROR.invalidMimeForResource, 415); return; } let issueData: Issue; try { let issuePostData = await parseSimplePostData(req); issueData = JSON.parse(issuePostData.toString()); } catch (error) { console.error(error); sendJsonResponse(res, ERROR.badRequest, 400); return; } if (!issueData.lenderid || !issueData.bookid) { sendJsonResponse(res, ERROR.badRequest, 400); return; } let foundLender = await USER_DB.getUserByID(issueData.lenderid); let foundBook = await BOOK_DB.getBook(issueData.bookid); if (!foundLender || !foundBook) { sendJsonResponse(res, ERROR.resourceNotExists, 404); return; }
let foundIssue = await ISSUE_DB.getIssue( foundLender.id, foundBook.id, parsedAuthToken.id );
if (foundIssue) { sendJsonResponse( res, { ...ERROR.resourceExists, data: { id: foundIssue.id, bookid: foundIssue.bookid, }, }, 409 ); return; } let issueid = uuid(); let issueEntry: Issue = { id: issueid, borrowerid: parsedAuthToken.id, lenderid: foundLender.id, bookid: foundBook.id, }; const pushed = await ISSUE_DB.pushIssue(issueEntry); if (!pushed) { sendJsonResponse(res, ERROR.internalErr, 500); return; } sendJsonResponse( res, { error: null, message: `successfully created a new issue of id ${issueEntry.id}`, data: { id: pushed.id, borrower: pushed.borrowerid, lender: pushed.lenderid, book: foundBook.title, }, }, 201 ); } } finally { await ISSUE_DB.close(); await BOOK_DB.close(); await USER_DB.close(); } }
src/routes/Issue.ts
Aadv1k-quillia-52c5b34
[ { "filename": "src/routes/Books.ts", "retrieved_chunk": " }\n if (!data.bookid) {\n sendJsonResponse(res, ERROR.badRequest, 400);\n return;\n }\n let bookDeleted = await BOOK_DB.deleteBook(data.bookid, parsedAuthToken.id);\n if (!bookDeleted) {\n sendJsonResponse(res, {\n error: \"unable-to-delete-book\",\n message: `was unable to delete book ${data.bookid}, perhaps the id was invalid?`,", "score": 0.8205275535583496 }, { "filename": "src/routes/Login.ts", "retrieved_chunk": " } catch(error) {\n sendJsonResponse(res, ERROR.invalidJSONData, 400)\n return;\n }\n await DB.init();\n const foundUser: User = await DB.getUser(parsedData.email);\n await DB.close();\n if (!foundUser) {\n sendJsonResponse(res, ERROR.userNotFound, 404);\n return;", "score": 0.7783699631690979 }, { "filename": "src/routes/Signup.ts", "retrieved_chunk": " sendJsonResponse(res, ERROR.badRequest, 400);\n return;\n }\n await DB.init();\n let foundUser = await DB.getUser(parsedData.email);\n if (foundUser) {\n sendJsonResponse(res, ERROR.userAlreadyExists, 409)\n return;\n }\n let user: User = {", "score": 0.7719981670379639 }, { "filename": "src/routes/Books.ts", "retrieved_chunk": " try {\n if (req.method === \"GET\") {\n try {\n let userBooks = await BOOK_DB.getBooks();\n userBooks = userBooks.map((e) => {\n delete e.path;\n return e;\n });\n sendJsonResponse(res, userBooks, 200);\n } catch (error) {", "score": 0.7549883723258972 }, { "filename": "src/models/IssueModel.ts", "retrieved_chunk": " async getIssues(borrowerid: string): Promise<Array<Issue> | null> {\n try {\n let response = await this.client.query(\n \"SELECT * FROM issues WHERE borrowerid = $1\",\n [borrowerid]\n );\n return response.rows;\n } catch (error) {\n console.error(error);\n return null;", "score": 0.7437353730201721 } ]
typescript
let foundIssue = await ISSUE_DB.getIssue( foundLender.id, foundBook.id, parsedAuthToken.id );
import IssueModel from "../models/IssueModel"; import BookModel from "../models/BookModel"; import UserModel from "../models/UserModel"; import Token from "../lib/GenerateToken"; import { ERROR } from "../common/const"; import { TokStatus, Issue } from "../common/types"; import { sendJsonResponse, sendEpubResponse, parseSimplePostData, uuid, getBufferFromRawURL, } from "../common/utils"; import http from "node:http"; import https from "node:https"; export default async function ( req: http.IncomingMessage, res: http.ServerResponse ) { const ISSUE_DB = new IssueModel(); const BOOK_DB = new BookModel(); const USER_DB = new UserModel(); const authorization = req.headers?.authorization; const authToken = authorization?.split(" ")?.pop()?.trim(); try { if (req.method === "OPTIONS") { sendJsonResponse(res, {}, 200); return; } if (!authorization || !authToken) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } const token = new Token(); const tokenStatus: TokStatus = token.verify(authToken); if ( tokenStatus === TokStatus.INVALID || tokenStatus === TokStatus.INVALID_SIG ) { sendJsonResponse(res, ERROR.unauthorized, 401); return; }
await ISSUE_DB.init();
await BOOK_DB.init(); await USER_DB.init(); const parsedAuthToken: any = token.UNSAFE_parse(authToken); if (req.method === "GET") { let URLParams = req.url.split("/").slice(3); let requestedBook = URLParams?.[0]; if (requestedBook) { let targetBook = await BOOK_DB.getBook(requestedBook); if (!targetBook) { sendJsonResponse(res, ERROR.resourceNotExists, 404); return; } let epubResourcePath = targetBook.path; const response: Array<Buffer> = await new Promise((resolve, reject) => { https.get(epubResourcePath, (res) => { let data: Array<Buffer> = []; res.on("data", (d: Buffer) => data.push(d)); res.on("end", () => resolve(data)); res.on("error", (error) => reject(error)); }); }); let epubBuffer = Buffer.concat(response); sendEpubResponse(res, epubBuffer); return; } else { let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id); if (!userIssues) { sendJsonResponse(res, ERROR.resourceNotExists, 404); } else { sendJsonResponse(res, userIssues, 200); } } } else if (req.method === "POST") { if (req.headers?.["content-type"] != "application/json") { sendJsonResponse(res, ERROR.invalidMimeForResource, 415); return; } let issueData: Issue; try { let issuePostData = await parseSimplePostData(req); issueData = JSON.parse(issuePostData.toString()); } catch (error) { console.error(error); sendJsonResponse(res, ERROR.badRequest, 400); return; } if (!issueData.lenderid || !issueData.bookid) { sendJsonResponse(res, ERROR.badRequest, 400); return; } let foundLender = await USER_DB.getUserByID(issueData.lenderid); let foundBook = await BOOK_DB.getBook(issueData.bookid); if (!foundLender || !foundBook) { sendJsonResponse(res, ERROR.resourceNotExists, 404); return; } let foundIssue = await ISSUE_DB.getIssue( foundLender.id, foundBook.id, parsedAuthToken.id ); if (foundIssue) { sendJsonResponse( res, { ...ERROR.resourceExists, data: { id: foundIssue.id, bookid: foundIssue.bookid, }, }, 409 ); return; } let issueid = uuid(); let issueEntry: Issue = { id: issueid, borrowerid: parsedAuthToken.id, lenderid: foundLender.id, bookid: foundBook.id, }; const pushed = await ISSUE_DB.pushIssue(issueEntry); if (!pushed) { sendJsonResponse(res, ERROR.internalErr, 500); return; } sendJsonResponse( res, { error: null, message: `successfully created a new issue of id ${issueEntry.id}`, data: { id: pushed.id, borrower: pushed.borrowerid, lender: pushed.lenderid, book: foundBook.title, }, }, 201 ); } } finally { await ISSUE_DB.close(); await BOOK_DB.close(); await USER_DB.close(); } }
src/routes/Issue.ts
Aadv1k-quillia-52c5b34
[ { "filename": "src/routes/Books.ts", "retrieved_chunk": " return;\n }\n const token = new Token();\n const tokenStatus: TokStatus = token.verify(authToken);\n if (\n tokenStatus === TokStatus.INVALID ||\n tokenStatus === TokStatus.INVALID_SIG\n ) {\n sendJsonResponse(res, ERROR.unauthorized, 401);\n return;", "score": 0.9658528566360474 }, { "filename": "src/routes/Books.ts", "retrieved_chunk": " const token = new Token();\n const tokenStatus: TokStatus = token.verify(authToken);\n if (\n tokenStatus === TokStatus.INVALID ||\n tokenStatus === TokStatus.INVALID_SIG\n ) {\n sendJsonResponse(res, ERROR.unauthorized, 401);\n return;\n }\n const parsedAuthToken: any = token.UNSAFE_parse(authToken);", "score": 0.9625129699707031 }, { "filename": "src/routes/Books.ts", "retrieved_chunk": " }\n const parsedAuthToken: any = token.UNSAFE_parse(authToken);\n let body: Buffer;\n body = await parseSimplePostData(req);\n let data: any;\n try {\n data = JSON.parse(body.toString());\n } catch {\n sendJsonResponse(res, ERROR.invalidJSONData, 400);\n return;", "score": 0.8329495787620544 }, { "filename": "src/routes/Login.ts", "retrieved_chunk": " } catch(error) {\n sendJsonResponse(res, ERROR.invalidJSONData, 400)\n return;\n }\n await DB.init();\n const foundUser: User = await DB.getUser(parsedData.email);\n await DB.close();\n if (!foundUser) {\n sendJsonResponse(res, ERROR.userNotFound, 404);\n return;", "score": 0.8309913873672485 }, { "filename": "src/routes/Books.ts", "retrieved_chunk": " console.error(error);\n sendJsonResponse(res, ERROR.internalErr);\n }\n } else if (req.method === \"POST\") {\n const authorization = req.headers?.authorization;\n const authToken = authorization?.split(\" \")?.pop();\n if (!authorization || !authToken) {\n sendJsonResponse(res, ERROR.unauthorized, 401);\n return;\n }", "score": 0.8303263783454895 } ]
typescript
await ISSUE_DB.init();
import IssueModel from "../models/IssueModel"; import BookModel from "../models/BookModel"; import UserModel from "../models/UserModel"; import Token from "../lib/GenerateToken"; import { ERROR } from "../common/const"; import { TokStatus, Issue } from "../common/types"; import { sendJsonResponse, sendEpubResponse, parseSimplePostData, uuid, getBufferFromRawURL, } from "../common/utils"; import http from "node:http"; import https from "node:https"; export default async function ( req: http.IncomingMessage, res: http.ServerResponse ) { const ISSUE_DB = new IssueModel(); const BOOK_DB = new BookModel(); const USER_DB = new UserModel(); const authorization = req.headers?.authorization; const authToken = authorization?.split(" ")?.pop()?.trim(); try { if (req.method === "OPTIONS") { sendJsonResponse(res, {}, 200); return; } if (!authorization || !authToken) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } const token = new Token(); const tokenStatus: TokStatus = token.verify(authToken); if ( tokenStatus === TokStatus.INVALID || tokenStatus === TokStatus.INVALID_SIG ) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } await ISSUE_DB.init(); await BOOK_DB.init(); await USER_DB.init(); const parsedAuthToken: any = token.UNSAFE_parse(authToken); if (req.method === "GET") { let URLParams = req.url.split("/").slice(3); let requestedBook = URLParams?.[0]; if (requestedBook) { let targetBook = await BOOK_DB.getBook(requestedBook); if (!targetBook) { sendJsonResponse(res, ERROR.resourceNotExists, 404); return; } let epubResourcePath = targetBook.path; const response: Array<Buffer> = await new Promise((resolve, reject) => { https.get(epubResourcePath, (res) => { let data: Array<Buffer> = []; res.on("data", (d: Buffer) => data.push(d)); res.on("end", () => resolve(data)); res.on("error", (error) => reject(error)); }); }); let epubBuffer = Buffer.concat(response); sendEpubResponse(res, epubBuffer); return; } else { let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id); if (!userIssues) { sendJsonResponse(res, ERROR.resourceNotExists, 404); } else { sendJsonResponse(res, userIssues, 200); } } } else if (req.method === "POST") { if (req.headers?.["content-type"] != "application/json") { sendJsonResponse(res, ERROR.invalidMimeForResource, 415); return; } let issueData: Issue; try { let issuePostData = await parseSimplePostData(req); issueData = JSON.parse(issuePostData.toString()); } catch (error) { console.error(error); sendJsonResponse(res, ERROR.badRequest, 400); return; } if (!issueData.lenderid || !issueData.bookid) { sendJsonResponse(res, ERROR.badRequest, 400); return; } let foundLender = await USER_DB
.getUserByID(issueData.lenderid);
let foundBook = await BOOK_DB.getBook(issueData.bookid); if (!foundLender || !foundBook) { sendJsonResponse(res, ERROR.resourceNotExists, 404); return; } let foundIssue = await ISSUE_DB.getIssue( foundLender.id, foundBook.id, parsedAuthToken.id ); if (foundIssue) { sendJsonResponse( res, { ...ERROR.resourceExists, data: { id: foundIssue.id, bookid: foundIssue.bookid, }, }, 409 ); return; } let issueid = uuid(); let issueEntry: Issue = { id: issueid, borrowerid: parsedAuthToken.id, lenderid: foundLender.id, bookid: foundBook.id, }; const pushed = await ISSUE_DB.pushIssue(issueEntry); if (!pushed) { sendJsonResponse(res, ERROR.internalErr, 500); return; } sendJsonResponse( res, { error: null, message: `successfully created a new issue of id ${issueEntry.id}`, data: { id: pushed.id, borrower: pushed.borrowerid, lender: pushed.lenderid, book: foundBook.title, }, }, 201 ); } } finally { await ISSUE_DB.close(); await BOOK_DB.close(); await USER_DB.close(); } }
src/routes/Issue.ts
Aadv1k-quillia-52c5b34
[ { "filename": "src/routes/Books.ts", "retrieved_chunk": " }\n if (!data.bookid) {\n sendJsonResponse(res, ERROR.badRequest, 400);\n return;\n }\n let bookDeleted = await BOOK_DB.deleteBook(data.bookid, parsedAuthToken.id);\n if (!bookDeleted) {\n sendJsonResponse(res, {\n error: \"unable-to-delete-book\",\n message: `was unable to delete book ${data.bookid}, perhaps the id was invalid?`,", "score": 0.8707197308540344 }, { "filename": "src/routes/Login.ts", "retrieved_chunk": " } catch(error) {\n sendJsonResponse(res, ERROR.invalidJSONData, 400)\n return;\n }\n await DB.init();\n const foundUser: User = await DB.getUser(parsedData.email);\n await DB.close();\n if (!foundUser) {\n sendJsonResponse(res, ERROR.userNotFound, 404);\n return;", "score": 0.860617458820343 }, { "filename": "src/routes/Signup.ts", "retrieved_chunk": " sendJsonResponse(res, ERROR.badRequest, 400);\n return;\n }\n await DB.init();\n let foundUser = await DB.getUser(parsedData.email);\n if (foundUser) {\n sendJsonResponse(res, ERROR.userAlreadyExists, 409)\n return;\n }\n let user: User = {", "score": 0.8524090051651001 }, { "filename": "src/routes/Signup.ts", "retrieved_chunk": " parsedData = JSON.parse(data === \"\" ? '{}' : data);\n } catch {\n sendJsonResponse(res, ERROR.invalidJSONData, 400)\n return;\n }\n if (!parsedData.email || !parsedData.password) {\n sendJsonResponse(res, ERROR.badRequest, 400);\n return;\n }\n if (!isEmailValid(parsedData.email)) {", "score": 0.8107748031616211 }, { "filename": "src/routes/Books.ts", "retrieved_chunk": " console.error(error);\n sendJsonResponse(res, ERROR.internalErr);\n }\n } else if (req.method === \"POST\") {\n const authorization = req.headers?.authorization;\n const authToken = authorization?.split(\" \")?.pop();\n if (!authorization || !authToken) {\n sendJsonResponse(res, ERROR.unauthorized, 401);\n return;\n }", "score": 0.7849440574645996 } ]
typescript
.getUserByID(issueData.lenderid);
import { ObjectDiscovery } from "./object-discovery"; import { Condition, Constraint, Operator, Rule } from "../types/rule"; export interface ValidationResult { isValid: boolean; error?: { message: string; element: object; }; } export class Validator { private objectDiscovery: ObjectDiscovery = new ObjectDiscovery(); /** * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not. * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { // Assume the rule is valid. let result: ValidationResult = { isValid: true }; // Check the rule is a valid JSON if (!this.objectDiscovery.isObject(rule)) { return { isValid: false, error: { message: "The rule must be a valid JSON object.", element: rule, }, }; } // Cater for the case where the conditions property is not an array. const conditions = rule.conditions instanceof Array ? rule.conditions : [rule.conditions]; // Validate the 'conditions' property. if ( conditions.length === 0 || (this.objectDiscovery.isObject(conditions[0]) && !Object.keys(conditions[0]).length) ) { return { isValid: false, error: { message: "The conditions property must contain at least one condition.", element: rule, }, }; } // Validate each condition in the rule. for (const condition of conditions) { const subResult = this.validateCondition(condition); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } return result; } /** ml/l.k, * Evaluates a condition to ensure it is syntactically correct. * @param condition The condition to validate. * @param depth The current recursion depth */ private validateCondition( condition:
Condition, depth: number = 0 ): ValidationResult {
// Check to see if the condition is valid. let result = this.isValidCondition(condition); if (!result.isValid) { return result; } // Set the type of condition. const type = this.objectDiscovery.conditionType(condition); // Check if the condition is iterable if(!Array.isArray(condition[type])) { return { isValid: false, error: { message: `The condition '${type}' should be iterable.`, element: condition, }, }; } // Validate each item in the condition. for (const node of condition[type]) { const isCondition = this.objectDiscovery.isCondition(node); if (isCondition) { const subResult = this.validateCondition(node as Condition, depth + 1); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } const isConstraint = this.objectDiscovery.isConstraint(node); if (isConstraint) { const subResult = this.validateConstraint(node as Constraint); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } if (!isConstraint && !isCondition) { return { isValid: false, error: { message: "Each node should be a condition or constraint.", element: node, }, }; } // Result is only valid on the root condition. if (depth > 0 && "result" in condition) { return { isValid: false, error: { message: 'Nested conditions cannot have a property "result".', element: node, }, }; } // If any part fails validation there is no point to continue. if (!result.isValid) { break; } } return result; } /** * Checks a constraint to ensure it is syntactically correct. * @param constraint The constraint to validate. */ private validateConstraint(constraint: Constraint): ValidationResult { if ("string" !== typeof constraint.field) { return { isValid: false, error: { message: 'Constraint "field" must be of type string.', element: constraint, }, }; } const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"]; if (!operators.includes(constraint.operator as Operator)) { return { isValid: false, error: { message: 'Constraint "operator" has invalid type.', element: constraint, }, }; } // We must check that the value is an array if the operator is 'in' or 'not in'. if ( ["in", "not in"].includes(constraint.operator) && !Array.isArray(constraint.value) ) { return { isValid: false, error: { message: 'Constraint "value" must be an array if the "operator" is "in" or "not in"', element: constraint, }, }; } return { isValid: true }; } /** * Checks an object to see if it is a valid condition. * @param obj The object to check. */ private isValidCondition(obj: any): ValidationResult { if (!this.objectDiscovery.isCondition(obj)) { return { isValid: false, error: { message: "Invalid condition structure.", element: obj, }, }; } const isAny = "any" in obj; const isAll = "all" in obj; const isNone = "none" in obj; // A valid condition must have an 'any', 'all', or 'none' property, // but cannot have more than one. if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) { return { isValid: false, error: { message: 'A condition cannot have more than one "any", "all", or "none" property.', element: obj, }, }; } return { isValid: true }; } }
src/services/validator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/mutator.ts", "retrieved_chunk": " * @param criteria The criteria to check.\n * @param result Whether a mutate-able property has been found.\n * @param parentPath The parent path to the current property.\n */\n private hasMutations(\n criteria: object,\n result: boolean = false,\n parentPath: string = \"\"\n ): boolean {\n // If we have already found a mutation, we can stop.", "score": 0.9396495223045349 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param defaultResult The default result to return if no conditions pass.\n */\n private evaluateRule(\n conditions: Condition[],\n criteria: object,\n defaultResult?: any\n ): boolean | any {\n // We should evaluate all conditions and return the result\n // of the first condition that passes.\n for (const condition of conditions) {", "score": 0.9236538410186768 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * Evaluates a condition against a set of criteria and returns the result.\n * Uses recursion to evaluate nested conditions.\n * @param condition The condition to evaluate.\n * @param criteria The criteria to evaluate the condition against.\n */\n private evaluateCondition(condition: Condition, criteria: object): boolean {\n // The condition must have an 'any' or 'all' property.\n const type = this._objectDiscovery.conditionType(condition);\n if (!type) {\n return false;", "score": 0.9212482571601868 }, { "filename": "src/services/mutator.ts", "retrieved_chunk": " return result;\n }\n /**\n * Recursively applies mutations to the criteria.\n * @param criteria The criteria to mutate.\n * @param parentPath The parent path to the current property.\n */\n private async applyMutations(\n criteria: object,\n parentPath: string = \"\"", "score": 0.918412983417511 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n * @param trustRule Set true to avoid validating the rule before evaluating it (faster).\n * @throws Error if the rule is invalid.\n */\n static async evaluate<T>(\n rule: Rule,\n criteria: object | object[],\n trustRule = false\n ): Promise<T> {", "score": 0.915861964225769 } ]
typescript
Condition, depth: number = 0 ): ValidationResult {
import IssueModel from "../models/IssueModel"; import BookModel from "../models/BookModel"; import UserModel from "../models/UserModel"; import Token from "../lib/GenerateToken"; import { ERROR } from "../common/const"; import { TokStatus, Issue } from "../common/types"; import { sendJsonResponse, sendEpubResponse, parseSimplePostData, uuid, getBufferFromRawURL, } from "../common/utils"; import http from "node:http"; import https from "node:https"; export default async function ( req: http.IncomingMessage, res: http.ServerResponse ) { const ISSUE_DB = new IssueModel(); const BOOK_DB = new BookModel(); const USER_DB = new UserModel(); const authorization = req.headers?.authorization; const authToken = authorization?.split(" ")?.pop()?.trim(); try { if (req.method === "OPTIONS") { sendJsonResponse(res, {}, 200); return; } if (!authorization || !authToken) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } const token = new Token(); const tokenStatus: TokStatus = token.verify(authToken); if ( tokenStatus === TokStatus.INVALID || tokenStatus === TokStatus.INVALID_SIG ) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } await ISSUE_DB.init(); await BOOK_DB.init(); await USER_DB.init(); const parsedAuthToken: any = token.UNSAFE_parse(authToken); if (req.method === "GET") { let URLParams = req.url.split("/").slice(3); let requestedBook = URLParams?.[0]; if (requestedBook) { let targetBook = await BOOK_DB.getBook(requestedBook); if (!targetBook) { sendJsonResponse(res, ERROR.resourceNotExists, 404); return; } let epubResourcePath = targetBook.path; const response: Array<Buffer> = await new Promise((resolve, reject) => { https.get(epubResourcePath, (res) => { let data: Array<Buffer> = []; res.on("data", (d: Buffer) => data.push(d)); res.on("end", () => resolve(data)); res.on("error", (error) => reject(error)); }); }); let epubBuffer = Buffer.concat(response); sendEpubResponse(res, epubBuffer); return; } else { let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id); if (!userIssues) { sendJsonResponse(res, ERROR.resourceNotExists, 404); } else { sendJsonResponse(res, userIssues, 200); } } } else if (req.method === "POST") { if (req.headers?.["content-type"] != "application/json") { sendJsonResponse(res, ERROR.invalidMimeForResource, 415); return; } let issueData: Issue; try { let issuePostData = await parseSimplePostData(req); issueData = JSON.parse(issuePostData.toString()); } catch (error) { console.error(error); sendJsonResponse(res, ERROR.badRequest, 400); return; } if (!issueData.lenderid || !issueData.bookid) { sendJsonResponse(res, ERROR.badRequest, 400); return; } let foundLender = await USER_DB.getUserByID(issueData.lenderid); let foundBook = await BOOK_DB.getBook(issueData.bookid); if (!foundLender || !foundBook) { sendJsonResponse(res, ERROR.resourceNotExists, 404); return; } let foundIssue = await ISSUE_DB.getIssue( foundLender.id, foundBook.id, parsedAuthToken.id ); if (foundIssue) { sendJsonResponse( res, { ...ERROR.resourceExists, data: { id: foundIssue.id, bookid: foundIssue.bookid, }, }, 409 ); return; } let issueid = uuid(); let issueEntry: Issue = { id: issueid, borrowerid: parsedAuthToken.id, lenderid: foundLender.id, bookid: foundBook.id, }; const pushed
= await ISSUE_DB.pushIssue(issueEntry);
if (!pushed) { sendJsonResponse(res, ERROR.internalErr, 500); return; } sendJsonResponse( res, { error: null, message: `successfully created a new issue of id ${issueEntry.id}`, data: { id: pushed.id, borrower: pushed.borrowerid, lender: pushed.lenderid, book: foundBook.title, }, }, 201 ); } } finally { await ISSUE_DB.close(); await BOOK_DB.close(); await USER_DB.close(); } }
src/routes/Issue.ts
Aadv1k-quillia-52c5b34
[ { "filename": "src/models/IssueModel.ts", "retrieved_chunk": " const result = await this.client.query(\"SELECT EXISTS (SELECT 1 FROM issues WHERE id = $1)\", [issueid])\n return result.rows[0].exists\n } \n async pushIssue(data: Issue): Promise<Issue | null> {\n try {\n await this.client.query(\n \"INSERT INTO issues (id, lenderid, borrowerid, bookid) VALUES ($1, $2, $3, $4)\",\n [data.id, data.lenderid, data.borrowerid, data.bookid]\n );\n return data;", "score": 0.7944564819335938 }, { "filename": "src/models/IssueModel.ts", "retrieved_chunk": " try {\n await this.client.query(\n \"DELETE FROM issues WHERE issueid = $1 OR borrowerid = $2 OR lenderid = $3\",\n [issueid ?? \"\", borrowerid ?? \"\", lenderid ?? \"\"]\n );\n } catch (error) {\n console.error(error);\n return null;\n }\n }", "score": 0.7814086675643921 }, { "filename": "src/routes/Books.ts", "retrieved_chunk": " let epubEntry: Book = {\n id: epubID,\n userid: parsedAuthToken.id,\n title: epub.metadata?.title ?? epubID.split(\"-\").pop(),\n author: epub.metadata?.creator ?? parsedAuthToken.email,\n path: epubFilePermalink,\n signature: epubSignature,\n cover: epubCoverPermalink,\n };\n const pushed = await BOOK_DB.pushBook(epubEntry);", "score": 0.7650880217552185 }, { "filename": "src/models/IssueModel.ts", "retrieved_chunk": " }\n }\n async getIssue(\n lenderid: string,\n bookid?: string,\n borrowerid?: string,\n ): Promise<Issue | null> {\n try {\n let response = await this.client.query(\n `SELECT * FROM issues ", "score": 0.7541971206665039 }, { "filename": "src/common/types.ts", "retrieved_chunk": "export interface User {\n id?: string,\n email: string;\n password: string;\n}\nexport interface Issue {\n id: string,\n lenderid: string,\n borrowerid: string,\n bookid: string", "score": 0.747358500957489 } ]
typescript
= await ISSUE_DB.pushIssue(issueEntry);
import { Builder } from "./builder"; import { Mutator } from "./mutator"; import { Evaluator } from "./evaluator"; import { ValidationResult, Validator } from "./validator"; import { Rule } from "../types/rule"; import { RuleError } from "../types/error"; export class RulePilot { private static _rulePilot = new RulePilot(); private _mutator: Mutator = new Mutator(); private _validator: Validator = new Validator(); private _evaluator: Evaluator = new Evaluator(); /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ builder(): Builder { return new Builder(this._validator); } /** * Adds a mutation to the rule pilot instance. * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ addMutation(name: string, mutation: Function): RulePilot { this._mutator.add(name, mutation); return this; } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ removeMutation(name: string): RulePilot { this._mutator.remove(name); return this; } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ clearMutationCache(name?: string): RulePilot { this._mutator.clearCache(name); return this; } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { // Before we evaluate the rule, we should validate it. // If `trustRuleset` is set to true, we will skip validation. const validationResult = !trustRule && this.validate(rule); if (!trustRule && !validationResult.isValid) {
throw new RuleError(validationResult);
} return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria)); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { return this._validator.validate(rule); } /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ static builder(): Builder { return this._rulePilot.builder(); } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ static async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ static validate(rule: Rule): ValidationResult { return RulePilot._rulePilot.validate(rule); } /** * Adds a mutation. * * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ static addMutation(name: string, mutation: Function): RulePilot { return RulePilot._rulePilot.addMutation(name, mutation); } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ static removeMutation(name: string): RulePilot { return RulePilot._rulePilot.removeMutation(name); } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ static clearMutationCache(name?: string): RulePilot { return RulePilot._rulePilot.clearMutationCache(name); } }
src/services/rule-pilot.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/validator.ts", "retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {", "score": 0.9024075269699097 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " condition: Condition,\n depth: number = 0\n ): ValidationResult {\n // Check to see if the condition is valid.\n let result = this.isValidCondition(condition);\n if (!result.isValid) {\n return result;\n }\n // Set the type of condition.\n const type = this.objectDiscovery.conditionType(condition);", "score": 0.9006898999214172 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param defaultResult The default result to return if no conditions pass.\n */\n private evaluateRule(\n conditions: Condition[],\n criteria: object,\n defaultResult?: any\n ): boolean | any {\n // We should evaluate all conditions and return the result\n // of the first condition that passes.\n for (const condition of conditions) {", "score": 0.8956193923950195 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {", "score": 0.8931875228881836 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n */\n evaluate(rule: Rule, criteria: object | object[]): boolean | any {\n // Cater for the case where the conditions property is not an array.\n const conditions =\n rule.conditions instanceof Array ? rule.conditions : [rule.conditions];\n if (criteria instanceof Array) {\n const result = [];\n for (const c of criteria) {", "score": 0.8909050822257996 } ]
typescript
throw new RuleError(validationResult);
import { Builder } from "./builder"; import { Mutator } from "./mutator"; import { Evaluator } from "./evaluator"; import { ValidationResult, Validator } from "./validator"; import { Rule } from "../types/rule"; import { RuleError } from "../types/error"; export class RulePilot { private static _rulePilot = new RulePilot(); private _mutator: Mutator = new Mutator(); private _validator: Validator = new Validator(); private _evaluator: Evaluator = new Evaluator(); /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ builder(): Builder { return new Builder(this._validator); } /** * Adds a mutation to the rule pilot instance. * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ addMutation(name: string, mutation: Function): RulePilot { this._mutator.add(name, mutation); return this; } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ removeMutation(name: string): RulePilot { this._mutator.remove(name); return this; } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ clearMutationCache(name?: string): RulePilot { this._mutator.clearCache(name); return this; } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { // Before we evaluate the rule, we should validate it. // If `trustRuleset` is set to true, we will skip validation. const validationResult = !trustRule && this.validate(rule); if (!trustRule && !validationResult.isValid) { throw new RuleError(validationResult); } return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria)); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { return this._validator.validate(rule); } /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */
static builder(): Builder {
return this._rulePilot.builder(); } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ static async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ static validate(rule: Rule): ValidationResult { return RulePilot._rulePilot.validate(rule); } /** * Adds a mutation. * * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ static addMutation(name: string, mutation: Function): RulePilot { return RulePilot._rulePilot.addMutation(name, mutation); } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ static removeMutation(name: string): RulePilot { return RulePilot._rulePilot.removeMutation(name); } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ static clearMutationCache(name?: string): RulePilot { return RulePilot._rulePilot.clearMutationCache(name); } }
src/services/rule-pilot.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/builder.ts", "retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {", "score": 0.9336355328559875 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {", "score": 0.929800271987915 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " constructor(validator: Validator) {\n this.validator = validator;\n }\n /** Stores to rule being constructed */\n private rule: Rule = { conditions: [] };\n /** Holds a reference to the Validator class */\n private validator: Validator;\n /**\n * Adds a node (in the root) to the rule being constructed\n * @param node The node to add to the rule", "score": 0.9150264859199524 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " /**\n * Checks an object to see if it is a valid condition.\n * @param obj The object to check.\n */\n private isValidCondition(obj: any): ValidationResult {\n if (!this.objectDiscovery.isCondition(obj)) {\n return {\n isValid: false,\n error: {\n message: \"Invalid condition structure.\",", "score": 0.8961055874824524 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " /**\n * Checks a constraint to ensure it is syntactically correct.\n * @param constraint The constraint to validate.\n */\n private validateConstraint(constraint: Constraint): ValidationResult {\n if (\"string\" !== typeof constraint.field) {\n return {\n isValid: false,\n error: {\n message: 'Constraint \"field\" must be of type string.',", "score": 0.8930511474609375 } ]
typescript
static builder(): Builder {
import { Builder } from "./builder"; import { Mutator } from "./mutator"; import { Evaluator } from "./evaluator"; import { ValidationResult, Validator } from "./validator"; import { Rule } from "../types/rule"; import { RuleError } from "../types/error"; export class RulePilot { private static _rulePilot = new RulePilot(); private _mutator: Mutator = new Mutator(); private _validator: Validator = new Validator(); private _evaluator: Evaluator = new Evaluator(); /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ builder(): Builder { return new Builder(this._validator); } /** * Adds a mutation to the rule pilot instance. * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ addMutation(name: string, mutation: Function): RulePilot { this._mutator.add(name, mutation); return this; } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ removeMutation(name: string): RulePilot { this._mutator.remove(name); return this; } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ clearMutationCache(name?: string): RulePilot { this._mutator.clearCache(name); return this; } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ async evaluate<T>( rule:
Rule, criteria: object | object[], trustRule = false ): Promise<T> {
// Before we evaluate the rule, we should validate it. // If `trustRuleset` is set to true, we will skip validation. const validationResult = !trustRule && this.validate(rule); if (!trustRule && !validationResult.isValid) { throw new RuleError(validationResult); } return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria)); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { return this._validator.validate(rule); } /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ static builder(): Builder { return this._rulePilot.builder(); } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ static async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ static validate(rule: Rule): ValidationResult { return RulePilot._rulePilot.validate(rule); } /** * Adds a mutation. * * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ static addMutation(name: string, mutation: Function): RulePilot { return RulePilot._rulePilot.addMutation(name, mutation); } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ static removeMutation(name: string): RulePilot { return RulePilot._rulePilot.removeMutation(name); } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ static clearMutationCache(name?: string): RulePilot { return RulePilot._rulePilot.clearMutationCache(name); } }
src/services/rule-pilot.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n */\n evaluate(rule: Rule, criteria: object | object[]): boolean | any {\n // Cater for the case where the conditions property is not an array.\n const conditions =\n rule.conditions instanceof Array ? rule.conditions : [rule.conditions];\n if (criteria instanceof Array) {\n const result = [];\n for (const c of criteria) {", "score": 0.9173113703727722 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param defaultResult The default result to return if no conditions pass.\n */\n private evaluateRule(\n conditions: Condition[],\n criteria: object,\n defaultResult?: any\n ): boolean | any {\n // We should evaluate all conditions and return the result\n // of the first condition that passes.\n for (const condition of conditions) {", "score": 0.9172881841659546 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {", "score": 0.9148225784301758 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {", "score": 0.9102416634559631 }, { "filename": "src/services/mutator.ts", "retrieved_chunk": " this._cache.delete(key);\n }\n }\n }\n /**\n * Mutates and returns a criteria object.\n * @param criteria The criteria to mutate.\n */\n async mutate(criteria: object | object[]): Promise<object | object[]> {\n // Handles checking the mutability of a criteria object", "score": 0.910205602645874 } ]
typescript
Rule, criteria: object | object[], trustRule = false ): Promise<T> {
import { ObjectDiscovery } from "./object-discovery"; import { Condition, Constraint, Operator, Rule } from "../types/rule"; export interface ValidationResult { isValid: boolean; error?: { message: string; element: object; }; } export class Validator { private objectDiscovery: ObjectDiscovery = new ObjectDiscovery(); /** * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not. * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { // Assume the rule is valid. let result: ValidationResult = { isValid: true }; // Check the rule is a valid JSON if (!this.objectDiscovery.isObject(rule)) { return { isValid: false, error: { message: "The rule must be a valid JSON object.", element: rule, }, }; } // Cater for the case where the conditions property is not an array. const conditions = rule.conditions instanceof Array ? rule.conditions : [rule.conditions]; // Validate the 'conditions' property. if ( conditions.length === 0 || (this.objectDiscovery.isObject(conditions[0]) && !Object.keys(conditions[0]).length) ) { return { isValid: false, error: { message: "The conditions property must contain at least one condition.", element: rule, }, }; } // Validate each condition in the rule. for (const condition of conditions) { const subResult = this.validateCondition(condition); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } return result; } /** ml/l.k, * Evaluates a condition to ensure it is syntactically correct. * @param condition The condition to validate. * @param depth The current recursion depth */ private validateCondition( condition: Condition, depth: number = 0 ): ValidationResult { // Check to see if the condition is valid. let result = this.isValidCondition(condition); if (!result.isValid) { return result; } // Set the type of condition. const type = this.objectDiscovery.conditionType(condition); // Check if the condition is iterable if(!Array.isArray(condition[type])) { return { isValid: false, error: { message: `The condition '${type}' should be iterable.`, element: condition, }, }; } // Validate each item in the condition. for (const node of condition[type]) { const isCondition = this.objectDiscovery.isCondition(node); if (isCondition) { const subResult = this.validateCondition(node as Condition, depth + 1); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } const isConstraint = this.objectDiscovery.isConstraint(node); if (isConstraint) {
const subResult = this.validateConstraint(node as Constraint);
result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } if (!isConstraint && !isCondition) { return { isValid: false, error: { message: "Each node should be a condition or constraint.", element: node, }, }; } // Result is only valid on the root condition. if (depth > 0 && "result" in condition) { return { isValid: false, error: { message: 'Nested conditions cannot have a property "result".', element: node, }, }; } // If any part fails validation there is no point to continue. if (!result.isValid) { break; } } return result; } /** * Checks a constraint to ensure it is syntactically correct. * @param constraint The constraint to validate. */ private validateConstraint(constraint: Constraint): ValidationResult { if ("string" !== typeof constraint.field) { return { isValid: false, error: { message: 'Constraint "field" must be of type string.', element: constraint, }, }; } const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"]; if (!operators.includes(constraint.operator as Operator)) { return { isValid: false, error: { message: 'Constraint "operator" has invalid type.', element: constraint, }, }; } // We must check that the value is an array if the operator is 'in' or 'not in'. if ( ["in", "not in"].includes(constraint.operator) && !Array.isArray(constraint.value) ) { return { isValid: false, error: { message: 'Constraint "value" must be an array if the "operator" is "in" or "not in"', element: constraint, }, }; } return { isValid: true }; } /** * Checks an object to see if it is a valid condition. * @param obj The object to check. */ private isValidCondition(obj: any): ValidationResult { if (!this.objectDiscovery.isCondition(obj)) { return { isValid: false, error: { message: "Invalid condition structure.", element: obj, }, }; } const isAny = "any" in obj; const isAll = "all" in obj; const isNone = "none" in obj; // A valid condition must have an 'any', 'all', or 'none' property, // but cannot have more than one. if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) { return { isValid: false, error: { message: 'A condition cannot have more than one "any", "all", or "none" property.', element: obj, }, }; } return { isValid: true }; } }
src/services/validator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/evaluator.ts", "retrieved_chunk": " if (this._objectDiscovery.isConstraint(node)) {\n fn = \"checkConstraint\";\n }\n // Process the node\n switch (type) {\n case \"any\":\n result = result || this[fn](node, criteria);\n break;\n case \"all\":\n result = result && this[fn](node, criteria);", "score": 0.8107764720916748 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " return this.rule;\n }\n const validationResult = this.validator.validate(this.rule);\n if (validationResult.isValid) {\n return this.rule;\n }\n throw new RuleError(validationResult);\n }\n /**\n * Creates a new condition node", "score": 0.8102575540542603 }, { "filename": "src/services/mutator.ts", "retrieved_chunk": " if (result) return true;\n for (const key of Object.keys(criteria)) {\n if (result) return true;\n // Prepare dotted path to the current property.\n const path = parentPath ? `${parentPath}.${key}` : key;\n // If the value is an object, we should recurse.\n result = this._objectDiscovery.isObject(criteria[key])\n ? result || this.hasMutations(criteria[key], result, path)\n : result || this._mutations.has(path);\n }", "score": 0.794758141040802 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }", "score": 0.7661482095718384 }, { "filename": "src/services/object-discovery.ts", "retrieved_chunk": " }\n /**\n * Checks an object to see if it is a valid constraint.\n * @param obj The object to check.\n */\n isConstraint(obj: unknown): obj is Constraint {\n return !this.isObject(obj)\n ? false\n : \"field\" in obj && \"operator\" in obj && \"value\" in obj;\n }", "score": 0.7436776161193848 } ]
typescript
const subResult = this.validateConstraint(node as Constraint);
import http from "node:http"; import { sendJsonResponse, md5, uuid, parseSimplePostData } from "../common/utils"; import { ERROR } from "../common/const"; import { User } from "../common/types"; import UserModel from "../models/UserModel"; import Token from "../lib/GenerateToken"; import isEmailValid from "../lib/isEmailValid"; export default async function ( req: http.IncomingMessage, res: http.ServerResponse ) { const DB = new UserModel(); if (req.method !== "POST") { sendJsonResponse(res, ERROR.methodNotAllowed, 405); return; } let data: any = await parseSimplePostData(req); data = data.toString(); let parsedData: User; try { parsedData = JSON.parse(data === "" ? '{}' : data); } catch { sendJsonResponse(res, ERROR.invalidJSONData, 400) return; } if (!parsedData.email || !parsedData.password) { sendJsonResponse(res, ERROR.badRequest, 400); return; } if (!isEmailValid(parsedData.email)) { sendJsonResponse(res, ERROR.badRequest, 400); return; } await DB.init(); let foundUser = await DB.getUser(parsedData.email); if (foundUser) { sendJsonResponse(res, ERROR.userAlreadyExists, 409) return; } let user: User = { id: uuid(), email: parsedData.email, password: md5(parsedData.password), } const token = new Token(); let pushed = await DB.pushUser(user) const { password, ...tokenBody} = user; let accessToken = token.generate(tokenBody); if (pushed !== null) { sendJsonResponse(res, { status: 201, message: "successfully created new user", error: null, token: accessToken, data: { email: user.email,
id: user.id }
}, 201) } else { sendJsonResponse(res, ERROR.internalErr, 500); } await DB.close(); }
src/routes/Signup.ts
Aadv1k-quillia-52c5b34
[ { "filename": "src/routes/Login.ts", "retrieved_chunk": " status: 200,\n error: null,\n token: accessToken,\n data: {\n email: foundUser.email,\n id: foundUser.id,\n }\n }, 200)\n}", "score": 0.8805622458457947 }, { "filename": "src/routes/Books.ts", "retrieved_chunk": " status: 404\n }, 404)\n return;\n }\n sendJsonResponse(res, {\n error: null,\n message: `successfully deleted book of id ${data.bookid}`,\n status: 204,\n data: {\n id: data.bookid,", "score": 0.8675711750984192 }, { "filename": "src/routes/Books.ts", "retrieved_chunk": " if (!pushed) {\n sendJsonResponse(res, ERROR.internalErr, 500);\n return;\n }\n sendJsonResponse(\n res,\n {\n error: null,\n message: `successfully published a book of id ${epubEntry.id}`,\n data: {", "score": 0.8606588244438171 }, { "filename": "src/routes/Login.ts", "retrieved_chunk": " }\n if (md5(parsedData.password) !== foundUser.password) {\n sendJsonResponse(res, ERROR.unauthorized, 401);\n return;\n }\n const token = new Token();\n const { password, ...tokenBody} = foundUser;\n let accessToken = token.generate(tokenBody);\n sendJsonResponse(res, {\n messaged: \"found the given user\",", "score": 0.8339876532554626 }, { "filename": "src/routes/Issue.ts", "retrieved_chunk": " foundLender.id,\n foundBook.id,\n parsedAuthToken.id\n );\n if (foundIssue) {\n sendJsonResponse(\n res,\n {\n ...ERROR.resourceExists,\n data: {", "score": 0.8149024248123169 } ]
typescript
id: user.id }
import { Builder } from "./builder"; import { Mutator } from "./mutator"; import { Evaluator } from "./evaluator"; import { ValidationResult, Validator } from "./validator"; import { Rule } from "../types/rule"; import { RuleError } from "../types/error"; export class RulePilot { private static _rulePilot = new RulePilot(); private _mutator: Mutator = new Mutator(); private _validator: Validator = new Validator(); private _evaluator: Evaluator = new Evaluator(); /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ builder(): Builder { return new Builder(this._validator); } /** * Adds a mutation to the rule pilot instance. * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ addMutation(name: string, mutation: Function): RulePilot { this._mutator.add(name, mutation); return this; } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ removeMutation(name: string): RulePilot { this._mutator.remove(name); return this; } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ clearMutationCache(name?: string): RulePilot { this._mutator.clearCache(name); return this; } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { // Before we evaluate the rule, we should validate it. // If `trustRuleset` is set to true, we will skip validation. const validationResult = !trustRule && this.validate(rule); if (!trustRule && !validationResult.isValid) { throw new RuleError(validationResult); } return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria)); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { return this._validator.validate(rule); } /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ static builder(): Builder { return this._rulePilot.builder(); } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ static async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */
static validate(rule: Rule): ValidationResult {
return RulePilot._rulePilot.validate(rule); } /** * Adds a mutation. * * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ static addMutation(name: string, mutation: Function): RulePilot { return RulePilot._rulePilot.addMutation(name, mutation); } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ static removeMutation(name: string): RulePilot { return RulePilot._rulePilot.removeMutation(name); } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ static clearMutationCache(name?: string): RulePilot { return RulePilot._rulePilot.clearMutationCache(name); } }
src/services/rule-pilot.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/validator.ts", "retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {", "score": 0.9360529184341431 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {", "score": 0.9189267158508301 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " constructor(validator: Validator) {\n this.validator = validator;\n }\n /** Stores to rule being constructed */\n private rule: Rule = { conditions: [] };\n /** Holds a reference to the Validator class */\n private validator: Validator;\n /**\n * Adds a node (in the root) to the rule being constructed\n * @param node The node to add to the rule", "score": 0.9121075868606567 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " /**\n * Checks a constraint to ensure it is syntactically correct.\n * @param constraint The constraint to validate.\n */\n private validateConstraint(constraint: Constraint): ValidationResult {\n if (\"string\" !== typeof constraint.field) {\n return {\n isValid: false,\n error: {\n message: 'Constraint \"field\" must be of type string.',", "score": 0.9116163849830627 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " /**\n * Checks an object to see if it is a valid condition.\n * @param obj The object to check.\n */\n private isValidCondition(obj: any): ValidationResult {\n if (!this.objectDiscovery.isCondition(obj)) {\n return {\n isValid: false,\n error: {\n message: \"Invalid condition structure.\",", "score": 0.9069422483444214 } ]
typescript
static validate(rule: Rule): ValidationResult {
import { Rule, Operator, Condition, Constraint, ConditionType, } from "../types/rule"; import { Validator } from "./validator"; import { RuleError } from "../types/error"; export class Builder { constructor(validator: Validator) { this.validator = validator; } /** Stores to rule being constructed */ private rule: Rule = { conditions: [] }; /** Holds a reference to the Validator class */ private validator: Validator; /** * Adds a node (in the root) to the rule being constructed * @param node The node to add to the rule */ add(node: Condition): Builder { (this.rule.conditions as Condition[]).push(node); return this; } /** * Sets the default value of the rule being constructed * @param value The default value of the rule */ default(value: Rule["default"]): Builder { this.rule.default = value; return this; } /** * Builds the rule being and returns it * @param validate Whether to validate the rule before returning it * @throws Error if validation is enabled and the rule is invalid */ build(validate?: boolean): Rule { if (!validate) { return this.rule; }
const validationResult = this.validator.validate(this.rule);
if (validationResult.isValid) { return this.rule; } throw new RuleError(validationResult); } /** * Creates a new condition node * @param type The type of condition * @param nodes Any child nodes of the condition * @param result The result of the condition node (for granular rules) */ condition( type: ConditionType, nodes: Condition[ConditionType], result?: Condition["result"] ): Condition { return { [type]: nodes, ...(result ? { result } : {}), }; } /** * Creates a new constraint node * @param field The field to apply the constraint to * @param operator The operator to apply to the field * @param value The value to compare the field to */ constraint( field: string, operator: Operator, value: Constraint["value"] ): Constraint { return { field, operator, value, }; } }
src/services/builder.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/validator.ts", "retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {", "score": 0.9296896457672119 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " * that caused the validation to fail.\n *\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n return this._validator.validate(rule);\n }\n /**\n * Returns a rule builder class instance.\n * Allows for the construction of rules using a fluent interface.", "score": 0.9244483113288879 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " * @throws Error if the rule is invalid.\n */\n async evaluate<T>(\n rule: Rule,\n criteria: object | object[],\n trustRule = false\n ): Promise<T> {\n // Before we evaluate the rule, we should validate it.\n // If `trustRuleset` is set to true, we will skip validation.\n const validationResult = !trustRule && this.validate(rule);", "score": 0.9234300255775452 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " if (!trustRule && !validationResult.isValid) {\n throw new RuleError(validationResult);\n }\n return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria));\n }\n /**\n * Takes in a rule as a parameter and returns a ValidationResult\n * indicating whether the rule is valid or not.\n *\n * Invalid rules will contain an error property which contains a message and the element", "score": 0.9144032597541809 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n * @param trustRule Set true to avoid validating the rule before evaluating it (faster).\n * @throws Error if the rule is invalid.\n */\n static async evaluate<T>(\n rule: Rule,\n criteria: object | object[],\n trustRule = false\n ): Promise<T> {", "score": 0.9029121994972229 } ]
typescript
const validationResult = this.validator.validate(this.rule);
import { ObjectDiscovery } from "./object-discovery"; import { Condition, Constraint, Rule } from "../types/rule"; export class Evaluator { private _objectDiscovery: ObjectDiscovery = new ObjectDiscovery(); /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. */ evaluate(rule: Rule, criteria: object | object[]): boolean | any { // Cater for the case where the conditions property is not an array. const conditions = rule.conditions instanceof Array ? rule.conditions : [rule.conditions]; if (criteria instanceof Array) { const result = []; for (const c of criteria) { result.push(this.evaluateRule(conditions, c, rule?.default)); } return result; } return this.evaluateRule(conditions, criteria, rule?.default); } /** * Evaluates a rule against a set of criteria and returns the result. * @param conditions The conditions to evaluate. * @param criteria The criteria to evaluate the conditions against. * @param defaultResult The default result to return if no conditions pass. */ private evaluateRule( conditions: Condition[], criteria: object, defaultResult?: any ): boolean | any { // We should evaluate all conditions and return the result // of the first condition that passes. for (const condition of conditions) { const result = this.evaluateCondition(condition, criteria); if (result) { return condition?.result ?? true; } } // If no conditions pass, we should return the default result of // the rule or false if no default result is provided. return defaultResult ?? false; } /** * Evaluates a condition against a set of criteria and returns the result. * Uses recursion to evaluate nested conditions. * @param condition The condition to evaluate. * @param criteria The criteria to evaluate the condition against. */ private evaluateCondition(condition: Condition, criteria: object): boolean { // The condition must have an 'any' or 'all' property. const type = this._objectDiscovery.conditionType(condition); if (!type) { return false; } // If the type is 'all' or 'none', we should set the initial // result to true, otherwise we should set it to false. let result = ["all", "none"].includes(type); // Check each node in the condition. for (const node of condition[type]) { let fn;
if (this._objectDiscovery.isCondition(node)) {
fn = "evaluateCondition"; } if (this._objectDiscovery.isConstraint(node)) { fn = "checkConstraint"; } // Process the node switch (type) { case "any": result = result || this[fn](node, criteria); break; case "all": result = result && this[fn](node, criteria); break; case "none": result = result && !this[fn](node, criteria); } } return result; } /** * Checks a constraint against a set of criteria and returns true whenever the constraint passes. * @param constraint The constraint to evaluate. * @param criteria The criteria to evaluate the constraint with. */ private checkConstraint(constraint: Constraint, criteria: object): boolean { // If the value contains '.' we should assume it is a nested property const criterion = constraint.field.includes(".") ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria) : criteria[constraint.field]; // If the criteria object does not have the field // we are looking for, we should return false. if (!criterion) { return false; } switch (constraint.operator) { case "==": return criterion == constraint.value; case "!=": return criterion != constraint.value; case ">": return criterion > constraint.value; case ">=": return criterion >= constraint.value; case "<": return criterion < constraint.value; case "<=": return criterion <= constraint.value; case "in": return ( Array.isArray(constraint.value) && constraint.value.includes(criterion as never) ); case "not in": return ( !Array.isArray(constraint.value) || !constraint.value.includes(criterion as never) ); default: return false; } } }
src/services/evaluator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/validator.ts", "retrieved_chunk": " condition: Condition,\n depth: number = 0\n ): ValidationResult {\n // Check to see if the condition is valid.\n let result = this.isValidCondition(condition);\n if (!result.isValid) {\n return result;\n }\n // Set the type of condition.\n const type = this.objectDiscovery.conditionType(condition);", "score": 0.9139735102653503 }, { "filename": "src/services/object-discovery.ts", "retrieved_chunk": "import { Condition, ConditionType, Constraint } from \"../types/rule\";\nexport class ObjectDiscovery {\n /**\n * Returns the type of condition passed to the function.\n * @param condition The condition to check.\n */\n conditionType(condition: Condition): ConditionType | null {\n if (\"any\" in condition) return \"any\";\n if (\"all\" in condition) return \"all\";\n if (\"none\" in condition) return \"none\";", "score": 0.8826168775558472 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " message:\n \"The conditions property must contain at least one condition.\",\n element: rule,\n },\n };\n }\n // Validate each condition in the rule.\n for (const condition of conditions) {\n const subResult = this.validateCondition(condition);\n result.isValid = result.isValid && subResult.isValid;", "score": 0.8753949403762817 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " /**\n * Checks an object to see if it is a valid condition.\n * @param obj The object to check.\n */\n private isValidCondition(obj: any): ValidationResult {\n if (!this.objectDiscovery.isCondition(obj)) {\n return {\n isValid: false,\n error: {\n message: \"Invalid condition structure.\",", "score": 0.8692376017570496 }, { "filename": "src/services/mutator.ts", "retrieved_chunk": " // If it is mutable it will be cloned, mutated and returned\n const exec = async (criteria) => {\n // If there are no mutations or the criteria does not contain\n // any of the mutation keys, return the criteria as is.\n if (!this._mutations.size || !this.hasMutations(criteria)) {\n return criteria;\n }\n // Make a copy of the criteria.\n const copy = { ...criteria };\n // Apply the mutations to the copy and return it.", "score": 0.8646004796028137 } ]
typescript
if (this._objectDiscovery.isCondition(node)) {
import { ObjectDiscovery } from "./object-discovery"; import { Condition, Constraint, Rule } from "../types/rule"; export class Evaluator { private _objectDiscovery: ObjectDiscovery = new ObjectDiscovery(); /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. */ evaluate(rule: Rule, criteria: object | object[]): boolean | any { // Cater for the case where the conditions property is not an array. const conditions = rule.conditions instanceof Array ? rule.conditions : [rule.conditions]; if (criteria instanceof Array) { const result = []; for (const c of criteria) { result.push(this.evaluateRule(conditions, c, rule?.default)); } return result; } return this.evaluateRule(conditions, criteria, rule?.default); } /** * Evaluates a rule against a set of criteria and returns the result. * @param conditions The conditions to evaluate. * @param criteria The criteria to evaluate the conditions against. * @param defaultResult The default result to return if no conditions pass. */ private evaluateRule( conditions: Condition[], criteria: object, defaultResult?: any ): boolean | any { // We should evaluate all conditions and return the result // of the first condition that passes. for (const condition of conditions) { const result = this.evaluateCondition(condition, criteria); if (result) { return condition?.result ?? true; } } // If no conditions pass, we should return the default result of // the rule or false if no default result is provided. return defaultResult ?? false; } /** * Evaluates a condition against a set of criteria and returns the result. * Uses recursion to evaluate nested conditions. * @param condition The condition to evaluate. * @param criteria The criteria to evaluate the condition against. */ private evaluateCondition(condition: Condition, criteria: object): boolean { // The condition must have an 'any' or 'all' property. const type = this._objectDiscovery.conditionType(condition); if (!type) { return false; } // If the type is 'all' or 'none', we should set the initial // result to true, otherwise we should set it to false. let result = ["all", "none"].includes(type); // Check each node in the condition. for (const node of condition[type]) { let fn; if (this._objectDiscovery.isCondition(node)) { fn = "evaluateCondition"; } if (this._objectDiscovery.isConstraint(node)) { fn = "checkConstraint"; } // Process the node switch (type) { case "any": result = result || this[fn](node, criteria); break; case "all": result = result && this[fn](node, criteria); break; case "none": result = result && !this[fn](node, criteria); } } return result; } /** * Checks a constraint against a set of criteria and returns true whenever the constraint passes. * @param constraint The constraint to evaluate. * @param criteria The criteria to evaluate the constraint with. */ private checkConstraint(constraint: Constraint, criteria: object): boolean { // If the value contains '.' we should assume it is a nested property const criterion = constraint.field.includes(".")
? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria) : criteria[constraint.field];
// If the criteria object does not have the field // we are looking for, we should return false. if (!criterion) { return false; } switch (constraint.operator) { case "==": return criterion == constraint.value; case "!=": return criterion != constraint.value; case ">": return criterion > constraint.value; case ">=": return criterion >= constraint.value; case "<": return criterion < constraint.value; case "<=": return criterion <= constraint.value; case "in": return ( Array.isArray(constraint.value) && constraint.value.includes(criterion as never) ); case "not in": return ( !Array.isArray(constraint.value) || !constraint.value.includes(criterion as never) ); default: return false; } } }
src/services/evaluator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/mutator.ts", "retrieved_chunk": " * @param criteria The criteria to check.\n * @param result Whether a mutate-able property has been found.\n * @param parentPath The parent path to the current property.\n */\n private hasMutations(\n criteria: object,\n result: boolean = false,\n parentPath: string = \"\"\n ): boolean {\n // If we have already found a mutation, we can stop.", "score": 0.9176802635192871 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " /**\n * Checks a constraint to ensure it is syntactically correct.\n * @param constraint The constraint to validate.\n */\n private validateConstraint(constraint: Constraint): ValidationResult {\n if (\"string\" !== typeof constraint.field) {\n return {\n isValid: false,\n error: {\n message: 'Constraint \"field\" must be of type string.',", "score": 0.9176672697067261 }, { "filename": "src/services/mutator.ts", "retrieved_chunk": " return result;\n }\n /**\n * Recursively applies mutations to the criteria.\n * @param criteria The criteria to mutate.\n * @param parentPath The parent path to the current property.\n */\n private async applyMutations(\n criteria: object,\n parentPath: string = \"\"", "score": 0.9100797176361084 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {", "score": 0.9098504781723022 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n * @param trustRule Set true to avoid validating the rule before evaluating it (faster).\n * @throws Error if the rule is invalid.\n */\n static async evaluate<T>(\n rule: Rule,\n criteria: object | object[],\n trustRule = false\n ): Promise<T> {", "score": 0.9097380638122559 } ]
typescript
? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria) : criteria[constraint.field];
import IssueModel from "../models/IssueModel"; import BookModel from "../models/BookModel"; import UserModel from "../models/UserModel"; import Token from "../lib/GenerateToken"; import { ERROR } from "../common/const"; import { TokStatus, Issue } from "../common/types"; import { sendJsonResponse, sendEpubResponse, parseSimplePostData, uuid, getBufferFromRawURL, } from "../common/utils"; import http from "node:http"; import https from "node:https"; export default async function ( req: http.IncomingMessage, res: http.ServerResponse ) { const ISSUE_DB = new IssueModel(); const BOOK_DB = new BookModel(); const USER_DB = new UserModel(); const authorization = req.headers?.authorization; const authToken = authorization?.split(" ")?.pop()?.trim(); try { if (req.method === "OPTIONS") { sendJsonResponse(res, {}, 200); return; } if (!authorization || !authToken) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } const token = new Token(); const tokenStatus: TokStatus = token.verify(authToken); if ( tokenStatus === TokStatus.INVALID || tokenStatus === TokStatus.INVALID_SIG ) { sendJsonResponse(res, ERROR.unauthorized, 401); return; } await ISSUE_DB.init(); await BOOK_DB.init(); await USER_DB.init(); const parsedAuthToken: any = token.UNSAFE_parse(authToken); if (req.method === "GET") { let URLParams = req.url.split("/").slice(3); let requestedBook = URLParams?.[0]; if (requestedBook) { let targetBook = await BOOK_DB.getBook(requestedBook); if (!targetBook) { sendJsonResponse(
res, ERROR.resourceNotExists, 404);
return; } let epubResourcePath = targetBook.path; const response: Array<Buffer> = await new Promise((resolve, reject) => { https.get(epubResourcePath, (res) => { let data: Array<Buffer> = []; res.on("data", (d: Buffer) => data.push(d)); res.on("end", () => resolve(data)); res.on("error", (error) => reject(error)); }); }); let epubBuffer = Buffer.concat(response); sendEpubResponse(res, epubBuffer); return; } else { let userIssues = await ISSUE_DB.getIssues(parsedAuthToken.id); if (!userIssues) { sendJsonResponse(res, ERROR.resourceNotExists, 404); } else { sendJsonResponse(res, userIssues, 200); } } } else if (req.method === "POST") { if (req.headers?.["content-type"] != "application/json") { sendJsonResponse(res, ERROR.invalidMimeForResource, 415); return; } let issueData: Issue; try { let issuePostData = await parseSimplePostData(req); issueData = JSON.parse(issuePostData.toString()); } catch (error) { console.error(error); sendJsonResponse(res, ERROR.badRequest, 400); return; } if (!issueData.lenderid || !issueData.bookid) { sendJsonResponse(res, ERROR.badRequest, 400); return; } let foundLender = await USER_DB.getUserByID(issueData.lenderid); let foundBook = await BOOK_DB.getBook(issueData.bookid); if (!foundLender || !foundBook) { sendJsonResponse(res, ERROR.resourceNotExists, 404); return; } let foundIssue = await ISSUE_DB.getIssue( foundLender.id, foundBook.id, parsedAuthToken.id ); if (foundIssue) { sendJsonResponse( res, { ...ERROR.resourceExists, data: { id: foundIssue.id, bookid: foundIssue.bookid, }, }, 409 ); return; } let issueid = uuid(); let issueEntry: Issue = { id: issueid, borrowerid: parsedAuthToken.id, lenderid: foundLender.id, bookid: foundBook.id, }; const pushed = await ISSUE_DB.pushIssue(issueEntry); if (!pushed) { sendJsonResponse(res, ERROR.internalErr, 500); return; } sendJsonResponse( res, { error: null, message: `successfully created a new issue of id ${issueEntry.id}`, data: { id: pushed.id, borrower: pushed.borrowerid, lender: pushed.lenderid, book: foundBook.title, }, }, 201 ); } } finally { await ISSUE_DB.close(); await BOOK_DB.close(); await USER_DB.close(); } }
src/routes/Issue.ts
Aadv1k-quillia-52c5b34
[ { "filename": "src/routes/Books.ts", "retrieved_chunk": " try {\n if (req.method === \"GET\") {\n try {\n let userBooks = await BOOK_DB.getBooks();\n userBooks = userBooks.map((e) => {\n delete e.path;\n return e;\n });\n sendJsonResponse(res, userBooks, 200);\n } catch (error) {", "score": 0.8513033390045166 }, { "filename": "src/routes/Signup.ts", "retrieved_chunk": ") {\n const DB = new UserModel();\n if (req.method !== \"POST\") {\n sendJsonResponse(res, ERROR.methodNotAllowed, 405);\n return;\n }\n let data: any = await parseSimplePostData(req);\n data = data.toString();\n let parsedData: User;\n try {", "score": 0.8242897987365723 }, { "filename": "src/routes/Books.ts", "retrieved_chunk": " }\n const parsedAuthToken: any = token.UNSAFE_parse(authToken);\n let body: Buffer;\n body = await parseSimplePostData(req);\n let data: any;\n try {\n data = JSON.parse(body.toString());\n } catch {\n sendJsonResponse(res, ERROR.invalidJSONData, 400);\n return;", "score": 0.8118864893913269 }, { "filename": "src/routes/Books.ts", "retrieved_chunk": " id: epubEntry.id,\n },\n },\n 201\n );\n } else if (req.method === \"DELETE\") {\n const authorization = req.headers?.authorization;\n const authToken = authorization?.split(\" \")?.pop();\n if (!authorization || !authToken) {\n sendJsonResponse(res, ERROR.unauthorized, 401);", "score": 0.8094217777252197 }, { "filename": "src/routes/Login.ts", "retrieved_chunk": " const DB = new UserModel();\n let data: any = await parseSimplePostData(req);\n data = data.toString();\n if (req.method !== \"POST\") {\n sendJsonResponse(res, ERROR.methodNotAllowed, 405);\n return;\n }\n let parsedData: User;\n try {\n parsedData = JSON.parse(data);", "score": 0.808125376701355 } ]
typescript
res, ERROR.resourceNotExists, 404);
import { ObjectDiscovery } from "./object-discovery"; import { Condition, Constraint, Operator, Rule } from "../types/rule"; export interface ValidationResult { isValid: boolean; error?: { message: string; element: object; }; } export class Validator { private objectDiscovery: ObjectDiscovery = new ObjectDiscovery(); /** * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not. * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { // Assume the rule is valid. let result: ValidationResult = { isValid: true }; // Check the rule is a valid JSON if (!this.objectDiscovery.isObject(rule)) { return { isValid: false, error: { message: "The rule must be a valid JSON object.", element: rule, }, }; } // Cater for the case where the conditions property is not an array. const conditions = rule.conditions instanceof Array ? rule.conditions : [rule.conditions]; // Validate the 'conditions' property. if ( conditions.length === 0 || (this.objectDiscovery.isObject(conditions[0]) && !Object.keys(conditions[0]).length) ) { return { isValid: false, error: { message: "The conditions property must contain at least one condition.", element: rule, }, }; } // Validate each condition in the rule. for (const condition of conditions) { const subResult = this.validateCondition(condition); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } return result; } /** ml/l.k, * Evaluates a condition to ensure it is syntactically correct. * @param condition The condition to validate. * @param depth The current recursion depth */ private validateCondition( condition: Condition, depth: number = 0 ): ValidationResult { // Check to see if the condition is valid. let result = this.isValidCondition(condition); if (!result.isValid) { return result; } // Set the type of condition. const type = this.objectDiscovery.conditionType(condition); // Check if the condition is iterable if(!Array.isArray(condition[type])) { return { isValid: false, error: { message: `The condition '${type}' should be iterable.`, element: condition, }, }; } // Validate each item in the condition. for (const node of condition[type]) { const isCondition = this.objectDiscovery.isCondition(node); if (isCondition) { const subResult = this.validateCondition(node as Condition, depth + 1); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } const isConstraint = this.objectDiscovery.isConstraint(node); if (isConstraint) { const subResult = this.validateConstraint(node as Constraint); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } if (!isConstraint && !isCondition) { return { isValid: false, error: { message: "Each node should be a condition or constraint.", element: node, }, }; } // Result is only valid on the root condition. if (depth > 0 && "result" in condition) { return { isValid: false, error: { message: 'Nested conditions cannot have a property "result".', element: node, }, }; } // If any part fails validation there is no point to continue. if (!result.isValid) { break; } } return result; } /** * Checks a constraint to ensure it is syntactically correct. * @param constraint The constraint to validate. */ private validateConstraint(constraint: Constraint): ValidationResult { if ("string" !== typeof constraint.field) { return { isValid: false, error: { message: 'Constraint "field" must be of type string.', element: constraint, }, }; } const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"];
if (!operators.includes(constraint.operator as Operator)) {
return { isValid: false, error: { message: 'Constraint "operator" has invalid type.', element: constraint, }, }; } // We must check that the value is an array if the operator is 'in' or 'not in'. if ( ["in", "not in"].includes(constraint.operator) && !Array.isArray(constraint.value) ) { return { isValid: false, error: { message: 'Constraint "value" must be an array if the "operator" is "in" or "not in"', element: constraint, }, }; } return { isValid: true }; } /** * Checks an object to see if it is a valid condition. * @param obj The object to check. */ private isValidCondition(obj: any): ValidationResult { if (!this.objectDiscovery.isCondition(obj)) { return { isValid: false, error: { message: "Invalid condition structure.", element: obj, }, }; } const isAny = "any" in obj; const isAll = "all" in obj; const isNone = "none" in obj; // A valid condition must have an 'any', 'all', or 'none' property, // but cannot have more than one. if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) { return { isValid: false, error: { message: 'A condition cannot have more than one "any", "all", or "none" property.', element: obj, }, }; } return { isValid: true }; } }
src/services/validator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/types/rule.ts", "retrieved_chunk": "export type ConditionType = \"any\" | \"all\" | \"none\";\nexport type Operator = \"==\" | \"!=\" | \">\" | \"<\" | \">=\" | \"<=\" | \"in\" | \"not in\";\nexport interface Constraint {\n field: string;\n operator: Operator;\n value:\n | string\n | number\n | boolean\n | object", "score": 0.8472096920013428 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " return false;\n }\n switch (constraint.operator) {\n case \"==\":\n return criterion == constraint.value;\n case \"!=\":\n return criterion != constraint.value;\n case \">\":\n return criterion > constraint.value;\n case \">=\":", "score": 0.8190062046051025 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " return criterion >= constraint.value;\n case \"<\":\n return criterion < constraint.value;\n case \"<=\":\n return criterion <= constraint.value;\n case \"in\":\n return (\n Array.isArray(constraint.value) &&\n constraint.value.includes(criterion as never)\n );", "score": 0.8141763210296631 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " constraint(\n field: string,\n operator: Operator,\n value: Constraint[\"value\"]\n ): Constraint {\n return {\n field,\n operator,\n value,\n };", "score": 0.8045507669448853 }, { "filename": "src/services/object-discovery.ts", "retrieved_chunk": " }\n /**\n * Checks an object to see if it is a valid constraint.\n * @param obj The object to check.\n */\n isConstraint(obj: unknown): obj is Constraint {\n return !this.isObject(obj)\n ? false\n : \"field\" in obj && \"operator\" in obj && \"value\" in obj;\n }", "score": 0.7893792390823364 } ]
typescript
if (!operators.includes(constraint.operator as Operator)) {
import { Builder } from "./builder"; import { Mutator } from "./mutator"; import { Evaluator } from "./evaluator"; import { ValidationResult, Validator } from "./validator"; import { Rule } from "../types/rule"; import { RuleError } from "../types/error"; export class RulePilot { private static _rulePilot = new RulePilot(); private _mutator: Mutator = new Mutator(); private _validator: Validator = new Validator(); private _evaluator: Evaluator = new Evaluator(); /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ builder(): Builder { return new Builder(this._validator); } /** * Adds a mutation to the rule pilot instance. * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ addMutation(name: string, mutation: Function): RulePilot { this._mutator.add(name, mutation); return this; } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ removeMutation(name: string): RulePilot { this._mutator.remove(name); return this; } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ clearMutationCache(name?: string): RulePilot { this._mutator.clearCache(name); return this; } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { // Before we evaluate the rule, we should validate it. // If `trustRuleset` is set to true, we will skip validation. const validationResult = !trustRule && this.validate(rule);
if (!trustRule && !validationResult.isValid) {
throw new RuleError(validationResult); } return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria)); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { return this._validator.validate(rule); } /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ static builder(): Builder { return this._rulePilot.builder(); } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ static async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ static validate(rule: Rule): ValidationResult { return RulePilot._rulePilot.validate(rule); } /** * Adds a mutation. * * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ static addMutation(name: string, mutation: Function): RulePilot { return RulePilot._rulePilot.addMutation(name, mutation); } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ static removeMutation(name: string): RulePilot { return RulePilot._rulePilot.removeMutation(name); } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ static clearMutationCache(name?: string): RulePilot { return RulePilot._rulePilot.clearMutationCache(name); } }
src/services/rule-pilot.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param defaultResult The default result to return if no conditions pass.\n */\n private evaluateRule(\n conditions: Condition[],\n criteria: object,\n defaultResult?: any\n ): boolean | any {\n // We should evaluate all conditions and return the result\n // of the first condition that passes.\n for (const condition of conditions) {", "score": 0.8958262801170349 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {", "score": 0.8946452140808105 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n */\n evaluate(rule: Rule, criteria: object | object[]): boolean | any {\n // Cater for the case where the conditions property is not an array.\n const conditions =\n rule.conditions instanceof Array ? rule.conditions : [rule.conditions];\n if (criteria instanceof Array) {\n const result = [];\n for (const c of criteria) {", "score": 0.8898243308067322 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " condition: Condition,\n depth: number = 0\n ): ValidationResult {\n // Check to see if the condition is valid.\n let result = this.isValidCondition(condition);\n if (!result.isValid) {\n return result;\n }\n // Set the type of condition.\n const type = this.objectDiscovery.conditionType(condition);", "score": 0.8857578635215759 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {", "score": 0.8857022523880005 } ]
typescript
if (!trustRule && !validationResult.isValid) {
import { createHash } from "crypto"; import { EventEmitter } from "events"; import { Logger } from "./logger"; import { ObjectDiscovery } from "./object-discovery"; export class Mutator { private _cache: Map<string, any> = new Map(); private _buffer: Map<string, boolean> = new Map(); private _mutations: Map<string, Function> = new Map(); private _objectDiscovery = new ObjectDiscovery(); private _eventEmitter = new EventEmitter(); /** * Adds a mutation to the mutator instance. * @param name The name of the mutation. * @param mutation The mutation function. */ add(name: string, mutation: Function): void { this._mutations.set(name, mutation); } /** * Removes a mutation to the mutator instance. * Any cached mutation values for this mutation will be purged. * @param name The name of the mutation. */ remove(name: string): void { this.clearCache(name); this._mutations.delete(name); } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * @param name The mutator name to clear the cache for. */ clearCache(name?: string): void { if (!name) { this._cache.clear(); return; } for (const key of this._cache.keys()) { if (key.startsWith(name)) { this._cache.delete(key); } } } /** * Mutates and returns a criteria object. * @param criteria The criteria to mutate. */ async mutate(criteria: object | object[]): Promise<object | object[]> { // Handles checking the mutability of a criteria object // If it is mutable it will be cloned, mutated and returned const exec = async (criteria) => { // If there are no mutations or the criteria does not contain // any of the mutation keys, return the criteria as is. if (!this._mutations.size || !this.hasMutations(criteria)) { return criteria; } // Make a copy of the criteria. const copy = { ...criteria }; // Apply the mutations to the copy and return it. await this.applyMutations(copy); return copy; }; // If the criteria is an array, we want to apply the mutations // to each item in the array in parallel. if (criteria instanceof Array) { return await Promise.all( criteria.map( (c) => new Promise(async (resolve) => { resolve(await exec(c)); }) ) ); } else { return await exec(criteria); } } /** * Checks if the criteria contains any mutate-able properties. * @param criteria The criteria to check. * @param result Whether a mutate-able property has been found. * @param parentPath The parent path to the current property. */ private hasMutations( criteria: object, result: boolean = false, parentPath: string = "" ): boolean { // If we have already found a mutation, we can stop. if (result) return true; for (const key of Object.keys(criteria)) { if (result) return true; // Prepare dotted path to the current property. const path = parentPath ? `${parentPath}.${key}` : key; // If the value is an object, we should recurse. result = this._objectDiscovery.isObject(criteria[key]) ? result || this.hasMutations(criteria[key], result, path) : result || this._mutations.has(path); } return result; } /** * Recursively applies mutations to the criteria. * @param criteria The criteria to mutate. * @param parentPath The parent path to the current property. */ private async applyMutations( criteria: object, parentPath: string = "" ): Promise<void> { const promises = Object.keys(criteria).map( async (key) => new Promise(async (resolve) => { // Prepare dotted path to the current property. const path = parentPath ? `${parentPath}.${key}` : key; if (this._objectDiscovery.isObject(criteria[key])) { await this.applyMutations(criteria[key], path); } if (this._mutations.has(path)) { criteria[key] = await this.execMutation(key, criteria, path); } resolve(criteria[key]); }) ); await Promise.all(promises); } /** * Executes a mutation. * Defers duplicate executions to the same object from a memory cache. * @param criteriaProp The criteria property to execute the mutation on. * @param criteria The criteria to execute the mutation with. * @param mutationKey The key of the mutation to execute. */ private async execMutation( criteriaProp: string, criteria: unknown, mutationKey: string ): Promise<any> { const value = criteria[criteriaProp]; // Create a cache key const cacheKey = `${mutationKey}${createHash("md5") .update(value.toString()) .digest("hex")}`; // If the mutation has already been executed, return the cached result. if (this._cache.has(cacheKey)) {
Logger.debug(`Cache hit on "${mutationKey}" with param "${value}"`);
return this._cache.get(cacheKey); } // If the mutation is already in progress, wait for it to finish. if (this._buffer.get(cacheKey)) { return await new Promise((resolve) => { Logger.debug( `Waiting on mutation "${mutationKey}" with param "${value}"` ); this._eventEmitter.once(`mutation:${cacheKey}`, (result) => { Logger.debug( `Resolved mutation "${mutationKey}" with param "${value}"` ); resolve(result); }); }); } // Set the buffer to true to indicate that the mutation is in progress. // This prevents duplicate executions of the same mutation. this._buffer.set(cacheKey, true); // Execute the mutation Logger.debug(`Running mutation "${mutationKey}" with param "${value}"`); const mutation = this._mutations.get(mutationKey); const result = await mutation(value, criteria); // Cache the result and release the buffer to false. this._cache.set(cacheKey, result); this._buffer.set(cacheKey, false); // Emit an event to indicate that the mutation has been executed. this._eventEmitter.emit(`mutation:${cacheKey}`, result); return result; } }
src/services/mutator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param criteria The criteria to evaluate the constraint with.\n */\n private checkConstraint(constraint: Constraint, criteria: object): boolean {\n // If the value contains '.' we should assume it is a nested property\n const criterion = constraint.field.includes(\".\")\n ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria)\n : criteria[constraint.field];\n // If the criteria object does not have the field\n // we are looking for, we should return false.\n if (!criterion) {", "score": 0.7678075432777405 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " condition: Condition,\n depth: number = 0\n ): ValidationResult {\n // Check to see if the condition is valid.\n let result = this.isValidCondition(condition);\n if (!result.isValid) {\n return result;\n }\n // Set the type of condition.\n const type = this.objectDiscovery.conditionType(condition);", "score": 0.7638512253761292 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " * @throws Error if the rule is invalid.\n */\n async evaluate<T>(\n rule: Rule,\n criteria: object | object[],\n trustRule = false\n ): Promise<T> {\n // Before we evaluate the rule, we should validate it.\n // If `trustRuleset` is set to true, we will skip validation.\n const validationResult = !trustRule && this.validate(rule);", "score": 0.762938916683197 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n */\n evaluate(rule: Rule, criteria: object | object[]): boolean | any {\n // Cater for the case where the conditions property is not an array.\n const conditions =\n rule.conditions instanceof Array ? rule.conditions : [rule.conditions];\n if (criteria instanceof Array) {\n const result = [];\n for (const c of criteria) {", "score": 0.7543551921844482 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }", "score": 0.7506780624389648 } ]
typescript
Logger.debug(`Cache hit on "${mutationKey}" with param "${value}"`);
import { Inject, Injectable, Logger } from '@nestjs/common' import { ExchangeRateRepository } from './exchange-rate.repository' import { FreeCurrencyConversionExchangeRateRepository } from './free-currency-conversion-exchange-rate.repository' import { HostExchangeRateRepository } from './host-exchange-rate.repository' @Injectable() export class RedundantExchangeRateRepository implements ExchangeRateRepository { private logger = new Logger(RedundantExchangeRateRepository.name) constructor( @Inject(FreeCurrencyConversionExchangeRateRepository) private freeCurrencyConversionExchangeRateRepository: FreeCurrencyConversionExchangeRateRepository, @Inject(HostExchangeRateRepository) private hostExchangeRateRepository: HostExchangeRateRepository ) {} async getSpotPrice(fromCurrency: string, toCurrency: string): Promise<number> { this.logger.log({ message: 'Get spot price', fromCurrency, toCurrency }) try { const spotPrice = await this.freeCurrencyConversionExchangeRateRepository.getSpotPrice( fromCurrency, toCurrency ) this.logger.log({ message: 'Successfully got spot price', fromCurrency, toCurrency, spotPrice }) return spotPrice } catch (error) { this.logger.log({ message: 'Failed to get spot price. Falling back to another exchange rate', fromCurrency, toCurrency, error })
return this.hostExchangeRateRepository.getSpotPrice(fromCurrency, toCurrency) }
} }
src/repository/redundant-exchange-rate.repository.ts
tech-leads-club-nestjs-dependency-inversion-5d4fefe
[ { "filename": "src/client/free-currency-conversion.client.ts", "retrieved_chunk": " }\n })\n .pipe(\n map((response) => response.data.data),\n tap((rates) =>\n this.logger.log({\n message: 'Received latest rates',\n baseCurrency,\n rates\n })", "score": 0.8034064769744873 }, { "filename": "src/service/exchange-rate.service.ts", "retrieved_chunk": " getSpotPrice(fromCurrency: string, toCurrency: string): Promise<number> {\n return this.repository.getSpotPrice(fromCurrency, toCurrency)\n }\n}", "score": 0.7759429216384888 }, { "filename": "src/client/exchange-host.client.ts", "retrieved_chunk": " params: {\n base: baseCurrency.toUpperCase()\n }\n })\n .pipe(\n map((response) => LatestResponse.parse(response.data)),\n map((data) => data.rates),\n tap((rates) =>\n this.logger.log({\n message: 'Received latest rates',", "score": 0.7629655599594116 }, { "filename": "src/client/exchange-host.client.ts", "retrieved_chunk": " getLatestRates(baseCurrency: string): Promise<Rates> {\n this.logger.log({\n message: 'Fetching latest rates',\n baseCurrency\n })\n return lastValueFrom(\n this.http\n .request<unknown>({\n method: 'GET',\n url: `${ExchangeHostClient.BASE_URL}/latest`,", "score": 0.759325385093689 }, { "filename": "src/client/free-currency-conversion.client.ts", "retrieved_chunk": "export class FreeCurrencyConversionClient {\n private logger = new Logger(FreeCurrencyConversionClient.name)\n static BASE_URL = 'https://api.freecurrencyapi.com/v1'\n constructor(\n @Inject(HttpService) private http: HttpService,\n @Inject(ConfigService) private config: ConfigService\n ) {}\n getLatestRates(baseCurrency: string): Promise<Rates> {\n this.logger.log({\n message: 'Fetching latest rates',", "score": 0.7459326982498169 } ]
typescript
return this.hostExchangeRateRepository.getSpotPrice(fromCurrency, toCurrency) }
import { Builder } from "./builder"; import { Mutator } from "./mutator"; import { Evaluator } from "./evaluator"; import { ValidationResult, Validator } from "./validator"; import { Rule } from "../types/rule"; import { RuleError } from "../types/error"; export class RulePilot { private static _rulePilot = new RulePilot(); private _mutator: Mutator = new Mutator(); private _validator: Validator = new Validator(); private _evaluator: Evaluator = new Evaluator(); /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ builder(): Builder { return new Builder(this._validator); } /** * Adds a mutation to the rule pilot instance. * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ addMutation(name: string, mutation: Function): RulePilot { this._mutator.add(name, mutation); return this; } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ removeMutation(name: string): RulePilot { this._mutator.remove(name); return this; } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ clearMutationCache(name?: string): RulePilot { this._mutator.clearCache(name); return this; } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { // Before we evaluate the rule, we should validate it. // If `trustRuleset` is set to true, we will skip validation. const validationResult = !trustRule && this.validate(rule); if (!trustRule && !validationResult.isValid) { throw new RuleError(validationResult); }
return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria));
} /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { return this._validator.validate(rule); } /** * Returns a rule builder class instance. * Allows for the construction of rules using a fluent interface. */ static builder(): Builder { return this._rulePilot.builder(); } /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. * @param trustRule Set true to avoid validating the rule before evaluating it (faster). * @throws Error if the rule is invalid. */ static async evaluate<T>( rule: Rule, criteria: object | object[], trustRule = false ): Promise<T> { return RulePilot._rulePilot.evaluate<T>(rule, criteria, trustRule); } /** * Takes in a rule as a parameter and returns a ValidationResult * indicating whether the rule is valid or not. * * Invalid rules will contain an error property which contains a message and the element * that caused the validation to fail. * * @param rule The rule to validate. */ static validate(rule: Rule): ValidationResult { return RulePilot._rulePilot.validate(rule); } /** * Adds a mutation. * * Mutations allow for the modification of the criteria before * it is evaluated against a rule. * * @param name The name of the mutation. * @param mutation The mutation function. */ static addMutation(name: string, mutation: Function): RulePilot { return RulePilot._rulePilot.addMutation(name, mutation); } /** * Removes a mutation to the rule pilot instance. * Any cached mutation values for this mutation will be purged. * * @param name The name of the mutation. */ static removeMutation(name: string): RulePilot { return RulePilot._rulePilot.removeMutation(name); } /** * Clears the mutator cache. * The entire cache, or cache for a specific mutator, can be cleared * by passing or omitting the mutator name as an argument. * * @param name The mutator name to clear the cache for. */ static clearMutationCache(name?: string): RulePilot { return RulePilot._rulePilot.clearMutationCache(name); } }
src/services/rule-pilot.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/validator.ts", "retrieved_chunk": " condition: Condition,\n depth: number = 0\n ): ValidationResult {\n // Check to see if the condition is valid.\n let result = this.isValidCondition(condition);\n if (!result.isValid) {\n return result;\n }\n // Set the type of condition.\n const type = this.objectDiscovery.conditionType(condition);", "score": 0.8802819848060608 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " this.rule.default = value;\n return this;\n }\n /**\n * Builds the rule being and returns it\n * @param validate Whether to validate the rule before returning it\n * @throws Error if validation is enabled and the rule is invalid\n */\n build(validate?: boolean): Rule {\n if (!validate) {", "score": 0.8631728887557983 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " private objectDiscovery: ObjectDiscovery = new ObjectDiscovery();\n /**\n * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not.\n * @param rule The rule to validate.\n */\n validate(rule: Rule): ValidationResult {\n // Assume the rule is valid.\n let result: ValidationResult = { isValid: true };\n // Check the rule is a valid JSON\n if (!this.objectDiscovery.isObject(rule)) {", "score": 0.8593288660049438 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " return this.rule;\n }\n const validationResult = this.validator.validate(this.rule);\n if (validationResult.isValid) {\n return this.rule;\n }\n throw new RuleError(validationResult);\n }\n /**\n * Creates a new condition node", "score": 0.858710527420044 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n */\n evaluate(rule: Rule, criteria: object | object[]): boolean | any {\n // Cater for the case where the conditions property is not an array.\n const conditions =\n rule.conditions instanceof Array ? rule.conditions : [rule.conditions];\n if (criteria instanceof Array) {\n const result = [];\n for (const c of criteria) {", "score": 0.8526898622512817 } ]
typescript
return this._evaluator.evaluate(rule, await this._mutator.mutate(criteria));
import { ObjectDiscovery } from "./object-discovery"; import { Condition, Constraint, Rule } from "../types/rule"; export class Evaluator { private _objectDiscovery: ObjectDiscovery = new ObjectDiscovery(); /** * Evaluates a rule against a set of criteria and returns the result. * If the criteria is an array (indicating multiple criteria to test), * the rule will be evaluated against each item in the array and * an array of results will be returned. * * @param rule The rule to evaluate. * @param criteria The criteria to evaluate the rule against. */ evaluate(rule: Rule, criteria: object | object[]): boolean | any { // Cater for the case where the conditions property is not an array. const conditions = rule.conditions instanceof Array ? rule.conditions : [rule.conditions]; if (criteria instanceof Array) { const result = []; for (const c of criteria) { result.push(this.evaluateRule(conditions, c, rule?.default)); } return result; } return this.evaluateRule(conditions, criteria, rule?.default); } /** * Evaluates a rule against a set of criteria and returns the result. * @param conditions The conditions to evaluate. * @param criteria The criteria to evaluate the conditions against. * @param defaultResult The default result to return if no conditions pass. */ private evaluateRule( conditions: Condition[], criteria: object, defaultResult?: any ): boolean | any { // We should evaluate all conditions and return the result // of the first condition that passes. for (const condition of conditions) { const result = this.evaluateCondition(condition, criteria); if (result) { return condition?.result ?? true; } } // If no conditions pass, we should return the default result of // the rule or false if no default result is provided. return defaultResult ?? false; } /** * Evaluates a condition against a set of criteria and returns the result. * Uses recursion to evaluate nested conditions. * @param condition The condition to evaluate. * @param criteria The criteria to evaluate the condition against. */ private evaluateCondition(condition: Condition, criteria: object): boolean { // The condition must have an 'any' or 'all' property.
const type = this._objectDiscovery.conditionType(condition);
if (!type) { return false; } // If the type is 'all' or 'none', we should set the initial // result to true, otherwise we should set it to false. let result = ["all", "none"].includes(type); // Check each node in the condition. for (const node of condition[type]) { let fn; if (this._objectDiscovery.isCondition(node)) { fn = "evaluateCondition"; } if (this._objectDiscovery.isConstraint(node)) { fn = "checkConstraint"; } // Process the node switch (type) { case "any": result = result || this[fn](node, criteria); break; case "all": result = result && this[fn](node, criteria); break; case "none": result = result && !this[fn](node, criteria); } } return result; } /** * Checks a constraint against a set of criteria and returns true whenever the constraint passes. * @param constraint The constraint to evaluate. * @param criteria The criteria to evaluate the constraint with. */ private checkConstraint(constraint: Constraint, criteria: object): boolean { // If the value contains '.' we should assume it is a nested property const criterion = constraint.field.includes(".") ? this._objectDiscovery.resolveNestedProperty(constraint.field, criteria) : criteria[constraint.field]; // If the criteria object does not have the field // we are looking for, we should return false. if (!criterion) { return false; } switch (constraint.operator) { case "==": return criterion == constraint.value; case "!=": return criterion != constraint.value; case ">": return criterion > constraint.value; case ">=": return criterion >= constraint.value; case "<": return criterion < constraint.value; case "<=": return criterion <= constraint.value; case "in": return ( Array.isArray(constraint.value) && constraint.value.includes(criterion as never) ); case "not in": return ( !Array.isArray(constraint.value) || !constraint.value.includes(criterion as never) ); default: return false; } } }
src/services/evaluator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/mutator.ts", "retrieved_chunk": " * @param criteria The criteria to check.\n * @param result Whether a mutate-able property has been found.\n * @param parentPath The parent path to the current property.\n */\n private hasMutations(\n criteria: object,\n result: boolean = false,\n parentPath: string = \"\"\n ): boolean {\n // If we have already found a mutation, we can stop.", "score": 0.9285598397254944 }, { "filename": "src/services/mutator.ts", "retrieved_chunk": " return result;\n }\n /**\n * Recursively applies mutations to the criteria.\n * @param criteria The criteria to mutate.\n * @param parentPath The parent path to the current property.\n */\n private async applyMutations(\n criteria: object,\n parentPath: string = \"\"", "score": 0.9282577037811279 }, { "filename": "src/services/validator.ts", "retrieved_chunk": " /**\n * Checks an object to see if it is a valid condition.\n * @param obj The object to check.\n */\n private isValidCondition(obj: any): ValidationResult {\n if (!this.objectDiscovery.isCondition(obj)) {\n return {\n isValid: false,\n error: {\n message: \"Invalid condition structure.\",", "score": 0.9227027297019958 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " */\n static builder(): Builder {\n return this._rulePilot.builder();\n }\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * If the criteria is an array (indicating multiple criteria to test),\n * the rule will be evaluated against each item in the array and\n * an array of results will be returned.\n *", "score": 0.9186381101608276 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " }\n /**\n * Evaluates a rule against a set of criteria and returns the result.\n * If the criteria is an array (indicating multiple criteria to test),\n * the rule will be evaluated against each item in the array and\n * an array of results will be returned.\n *\n * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n * @param trustRule Set true to avoid validating the rule before evaluating it (faster).", "score": 0.9151118993759155 } ]
typescript
const type = this._objectDiscovery.conditionType(condition);
import { ObjectDiscovery } from "./object-discovery"; import { Condition, Constraint, Operator, Rule } from "../types/rule"; export interface ValidationResult { isValid: boolean; error?: { message: string; element: object; }; } export class Validator { private objectDiscovery: ObjectDiscovery = new ObjectDiscovery(); /** * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not. * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { // Assume the rule is valid. let result: ValidationResult = { isValid: true }; // Check the rule is a valid JSON if (!this.objectDiscovery.isObject(rule)) { return { isValid: false, error: { message: "The rule must be a valid JSON object.", element: rule, }, }; } // Cater for the case where the conditions property is not an array. const conditions = rule.conditions instanceof Array ? rule.conditions : [rule.conditions]; // Validate the 'conditions' property. if ( conditions.length === 0 || (this.objectDiscovery.isObject(conditions[0]) && !Object.keys(conditions[0]).length) ) { return { isValid: false, error: { message: "The conditions property must contain at least one condition.", element: rule, }, }; } // Validate each condition in the rule. for (const condition of conditions) { const subResult = this.validateCondition(condition); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } return result; } /** ml/l.k, * Evaluates a condition to ensure it is syntactically correct. * @param condition The condition to validate. * @param depth The current recursion depth */ private validateCondition( condition: Condition, depth: number = 0 ): ValidationResult { // Check to see if the condition is valid. let result = this.isValidCondition(condition); if (!result.isValid) { return result; } // Set the type of condition.
const type = this.objectDiscovery.conditionType(condition);
// Check if the condition is iterable if(!Array.isArray(condition[type])) { return { isValid: false, error: { message: `The condition '${type}' should be iterable.`, element: condition, }, }; } // Validate each item in the condition. for (const node of condition[type]) { const isCondition = this.objectDiscovery.isCondition(node); if (isCondition) { const subResult = this.validateCondition(node as Condition, depth + 1); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } const isConstraint = this.objectDiscovery.isConstraint(node); if (isConstraint) { const subResult = this.validateConstraint(node as Constraint); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } if (!isConstraint && !isCondition) { return { isValid: false, error: { message: "Each node should be a condition or constraint.", element: node, }, }; } // Result is only valid on the root condition. if (depth > 0 && "result" in condition) { return { isValid: false, error: { message: 'Nested conditions cannot have a property "result".', element: node, }, }; } // If any part fails validation there is no point to continue. if (!result.isValid) { break; } } return result; } /** * Checks a constraint to ensure it is syntactically correct. * @param constraint The constraint to validate. */ private validateConstraint(constraint: Constraint): ValidationResult { if ("string" !== typeof constraint.field) { return { isValid: false, error: { message: 'Constraint "field" must be of type string.', element: constraint, }, }; } const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"]; if (!operators.includes(constraint.operator as Operator)) { return { isValid: false, error: { message: 'Constraint "operator" has invalid type.', element: constraint, }, }; } // We must check that the value is an array if the operator is 'in' or 'not in'. if ( ["in", "not in"].includes(constraint.operator) && !Array.isArray(constraint.value) ) { return { isValid: false, error: { message: 'Constraint "value" must be an array if the "operator" is "in" or "not in"', element: constraint, }, }; } return { isValid: true }; } /** * Checks an object to see if it is a valid condition. * @param obj The object to check. */ private isValidCondition(obj: any): ValidationResult { if (!this.objectDiscovery.isCondition(obj)) { return { isValid: false, error: { message: "Invalid condition structure.", element: obj, }, }; } const isAny = "any" in obj; const isAll = "all" in obj; const isNone = "none" in obj; // A valid condition must have an 'any', 'all', or 'none' property, // but cannot have more than one. if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) { return { isValid: false, error: { message: 'A condition cannot have more than one "any", "all", or "none" property.', element: obj, }, }; } return { isValid: true }; } }
src/services/validator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * Evaluates a condition against a set of criteria and returns the result.\n * Uses recursion to evaluate nested conditions.\n * @param condition The condition to evaluate.\n * @param criteria The criteria to evaluate the condition against.\n */\n private evaluateCondition(condition: Condition, criteria: object): boolean {\n // The condition must have an 'any' or 'all' property.\n const type = this._objectDiscovery.conditionType(condition);\n if (!type) {\n return false;", "score": 0.9125041961669922 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param defaultResult The default result to return if no conditions pass.\n */\n private evaluateRule(\n conditions: Condition[],\n criteria: object,\n defaultResult?: any\n ): boolean | any {\n // We should evaluate all conditions and return the result\n // of the first condition that passes.\n for (const condition of conditions) {", "score": 0.8930202722549438 }, { "filename": "src/services/rule-pilot.ts", "retrieved_chunk": " * @throws Error if the rule is invalid.\n */\n async evaluate<T>(\n rule: Rule,\n criteria: object | object[],\n trustRule = false\n ): Promise<T> {\n // Before we evaluate the rule, we should validate it.\n // If `trustRuleset` is set to true, we will skip validation.\n const validationResult = !trustRule && this.validate(rule);", "score": 0.8918649554252625 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n */\n evaluate(rule: Rule, criteria: object | object[]): boolean | any {\n // Cater for the case where the conditions property is not an array.\n const conditions =\n rule.conditions instanceof Array ? rule.conditions : [rule.conditions];\n if (criteria instanceof Array) {\n const result = [];\n for (const c of criteria) {", "score": 0.8912695646286011 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }", "score": 0.890164315700531 } ]
typescript
const type = this.objectDiscovery.conditionType(condition);
import { ObjectDiscovery } from "./object-discovery"; import { Condition, Constraint, Operator, Rule } from "../types/rule"; export interface ValidationResult { isValid: boolean; error?: { message: string; element: object; }; } export class Validator { private objectDiscovery: ObjectDiscovery = new ObjectDiscovery(); /** * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not. * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { // Assume the rule is valid. let result: ValidationResult = { isValid: true }; // Check the rule is a valid JSON if (!this.objectDiscovery.isObject(rule)) { return { isValid: false, error: { message: "The rule must be a valid JSON object.", element: rule, }, }; } // Cater for the case where the conditions property is not an array. const conditions = rule.conditions instanceof Array ? rule.conditions : [rule.conditions]; // Validate the 'conditions' property. if ( conditions.length === 0 || (this.objectDiscovery.isObject(conditions[0]) && !Object.keys(conditions[0]).length) ) { return { isValid: false, error: { message: "The conditions property must contain at least one condition.", element: rule, }, }; } // Validate each condition in the rule. for (const condition of conditions) { const subResult = this.validateCondition(condition); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } return result; } /** ml/l.k, * Evaluates a condition to ensure it is syntactically correct. * @param condition The condition to validate. * @param depth The current recursion depth */ private validateCondition( condition: Condition, depth: number = 0 ): ValidationResult { // Check to see if the condition is valid. let result = this.isValidCondition(condition); if (!result.isValid) { return result; } // Set the type of condition. const type = this.objectDiscovery.conditionType(condition); // Check if the condition is iterable if(!Array.isArray(condition[type])) { return { isValid: false, error: { message: `The condition '${type}' should be iterable.`, element: condition, }, }; } // Validate each item in the condition. for (const node of condition[type]) {
const isCondition = this.objectDiscovery.isCondition(node);
if (isCondition) { const subResult = this.validateCondition(node as Condition, depth + 1); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } const isConstraint = this.objectDiscovery.isConstraint(node); if (isConstraint) { const subResult = this.validateConstraint(node as Constraint); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } if (!isConstraint && !isCondition) { return { isValid: false, error: { message: "Each node should be a condition or constraint.", element: node, }, }; } // Result is only valid on the root condition. if (depth > 0 && "result" in condition) { return { isValid: false, error: { message: 'Nested conditions cannot have a property "result".', element: node, }, }; } // If any part fails validation there is no point to continue. if (!result.isValid) { break; } } return result; } /** * Checks a constraint to ensure it is syntactically correct. * @param constraint The constraint to validate. */ private validateConstraint(constraint: Constraint): ValidationResult { if ("string" !== typeof constraint.field) { return { isValid: false, error: { message: 'Constraint "field" must be of type string.', element: constraint, }, }; } const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"]; if (!operators.includes(constraint.operator as Operator)) { return { isValid: false, error: { message: 'Constraint "operator" has invalid type.', element: constraint, }, }; } // We must check that the value is an array if the operator is 'in' or 'not in'. if ( ["in", "not in"].includes(constraint.operator) && !Array.isArray(constraint.value) ) { return { isValid: false, error: { message: 'Constraint "value" must be an array if the "operator" is "in" or "not in"', element: constraint, }, }; } return { isValid: true }; } /** * Checks an object to see if it is a valid condition. * @param obj The object to check. */ private isValidCondition(obj: any): ValidationResult { if (!this.objectDiscovery.isCondition(obj)) { return { isValid: false, error: { message: "Invalid condition structure.", element: obj, }, }; } const isAny = "any" in obj; const isAll = "all" in obj; const isNone = "none" in obj; // A valid condition must have an 'any', 'all', or 'none' property, // but cannot have more than one. if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) { return { isValid: false, error: { message: 'A condition cannot have more than one "any", "all", or "none" property.', element: obj, }, }; } return { isValid: true }; } }
src/services/validator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * Evaluates a condition against a set of criteria and returns the result.\n * Uses recursion to evaluate nested conditions.\n * @param condition The condition to evaluate.\n * @param criteria The criteria to evaluate the condition against.\n */\n private evaluateCondition(condition: Condition, criteria: object): boolean {\n // The condition must have an 'any' or 'all' property.\n const type = this._objectDiscovery.conditionType(condition);\n if (!type) {\n return false;", "score": 0.8693563342094421 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }", "score": 0.8648900389671326 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " * @param rule The rule to evaluate.\n * @param criteria The criteria to evaluate the rule against.\n */\n evaluate(rule: Rule, criteria: object | object[]): boolean | any {\n // Cater for the case where the conditions property is not an array.\n const conditions =\n rule.conditions instanceof Array ? rule.conditions : [rule.conditions];\n if (criteria instanceof Array) {\n const result = [];\n for (const c of criteria) {", "score": 0.8590830564498901 }, { "filename": "src/services/object-discovery.ts", "retrieved_chunk": "import { Condition, ConditionType, Constraint } from \"../types/rule\";\nexport class ObjectDiscovery {\n /**\n * Returns the type of condition passed to the function.\n * @param condition The condition to check.\n */\n conditionType(condition: Condition): ConditionType | null {\n if (\"any\" in condition) return \"any\";\n if (\"all\" in condition) return \"all\";\n if (\"none\" in condition) return \"none\";", "score": 0.8503174781799316 }, { "filename": "src/services/builder.ts", "retrieved_chunk": " * @param type The type of condition\n * @param nodes Any child nodes of the condition\n * @param result The result of the condition node (for granular rules)\n */\n condition(\n type: ConditionType,\n nodes: Condition[ConditionType],\n result?: Condition[\"result\"]\n ): Condition {\n return {", "score": 0.8475513458251953 } ]
typescript
const isCondition = this.objectDiscovery.isCondition(node);
import { ObjectDiscovery } from "./object-discovery"; import { Condition, Constraint, Operator, Rule } from "../types/rule"; export interface ValidationResult { isValid: boolean; error?: { message: string; element: object; }; } export class Validator { private objectDiscovery: ObjectDiscovery = new ObjectDiscovery(); /** * Takes in a rule as a parameter and returns a boolean indicating whether the rule is valid or not. * @param rule The rule to validate. */ validate(rule: Rule): ValidationResult { // Assume the rule is valid. let result: ValidationResult = { isValid: true }; // Check the rule is a valid JSON if (!this.objectDiscovery.isObject(rule)) { return { isValid: false, error: { message: "The rule must be a valid JSON object.", element: rule, }, }; } // Cater for the case where the conditions property is not an array. const conditions = rule.conditions instanceof Array ? rule.conditions : [rule.conditions]; // Validate the 'conditions' property. if ( conditions.length === 0 || (this.objectDiscovery.isObject(conditions[0]) && !Object.keys(conditions[0]).length) ) { return { isValid: false, error: { message: "The conditions property must contain at least one condition.", element: rule, }, }; } // Validate each condition in the rule. for (const condition of conditions) { const subResult = this.validateCondition(condition); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } return result; } /** ml/l.k, * Evaluates a condition to ensure it is syntactically correct. * @param condition The condition to validate. * @param depth The current recursion depth */ private validateCondition( condition: Condition, depth: number = 0 ): ValidationResult { // Check to see if the condition is valid. let result = this.isValidCondition(condition); if (!result.isValid) { return result; } // Set the type of condition. const type = this.objectDiscovery.conditionType(condition); // Check if the condition is iterable if(!Array.isArray(condition[type])) { return { isValid: false, error: { message: `The condition '${type}' should be iterable.`, element: condition, }, }; } // Validate each item in the condition. for (const node of condition[type]) { const isCondition = this.objectDiscovery.isCondition(node); if (isCondition) { const subResult = this.validateCondition(node as Condition, depth + 1); result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } const isConstraint = this.objectDiscovery.isConstraint(node); if (isConstraint) { const subResult = this
.validateConstraint(node as Constraint);
result.isValid = result.isValid && subResult.isValid; result.error = result?.error ?? subResult?.error; } if (!isConstraint && !isCondition) { return { isValid: false, error: { message: "Each node should be a condition or constraint.", element: node, }, }; } // Result is only valid on the root condition. if (depth > 0 && "result" in condition) { return { isValid: false, error: { message: 'Nested conditions cannot have a property "result".', element: node, }, }; } // If any part fails validation there is no point to continue. if (!result.isValid) { break; } } return result; } /** * Checks a constraint to ensure it is syntactically correct. * @param constraint The constraint to validate. */ private validateConstraint(constraint: Constraint): ValidationResult { if ("string" !== typeof constraint.field) { return { isValid: false, error: { message: 'Constraint "field" must be of type string.', element: constraint, }, }; } const operators = ["==", "!=", ">", "<", ">=", "<=", "in", "not in"]; if (!operators.includes(constraint.operator as Operator)) { return { isValid: false, error: { message: 'Constraint "operator" has invalid type.', element: constraint, }, }; } // We must check that the value is an array if the operator is 'in' or 'not in'. if ( ["in", "not in"].includes(constraint.operator) && !Array.isArray(constraint.value) ) { return { isValid: false, error: { message: 'Constraint "value" must be an array if the "operator" is "in" or "not in"', element: constraint, }, }; } return { isValid: true }; } /** * Checks an object to see if it is a valid condition. * @param obj The object to check. */ private isValidCondition(obj: any): ValidationResult { if (!this.objectDiscovery.isCondition(obj)) { return { isValid: false, error: { message: "Invalid condition structure.", element: obj, }, }; } const isAny = "any" in obj; const isAll = "all" in obj; const isNone = "none" in obj; // A valid condition must have an 'any', 'all', or 'none' property, // but cannot have more than one. if ((isAny && isAll) || (isAny && isNone) || (isAll && isNone)) { return { isValid: false, error: { message: 'A condition cannot have more than one "any", "all", or "none" property.', element: obj, }, }; } return { isValid: true }; } }
src/services/validator.ts
andrewbrg-rulepilot-517f473
[ { "filename": "src/services/builder.ts", "retrieved_chunk": " return this.rule;\n }\n const validationResult = this.validator.validate(this.rule);\n if (validationResult.isValid) {\n return this.rule;\n }\n throw new RuleError(validationResult);\n }\n /**\n * Creates a new condition node", "score": 0.8060815930366516 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " if (this._objectDiscovery.isConstraint(node)) {\n fn = \"checkConstraint\";\n }\n // Process the node\n switch (type) {\n case \"any\":\n result = result || this[fn](node, criteria);\n break;\n case \"all\":\n result = result && this[fn](node, criteria);", "score": 0.7890810966491699 }, { "filename": "src/services/mutator.ts", "retrieved_chunk": " if (result) return true;\n for (const key of Object.keys(criteria)) {\n if (result) return true;\n // Prepare dotted path to the current property.\n const path = parentPath ? `${parentPath}.${key}` : key;\n // If the value is an object, we should recurse.\n result = this._objectDiscovery.isObject(criteria[key])\n ? result || this.hasMutations(criteria[key], result, path)\n : result || this._mutations.has(path);\n }", "score": 0.7716595530509949 }, { "filename": "src/services/evaluator.ts", "retrieved_chunk": " }\n // If the type is 'all' or 'none', we should set the initial\n // result to true, otherwise we should set it to false.\n let result = [\"all\", \"none\"].includes(type);\n // Check each node in the condition.\n for (const node of condition[type]) {\n let fn;\n if (this._objectDiscovery.isCondition(node)) {\n fn = \"evaluateCondition\";\n }", "score": 0.7257800698280334 }, { "filename": "src/services/object-discovery.ts", "retrieved_chunk": " }\n /**\n * Checks an object to see if it is a valid constraint.\n * @param obj The object to check.\n */\n isConstraint(obj: unknown): obj is Constraint {\n return !this.isObject(obj)\n ? false\n : \"field\" in obj && \"operator\" in obj && \"value\" in obj;\n }", "score": 0.7183318138122559 } ]
typescript
.validateConstraint(node as Constraint);
import type { FastifyInstance, FastifyRequest } from 'fastify' import { wechatApiPath } from '../const' import { toSha1 } from '../utils/encryptor' import type { VerifyQuery } from './types' export function checkIsWechatRequest(request: FastifyRequest) { const q = request.query as VerifyQuery try { const arr: string[] = [process.env.WECHAT_TOKEN, q.timestamp.toString(), q.nonce.toString()] arr.sort() const sha1 = toSha1(arr.join('')) if (sha1 === q.signature) { // Success. return true } else { return false } } catch (error) { console.error(error) return false } } function route(server: FastifyInstance) { // setup hook server.addHook('onRequest', (request, reply, done) => { // TODO: Do we need to add this hook for all wechat request? if (request?.url?.startsWith(wechatApiPath)) { if (checkIsWechatRequest(request)) { // Continue. done() } else { reply.send('who are you?') } } else { done() } }) server.get(wechatApiPath, (request: FastifyRequest, reply) => { const q = request.query as VerifyQuery if (checkIsWechatRequest(request)) { // Success.
reply.send(q.echostr) }
else { reply.send('who are you?') } }) } export default route
src/wechat/verify.ts
zhouchaoyuan-azure-openai-node-wechat-624e8f4
[ { "filename": "src/azureopenai/acceptor.ts", "retrieved_chunk": " handleChat(request.body, reply)\n })\n}\nasync function handlePrompt(requestBody: any, reply: FastifyReply) {\n GetAzureOpenAIAnswerAsync(requestBody.prompt, 'prompt restapi').then((response) => {\n reply.send(response)\n }).catch((reason) => {\n reply.send(reason)\n })\n}", "score": 0.8244911432266235 }, { "filename": "src/azureopenai/acceptor.ts", "retrieved_chunk": "async function handleChat(requestBody: any, reply: FastifyReply) {\n GetAzureOpenAIChatAnswerAsync(requestBody.messages, 'chat restapi').then((response) => {\n reply.send(response)\n }).catch((reason) => {\n reply.send(reason)\n })\n}\nexport default route", "score": 0.8189043998718262 }, { "filename": "src/wechat/acceptor.ts", "retrieved_chunk": "function getChatHistoryForUser(requestKey: string) {\n if (!chatHistory.has(requestKey))\n chatHistory.set(requestKey, new FixedQueue<ChatCompletionRequestMessage>(pastMessagesIncluded))\n return chatHistory.get(requestKey)\n}\nfunction route(server: FastifyInstance) {\n server.post(wechatApiPath, (request, reply) => {\n const xml = request.body as any\n handleMsg(xml.xml, reply)\n })", "score": 0.8121349811553955 }, { "filename": "src/azureopenai/acceptor.ts", "retrieved_chunk": "import type { FastifyInstance, FastifyReply } from 'fastify'\nimport { chatPath, promptPath } from '../const'\nimport { GetAzureOpenAIAnswerAsync, GetAzureOpenAIChatAnswerAsync } from '../azureopenai/chatgpt'\nfunction route(server: FastifyInstance) {\n server.post(promptPath, (request, reply) => {\n // eslint-disable-next-line no-console\n console.log('prompt')\n handlePrompt(request.body, reply)\n })\n server.post(chatPath, (request, reply) => {", "score": 0.78342205286026 }, { "filename": "src/wechat/acceptor.ts", "retrieved_chunk": " reply.send(generateTextResponse(xml.FromUserName, xml.ToUserName, resp))\n }\n else {\n const checkTime = checkTimes.get(requestKey) as number\n if (checkTime === 2) { // this is the third retry from wechat, we need to response the result within 5s\n const resp = cacheMap.get(requestKey)\n if (resp != null) {\n reply.send(generateTextResponse(xml.FromUserName, xml.ToUserName, resp))\n }\n else {", "score": 0.7655603885650635 } ]
typescript
reply.send(q.echostr) }
import { Action, InputDefinition, Output, OutputDefinition } from '@binsoul/node-red-bundle-processing'; import { ModbusRtu } from '@binsoul/nodejs-modbus'; import { SolarmanV5 } from '@binsoul/nodejs-solarman'; import * as net from 'net'; import { NodeStatus } from 'node-red'; import type { Configuration } from '../Configuration'; import { DeyeRegisters } from '../DeyeRegisters'; import { Storage } from '../Storage'; export class UpdateAction implements Action { private readonly configuration: Configuration; private readonly storage: Storage; private readonly outputCallback: () => void; private readonly nodeStatusCallback: (status: NodeStatus) => void; constructor(configuration: Configuration, storage: Storage, outputCallback: () => void, nodeStatusCallback: (status: NodeStatus) => void) { this.configuration = configuration; this.storage = storage; this.outputCallback = outputCallback; this.nodeStatusCallback = nodeStatusCallback; } defineInput(): InputDefinition { return new InputDefinition(); } defineOutput(): OutputDefinition { return new OutputDefinition(); } execute(): Output { const client = new net.Socket(); client.setTimeout(5000); let hasConnected = false; let errorMessage = ''; let retryCount = 0; const unitAddress = 1; const firstRegister = 0x0003; const lastRegister = 0x0080; const modbus = new ModbusRtu(unitAddress); const modbusFrame = modbus.requestHoldingRegisters(firstRegister, lastRegister); const solarman = new SolarmanV5(this.configuration.deviceSerialNumber, true); const request = solarman.wrapModbusFrame(modbusFrame); // Functions to handle socket events const makeConnection = () => { client.connect({ host: this.configuration.deviceIp, port: 8899 }); }; const connectEventHandler = () => { hasConnected = true; this.storage.setConnected(); client.write(request); }; const dataEventHandler = (data: Buffer) => { try { const modbusFrame = solarman.unwrapModbusFrame(data); const values = modbus.fetchHoldingRegisters(modbusFrame);
const parser = new DeyeRegisters();
this.storage.setData(parser.parse(values)); this.outputCallback(); } catch (error) { if (error instanceof Error) { this.nodeStatusCallback({ fill: 'red', shape: 'dot', text: error.message, }); } } client.end(); }; const timeoutEventHandler = () => { errorMessage = 'Connection timed out'; client.end(); }; const errorEventHandler = (error: Error) => { errorMessage = error.message; client.end(); }; const closeEventHandler = () => { if (hasConnected) { return; } if (!this.storage.isAvailable()) { this.nodeStatusCallback({ fill: 'yellow', shape: 'dot', text: 'unavailable', }); } else if (retryCount < 5) { retryCount++; this.nodeStatusCallback({ fill: 'yellow', shape: 'dot', text: 'retry ' + retryCount, }); setTimeout(makeConnection, 5000); } else { this.nodeStatusCallback({ fill: 'red', shape: 'dot', text: errorMessage, }); } }; client.on('connect', connectEventHandler); client.on('data', dataEventHandler); client.on('timeout', timeoutEventHandler); client.on('error', errorEventHandler); client.on('close', closeEventHandler); this.nodeStatusCallback({ fill: 'yellow', shape: 'dot', text: 'updating', }); makeConnection(); return new Output(); } }
src/deye-sun-g3/Action/UpdateAction.ts
binsoul-node-red-contrib-deye-sun-g3-f1f71cc
[ { "filename": "src/deye-sun-g3/DeyeRegisters.ts", "retrieved_chunk": " } else {\n value = value * scale;\n }\n return this.round(value, '4');\n }\n private parseString(modbusRegisters: Array<number>, registers: Array<number>): string {\n let value = '';\n for (const index of registers) {\n const temp = modbusRegisters[index];\n value = value + String.fromCharCode(temp >> 8) + String.fromCharCode(temp & 0xff);", "score": 0.8066527843475342 }, { "filename": "src/deye-sun-g3/DeyeRegisters.ts", "retrieved_chunk": " result[definition.name] = value;\n }\n return result;\n }\n private parseUnsigned(modbusRegisters: Array<number>, registers: Array<number>, scale: number, offset: number): number {\n let value = 0;\n let shift = 0;\n for (const index of registers) {\n const temp = modbusRegisters[index];\n value += (temp & 0xffff) << shift;", "score": 0.8011058568954468 }, { "filename": "src/deye-sun-g3/Action/UnavailableAction.ts", "retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n this.storage.setAvailable(true);\n this.storage.resetRuntime();\n const data = this.storage.getData();\n this.storage.setAvailable(false);\n if (data !== null) {", "score": 0.7647110223770142 }, { "filename": "src/deye-sun-g3/ActionFactory.ts", "retrieved_chunk": " outputCallback(): void {\n this.node.receive(<MessageData>{\n command: 'output',\n });\n }\n nodeStatusCallback(status: NodeStatus): void {\n this.node.status(status);\n }\n private getStartOfSlot(timestamp: number) {\n return Math.floor(timestamp / 60000) * 60000;", "score": 0.7642794847488403 }, { "filename": "src/deye-sun-g3/Action/OutputAction.ts", "retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const data = this.storage.getData();\n if (data !== null) {\n result.setValue('output', data);\n result.setNodeStatus({\n fill: 'green',", "score": 0.759901762008667 } ]
typescript
const parser = new DeyeRegisters();
import type { FastifyInstance, FastifyRequest } from 'fastify' import { wechatApiPath } from '../const' import { toSha1 } from '../utils/encryptor' import type { VerifyQuery } from './types' export function checkIsWechatRequest(request: FastifyRequest) { const q = request.query as VerifyQuery try { const arr: string[] = [process.env.WECHAT_TOKEN, q.timestamp.toString(), q.nonce.toString()] arr.sort() const sha1 = toSha1(arr.join('')) if (sha1 === q.signature) { // Success. return true } else { return false } } catch (error) { console.error(error) return false } } function route(server: FastifyInstance) { // setup hook server.addHook('onRequest', (request, reply, done) => { // TODO: Do we need to add this hook for all wechat request? if (request?.url?.startsWith(wechatApiPath)) { if (checkIsWechatRequest(request)) { // Continue. done() } else { reply.send('who are you?') } } else { done() } })
server.get(wechatApiPath, (request: FastifyRequest, reply) => {
const q = request.query as VerifyQuery if (checkIsWechatRequest(request)) { // Success. reply.send(q.echostr) } else { reply.send('who are you?') } }) } export default route
src/wechat/verify.ts
zhouchaoyuan-azure-openai-node-wechat-624e8f4
[ { "filename": "src/azureopenai/acceptor.ts", "retrieved_chunk": " handleChat(request.body, reply)\n })\n}\nasync function handlePrompt(requestBody: any, reply: FastifyReply) {\n GetAzureOpenAIAnswerAsync(requestBody.prompt, 'prompt restapi').then((response) => {\n reply.send(response)\n }).catch((reason) => {\n reply.send(reason)\n })\n}", "score": 0.7903872728347778 }, { "filename": "src/azureopenai/acceptor.ts", "retrieved_chunk": "async function handleChat(requestBody: any, reply: FastifyReply) {\n GetAzureOpenAIChatAnswerAsync(requestBody.messages, 'chat restapi').then((response) => {\n reply.send(response)\n }).catch((reason) => {\n reply.send(reason)\n })\n}\nexport default route", "score": 0.7795529365539551 }, { "filename": "src/wechat/acceptor.ts", "retrieved_chunk": " if (!reply.sent) // return the result directly within 5s\n reply.send(generateTextResponse(xml.FromUserName, xml.ToUserName, reason))\n cacheMap.set(requestKey, reason)\n })\n cacheMap.set(requestKey, null)\n checkTimes.set(requestKey, 1)\n }\n else {\n const resp = cacheMap.get(requestKey)\n if (resp != null) {", "score": 0.765694797039032 }, { "filename": "src/wechat/acceptor.ts", "retrieved_chunk": "function getChatHistoryForUser(requestKey: string) {\n if (!chatHistory.has(requestKey))\n chatHistory.set(requestKey, new FixedQueue<ChatCompletionRequestMessage>(pastMessagesIncluded))\n return chatHistory.get(requestKey)\n}\nfunction route(server: FastifyInstance) {\n server.post(wechatApiPath, (request, reply) => {\n const xml = request.body as any\n handleMsg(xml.xml, reply)\n })", "score": 0.7605997323989868 }, { "filename": "src/index.ts", "retrieved_chunk": " process.exit(1)\n }\n // Server is now listening on ${address}\n console.log('Server listening at', port)\n })\n}\nmain()", "score": 0.7573972940444946 } ]
typescript
server.get(wechatApiPath, (request: FastifyRequest, reply) => {
import { Action, ActionFactory as ActionFactoryInterface, Message } from '@binsoul/node-red-bundle-processing'; import type { Node, NodeAPI } from '@node-red/registry'; import { NodeMessageInFlow, NodeStatus } from 'node-red'; import { clearTimeout, setTimeout } from 'timers'; import { DailyResetAction } from './Action/DailyResetAction'; import { OutputAction } from './Action/OutputAction'; import { UnavailableAction } from './Action/UnavailableAction'; import { UpdateAction } from './Action/UpdateAction'; import type { Configuration } from './Configuration'; import { Storage } from './Storage'; interface MessageData extends NodeMessageInFlow { command?: string; timestamp?: number; } function formatTime(timestamp: number) { const date = new Date(timestamp); return date.getHours().toString().padStart(2, '0') + ':' + date.getMinutes().toString().padStart(2, '0'); } /** * Generates actions. */ export class ActionFactory implements ActionFactoryInterface { private readonly configuration: Configuration; private readonly RED: NodeAPI; private readonly node: Node; private readonly storage: Storage; private firstMessage = true; private updateTimer: NodeJS.Timeout | null = null; private dailyResetTimer: NodeJS.Timeout | null = null; private unavailableTimer: NodeJS.Timeout | null = null; constructor(RED: NodeAPI, node: Node, configuration: Configuration) { this.RED = RED; this.node = node; this.configuration = configuration; this.storage = new Storage(configuration); } build(message: Message): Action | Array<Action> | null { const data: MessageData = message.data; const command = data.command; if (this.firstMessage) { this.firstMessage = false; this.scheduleUnavailableCheck(); } if (typeof command !== 'undefined' && ('' + command).trim() !== '') { switch (command.toLowerCase()) { case 'update': this.storage.setUpdating(true); return new UpdateAction( this.configuration, this.storage, () => this.outputCallback(), (status: NodeStatus) => this.nodeStatusCallback(status), ); case 'output': this.storage.setUpdating(false); this.scheduleUnavailableCheck(); return new OutputAction(this.configuration, this.storage); case 'dailyreset':
return new DailyResetAction(this.configuration, this.storage);
case 'unavailable': return new UnavailableAction(this.configuration, this.storage); } } if (!this.storage.isUpdating()) { if (this.updateTimer !== null) { clearTimeout(this.updateTimer); this.updateTimer = null; } this.scheduleUpdate(); this.storage.setUpdating(true); return new UpdateAction( this.configuration, this.storage, () => this.outputCallback(), (status: NodeStatus) => this.nodeStatusCallback(status), ); } return null; } setup(): void { if (this.configuration.updateMode === 'never') { this.node.status({ fill: 'yellow', shape: 'dot', text: 'waiting for message', }); return; } const now = Date.now(); const firstUpdateAt = Math.ceil(now / (this.configuration.updateFrequency * 60000)) * this.configuration.updateFrequency * 60000; this.updateTimer = setTimeout(() => this.executeUpdate(), firstUpdateAt - now + 1000); const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(0, 0, 0); this.dailyResetTimer = setTimeout(() => this.executeDailyReset(), tomorrow.getTime() - now); this.node.status({ fill: 'yellow', shape: 'dot', text: `waiting until ${formatTime(firstUpdateAt)}`, }); } teardown(): void { if (this.updateTimer !== null) { clearTimeout(this.updateTimer); this.updateTimer = null; } if (this.dailyResetTimer !== null) { clearTimeout(this.dailyResetTimer); this.dailyResetTimer = null; } if (this.unavailableTimer !== null) { clearTimeout(this.unavailableTimer); this.unavailableTimer = null; } } /** * Starts a timer if automatic updates are enabled and no timer exists. */ private scheduleUpdate(): void { if (this.updateTimer !== null || this.configuration.updateMode === 'never') { return; } const now = Date.now(); this.updateTimer = setTimeout(() => this.executeUpdate(), this.getStartOfSlot(now) - now + this.configuration.updateFrequency * 60000 + 1000); } /** * Handles automatic updates. */ executeUpdate(): void { const now = new Date().getTime(); const nextUpdateAt = this.getStartOfSlot(now) + this.configuration.updateFrequency * 60000 + 1000; this.updateTimer = setTimeout(() => this.executeUpdate(), nextUpdateAt - now); // trigger node.on('input', () => {}) this.node.receive(<MessageData>{ command: 'update', timestamp: now, }); } /** * Handles daily resets of counters. */ executeDailyReset(): void { const now = Date.now(); const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(0, 0, 0); this.dailyResetTimer = setTimeout(() => this.executeDailyReset(), tomorrow.getTime() - now); // trigger node.on('input', () => {}) this.node.receive(<MessageData>{ command: 'dailyReset', timestamp: now, }); } /** * Starts a timer which changes the device status to unavailable. */ private scheduleUnavailableCheck(): void { if (this.unavailableTimer !== null) { clearTimeout(this.unavailableTimer); this.unavailableTimer = null; } const now = Date.now(); this.unavailableTimer = setTimeout(() => this.executeUnavailableCheck(), this.getStartOfSlot(now) - now + this.configuration.deviceTimeout * 60000); } private executeUnavailableCheck(): void { this.unavailableTimer = null; this.node.receive(<MessageData>{ command: 'unavailable', }); } outputCallback(): void { this.node.receive(<MessageData>{ command: 'output', }); } nodeStatusCallback(status: NodeStatus): void { this.node.status(status); } private getStartOfSlot(timestamp: number) { return Math.floor(timestamp / 60000) * 60000; } }
src/deye-sun-g3/ActionFactory.ts
binsoul-node-red-contrib-deye-sun-g3-f1f71cc
[ { "filename": "src/deye-sun-g3/Action/UpdateAction.ts", "retrieved_chunk": " private readonly storage: Storage;\n private readonly outputCallback: () => void;\n private readonly nodeStatusCallback: (status: NodeStatus) => void;\n constructor(configuration: Configuration, storage: Storage, outputCallback: () => void, nodeStatusCallback: (status: NodeStatus) => void) {\n this.configuration = configuration;\n this.storage = storage;\n this.outputCallback = outputCallback;\n this.nodeStatusCallback = nodeStatusCallback;\n }\n defineInput(): InputDefinition {", "score": 0.7812319993972778 }, { "filename": "src/deye-sun-g3/Action/DailyResetAction.ts", "retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const isAvailable = this.storage.isAvailable();\n this.storage.setAvailable(true);\n this.storage.resetCounters();\n const data = this.storage.getData();\n this.storage.setAvailable(isAvailable);", "score": 0.750087320804596 }, { "filename": "src/deye-sun-g3/Action/OutputAction.ts", "retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const data = this.storage.getData();\n if (data !== null) {\n result.setValue('output', data);\n result.setNodeStatus({\n fill: 'green',", "score": 0.7493946552276611 }, { "filename": "src/deye-sun-g3/Action/DailyResetAction.ts", "retrieved_chunk": "import { Action, InputDefinition, Output, OutputDefinition } from '@binsoul/node-red-bundle-processing';\nimport type { Configuration } from '../Configuration';\nimport { Storage } from '../Storage';\nexport class DailyResetAction implements Action {\n private readonly configuration: Configuration;\n private storage: Storage;\n constructor(configuration: Configuration, storage: Storage) {\n this.configuration = configuration;\n this.storage = storage;\n }", "score": 0.7448440790176392 }, { "filename": "src/deye-sun-g3/Action/UnavailableAction.ts", "retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n this.storage.setAvailable(true);\n this.storage.resetRuntime();\n const data = this.storage.getData();\n this.storage.setAvailable(false);\n if (data !== null) {", "score": 0.7410135269165039 } ]
typescript
return new DailyResetAction(this.configuration, this.storage);
import { Action, ActionFactory as ActionFactoryInterface, Message } from '@binsoul/node-red-bundle-processing'; import type { Node, NodeAPI } from '@node-red/registry'; import { NodeMessageInFlow, NodeStatus } from 'node-red'; import { clearTimeout, setTimeout } from 'timers'; import { DailyResetAction } from './Action/DailyResetAction'; import { OutputAction } from './Action/OutputAction'; import { UnavailableAction } from './Action/UnavailableAction'; import { UpdateAction } from './Action/UpdateAction'; import type { Configuration } from './Configuration'; import { Storage } from './Storage'; interface MessageData extends NodeMessageInFlow { command?: string; timestamp?: number; } function formatTime(timestamp: number) { const date = new Date(timestamp); return date.getHours().toString().padStart(2, '0') + ':' + date.getMinutes().toString().padStart(2, '0'); } /** * Generates actions. */ export class ActionFactory implements ActionFactoryInterface { private readonly configuration: Configuration; private readonly RED: NodeAPI; private readonly node: Node; private readonly storage: Storage; private firstMessage = true; private updateTimer: NodeJS.Timeout | null = null; private dailyResetTimer: NodeJS.Timeout | null = null; private unavailableTimer: NodeJS.Timeout | null = null; constructor(RED: NodeAPI, node: Node, configuration: Configuration) { this.RED = RED; this.node = node; this.configuration = configuration; this.storage = new Storage(configuration); } build(message: Message): Action | Array<Action> | null { const data: MessageData = message.data; const command = data.command; if (this.firstMessage) { this.firstMessage = false; this.scheduleUnavailableCheck(); } if (typeof command !== 'undefined' && ('' + command).trim() !== '') { switch (command.toLowerCase()) { case 'update': this.storage.setUpdating(true); return new UpdateAction( this.configuration, this.storage, () => this.outputCallback(), (status: NodeStatus) => this.nodeStatusCallback(status), ); case 'output': this.storage.setUpdating(false); this.scheduleUnavailableCheck();
return new OutputAction(this.configuration, this.storage);
case 'dailyreset': return new DailyResetAction(this.configuration, this.storage); case 'unavailable': return new UnavailableAction(this.configuration, this.storage); } } if (!this.storage.isUpdating()) { if (this.updateTimer !== null) { clearTimeout(this.updateTimer); this.updateTimer = null; } this.scheduleUpdate(); this.storage.setUpdating(true); return new UpdateAction( this.configuration, this.storage, () => this.outputCallback(), (status: NodeStatus) => this.nodeStatusCallback(status), ); } return null; } setup(): void { if (this.configuration.updateMode === 'never') { this.node.status({ fill: 'yellow', shape: 'dot', text: 'waiting for message', }); return; } const now = Date.now(); const firstUpdateAt = Math.ceil(now / (this.configuration.updateFrequency * 60000)) * this.configuration.updateFrequency * 60000; this.updateTimer = setTimeout(() => this.executeUpdate(), firstUpdateAt - now + 1000); const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(0, 0, 0); this.dailyResetTimer = setTimeout(() => this.executeDailyReset(), tomorrow.getTime() - now); this.node.status({ fill: 'yellow', shape: 'dot', text: `waiting until ${formatTime(firstUpdateAt)}`, }); } teardown(): void { if (this.updateTimer !== null) { clearTimeout(this.updateTimer); this.updateTimer = null; } if (this.dailyResetTimer !== null) { clearTimeout(this.dailyResetTimer); this.dailyResetTimer = null; } if (this.unavailableTimer !== null) { clearTimeout(this.unavailableTimer); this.unavailableTimer = null; } } /** * Starts a timer if automatic updates are enabled and no timer exists. */ private scheduleUpdate(): void { if (this.updateTimer !== null || this.configuration.updateMode === 'never') { return; } const now = Date.now(); this.updateTimer = setTimeout(() => this.executeUpdate(), this.getStartOfSlot(now) - now + this.configuration.updateFrequency * 60000 + 1000); } /** * Handles automatic updates. */ executeUpdate(): void { const now = new Date().getTime(); const nextUpdateAt = this.getStartOfSlot(now) + this.configuration.updateFrequency * 60000 + 1000; this.updateTimer = setTimeout(() => this.executeUpdate(), nextUpdateAt - now); // trigger node.on('input', () => {}) this.node.receive(<MessageData>{ command: 'update', timestamp: now, }); } /** * Handles daily resets of counters. */ executeDailyReset(): void { const now = Date.now(); const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); tomorrow.setHours(0, 0, 0); this.dailyResetTimer = setTimeout(() => this.executeDailyReset(), tomorrow.getTime() - now); // trigger node.on('input', () => {}) this.node.receive(<MessageData>{ command: 'dailyReset', timestamp: now, }); } /** * Starts a timer which changes the device status to unavailable. */ private scheduleUnavailableCheck(): void { if (this.unavailableTimer !== null) { clearTimeout(this.unavailableTimer); this.unavailableTimer = null; } const now = Date.now(); this.unavailableTimer = setTimeout(() => this.executeUnavailableCheck(), this.getStartOfSlot(now) - now + this.configuration.deviceTimeout * 60000); } private executeUnavailableCheck(): void { this.unavailableTimer = null; this.node.receive(<MessageData>{ command: 'unavailable', }); } outputCallback(): void { this.node.receive(<MessageData>{ command: 'output', }); } nodeStatusCallback(status: NodeStatus): void { this.node.status(status); } private getStartOfSlot(timestamp: number) { return Math.floor(timestamp / 60000) * 60000; } }
src/deye-sun-g3/ActionFactory.ts
binsoul-node-red-contrib-deye-sun-g3-f1f71cc
[ { "filename": "src/deye-sun-g3/Action/UpdateAction.ts", "retrieved_chunk": " private readonly storage: Storage;\n private readonly outputCallback: () => void;\n private readonly nodeStatusCallback: (status: NodeStatus) => void;\n constructor(configuration: Configuration, storage: Storage, outputCallback: () => void, nodeStatusCallback: (status: NodeStatus) => void) {\n this.configuration = configuration;\n this.storage = storage;\n this.outputCallback = outputCallback;\n this.nodeStatusCallback = nodeStatusCallback;\n }\n defineInput(): InputDefinition {", "score": 0.8433994650840759 }, { "filename": "src/deye-sun-g3/Action/OutputAction.ts", "retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const data = this.storage.getData();\n if (data !== null) {\n result.setValue('output', data);\n result.setNodeStatus({\n fill: 'green',", "score": 0.7939019799232483 }, { "filename": "src/deye-sun-g3/Action/UnavailableAction.ts", "retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n this.storage.setAvailable(true);\n this.storage.resetRuntime();\n const data = this.storage.getData();\n this.storage.setAvailable(false);\n if (data !== null) {", "score": 0.7764756679534912 }, { "filename": "src/deye-sun-g3/Action/UpdateAction.ts", "retrieved_chunk": " client.connect({ host: this.configuration.deviceIp, port: 8899 });\n };\n const connectEventHandler = () => {\n hasConnected = true;\n this.storage.setConnected();\n client.write(request);\n };\n const dataEventHandler = (data: Buffer) => {\n try {\n const modbusFrame = solarman.unwrapModbusFrame(data);", "score": 0.7740793228149414 }, { "filename": "src/deye-sun-g3/Action/UpdateAction.ts", "retrieved_chunk": " errorMessage = error.message;\n client.end();\n };\n const closeEventHandler = () => {\n if (hasConnected) {\n return;\n }\n if (!this.storage.isAvailable()) {\n this.nodeStatusCallback({\n fill: 'yellow',", "score": 0.7731947898864746 } ]
typescript
return new OutputAction(this.configuration, this.storage);
import { Action, InputDefinition, Output, OutputDefinition } from '@binsoul/node-red-bundle-processing'; import { ModbusRtu } from '@binsoul/nodejs-modbus'; import { SolarmanV5 } from '@binsoul/nodejs-solarman'; import * as net from 'net'; import { NodeStatus } from 'node-red'; import type { Configuration } from '../Configuration'; import { DeyeRegisters } from '../DeyeRegisters'; import { Storage } from '../Storage'; export class UpdateAction implements Action { private readonly configuration: Configuration; private readonly storage: Storage; private readonly outputCallback: () => void; private readonly nodeStatusCallback: (status: NodeStatus) => void; constructor(configuration: Configuration, storage: Storage, outputCallback: () => void, nodeStatusCallback: (status: NodeStatus) => void) { this.configuration = configuration; this.storage = storage; this.outputCallback = outputCallback; this.nodeStatusCallback = nodeStatusCallback; } defineInput(): InputDefinition { return new InputDefinition(); } defineOutput(): OutputDefinition { return new OutputDefinition(); } execute(): Output { const client = new net.Socket(); client.setTimeout(5000); let hasConnected = false; let errorMessage = ''; let retryCount = 0; const unitAddress = 1; const firstRegister = 0x0003; const lastRegister = 0x0080; const modbus = new ModbusRtu(unitAddress); const modbusFrame = modbus.requestHoldingRegisters(firstRegister, lastRegister); const solarman = new SolarmanV5(this.configuration.deviceSerialNumber, true); const request = solarman.wrapModbusFrame(modbusFrame); // Functions to handle socket events const makeConnection = () => { client.connect({ host: this.configuration.deviceIp, port: 8899 }); }; const connectEventHandler = () => { hasConnected = true; this.storage.setConnected(); client.write(request); }; const dataEventHandler = (data: Buffer) => { try { const modbusFrame = solarman.unwrapModbusFrame(data); const values = modbus.fetchHoldingRegisters(modbusFrame); const parser = new DeyeRegisters(); this
.storage.setData(parser.parse(values));
this.outputCallback(); } catch (error) { if (error instanceof Error) { this.nodeStatusCallback({ fill: 'red', shape: 'dot', text: error.message, }); } } client.end(); }; const timeoutEventHandler = () => { errorMessage = 'Connection timed out'; client.end(); }; const errorEventHandler = (error: Error) => { errorMessage = error.message; client.end(); }; const closeEventHandler = () => { if (hasConnected) { return; } if (!this.storage.isAvailable()) { this.nodeStatusCallback({ fill: 'yellow', shape: 'dot', text: 'unavailable', }); } else if (retryCount < 5) { retryCount++; this.nodeStatusCallback({ fill: 'yellow', shape: 'dot', text: 'retry ' + retryCount, }); setTimeout(makeConnection, 5000); } else { this.nodeStatusCallback({ fill: 'red', shape: 'dot', text: errorMessage, }); } }; client.on('connect', connectEventHandler); client.on('data', dataEventHandler); client.on('timeout', timeoutEventHandler); client.on('error', errorEventHandler); client.on('close', closeEventHandler); this.nodeStatusCallback({ fill: 'yellow', shape: 'dot', text: 'updating', }); makeConnection(); return new Output(); } }
src/deye-sun-g3/Action/UpdateAction.ts
binsoul-node-red-contrib-deye-sun-g3-f1f71cc
[ { "filename": "src/deye-sun-g3/DeyeRegisters.ts", "retrieved_chunk": " } else {\n value = value * scale;\n }\n return this.round(value, '4');\n }\n private parseString(modbusRegisters: Array<number>, registers: Array<number>): string {\n let value = '';\n for (const index of registers) {\n const temp = modbusRegisters[index];\n value = value + String.fromCharCode(temp >> 8) + String.fromCharCode(temp & 0xff);", "score": 0.7970486879348755 }, { "filename": "src/deye-sun-g3/DeyeRegisters.ts", "retrieved_chunk": " result[definition.name] = value;\n }\n return result;\n }\n private parseUnsigned(modbusRegisters: Array<number>, registers: Array<number>, scale: number, offset: number): number {\n let value = 0;\n let shift = 0;\n for (const index of registers) {\n const temp = modbusRegisters[index];\n value += (temp & 0xffff) << shift;", "score": 0.7819082736968994 }, { "filename": "src/deye-sun-g3/Action/UnavailableAction.ts", "retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n this.storage.setAvailable(true);\n this.storage.resetRuntime();\n const data = this.storage.getData();\n this.storage.setAvailable(false);\n if (data !== null) {", "score": 0.7471662759780884 }, { "filename": "src/deye-sun-g3/DeyeRegisters.ts", "retrieved_chunk": " shift += 16;\n }\n value = value - offset;\n value = value * scale;\n return this.round(value, '4');\n }\n private parseSigned(modbusRegisters: Array<number>, registers: Array<number>, scale: number, offset: number): number {\n let value = 0;\n let shift = 0;\n let maxint = 0;", "score": 0.7431756258010864 }, { "filename": "src/deye-sun-g3/Action/DailyResetAction.ts", "retrieved_chunk": " });\n return result;\n }\n execute(): Output {\n const result = new Output();\n const isAvailable = this.storage.isAvailable();\n this.storage.setAvailable(true);\n this.storage.resetCounters();\n const data = this.storage.getData();\n this.storage.setAvailable(isAvailable);", "score": 0.7398052215576172 } ]
typescript
.storage.setData(parser.parse(values));
import { GeneratorContext } from './generator-context' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, inline, jsDoc, NewLine } from '../output/writer' import * as algokit from '@algorandfoundation/algokit-utils' import { getEquivalentType } from './helpers/get-equivalent-type' import { makeSafePropertyIdentifier, makeSafeTypeIdentifier, makeSafeVariableIdentifier } from '../util/sanitization' export function* appTypes(ctx: GeneratorContext): DocumentParts { const { app, methodSignatureToUniqueName, name } = ctx yield* jsDoc(`Defines the types of available calls and state of the ${name} smart contract.`) yield `export type ${name} = {` yield IncIndent yield* jsDoc('Maps method signatures / names to their argument and return types.') yield 'methods:' yield IncIndent for (const method of app.contract.methods) { const methodSig = algokit.getABIMethodSignature(method) const uniqueName = methodSignatureToUniqueName[methodSig] yield `& Record<'${methodSig}'${methodSig !== uniqueName ? ` | '${uniqueName}'` : ''}, {` yield IncIndent yield `argsObj: {` yield IncIndent const argsMeta = method.args.map((arg) => ({ ...arg, hasDefault: app.hints?.[methodSig]?.default_arguments?.[arg.name], tsType: getEquivalentType(arg.type, 'input'), })) for (const arg of argsMeta) { if (arg.desc) yield* jsDoc(arg.desc) yield `${makeSafePropertyIdentifier(arg.name)}${arg.hasDefault ? '?' : ''}: ${arg.tsType}` } yield DecIndentAndCloseBlock yield* inline( `argsTuple: [`, argsMeta .map( (arg) => `${makeSafeVariableIdentifier(arg.name)}: ${getEquivalentType(arg.type, 'input')}${arg.hasDefault ? ' | undefined' : ''}`, ) .join(', '), ']', ) const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output if (method.returns.desc) yield* jsDoc(method.returns.desc) if (outputStruct) { yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}` } else { yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}` } yield
DecIndent yield '}>' }
yield DecIndent yield* appState(ctx) yield DecIndentAndCloseBlock yield* jsDoc('Defines the possible abi call signatures') yield `export type ${name}Sig = keyof ${name}['methods']` yield* jsDoc( 'Defines an object containing all relevant parameters for a single call to the contract. Where TSignature is undefined, a' + ' bare call is made', ) yield `export type TypedCallParams<TSignature extends ${name}Sig | undefined> = {` yield IncIndent yield 'method: TSignature' yield 'methodArgs: TSignature extends undefined ? undefined : Array<ABIAppCallArg | undefined>' yield DecIndent yield '} & AppClientCallCoreParams & CoreAppCallArgs' yield* jsDoc('Defines the arguments required for a bare call') yield `export type BareCallArgs = Omit<RawAppCallArgs, keyof CoreAppCallArgs>` yield* structs(ctx) yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's arguments in either tuple of struct form`) yield `export type MethodArgs<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['argsObj' | 'argsTuple']` yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's return type`) yield `export type MethodReturn<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['returns']` yield NewLine } function* structs({ app }: GeneratorContext): DocumentParts { if (app.hints === undefined) return for (const methodHint of Object.values(app.hints)) { if (methodHint.structs === undefined) continue for (const struct of Object.values(methodHint.structs)) { yield* jsDoc(`Represents a ${struct.name} result as a struct`) yield `export type ${makeSafeTypeIdentifier(struct.name)} = {` yield IncIndent for (const [key, type] of struct.elements) { yield `${makeSafePropertyIdentifier(key)}: ${getEquivalentType(type, 'output')}` } yield DecIndentAndCloseBlock yield* jsDoc(`Converts the tuple representation of a ${struct.name} to the struct representation`) yield* inline( `export function ${makeSafeTypeIdentifier(struct.name)}(`, `[${struct.elements.map(([key]) => makeSafeVariableIdentifier(key)).join(', ')}]: `, `[${struct.elements.map(([_, type]) => getEquivalentType(type, 'output')).join(', ')}] ) {`, ) yield IncIndent yield `return {` yield IncIndent for (const [key] of struct.elements) { const prop = makeSafePropertyIdentifier(key) const param = makeSafeVariableIdentifier(key) yield `${prop}${prop !== param ? `: ${param}` : ''},` } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock } } } function* appState({ app }: GeneratorContext): DocumentParts { const hasLocal = app.schema.local?.declared && Object.keys(app.schema.local.declared).length const hasGlobal = app.schema.global?.declared && Object.keys(app.schema.global.declared).length if (hasLocal || hasGlobal) { yield* jsDoc('Defines the shape of the global and local state of the application.') yield 'state: {' yield IncIndent if (hasGlobal) { yield 'global: {' yield IncIndent for (const prop of Object.values(app.schema.global!.declared!)) { if (prop.descr) { yield* jsDoc(prop.descr) } yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}` } yield DecIndentAndCloseBlock } if (hasLocal) { yield 'local: {' yield IncIndent for (const prop of Object.values(app.schema.local!.declared!)) { if (prop.descr) { yield* jsDoc(prop.descr) } yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}` } yield DecIndentAndCloseBlock } yield DecIndentAndCloseBlock } }
src/client/app-types.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-client.ts", "retrieved_chunk": " yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`\n yield IncIndent\n yield `? returnValueFormatter(result.return.returnValue)`\n yield `: result.return?.returnValue as TReturn | undefined`\n yield `return { ...result, return: returnValue }`\n yield DecIndent\n yield DecIndentAndCloseBlock\n yield NewLine\n yield* jsDoc({\n description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',", "score": 0.8093416690826416 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " if (method === BARE_CALL) {\n yield `| (TypedCallParams<undefined> & ${onComplete.type})`\n } else {\n yield `| (TypedCallParams<'${method}'> & ${onComplete.type})`\n }\n }\n yield DecIndent\n }\n if (callConfig.updateMethods.length > 0) {\n yield* jsDoc(`A factory for available 'update' calls`)", "score": 0.8008163571357727 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " }) {\n yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {`\n yield IncIndent\n yield `return {`\n yield IncIndent\n if (signature) {\n yield `method: '${signature}' as const,`\n yield `methodArgs: Array.isArray(args) ? args : [${args\n .map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`))\n .join(', ')}],`", "score": 0.7940465211868286 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,", "score": 0.7903922200202942 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`\n yield IncIndent\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `return this.call(${name}CallFactory.${methodName}(args, params)${", "score": 0.784476101398468 } ]
typescript
DecIndent yield '}>' }
import * as algokit from '@algorandfoundation/algokit-utils' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer' import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { GeneratorContext } from './generator-context' import { getCreateOnCompleteOptions } from './deploy-types' import { composeMethod } from './call-composer' export function* callClient(ctx: GeneratorContext): DocumentParts { const { app, name } = ctx yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`) yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {` yield IncIndent yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`) yield 'public readonly appClient: ApplicationClient' yield NewLine yield `private readonly sender: SendTransactionFrom | undefined` yield NewLine yield* jsDoc({ description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``, params: { appDetails: 'appDetails The details to identify the app to deploy', algod: 'An algod client instance', }, }) yield `constructor(appDetails: AppDetails, private algod: Algodv2) {` yield IncIndent yield `this.sender = appDetails.sender` yield 'this.appClient = algokit.getAppClient({' yield* indent('...appDetails,', 'app: APP_SPEC') yield '}, algod)' yield DecIndent yield '}' yield NewLine yield* jsDoc({ description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type', params: { result: 'The AppCallTransactionResult to be mapped', returnValueFormatter: 'An optional delegate to format the return value if required', }, returns: 'The smart contract response with an updated return value', }) yield* inline( `protected mapReturnValue<TReturn>`, `(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `, `AppCallTransactionResultOfType<TReturn> {`, ) yield IncIndent yield `if(result.return?.decodeError) {` yield* indent(`throw result.return.decodeError`) yield `}` yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined` yield IncIndent yield `? returnValueFormatter(result.return.returnValue)` yield `: result.return?.returnValue as TReturn | undefined` yield `return { ...result, return: returnValue }` yield DecIndent yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP', params: { typedCallParams: 'An object containing the method signature, args, and any other relevant parameters', returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type', }, returns: 'The result of the smart contract call', }) yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {` yield IncIndent yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)` yield DecIndentAndCloseBlock yield NewLine yield* opMethods(ctx) yield* clearState(ctx) yield* noopMethods(ctx) yield* getStateMethods(ctx) yield* composeMethod(ctx) yield DecIndentAndCloseBlock } function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig, name } = ctx yield* jsDoc({ description: `Idempotently deploys the ${app.contract.name} smart contract.`, params: { params: 'The arguments for the contract calls and any additional parameters for the call', }, returns: 'The deployment result', }) yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {` yield IncIndent if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)` if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)` if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)` yield `return this.appClient.deploy({` yield IncIndent yield `...params,` if (callConfig.updateMethods.length) yield 'updateArgs,' if (callConfig.deleteMethods.length) yield 'deleteArgs,' if (callConfig.createMethods.length) { yield 'createArgs,' yield `createOnCompleteAction: createArgs?.onCompleteAction,` } yield DecIndent yield `})` yield DecIndentAndCloseBlock yield NewLine yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true) yield* operationMethod( ctx, `Updates an existing instance of the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod( ctx, `Opts the user into an existing instance of the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn', ) yield* operationMethod( ctx, `Makes a close out call to an existing instance of the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName, name }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} methods`) yield `public get ${verb}() {` yield IncIndent yield `const $this = this` yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call.`, params: { args: `The arguments for the bare call`, }, returns: `The ${verb} result`, }) yield `bare(args: BareCallArgs & AppClientCallCoreParams ${ includeCompilation ? '& AppClientCompilationParams ' : '' }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<undefined>> {` yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`) yield '},' } else { const uniqueName = methodSignatureToUniqueName[methodSig] const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig) yield* jsDoc({ description: `${description} using the ${methodSig} ABI method.`, params: { args: `The arguments for the smart contract call`, params: `Any additional parameters for the call`, }, returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, })
yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${
includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {` yield* indent( `return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier( uniqueName, )}(args, params)))`, ) yield '},' } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* clearState({ app }: GeneratorContext): DocumentParts { yield* jsDoc({ description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`, params: { args: `The arguments for the bare call`, }, returns: `The clear_state result`, }) yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent yield `return this.appClient.clearState(args)` yield DecIndentAndCloseBlock yield NewLine } function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { for (const method of app.contract.methods) { const methodSignature = algokit.getABIMethodSignature(method) const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]) // Skip methods which don't support a no_op call config if (!callConfig.callMethods.includes(methodSignature)) continue yield* jsDoc({ description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`, abiDescription: method.desc, params: { args: `The arguments for the contract call`, params: `Any additional parameters for the call`, }, returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name yield `return this.call(${name}CallFactory.${methodName}(args, params)${ outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}` })` yield DecIndent yield '}' yield NewLine } } function* getStateMethods({ app, name }: GeneratorContext): DocumentParts { const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared) const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared) if (globalStateValues?.length || localStateValues?.length) { yield* jsDoc({ description: 'Extracts a binary state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'A BinaryState instance containing the state value, or undefined if the key was not found', }) yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if (!('valueRaw' in value))` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`) yield `return {` yield IncIndent yield `asString(): string {` yield* indent(`return value.value`) yield `},` yield `asByteArray(): Uint8Array {` yield* indent(`return value.valueRaw`) yield `}` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Extracts a integer state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'An IntegerState instance containing the state value, or undefined if the key was not found', }) yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if ('valueRaw' in value)` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`) yield `return {` yield IncIndent yield `asBigInt() {` yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`) yield `},` yield `asNumber(): number {` yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`) yield `},` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (globalStateValues?.length) { yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`) yield `public async getGlobalState(): Promise<${name}['state']['global']> {` yield IncIndent yield `const state = await this.appClient.getGlobalState()` yield `return {` yield IncIndent for (const stateValue of globalStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (localStateValues?.length) { yield* jsDoc({ description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`, params: { account: `The address of the account for which to read local state from`, }, }) yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {` yield IncIndent yield `const state = await this.appClient.getLocalState(account)` yield `return {` yield IncIndent for (const stateValue of localStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } }
src/client/call-client.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-factory.ts", "retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,", "score": 0.8957824110984802 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method.`,\n params: {\n args: `The arguments for the smart contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''", "score": 0.8563950061798096 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": "function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) {\n const methodSignature = algokit.getABIMethodSignature(method)\n if (!callConfig.callMethods.includes(methodSignature)) return\n yield* jsDoc({\n description: `Constructs a no op call for the ${methodSignature} ABI method`,\n abiDescription: method.desc,\n params: {\n args: `Any args for the contract call`,\n params: `Any additional parameters for the call`,\n },", "score": 0.8446071147918701 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`", "score": 0.8444288969039917 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,\n params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })", "score": 0.8365119099617004 } ]
typescript
yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${
import * as algokit from '@algorandfoundation/algokit-utils' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer' import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { GeneratorContext } from './generator-context' import { getCreateOnCompleteOptions } from './deploy-types' import { composeMethod } from './call-composer' export function* callClient(ctx: GeneratorContext): DocumentParts { const { app, name } = ctx yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`) yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {` yield IncIndent yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`) yield 'public readonly appClient: ApplicationClient' yield NewLine yield `private readonly sender: SendTransactionFrom | undefined` yield NewLine yield* jsDoc({ description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``, params: { appDetails: 'appDetails The details to identify the app to deploy', algod: 'An algod client instance', }, }) yield `constructor(appDetails: AppDetails, private algod: Algodv2) {` yield IncIndent yield `this.sender = appDetails.sender` yield 'this.appClient = algokit.getAppClient({' yield* indent('...appDetails,', 'app: APP_SPEC') yield '}, algod)' yield DecIndent yield '}' yield NewLine yield* jsDoc({ description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type', params: { result: 'The AppCallTransactionResult to be mapped', returnValueFormatter: 'An optional delegate to format the return value if required', }, returns: 'The smart contract response with an updated return value', }) yield* inline( `protected mapReturnValue<TReturn>`, `(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `, `AppCallTransactionResultOfType<TReturn> {`, ) yield IncIndent yield `if(result.return?.decodeError) {` yield* indent(`throw result.return.decodeError`) yield `}` yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined` yield IncIndent yield `? returnValueFormatter(result.return.returnValue)` yield `: result.return?.returnValue as TReturn | undefined` yield `return { ...result, return: returnValue }` yield DecIndent yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP', params: { typedCallParams: 'An object containing the method signature, args, and any other relevant parameters', returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type', }, returns: 'The result of the smart contract call', }) yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {` yield IncIndent yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)` yield DecIndentAndCloseBlock yield NewLine yield* opMethods(ctx) yield* clearState(ctx) yield* noopMethods(ctx) yield* getStateMethods(ctx) yield* composeMethod(ctx) yield DecIndentAndCloseBlock } function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig, name } = ctx yield* jsDoc({ description: `Idempotently deploys the ${app.contract.name} smart contract.`, params: { params: 'The arguments for the contract calls and any additional parameters for the call', }, returns: 'The deployment result', }) yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {` yield IncIndent if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)` if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)` if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)` yield `return this.appClient.deploy({` yield IncIndent yield `...params,` if (callConfig.updateMethods.length) yield 'updateArgs,' if (callConfig.deleteMethods.length) yield 'deleteArgs,' if (callConfig.createMethods.length) { yield 'createArgs,' yield `createOnCompleteAction: createArgs?.onCompleteAction,` } yield DecIndent yield `})` yield DecIndentAndCloseBlock yield NewLine yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true) yield* operationMethod( ctx, `Updates an existing instance of the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod( ctx, `Opts the user into an existing instance of the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn', ) yield* operationMethod( ctx, `Makes a close out call to an existing instance of the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName, name }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} methods`) yield `public get ${verb}() {` yield IncIndent yield `const $this = this` yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call.`, params: { args: `The arguments for the bare call`, }, returns: `The ${verb} result`, }) yield `bare(args: BareCallArgs & AppClientCallCoreParams ${ includeCompilation ? '& AppClientCompilationParams ' : '' }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<undefined>> {` yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`) yield '},' } else { const uniqueName = methodSignatureToUniqueName[methodSig] const method = app.contract.methods.find
((m) => algokit.getABIMethodSignature(m) === methodSig) yield* jsDoc({
description: `${description} using the ${methodSig} ABI method.`, params: { args: `The arguments for the smart contract call`, params: `Any additional parameters for the call`, }, returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${ includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {` yield* indent( `return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier( uniqueName, )}(args, params)))`, ) yield '},' } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* clearState({ app }: GeneratorContext): DocumentParts { yield* jsDoc({ description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`, params: { args: `The arguments for the bare call`, }, returns: `The clear_state result`, }) yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent yield `return this.appClient.clearState(args)` yield DecIndentAndCloseBlock yield NewLine } function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { for (const method of app.contract.methods) { const methodSignature = algokit.getABIMethodSignature(method) const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]) // Skip methods which don't support a no_op call config if (!callConfig.callMethods.includes(methodSignature)) continue yield* jsDoc({ description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`, abiDescription: method.desc, params: { args: `The arguments for the contract call`, params: `Any additional parameters for the call`, }, returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name yield `return this.call(${name}CallFactory.${methodName}(args, params)${ outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}` })` yield DecIndent yield '}' yield NewLine } } function* getStateMethods({ app, name }: GeneratorContext): DocumentParts { const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared) const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared) if (globalStateValues?.length || localStateValues?.length) { yield* jsDoc({ description: 'Extracts a binary state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'A BinaryState instance containing the state value, or undefined if the key was not found', }) yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if (!('valueRaw' in value))` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`) yield `return {` yield IncIndent yield `asString(): string {` yield* indent(`return value.value`) yield `},` yield `asByteArray(): Uint8Array {` yield* indent(`return value.valueRaw`) yield `}` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Extracts a integer state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'An IntegerState instance containing the state value, or undefined if the key was not found', }) yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if ('valueRaw' in value)` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`) yield `return {` yield IncIndent yield `asBigInt() {` yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`) yield `},` yield `asNumber(): number {` yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`) yield `},` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (globalStateValues?.length) { yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`) yield `public async getGlobalState(): Promise<${name}['state']['global']> {` yield IncIndent yield `const state = await this.appClient.getGlobalState()` yield `return {` yield IncIndent for (const stateValue of globalStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (localStateValues?.length) { yield* jsDoc({ description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`, params: { account: `The address of the account for which to read local state from`, }, }) yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {` yield IncIndent yield `const state = await this.appClient.getLocalState(account)` yield `return {` yield IncIndent for (const stateValue of localStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } }
src/client/call-client.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-factory.ts", "retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,", "score": 0.9144341945648193 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`", "score": 0.8854920864105225 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.bare({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`\n yield `resultMappers.push(undefined)`\n yield `return $this`\n yield DecIndent\n yield '},'\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]", "score": 0.8826367855072021 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " const methodName = makeSafeMethodIdentifier(uniqueName)\n yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''\n }: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${\n onComplete?.type ? ` & ${onComplete.type}` : ''\n }) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`", "score": 0.8512980341911316 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${", "score": 0.8436504006385803 } ]
typescript
((m) => algokit.getABIMethodSignature(m) === methodSig) yield* jsDoc({
import { GeneratorContext } from './generator-context' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, inline, jsDoc, NewLine } from '../output/writer' import * as algokit from '@algorandfoundation/algokit-utils' import { getEquivalentType } from './helpers/get-equivalent-type' import { makeSafePropertyIdentifier, makeSafeTypeIdentifier, makeSafeVariableIdentifier } from '../util/sanitization' export function* appTypes(ctx: GeneratorContext): DocumentParts { const { app, methodSignatureToUniqueName, name } = ctx yield* jsDoc(`Defines the types of available calls and state of the ${name} smart contract.`) yield `export type ${name} = {` yield IncIndent yield* jsDoc('Maps method signatures / names to their argument and return types.') yield 'methods:' yield IncIndent for (const method of app.contract.methods) { const methodSig = algokit.getABIMethodSignature(method) const uniqueName = methodSignatureToUniqueName[methodSig] yield `& Record<'${methodSig}'${methodSig !== uniqueName ? ` | '${uniqueName}'` : ''}, {` yield IncIndent yield `argsObj: {` yield IncIndent const argsMeta = method.args.map((arg) => ({ ...arg, hasDefault: app.hints?.[methodSig]?.default_arguments?.[arg.name], tsType: getEquivalentType(arg.type, 'input'), })) for (const arg of argsMeta) { if (arg.desc) yield* jsDoc(arg.desc) yield `${makeSafePropertyIdentifier(arg.name)}${arg.hasDefault ? '?' : ''}: ${arg.tsType}` } yield DecIndentAndCloseBlock yield* inline( `argsTuple: [`, argsMeta .map( (arg) => `${makeSafeVariableIdentifier(arg.name)}: ${getEquivalentType(arg.type, 'input')}${arg.hasDefault ? ' | undefined' : ''}`, ) .join(', '), ']', ) const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output if (method.returns.desc) yield* jsDoc(method.returns.desc) if (outputStruct) { yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}` } else { yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}` } yield DecIndent yield '}>' } yield DecIndent yield* appState(ctx) yield DecIndentAndCloseBlock yield* jsDoc('Defines the possible abi call signatures') yield `export type ${name}Sig = keyof ${name}['methods']` yield* jsDoc( 'Defines an object containing all relevant parameters for a single call to the contract. Where TSignature is undefined, a' + ' bare call is made', ) yield `export type TypedCallParams<TSignature extends ${name}Sig | undefined> = {` yield IncIndent yield 'method: TSignature' yield 'methodArgs: TSignature extends undefined ? undefined : Array<ABIAppCallArg | undefined>' yield DecIndent yield '} & AppClientCallCoreParams & CoreAppCallArgs' yield* jsDoc('Defines the arguments required for a bare call') yield `export type BareCallArgs = Omit<RawAppCallArgs, keyof CoreAppCallArgs>` yield* structs(ctx) yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's arguments in either tuple of struct form`) yield `export type MethodArgs<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['argsObj' | 'argsTuple']` yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's return type`) yield `export type MethodReturn<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['returns']` yield NewLine } function* structs({ app }: GeneratorContext): DocumentParts { if (app.hints === undefined) return for (const methodHint of Object.values(app.hints)) { if (methodHint.structs === undefined) continue for (const struct of Object.values(methodHint.structs)) { yield* jsDoc(`Represents a ${struct.name} result as a struct`) yield `export type ${makeSafeTypeIdentifier(struct.name)} = {` yield IncIndent for (const [key, type] of struct.elements) { yield `${makeSafePropertyIdentifier(key)}: ${getEquivalentType(type, 'output')}` } yield DecIndentAndCloseBlock yield* jsDoc(`Converts the tuple representation of a ${struct.name} to the struct representation`) yield* inline( `export function ${makeSafeTypeIdentifier(struct.name)}(`, `[${struct.elements.map(([key]) => makeSafeVariableIdentifier(key)).join(', ')}]: `, `[${struct.elements.map(([_, type]) => getEquivalentType(type, 'output')).join(', ')}] ) {`, ) yield IncIndent yield `return {` yield IncIndent for (const [key] of struct.elements) { const prop = makeSafePropertyIdentifier(key) const param = makeSafeVariableIdentifier(key) yield `${prop}${prop !== param ? `: ${param}` : ''},` } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock } } } function* appState({ app }: GeneratorContext): DocumentParts { const hasLocal = app.schema.local?.declared && Object.keys(app.schema.local.declared).length const hasGlobal = app.schema.global?.declared && Object.keys(app.schema.global.declared).length if (hasLocal || hasGlobal) { yield* jsDoc('Defines the shape of the global and local state of the application.') yield 'state: {' yield IncIndent if (hasGlobal) { yield 'global: {' yield IncIndent for (const prop of Object.values(app.schema.global!.declared!)) {
if (prop.descr) {
yield* jsDoc(prop.descr) } yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}` } yield DecIndentAndCloseBlock } if (hasLocal) { yield 'local: {' yield IncIndent for (const prop of Object.values(app.schema.local!.declared!)) { if (prop.descr) { yield* jsDoc(prop.descr) } yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}` } yield DecIndentAndCloseBlock } yield DecIndentAndCloseBlock } }
src/client/app-types.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-client.ts", "retrieved_chunk": " outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}`\n })`\n yield DecIndent\n yield '}'\n yield NewLine\n }\n}\nfunction* getStateMethods({ app, name }: GeneratorContext): DocumentParts {\n const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared)\n const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared)", "score": 0.823914647102356 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " yield NewLine\n }\n if (globalStateValues?.length) {\n yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)\n yield `public async getGlobalState(): Promise<${name}['state']['global']> {`\n yield IncIndent\n yield `const state = await this.appClient.getGlobalState()`\n yield `return {`\n yield IncIndent\n for (const stateValue of globalStateValues) {", "score": 0.7910946607589722 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${", "score": 0.7719240188598633 }, { "filename": "src/output/writer.ts", "retrieved_chunk": " } else {\n yield ` * ${docs.description}`\n if (docs.abiDescription) {\n yield ' *'\n yield ` * ${docs.abiDescription}`\n }\n if (docs.params || docs.returns) {\n yield ' *'\n }\n for (const [paramName, paramDesc] of Object.entries(docs.params ?? {})) {", "score": 0.7691103219985962 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " if (methods.length) {\n yield* jsDoc(`Gets available ${verb} call factories`)\n yield `static get ${verb}() {`\n yield IncIndent\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield* jsDoc({", "score": 0.7612364888191223 } ]
typescript
if (prop.descr) {
import * as algokit from '@algorandfoundation/algokit-utils' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer' import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { GeneratorContext } from './generator-context' import { getCreateOnCompleteOptions } from './deploy-types' import { composeMethod } from './call-composer' export function* callClient(ctx: GeneratorContext): DocumentParts { const { app, name } = ctx yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`) yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {` yield IncIndent yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`) yield 'public readonly appClient: ApplicationClient' yield NewLine yield `private readonly sender: SendTransactionFrom | undefined` yield NewLine yield* jsDoc({ description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``, params: { appDetails: 'appDetails The details to identify the app to deploy', algod: 'An algod client instance', }, }) yield `constructor(appDetails: AppDetails, private algod: Algodv2) {` yield IncIndent yield `this.sender = appDetails.sender` yield 'this.appClient = algokit.getAppClient({' yield* indent('...appDetails,', 'app: APP_SPEC') yield '}, algod)' yield DecIndent yield '}' yield NewLine yield* jsDoc({ description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type', params: { result: 'The AppCallTransactionResult to be mapped', returnValueFormatter: 'An optional delegate to format the return value if required', }, returns: 'The smart contract response with an updated return value', }) yield* inline( `protected mapReturnValue<TReturn>`, `(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `, `AppCallTransactionResultOfType<TReturn> {`, ) yield IncIndent yield `if(result.return?.decodeError) {` yield* indent(`throw result.return.decodeError`) yield `}` yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined` yield IncIndent yield `? returnValueFormatter(result.return.returnValue)` yield `: result.return?.returnValue as TReturn | undefined` yield `return { ...result, return: returnValue }` yield DecIndent yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP', params: { typedCallParams: 'An object containing the method signature, args, and any other relevant parameters', returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type', }, returns: 'The result of the smart contract call', }) yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {` yield IncIndent yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)` yield DecIndentAndCloseBlock yield NewLine yield* opMethods(ctx) yield* clearState(ctx) yield* noopMethods(ctx) yield* getStateMethods(ctx) yield* composeMethod(ctx) yield DecIndentAndCloseBlock } function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig, name } = ctx yield* jsDoc({ description: `Idempotently deploys the ${app.contract.name} smart contract.`, params: { params: 'The arguments for the contract calls and any additional parameters for the call', }, returns: 'The deployment result', }) yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {` yield IncIndent if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)` if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)` if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)` yield `return this.appClient.deploy({` yield IncIndent yield `...params,` if (callConfig.updateMethods.length) yield 'updateArgs,' if (callConfig.deleteMethods.length) yield 'deleteArgs,' if (callConfig.createMethods.length) { yield 'createArgs,' yield `createOnCompleteAction: createArgs?.onCompleteAction,` } yield DecIndent yield `})` yield DecIndentAndCloseBlock yield NewLine yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true) yield* operationMethod( ctx, `Updates an existing instance of the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod( ctx, `Opts the user into an existing instance of the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn', ) yield* operationMethod( ctx, `Makes a close out call to an existing instance of the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName, name }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} methods`) yield `public get ${verb}() {` yield IncIndent yield `const $this = this` yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call.`, params: { args: `The arguments for the bare call`, }, returns: `The ${verb} result`, }) yield `bare(args: BareCallArgs & AppClientCallCoreParams ${ includeCompilation ? '& AppClientCompilationParams ' : '' }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<undefined>> {` yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`) yield '},' } else { const uniqueName = methodSignatureToUniqueName[methodSig]
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig) yield* jsDoc({
description: `${description} using the ${methodSig} ABI method.`, params: { args: `The arguments for the smart contract call`, params: `Any additional parameters for the call`, }, returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${ includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {` yield* indent( `return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier( uniqueName, )}(args, params)))`, ) yield '},' } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* clearState({ app }: GeneratorContext): DocumentParts { yield* jsDoc({ description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`, params: { args: `The arguments for the bare call`, }, returns: `The clear_state result`, }) yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent yield `return this.appClient.clearState(args)` yield DecIndentAndCloseBlock yield NewLine } function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { for (const method of app.contract.methods) { const methodSignature = algokit.getABIMethodSignature(method) const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]) // Skip methods which don't support a no_op call config if (!callConfig.callMethods.includes(methodSignature)) continue yield* jsDoc({ description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`, abiDescription: method.desc, params: { args: `The arguments for the contract call`, params: `Any additional parameters for the call`, }, returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name yield `return this.call(${name}CallFactory.${methodName}(args, params)${ outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}` })` yield DecIndent yield '}' yield NewLine } } function* getStateMethods({ app, name }: GeneratorContext): DocumentParts { const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared) const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared) if (globalStateValues?.length || localStateValues?.length) { yield* jsDoc({ description: 'Extracts a binary state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'A BinaryState instance containing the state value, or undefined if the key was not found', }) yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if (!('valueRaw' in value))` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`) yield `return {` yield IncIndent yield `asString(): string {` yield* indent(`return value.value`) yield `},` yield `asByteArray(): Uint8Array {` yield* indent(`return value.valueRaw`) yield `}` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Extracts a integer state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'An IntegerState instance containing the state value, or undefined if the key was not found', }) yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if ('valueRaw' in value)` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`) yield `return {` yield IncIndent yield `asBigInt() {` yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`) yield `},` yield `asNumber(): number {` yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`) yield `},` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (globalStateValues?.length) { yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`) yield `public async getGlobalState(): Promise<${name}['state']['global']> {` yield IncIndent yield `const state = await this.appClient.getGlobalState()` yield `return {` yield IncIndent for (const stateValue of globalStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (localStateValues?.length) { yield* jsDoc({ description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`, params: { account: `The address of the account for which to read local state from`, }, }) yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {` yield IncIndent yield `const state = await this.appClient.getLocalState(account)` yield `return {` yield IncIndent for (const stateValue of localStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } }
src/client/call-client.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-factory.ts", "retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,", "score": 0.9283658266067505 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.bare({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`\n yield `resultMappers.push(undefined)`\n yield `return $this`\n yield DecIndent\n yield '},'\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]", "score": 0.8975082635879517 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`", "score": 0.8804148435592651 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " params: {\n args: `The arguments for the bare call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}): ${name}Composer<[...TReturns, undefined]>`\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]", "score": 0.8682490587234497 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " const methodName = makeSafeMethodIdentifier(uniqueName)\n yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''\n }: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${\n onComplete?.type ? ` & ${onComplete.type}` : ''\n }) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`", "score": 0.8544331789016724 } ]
typescript
const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig) yield* jsDoc({
import { ContractMethod } from '../schema/application' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer' import { isSafeVariableIdentifier, makeSafeMethodIdentifier, makeSafePropertyIdentifier } from '../util/sanitization' import * as algokit from '@algorandfoundation/algokit-utils' import { GeneratorContext } from './generator-context' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { getCreateOnCompleteOptions } from './deploy-types' export function* callFactory(ctx: GeneratorContext): DocumentParts { yield* jsDoc('Exposes methods for constructing all available smart contract calls') yield `export abstract class ${ctx.name}CallFactory {` yield IncIndent yield* opMethods(ctx) for (const method of ctx.app.contract.methods) { yield* callFactoryMethod(ctx, method) } yield DecIndent yield '}' } function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig } = ctx yield* operationMethod( ctx, `Constructs a create call for the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true, ) yield* operationMethod( ctx, `Constructs an update call for the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Constructs a delete call for the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod(ctx, `Constructs an opt in call for the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn') yield* operationMethod( ctx, `Constructs a close out call for the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} call factories`) yield `static get ${verb}() {` yield IncIndent yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call`, params: { params: `Any parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: true, name: 'bare', paramTypes: `BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs${ includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`, }) } else { const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)! const uniqueName = methodSignatureToUniqueName[methodSig] yield* jsDoc({ description: `${description} using the ${methodSig} ABI method`, params: { args: `Any args for the contract call`, params: `Any additional parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: true, name: makeSafeMethodIdentifier(uniqueName), signature: methodSig, args: method.args, paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${ onComplete?.type ? ` & ${onComplete.type}` : '' }${onComplete?.isOptional !== false ? ' = {}' : ''}`, }) } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } }
function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) {
const methodSignature = algokit.getABIMethodSignature(method) if (!callConfig.callMethods.includes(methodSignature)) return yield* jsDoc({ description: `Constructs a no op call for the ${methodSignature} ABI method`, abiDescription: method.desc, params: { args: `Any args for the contract call`, params: `Any additional parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: false, name: makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]), signature: methodSignature, args: method.args, paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs', }) } function* factoryMethod({ isNested, name, signature, args, paramTypes, }: | { isNested: boolean name?: string signature?: undefined args?: undefined paramTypes: string } | { isNested: boolean name?: string signature: string args: Array<{ name: string }> paramTypes: string }) { yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {` yield IncIndent yield `return {` yield IncIndent if (signature) { yield `method: '${signature}' as const,` yield `methodArgs: Array.isArray(args) ? args : [${args .map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`)) .join(', ')}],` } else { yield `method: undefined,` yield `methodArgs: undefined,` } yield '...params,' yield DecIndent yield '}' yield DecIndent yield `}${isNested ? ',' : ''}` }
src/client/call-factory.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-client.ts", "retrieved_chunk": " }\n }\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield NewLine\n }\n}\nfunction* clearState({ app }: GeneratorContext): DocumentParts {\n yield* jsDoc({\n description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,", "score": 0.8561102747917175 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " yield `return $this`\n yield DecIndent\n yield '},'\n }\n }\n yield DecIndentAndCloseBlock\n yield DecIndent\n yield '},'\n }\n}", "score": 0.848434329032898 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " if (callConfig.deleteMethods.length) {\n yield* jsDoc('A delegate which takes a delete call factory and returns the delete call params for this smart contract')\n yield `deleteCall?: (callFactory: ${name}DeleteCalls) => ${name}DeleteCallParams`\n }\n yield DecIndentAndCloseBlock\n yield NewLine\n}", "score": 0.8477015495300293 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " }\n yield '},'\n }\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield NewLine\n }\n}", "score": 0.8282036185264587 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " if (method === BARE_CALL) {\n yield `| TypedCallParams<undefined>`\n } else {\n yield `| TypedCallParams<'${method}'>`\n }\n }\n yield DecIndent\n }\n yield* jsDoc('Defines arguments required for the deploy method.')\n yield `export type ${name}DeployArgs = {`", "score": 0.8278299570083618 } ]
typescript
function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) {
import { GeneratorContext } from './generator-context' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, inline, jsDoc, NewLine } from '../output/writer' import * as algokit from '@algorandfoundation/algokit-utils' import { getEquivalentType } from './helpers/get-equivalent-type' import { makeSafePropertyIdentifier, makeSafeTypeIdentifier, makeSafeVariableIdentifier } from '../util/sanitization' export function* appTypes(ctx: GeneratorContext): DocumentParts { const { app, methodSignatureToUniqueName, name } = ctx yield* jsDoc(`Defines the types of available calls and state of the ${name} smart contract.`) yield `export type ${name} = {` yield IncIndent yield* jsDoc('Maps method signatures / names to their argument and return types.') yield 'methods:' yield IncIndent for (const method of app.contract.methods) { const methodSig = algokit.getABIMethodSignature(method) const uniqueName = methodSignatureToUniqueName[methodSig] yield `& Record<'${methodSig}'${methodSig !== uniqueName ? ` | '${uniqueName}'` : ''}, {` yield IncIndent yield `argsObj: {` yield IncIndent const argsMeta = method.args.map((arg) => ({ ...arg, hasDefault: app.hints?.[methodSig]?.default_arguments?.[arg.name], tsType: getEquivalentType(arg.type, 'input'), })) for (const arg of argsMeta) { if (arg.desc) yield* jsDoc(arg.desc) yield `${makeSafePropertyIdentifier(arg.name)}${arg.hasDefault ? '?' : ''}: ${arg.tsType}` } yield DecIndentAndCloseBlock yield* inline( `argsTuple: [`, argsMeta .map( (arg) => `${makeSafeVariableIdentifier(arg.name)}: ${getEquivalentType(arg.type, 'input')}${arg.hasDefault ? ' | undefined' : ''}`, ) .join(', '), ']', ) const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output if (method.returns.desc) yield* jsDoc(method.returns.desc) if (outputStruct) { yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}` } else { yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}` } yield DecIndent yield '}>' } yield DecIndent yield* appState(ctx) yield DecIndentAndCloseBlock yield* jsDoc('Defines the possible abi call signatures') yield `export type ${name}Sig = keyof ${name}['methods']` yield* jsDoc( 'Defines an object containing all relevant parameters for a single call to the contract. Where TSignature is undefined, a' + ' bare call is made', ) yield `export type TypedCallParams<TSignature extends ${name}Sig | undefined> = {` yield IncIndent yield 'method: TSignature' yield 'methodArgs: TSignature extends undefined ? undefined : Array<ABIAppCallArg | undefined>' yield DecIndent yield '} & AppClientCallCoreParams & CoreAppCallArgs' yield* jsDoc('Defines the arguments required for a bare call') yield `export type BareCallArgs = Omit<RawAppCallArgs, keyof CoreAppCallArgs>` yield* structs(ctx) yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's arguments in either tuple of struct form`) yield `export type MethodArgs<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['argsObj' | 'argsTuple']` yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's return type`) yield `export type MethodReturn<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['returns']` yield NewLine } function* structs({ app }: GeneratorContext): DocumentParts { if (app.hints === undefined) return for (const methodHint of Object.values(app.hints)) {
if (methodHint.structs === undefined) continue for (const struct of Object.values(methodHint.structs)) {
yield* jsDoc(`Represents a ${struct.name} result as a struct`) yield `export type ${makeSafeTypeIdentifier(struct.name)} = {` yield IncIndent for (const [key, type] of struct.elements) { yield `${makeSafePropertyIdentifier(key)}: ${getEquivalentType(type, 'output')}` } yield DecIndentAndCloseBlock yield* jsDoc(`Converts the tuple representation of a ${struct.name} to the struct representation`) yield* inline( `export function ${makeSafeTypeIdentifier(struct.name)}(`, `[${struct.elements.map(([key]) => makeSafeVariableIdentifier(key)).join(', ')}]: `, `[${struct.elements.map(([_, type]) => getEquivalentType(type, 'output')).join(', ')}] ) {`, ) yield IncIndent yield `return {` yield IncIndent for (const [key] of struct.elements) { const prop = makeSafePropertyIdentifier(key) const param = makeSafeVariableIdentifier(key) yield `${prop}${prop !== param ? `: ${param}` : ''},` } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock } } } function* appState({ app }: GeneratorContext): DocumentParts { const hasLocal = app.schema.local?.declared && Object.keys(app.schema.local.declared).length const hasGlobal = app.schema.global?.declared && Object.keys(app.schema.global.declared).length if (hasLocal || hasGlobal) { yield* jsDoc('Defines the shape of the global and local state of the application.') yield 'state: {' yield IncIndent if (hasGlobal) { yield 'global: {' yield IncIndent for (const prop of Object.values(app.schema.global!.declared!)) { if (prop.descr) { yield* jsDoc(prop.descr) } yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}` } yield DecIndentAndCloseBlock } if (hasLocal) { yield 'local: {' yield IncIndent for (const prop of Object.values(app.schema.local!.declared!)) { if (prop.descr) { yield* jsDoc(prop.descr) } yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}` } yield DecIndentAndCloseBlock } yield DecIndentAndCloseBlock } }
src/client/app-types.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-client.ts", "retrieved_chunk": " params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`\n yield IncIndent\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `return this.call(${name}CallFactory.${methodName}(args, params)${", "score": 0.8394572734832764 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, undefined]>`\n yield NewLine\n}\nfunction* callComposerTypeNoops({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config", "score": 0.8352124094963074 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`", "score": 0.8341038227081299 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " params: {\n typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',\n returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',\n },\n returns: 'The result of the smart contract call',\n })\n yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`\n yield IncIndent\n yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`\n yield DecIndentAndCloseBlock", "score": 0.823131799697876 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)", "score": 0.8217238783836365 } ]
typescript
if (methodHint.structs === undefined) continue for (const struct of Object.values(methodHint.structs)) {
import * as algokit from '@algorandfoundation/algokit-utils' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer' import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { GeneratorContext } from './generator-context' import { getCreateOnCompleteOptions } from './deploy-types' import { composeMethod } from './call-composer' export function* callClient(ctx: GeneratorContext): DocumentParts { const { app, name } = ctx yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`) yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {` yield IncIndent yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`) yield 'public readonly appClient: ApplicationClient' yield NewLine yield `private readonly sender: SendTransactionFrom | undefined` yield NewLine yield* jsDoc({ description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``, params: { appDetails: 'appDetails The details to identify the app to deploy', algod: 'An algod client instance', }, }) yield `constructor(appDetails: AppDetails, private algod: Algodv2) {` yield IncIndent yield `this.sender = appDetails.sender` yield 'this.appClient = algokit.getAppClient({' yield* indent('...appDetails,', 'app: APP_SPEC') yield '}, algod)' yield DecIndent yield '}' yield NewLine yield* jsDoc({ description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type', params: { result: 'The AppCallTransactionResult to be mapped', returnValueFormatter: 'An optional delegate to format the return value if required', }, returns: 'The smart contract response with an updated return value', }) yield* inline( `protected mapReturnValue<TReturn>`, `(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `, `AppCallTransactionResultOfType<TReturn> {`, ) yield IncIndent yield `if(result.return?.decodeError) {` yield* indent(`throw result.return.decodeError`) yield `}` yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined` yield IncIndent yield `? returnValueFormatter(result.return.returnValue)` yield `: result.return?.returnValue as TReturn | undefined` yield `return { ...result, return: returnValue }` yield DecIndent yield
DecIndentAndCloseBlock yield NewLine yield* jsDoc({
description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP', params: { typedCallParams: 'An object containing the method signature, args, and any other relevant parameters', returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type', }, returns: 'The result of the smart contract call', }) yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {` yield IncIndent yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)` yield DecIndentAndCloseBlock yield NewLine yield* opMethods(ctx) yield* clearState(ctx) yield* noopMethods(ctx) yield* getStateMethods(ctx) yield* composeMethod(ctx) yield DecIndentAndCloseBlock } function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig, name } = ctx yield* jsDoc({ description: `Idempotently deploys the ${app.contract.name} smart contract.`, params: { params: 'The arguments for the contract calls and any additional parameters for the call', }, returns: 'The deployment result', }) yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {` yield IncIndent if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)` if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)` if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)` yield `return this.appClient.deploy({` yield IncIndent yield `...params,` if (callConfig.updateMethods.length) yield 'updateArgs,' if (callConfig.deleteMethods.length) yield 'deleteArgs,' if (callConfig.createMethods.length) { yield 'createArgs,' yield `createOnCompleteAction: createArgs?.onCompleteAction,` } yield DecIndent yield `})` yield DecIndentAndCloseBlock yield NewLine yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true) yield* operationMethod( ctx, `Updates an existing instance of the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod( ctx, `Opts the user into an existing instance of the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn', ) yield* operationMethod( ctx, `Makes a close out call to an existing instance of the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName, name }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} methods`) yield `public get ${verb}() {` yield IncIndent yield `const $this = this` yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call.`, params: { args: `The arguments for the bare call`, }, returns: `The ${verb} result`, }) yield `bare(args: BareCallArgs & AppClientCallCoreParams ${ includeCompilation ? '& AppClientCompilationParams ' : '' }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<undefined>> {` yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`) yield '},' } else { const uniqueName = methodSignatureToUniqueName[methodSig] const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig) yield* jsDoc({ description: `${description} using the ${methodSig} ABI method.`, params: { args: `The arguments for the smart contract call`, params: `Any additional parameters for the call`, }, returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${ includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {` yield* indent( `return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier( uniqueName, )}(args, params)))`, ) yield '},' } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* clearState({ app }: GeneratorContext): DocumentParts { yield* jsDoc({ description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`, params: { args: `The arguments for the bare call`, }, returns: `The clear_state result`, }) yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent yield `return this.appClient.clearState(args)` yield DecIndentAndCloseBlock yield NewLine } function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { for (const method of app.contract.methods) { const methodSignature = algokit.getABIMethodSignature(method) const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]) // Skip methods which don't support a no_op call config if (!callConfig.callMethods.includes(methodSignature)) continue yield* jsDoc({ description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`, abiDescription: method.desc, params: { args: `The arguments for the contract call`, params: `Any additional parameters for the call`, }, returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name yield `return this.call(${name}CallFactory.${methodName}(args, params)${ outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}` })` yield DecIndent yield '}' yield NewLine } } function* getStateMethods({ app, name }: GeneratorContext): DocumentParts { const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared) const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared) if (globalStateValues?.length || localStateValues?.length) { yield* jsDoc({ description: 'Extracts a binary state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'A BinaryState instance containing the state value, or undefined if the key was not found', }) yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if (!('valueRaw' in value))` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`) yield `return {` yield IncIndent yield `asString(): string {` yield* indent(`return value.value`) yield `},` yield `asByteArray(): Uint8Array {` yield* indent(`return value.valueRaw`) yield `}` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Extracts a integer state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'An IntegerState instance containing the state value, or undefined if the key was not found', }) yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if ('valueRaw' in value)` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`) yield `return {` yield IncIndent yield `asBigInt() {` yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`) yield `},` yield `asNumber(): number {` yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`) yield `},` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (globalStateValues?.length) { yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`) yield `public async getGlobalState(): Promise<${name}['state']['global']> {` yield IncIndent yield `const state = await this.appClient.getGlobalState()` yield `return {` yield IncIndent for (const stateValue of globalStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (localStateValues?.length) { yield* jsDoc({ description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`, params: { account: `The address of the account for which to read local state from`, }, }) yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {` yield IncIndent yield `const state = await this.appClient.getLocalState(account)` yield `return {` yield IncIndent for (const stateValue of localStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } }
src/client/call-client.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-composer.ts", "retrieved_chunk": " yield IncIndent\n yield `...result,`\n yield `returns: result.returns?.map((val, i) => resultMappers[i] !== undefined ? resultMappers[i]!(val.returnValue) : val.returnValue)`\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield DecIndent\n yield `} as unknown as ${name}Composer`\n yield DecIndentAndCloseBlock\n}\nfunction* callComposerNoops({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {", "score": 0.8433945178985596 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " } else {\n yield `method: undefined,`\n yield `methodArgs: undefined,`\n }\n yield '...params,'\n yield DecIndent\n yield '}'\n yield DecIndent\n yield `}${isNested ? ',' : ''}`\n}", "score": 0.797166109085083 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " yield IncIndent\n yield 'await promiseChain'\n yield 'return atc'\n yield DecIndent\n yield '},'\n yield `async execute() {`\n yield IncIndent\n yield `await promiseChain`\n yield `const result = await algokit.sendAtomicTransactionComposer({ atc, sendParams: {} }, client.algod)`\n yield `return {`", "score": 0.7960028052330017 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " yield `atc(): Promise<AtomicTransactionComposer>`\n yield* jsDoc({\n description: 'Executes the transaction group and returns an array of results',\n })\n yield `execute(): Promise<${name}ComposerResults<TReturns>>`\n yield DecIndentAndCloseBlock\n yield `export type ${name}ComposerResults<TReturns extends [...any[]]> = {`\n yield IncIndent\n yield `returns: TReturns`\n yield `groupId: string`", "score": 0.7955677509307861 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " if (callConfig.deleteMethods.length) {\n yield* jsDoc('A delegate which takes a delete call factory and returns the delete call params for this smart contract')\n yield `deleteCall?: (callFactory: ${name}DeleteCalls) => ${name}DeleteCallParams`\n }\n yield DecIndentAndCloseBlock\n yield NewLine\n}", "score": 0.7898156642913818 } ]
typescript
DecIndentAndCloseBlock yield NewLine yield* jsDoc({
import * as algokit from '@algorandfoundation/algokit-utils' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer' import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { GeneratorContext } from './generator-context' import { getCreateOnCompleteOptions } from './deploy-types' import { composeMethod } from './call-composer' export function* callClient(ctx: GeneratorContext): DocumentParts { const { app, name } = ctx yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`) yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {` yield IncIndent yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`) yield 'public readonly appClient: ApplicationClient' yield NewLine yield `private readonly sender: SendTransactionFrom | undefined` yield NewLine yield* jsDoc({ description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``, params: { appDetails: 'appDetails The details to identify the app to deploy', algod: 'An algod client instance', }, }) yield `constructor(appDetails: AppDetails, private algod: Algodv2) {` yield IncIndent yield `this.sender = appDetails.sender` yield 'this.appClient = algokit.getAppClient({' yield* indent('...appDetails,', 'app: APP_SPEC') yield '}, algod)' yield DecIndent yield '}' yield NewLine yield* jsDoc({ description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type', params: { result: 'The AppCallTransactionResult to be mapped', returnValueFormatter: 'An optional delegate to format the return value if required', }, returns: 'The smart contract response with an updated return value', }) yield* inline( `protected mapReturnValue<TReturn>`, `(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `, `AppCallTransactionResultOfType<TReturn> {`, ) yield IncIndent yield `if(result.return?.decodeError) {` yield* indent(`throw result.return.decodeError`) yield `}` yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined` yield IncIndent yield `? returnValueFormatter(result.return.returnValue)` yield `: result.return?.returnValue as TReturn | undefined` yield `return { ...result, return: returnValue }` yield DecIndent yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP', params: { typedCallParams: 'An object containing the method signature, args, and any other relevant parameters', returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type', }, returns: 'The result of the smart contract call', }) yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {` yield IncIndent yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)` yield DecIndentAndCloseBlock yield NewLine yield* opMethods(ctx) yield* clearState(ctx) yield* noopMethods(ctx) yield* getStateMethods(ctx) yield*
composeMethod(ctx) yield DecIndentAndCloseBlock }
function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig, name } = ctx yield* jsDoc({ description: `Idempotently deploys the ${app.contract.name} smart contract.`, params: { params: 'The arguments for the contract calls and any additional parameters for the call', }, returns: 'The deployment result', }) yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {` yield IncIndent if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)` if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)` if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)` yield `return this.appClient.deploy({` yield IncIndent yield `...params,` if (callConfig.updateMethods.length) yield 'updateArgs,' if (callConfig.deleteMethods.length) yield 'deleteArgs,' if (callConfig.createMethods.length) { yield 'createArgs,' yield `createOnCompleteAction: createArgs?.onCompleteAction,` } yield DecIndent yield `})` yield DecIndentAndCloseBlock yield NewLine yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true) yield* operationMethod( ctx, `Updates an existing instance of the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod( ctx, `Opts the user into an existing instance of the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn', ) yield* operationMethod( ctx, `Makes a close out call to an existing instance of the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName, name }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} methods`) yield `public get ${verb}() {` yield IncIndent yield `const $this = this` yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call.`, params: { args: `The arguments for the bare call`, }, returns: `The ${verb} result`, }) yield `bare(args: BareCallArgs & AppClientCallCoreParams ${ includeCompilation ? '& AppClientCompilationParams ' : '' }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<undefined>> {` yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`) yield '},' } else { const uniqueName = methodSignatureToUniqueName[methodSig] const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig) yield* jsDoc({ description: `${description} using the ${methodSig} ABI method.`, params: { args: `The arguments for the smart contract call`, params: `Any additional parameters for the call`, }, returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${ includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {` yield* indent( `return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier( uniqueName, )}(args, params)))`, ) yield '},' } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* clearState({ app }: GeneratorContext): DocumentParts { yield* jsDoc({ description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`, params: { args: `The arguments for the bare call`, }, returns: `The clear_state result`, }) yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent yield `return this.appClient.clearState(args)` yield DecIndentAndCloseBlock yield NewLine } function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { for (const method of app.contract.methods) { const methodSignature = algokit.getABIMethodSignature(method) const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]) // Skip methods which don't support a no_op call config if (!callConfig.callMethods.includes(methodSignature)) continue yield* jsDoc({ description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`, abiDescription: method.desc, params: { args: `The arguments for the contract call`, params: `Any additional parameters for the call`, }, returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name yield `return this.call(${name}CallFactory.${methodName}(args, params)${ outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}` })` yield DecIndent yield '}' yield NewLine } } function* getStateMethods({ app, name }: GeneratorContext): DocumentParts { const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared) const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared) if (globalStateValues?.length || localStateValues?.length) { yield* jsDoc({ description: 'Extracts a binary state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'A BinaryState instance containing the state value, or undefined if the key was not found', }) yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if (!('valueRaw' in value))` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`) yield `return {` yield IncIndent yield `asString(): string {` yield* indent(`return value.value`) yield `},` yield `asByteArray(): Uint8Array {` yield* indent(`return value.valueRaw`) yield `}` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Extracts a integer state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'An IntegerState instance containing the state value, or undefined if the key was not found', }) yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if ('valueRaw' in value)` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`) yield `return {` yield IncIndent yield `asBigInt() {` yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`) yield `},` yield `asNumber(): number {` yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`) yield `},` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (globalStateValues?.length) { yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`) yield `public async getGlobalState(): Promise<${name}['state']['global']> {` yield IncIndent yield `const state = await this.appClient.getGlobalState()` yield `return {` yield IncIndent for (const stateValue of globalStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (localStateValues?.length) { yield* jsDoc({ description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`, params: { account: `The address of the account for which to read local state from`, }, }) yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {` yield IncIndent yield `const state = await this.appClient.getLocalState(account)` yield `return {` yield IncIndent for (const stateValue of localStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } }
src/client/call-client.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/generate.ts", "retrieved_chunk": " yield NewLine\n yield* utilityTypes()\n yield NewLine\n yield* appTypes(ctx)\n yield* deployTypes(ctx)\n yield NewLine\n // Write a call factory\n yield* callFactory(ctx)\n yield NewLine\n // Write a client", "score": 0.8380172252655029 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " yield IncIndent\n yield* opMethods(ctx)\n for (const method of ctx.app.contract.methods) {\n yield* callFactoryMethod(ctx, method)\n }\n yield DecIndent\n yield '}'\n}\nfunction* opMethods(ctx: GeneratorContext): DocumentParts {\n const { app, callConfig } = ctx", "score": 0.8231251239776611 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " yield `return $this`\n yield DecIndent\n yield '},'\n }\n }\n yield DecIndentAndCloseBlock\n yield DecIndent\n yield '},'\n }\n}", "score": 0.7999083995819092 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " } else {\n yield `method: undefined,`\n yield `methodArgs: undefined,`\n }\n yield '...params,'\n yield DecIndent\n yield '}'\n yield DecIndent\n yield `}${isNested ? ',' : ''}`\n}", "score": 0.7702479362487793 }, { "filename": "src/client/utility-types.ts", "retrieved_chunk": " yield* jsDoc('A state record containing binary data')\n yield `export type BinaryState = {`\n yield IncIndent\n yield* jsDoc('Gets the state value as a Uint8Array')\n yield `asByteArray(): Uint8Array`\n yield* jsDoc('Gets the state value as a string')\n yield `asString(): string`\n yield DecIndentAndCloseBlock\n}\nexport const OnCompleteCodeMap = {", "score": 0.7455530166625977 } ]
typescript
composeMethod(ctx) yield DecIndentAndCloseBlock }
import { GeneratorContext } from './generator-context' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, inline, jsDoc, NewLine } from '../output/writer' import * as algokit from '@algorandfoundation/algokit-utils' import { getEquivalentType } from './helpers/get-equivalent-type' import { makeSafePropertyIdentifier, makeSafeTypeIdentifier, makeSafeVariableIdentifier } from '../util/sanitization' export function* appTypes(ctx: GeneratorContext): DocumentParts { const { app, methodSignatureToUniqueName, name } = ctx yield* jsDoc(`Defines the types of available calls and state of the ${name} smart contract.`) yield `export type ${name} = {` yield IncIndent yield* jsDoc('Maps method signatures / names to their argument and return types.') yield 'methods:' yield IncIndent for (const method of app.contract.methods) { const methodSig = algokit.getABIMethodSignature(method) const uniqueName = methodSignatureToUniqueName[methodSig] yield `& Record<'${methodSig}'${methodSig !== uniqueName ? ` | '${uniqueName}'` : ''}, {` yield IncIndent yield `argsObj: {` yield IncIndent const argsMeta = method.args.map((arg) => ({ ...arg, hasDefault: app.hints?.[methodSig]?.default_arguments?.[arg.name], tsType: getEquivalentType(arg.type, 'input'), })) for (const arg of argsMeta) { if (arg.desc) yield* jsDoc(arg.desc) yield `${makeSafePropertyIdentifier(arg.name)}${arg.hasDefault ? '?' : ''}: ${arg.tsType}` } yield DecIndentAndCloseBlock yield* inline( `argsTuple: [`, argsMeta .map( (arg) => `${makeSafeVariableIdentifier(arg.name)}: ${getEquivalentType(arg.type, 'input')}${arg.hasDefault ? ' | undefined' : ''}`, ) .join(', '), ']', ) const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output if (method.returns.desc) yield* jsDoc(method.returns.desc) if (outputStruct) {
yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}` } else {
yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}` } yield DecIndent yield '}>' } yield DecIndent yield* appState(ctx) yield DecIndentAndCloseBlock yield* jsDoc('Defines the possible abi call signatures') yield `export type ${name}Sig = keyof ${name}['methods']` yield* jsDoc( 'Defines an object containing all relevant parameters for a single call to the contract. Where TSignature is undefined, a' + ' bare call is made', ) yield `export type TypedCallParams<TSignature extends ${name}Sig | undefined> = {` yield IncIndent yield 'method: TSignature' yield 'methodArgs: TSignature extends undefined ? undefined : Array<ABIAppCallArg | undefined>' yield DecIndent yield '} & AppClientCallCoreParams & CoreAppCallArgs' yield* jsDoc('Defines the arguments required for a bare call') yield `export type BareCallArgs = Omit<RawAppCallArgs, keyof CoreAppCallArgs>` yield* structs(ctx) yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's arguments in either tuple of struct form`) yield `export type MethodArgs<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['argsObj' | 'argsTuple']` yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's return type`) yield `export type MethodReturn<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['returns']` yield NewLine } function* structs({ app }: GeneratorContext): DocumentParts { if (app.hints === undefined) return for (const methodHint of Object.values(app.hints)) { if (methodHint.structs === undefined) continue for (const struct of Object.values(methodHint.structs)) { yield* jsDoc(`Represents a ${struct.name} result as a struct`) yield `export type ${makeSafeTypeIdentifier(struct.name)} = {` yield IncIndent for (const [key, type] of struct.elements) { yield `${makeSafePropertyIdentifier(key)}: ${getEquivalentType(type, 'output')}` } yield DecIndentAndCloseBlock yield* jsDoc(`Converts the tuple representation of a ${struct.name} to the struct representation`) yield* inline( `export function ${makeSafeTypeIdentifier(struct.name)}(`, `[${struct.elements.map(([key]) => makeSafeVariableIdentifier(key)).join(', ')}]: `, `[${struct.elements.map(([_, type]) => getEquivalentType(type, 'output')).join(', ')}] ) {`, ) yield IncIndent yield `return {` yield IncIndent for (const [key] of struct.elements) { const prop = makeSafePropertyIdentifier(key) const param = makeSafeVariableIdentifier(key) yield `${prop}${prop !== param ? `: ${param}` : ''},` } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock } } } function* appState({ app }: GeneratorContext): DocumentParts { const hasLocal = app.schema.local?.declared && Object.keys(app.schema.local.declared).length const hasGlobal = app.schema.global?.declared && Object.keys(app.schema.global.declared).length if (hasLocal || hasGlobal) { yield* jsDoc('Defines the shape of the global and local state of the application.') yield 'state: {' yield IncIndent if (hasGlobal) { yield 'global: {' yield IncIndent for (const prop of Object.values(app.schema.global!.declared!)) { if (prop.descr) { yield* jsDoc(prop.descr) } yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}` } yield DecIndentAndCloseBlock } if (hasLocal) { yield 'local: {' yield IncIndent for (const prop of Object.values(app.schema.local!.declared!)) { if (prop.descr) { yield* jsDoc(prop.descr) } yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}` } yield DecIndentAndCloseBlock } yield DecIndentAndCloseBlock } }
src/client/app-types.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-factory.ts", "retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,", "score": 0.8409797549247742 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " }) {\n yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {`\n yield IncIndent\n yield `return {`\n yield IncIndent\n if (signature) {\n yield `method: '${signature}' as const,`\n yield `methodArgs: Array.isArray(args) ? args : [${args\n .map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`))\n .join(', ')}],`", "score": 0.8393861651420593 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`", "score": 0.824775755405426 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {`\n yield IncIndent\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `return this.call(${name}CallFactory.${methodName}(args, params)${", "score": 0.8155325055122375 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " const methodName = makeSafeMethodIdentifier(uniqueName)\n yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''\n }: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${\n onComplete?.type ? ` & ${onComplete.type}` : ''\n }) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`", "score": 0.7914736270904541 } ]
typescript
yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}` } else {
import { GeneratorContext } from './generator-context' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, inline, jsDoc, NewLine } from '../output/writer' import * as algokit from '@algorandfoundation/algokit-utils' import { getEquivalentType } from './helpers/get-equivalent-type' import { makeSafePropertyIdentifier, makeSafeTypeIdentifier, makeSafeVariableIdentifier } from '../util/sanitization' export function* appTypes(ctx: GeneratorContext): DocumentParts { const { app, methodSignatureToUniqueName, name } = ctx yield* jsDoc(`Defines the types of available calls and state of the ${name} smart contract.`) yield `export type ${name} = {` yield IncIndent yield* jsDoc('Maps method signatures / names to their argument and return types.') yield 'methods:' yield IncIndent for (const method of app.contract.methods) { const methodSig = algokit.getABIMethodSignature(method) const uniqueName = methodSignatureToUniqueName[methodSig] yield `& Record<'${methodSig}'${methodSig !== uniqueName ? ` | '${uniqueName}'` : ''}, {` yield IncIndent yield `argsObj: {` yield IncIndent const argsMeta = method.args.map((arg) => ({ ...arg, hasDefault: app.hints?.[methodSig]?.default_arguments?.[arg.name], tsType: getEquivalentType(arg.type, 'input'), })) for (const arg of argsMeta) { if (arg.desc) yield* jsDoc(arg.desc) yield `${makeSafePropertyIdentifier(arg.name)}${arg.hasDefault ? '?' : ''}: ${arg.tsType}` } yield DecIndentAndCloseBlock yield* inline( `argsTuple: [`, argsMeta .map( (arg) => `${makeSafeVariableIdentifier(arg.name)}: ${getEquivalentType(arg.type, 'input')}${arg.hasDefault ? ' | undefined' : ''}`, ) .join(', '), ']', ) const outputStruct = ctx.app.hints?.[methodSig]?.structs?.output if (method.returns.desc) yield* jsDoc(method.returns.desc) if (outputStruct) { yield `returns: ${makeSafeTypeIdentifier(outputStruct.name)}` } else { yield `returns: ${getEquivalentType(method.returns.type ?? 'void', 'output')}` } yield DecIndent yield '}>' } yield DecIndent yield* appState(ctx) yield DecIndentAndCloseBlock yield* jsDoc('Defines the possible abi call signatures') yield `export type ${name}Sig = keyof ${name}['methods']` yield* jsDoc( 'Defines an object containing all relevant parameters for a single call to the contract. Where TSignature is undefined, a' + ' bare call is made', ) yield `export type TypedCallParams<TSignature extends ${name}Sig | undefined> = {` yield IncIndent yield 'method: TSignature' yield 'methodArgs: TSignature extends undefined ? undefined : Array<ABIAppCallArg | undefined>' yield DecIndent yield '} & AppClientCallCoreParams & CoreAppCallArgs' yield* jsDoc('Defines the arguments required for a bare call') yield `export type BareCallArgs = Omit<RawAppCallArgs, keyof CoreAppCallArgs>` yield* structs(ctx) yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's arguments in either tuple of struct form`) yield `export type MethodArgs<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['argsObj' | 'argsTuple']` yield* jsDoc(`Maps a method signature from the ${name} smart contract to the method's return type`) yield `export type MethodReturn<TSignature extends ${name}Sig> = ${name}['methods'][TSignature]['returns']` yield NewLine } function* structs({ app }: GeneratorContext): DocumentParts { if (app.hints === undefined) return for (const methodHint of Object.values(app.hints)) { if (methodHint.structs === undefined) continue for (const struct of Object.values(methodHint.structs)) { yield* jsDoc(`Represents a ${struct.name} result as a struct`) yield `export type ${makeSafeTypeIdentifier(struct.name)} = {` yield IncIndent for (const [key, type] of struct.elements) { yield `${makeSafePropertyIdentifier(key)}: ${getEquivalentType(type, 'output')}` } yield DecIndentAndCloseBlock yield* jsDoc(`Converts the tuple representation of a ${struct.name} to the struct representation`) yield* inline( `export function ${makeSafeTypeIdentifier(struct.name)}(`, `[${struct.elements.map(([key]) => makeSafeVariableIdentifier(key)).join(', ')}]: `, `[${struct.elements.map(([_, type]) => getEquivalentType(type, 'output')).join(', ')}] ) {`, ) yield IncIndent yield `return {` yield IncIndent for (const [key] of struct.elements) { const prop = makeSafePropertyIdentifier(key) const param = makeSafeVariableIdentifier(key) yield `${prop}${prop !== param ? `: ${param}` : ''},` } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock } } } function* appState({ app }: GeneratorContext): DocumentParts { const hasLocal = app.schema.local?.declared && Object.keys(app.schema.local.declared).length const hasGlobal = app.schema.global?.declared && Object.keys(app.schema.global.declared).length if (hasLocal || hasGlobal) { yield* jsDoc('Defines the shape of the global and local state of the application.') yield 'state: {' yield IncIndent if (hasGlobal) { yield 'global: {' yield IncIndent for (const prop of Object.values(app.schema.global!.declared!)) { if (
prop.descr) {
yield* jsDoc(prop.descr) } yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}` } yield DecIndentAndCloseBlock } if (hasLocal) { yield 'local: {' yield IncIndent for (const prop of Object.values(app.schema.local!.declared!)) { if (prop.descr) { yield* jsDoc(prop.descr) } yield `'${prop.key}'?: ${prop.type === 'uint64' ? 'IntegerState' : 'BinaryState'}` } yield DecIndentAndCloseBlock } yield DecIndentAndCloseBlock } }
src/client/app-types.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-client.ts", "retrieved_chunk": " yield NewLine\n }\n if (globalStateValues?.length) {\n yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`)\n yield `public async getGlobalState(): Promise<${name}['state']['global']> {`\n yield IncIndent\n yield `const state = await this.appClient.getGlobalState()`\n yield `return {`\n yield IncIndent\n for (const stateValue of globalStateValues) {", "score": 0.850174069404602 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " if (methods.length) {\n yield* jsDoc(`Gets available ${verb} call factories`)\n yield `static get ${verb}() {`\n yield IncIndent\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield* jsDoc({", "score": 0.8293808102607727 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${", "score": 0.8279805183410645 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": "): DocumentParts {\n if (methods.length) {\n yield* jsDoc(`Gets available ${verb} methods`)\n yield `readonly ${verb}: {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield* jsDoc({\n description: `${description} using a bare call.`,", "score": 0.8173201084136963 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " methods: MethodList,\n verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',\n includeCompilation?: boolean,\n): DocumentParts {\n if (methods.length) {\n yield* jsDoc(`Gets available ${verb} methods`)\n yield `public get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`", "score": 0.8128292560577393 } ]
typescript
prop.descr) {
import { pascalCase } from 'change-case' import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application' export const BARE_CALL = Symbol('bare') export type MethodIdentifier = string | typeof BARE_CALL export type MethodList = Array<MethodIdentifier> export type CallConfigSummary = { createMethods: MethodList callMethods: MethodList deleteMethods: MethodList updateMethods: MethodList optInMethods: MethodList closeOutMethods: MethodList } export const getCallConfigSummary = (app: AlgoAppSpec) => { const result: CallConfigSummary = { createMethods: [], callMethods: [], deleteMethods: [], updateMethods: [], optInMethods: [], closeOutMethods: [], } if (app.bare_call_config) { addToConfig(result, BARE_CALL, app.bare_call_config) } if (app.hints) { for (const [method, hints] of Object.entries(app.hints)) { if (hints.call_config) { addToConfig(result, method, hints.call_config) } } } return result } export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => { const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config if (!callConfig) { return '' } const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE' return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }` } const
getCreateOnCompleteTypes = (config: CallConfig) => {
return Object.keys(config) .map((oc) => oc as keyof CallConfig) .filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE') .map((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') } const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => { if (hasCall(config.no_op)) { result.callMethods.push(method) } if ( hasCreate(config.no_op) || hasCreate(config.opt_in) || hasCreate(config.close_out) || hasCreate(config.update_application) || hasCreate(config.delete_application) ) { result.createMethods.push(method) } if (hasCall(config.delete_application)) { result.deleteMethods.push(method) } if (hasCall(config.update_application)) { result.updateMethods.push(method) } if (hasCall(config.opt_in)) { result.optInMethods.push(method) } if (hasCall(config.close_out)) { result.closeOutMethods.push(method) } } const hasCall = (config: CallConfigValue | undefined) => { return config === 'CALL' || config === 'ALL' } const hasCreate = (config: CallConfigValue | undefined) => { return config === 'CREATE' || config === 'ALL' }
src/client/helpers/get-call-config-summary.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig", "score": 0.8614827990531921 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, undefined]>`\n yield NewLine\n}\nfunction* callComposerTypeNoops({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config", "score": 0.8308255672454834 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)", "score": 0.8261314630508423 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${", "score": 0.8253037929534912 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,", "score": 0.8146140575408936 } ]
typescript
getCreateOnCompleteTypes = (config: CallConfig) => {
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer' import { makeSafeTypeIdentifier } from '../util/sanitization' import { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary' import { GeneratorContext } from './generator-context' import { AlgoAppSpec, CallConfig } from '../schema/application' import { OnCompleteCodeMap } from './utility-types' export function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) { const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE' const onCompleteType = callConfig ? `(${Object.entries(callConfig) .filter(([_, value]) => value === 'ALL' || value === 'CREATE') .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig]) .join(' | ')})` : {} return { type: onCompleteType, isOptional: hasNoOp, } } export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts { const name = makeSafeTypeIdentifier(app.contract.name) if (callConfig.createMethods.length > 0) { yield* jsDoc(`A factory for available 'create' calls`) yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']` yield* jsDoc('Defines supported create methods for this smart contract') yield `export type ${name}CreateCallParams =` yield IncIndent for (const method of callConfig.createMethods) { const onComplete = getCreateOnCompleteOptions(method, app) if (method === BARE_CALL) { yield `| (TypedCallParams<undefined> & ${onComplete.type})` } else { yield `| (TypedCallParams<'${method}'> & ${onComplete.type})` } }
yield DecIndent }
if (callConfig.updateMethods.length > 0) { yield* jsDoc(`A factory for available 'update' calls`) yield `export type ${name}UpdateCalls = (typeof ${name}CallFactory)['update']` yield* jsDoc('Defines supported update methods for this smart contract') yield `export type ${name}UpdateCallParams =` yield IncIndent for (const method of callConfig.updateMethods) { if (method === BARE_CALL) { yield `| TypedCallParams<undefined>` } else { yield `| TypedCallParams<'${method}'>` } } yield DecIndent } if (callConfig.deleteMethods.length > 0) { yield* jsDoc(`A factory for available 'delete' calls`) yield `export type ${name}DeleteCalls = (typeof ${name}CallFactory)['delete']` yield* jsDoc('Defines supported delete methods for this smart contract') yield `export type ${name}DeleteCallParams =` yield IncIndent for (const method of callConfig.deleteMethods) { if (method === BARE_CALL) { yield `| TypedCallParams<undefined>` } else { yield `| TypedCallParams<'${method}'>` } } yield DecIndent } yield* jsDoc('Defines arguments required for the deploy method.') yield `export type ${name}DeployArgs = {` yield IncIndent yield `deployTimeParams?: TealTemplateParams` if (callConfig.createMethods.length) { yield* jsDoc('A delegate which takes a create call factory and returns the create call params for this smart contract') yield `createCall?: (callFactory: ${name}CreateCalls) => ${name}CreateCallParams` } if (callConfig.updateMethods.length) { yield* jsDoc('A delegate which takes a update call factory and returns the update call params for this smart contract') yield `updateCall?: (callFactory: ${name}UpdateCalls) => ${name}UpdateCallParams` } if (callConfig.deleteMethods.length) { yield* jsDoc('A delegate which takes a delete call factory and returns the delete call params for this smart contract') yield `deleteCall?: (callFactory: ${name}DeleteCalls) => ${name}DeleteCallParams` } yield DecIndentAndCloseBlock yield NewLine }
src/client/deploy-types.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-composer.ts", "retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${", "score": 0.8785149455070496 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " if (methods.length) {\n yield* jsDoc(`Gets available ${verb} call factories`)\n yield `static get ${verb}() {`\n yield IncIndent\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield* jsDoc({", "score": 0.8728287816047668 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": "): DocumentParts {\n if (methods.length) {\n yield* jsDoc(`Gets available ${verb} methods`)\n yield `readonly ${verb}: {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield* jsDoc({\n description: `${description} using a bare call.`,", "score": 0.8666098117828369 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " params: {\n args: `The arguments for the bare call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}): ${name}Composer<[...TReturns, undefined]>`\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]", "score": 0.8529503345489502 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield* jsDoc({\n description: `${description} using a bare call.`,\n params: {\n args: `The arguments for the bare call`,\n },\n returns: `The ${verb} result`,", "score": 0.8528546094894409 } ]
typescript
yield DecIndent }
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent } from '../output/writer' import { GeneratorContext } from './generator-context' import * as algokit from '@algorandfoundation/algokit-utils' import { makeSafeMethodIdentifier } from '../util/sanitization' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { getCreateOnCompleteOptions } from './deploy-types' export function* composeMethod(ctx: GeneratorContext): DocumentParts { const { name, callConfig } = ctx yield `public compose(): ${name}Composer {` yield IncIndent yield `const client = this` yield `const atc = new AtomicTransactionComposer()` yield `let promiseChain:Promise<unknown> = Promise.resolve()` yield `const resultMappers: Array<undefined | ((x: any) => any)> = []` yield `return {` yield IncIndent yield* callComposerNoops(ctx) yield* callComposerOperationMethods(ctx, callConfig.updateMethods, 'update', true) yield* callComposerOperationMethods(ctx, callConfig.deleteMethods, 'delete') yield* callComposerOperationMethods(ctx, callConfig.optInMethods, 'optIn') yield* callComposerOperationMethods(ctx, callConfig.closeOutMethods, 'closeOut') yield* callComposerClearState() yield `addTransaction(txn: TransactionWithSigner | TransactionToSign | Transaction | Promise<SendTransactionResult>, defaultSender?: SendTransactionFrom) {` yield IncIndent yield 'promiseChain = promiseChain.then(async () => atc.addTransaction(await algokit.getTransactionWithSigner(txn, defaultSender ??' + ' client.sender)))' yield 'return this' yield DecIndent yield '},' yield `async atc() {` yield IncIndent yield 'await promiseChain' yield 'return atc' yield DecIndent yield '},' yield `async execute() {` yield IncIndent yield `await promiseChain` yield `const result = await algokit.sendAtomicTransactionComposer({ atc, sendParams: {} }, client.algod)` yield `return {` yield IncIndent yield `...result,` yield `returns: result.returns?.map((val, i) => resultMappers[i] !== undefined ? resultMappers[i]!(val.returnValue) : val.returnValue)` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield DecIndent yield `} as unknown as ${name}Composer` yield DecIndentAndCloseBlock } function* callComposerNoops
({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
for (const method of app.contract.methods) { const methodSignature = algokit.getABIMethodSignature(method) const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]) // Skip methods which don't support a no_op call config if (!callConfig.callMethods.includes(methodSignature)) continue yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {` yield IncIndent yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))` const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name yield `resultMappers.push(${outputTypeName ?? 'undefined'})` yield `return this` yield DecIndent yield '},' } } function* callComposerClearState(): DocumentParts { yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs) {` yield IncIndent yield `promiseChain = promiseChain.then(() => client.clearState({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))` yield `resultMappers.push(undefined)` yield `return this` yield DecIndent yield '},' } function* callComposerOperationMethods( { app, methodSignatureToUniqueName }: GeneratorContext, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield `get ${verb}() {` yield IncIndent yield `const $this = this` yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${ includeCompilation ? '& AppClientCompilationParams ' : '' }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}) {` yield IncIndent yield `promiseChain = promiseChain.then(() => client.${verb}.bare({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))` yield `resultMappers.push(undefined)` yield `return $this` yield DecIndent yield '},' } else { const uniqueName = methodSignatureToUniqueName[methodSig] const methodName = makeSafeMethodIdentifier(uniqueName) yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${ onComplete?.isOptional !== false ? '?' : '' }: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${ onComplete?.type ? ` & ${onComplete.type}` : '' }) {` yield IncIndent yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))` const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name yield `resultMappers.push(${outputTypeName ?? 'undefined'})` yield `return $this` yield DecIndent yield '},' } } yield DecIndentAndCloseBlock yield DecIndent yield '},' } }
src/client/call-composer.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-client.ts", "retrieved_chunk": " yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`\n yield IncIndent\n yield `? returnValueFormatter(result.return.returnValue)`\n yield `: result.return?.returnValue as TReturn | undefined`\n yield `return { ...result, return: returnValue }`\n yield DecIndent\n yield DecIndentAndCloseBlock\n yield NewLine\n yield* jsDoc({\n description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',", "score": 0.8193483352661133 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " }\n }\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield NewLine\n }\n}\nfunction* clearState({ app }: GeneratorContext): DocumentParts {\n yield* jsDoc({\n description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,", "score": 0.8116304874420166 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " })\n yield* inline(\n `protected mapReturnValue<TReturn>`,\n `(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `,\n `AppCallTransactionResultOfType<TReturn> {`,\n )\n yield IncIndent\n yield `if(result.return?.decodeError) {`\n yield* indent(`throw result.return.decodeError`)\n yield `}`", "score": 0.7978686094284058 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " yield IncIndent\n yield* opMethods(ctx)\n for (const method of ctx.app.contract.methods) {\n yield* callFactoryMethod(ctx, method)\n }\n yield DecIndent\n yield '}'\n}\nfunction* opMethods(ctx: GeneratorContext): DocumentParts {\n const { app, callConfig } = ctx", "score": 0.7948653697967529 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " })\n yield `bare(args: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${\n onComplete?.isOptional !== false ? ' = {}' : ''\n }): Promise<AppCallTransactionResultOfType<undefined>> {`\n yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`)\n yield '},'\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]", "score": 0.78807532787323 } ]
typescript
({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
import { pascalCase } from 'change-case' import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application' export const BARE_CALL = Symbol('bare') export type MethodIdentifier = string | typeof BARE_CALL export type MethodList = Array<MethodIdentifier> export type CallConfigSummary = { createMethods: MethodList callMethods: MethodList deleteMethods: MethodList updateMethods: MethodList optInMethods: MethodList closeOutMethods: MethodList } export const getCallConfigSummary = (app: AlgoAppSpec) => { const result: CallConfigSummary = { createMethods: [], callMethods: [], deleteMethods: [], updateMethods: [], optInMethods: [], closeOutMethods: [], } if (app.bare_call_config) { addToConfig(result, BARE_CALL, app.bare_call_config) } if (app.hints) { for (const [method, hints] of Object.entries(app.hints)) { if (hints.call_config) { addToConfig(result, method, hints.call_config) } } } return result } export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => { const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config if (!callConfig) { return '' } const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE' return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }` } const getCreateOnCompleteTypes = (config: CallConfig) => { return Object.keys(config) .map((oc) => oc as keyof CallConfig) .filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE') .map((oc) =>
`'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') }
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => { if (hasCall(config.no_op)) { result.callMethods.push(method) } if ( hasCreate(config.no_op) || hasCreate(config.opt_in) || hasCreate(config.close_out) || hasCreate(config.update_application) || hasCreate(config.delete_application) ) { result.createMethods.push(method) } if (hasCall(config.delete_application)) { result.deleteMethods.push(method) } if (hasCall(config.update_application)) { result.updateMethods.push(method) } if (hasCall(config.opt_in)) { result.optInMethods.push(method) } if (hasCall(config.close_out)) { result.closeOutMethods.push(method) } } const hasCall = (config: CallConfigValue | undefined) => { return config === 'CALL' || config === 'ALL' } const hasCreate = (config: CallConfigValue | undefined) => { return config === 'CREATE' || config === 'ALL' }
src/client/helpers/get-call-config-summary.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " ? `(${Object.entries(callConfig)\n .filter(([_, value]) => value === 'ALL' || value === 'CREATE')\n .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])\n .join(' | ')})`\n : {}\n return {\n type: onCompleteType,\n isOptional: hasNoOp,\n }\n}", "score": 0.8619898557662964 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)", "score": 0.7623655796051025 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " if (method === BARE_CALL) {\n yield `| (TypedCallParams<undefined> & ${onComplete.type})`\n } else {\n yield `| (TypedCallParams<'${method}'> & ${onComplete.type})`\n }\n }\n yield DecIndent\n }\n if (callConfig.updateMethods.length > 0) {\n yield* jsDoc(`A factory for available 'update' calls`)", "score": 0.7462359070777893 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,", "score": 0.7373639345169067 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig", "score": 0.7373135089874268 } ]
typescript
`'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') }
import * as algokit from '@algorandfoundation/algokit-utils' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer' import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { GeneratorContext } from './generator-context' import { getCreateOnCompleteOptions } from './deploy-types' import { composeMethod } from './call-composer' export function* callClient(ctx: GeneratorContext): DocumentParts { const { app, name } = ctx yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`) yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {` yield IncIndent yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`) yield 'public readonly appClient: ApplicationClient' yield NewLine yield `private readonly sender: SendTransactionFrom | undefined` yield NewLine yield* jsDoc({ description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``, params: { appDetails: 'appDetails The details to identify the app to deploy', algod: 'An algod client instance', }, }) yield `constructor(appDetails: AppDetails, private algod: Algodv2) {` yield IncIndent yield `this.sender = appDetails.sender` yield 'this.appClient = algokit.getAppClient({' yield* indent('...appDetails,', 'app: APP_SPEC') yield '}, algod)' yield DecIndent yield '}' yield NewLine yield* jsDoc({ description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type', params: { result: 'The AppCallTransactionResult to be mapped', returnValueFormatter: 'An optional delegate to format the return value if required', }, returns: 'The smart contract response with an updated return value', }) yield* inline( `protected mapReturnValue<TReturn>`, `(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `, `AppCallTransactionResultOfType<TReturn> {`, ) yield IncIndent yield `if(result.return?.decodeError) {` yield* indent(`throw result.return.decodeError`) yield `}` yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined` yield IncIndent yield `? returnValueFormatter(result.return.returnValue)` yield `: result.return?.returnValue as TReturn | undefined` yield `return { ...result, return: returnValue }` yield DecIndent yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP', params: { typedCallParams: 'An object containing the method signature, args, and any other relevant parameters', returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type', }, returns: 'The result of the smart contract call', }) yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {` yield IncIndent yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)` yield DecIndentAndCloseBlock yield NewLine yield* opMethods(ctx) yield* clearState(ctx) yield* noopMethods(ctx) yield* getStateMethods(ctx)
yield* composeMethod(ctx) yield DecIndentAndCloseBlock }
function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig, name } = ctx yield* jsDoc({ description: `Idempotently deploys the ${app.contract.name} smart contract.`, params: { params: 'The arguments for the contract calls and any additional parameters for the call', }, returns: 'The deployment result', }) yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {` yield IncIndent if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)` if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)` if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)` yield `return this.appClient.deploy({` yield IncIndent yield `...params,` if (callConfig.updateMethods.length) yield 'updateArgs,' if (callConfig.deleteMethods.length) yield 'deleteArgs,' if (callConfig.createMethods.length) { yield 'createArgs,' yield `createOnCompleteAction: createArgs?.onCompleteAction,` } yield DecIndent yield `})` yield DecIndentAndCloseBlock yield NewLine yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true) yield* operationMethod( ctx, `Updates an existing instance of the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod( ctx, `Opts the user into an existing instance of the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn', ) yield* operationMethod( ctx, `Makes a close out call to an existing instance of the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName, name }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} methods`) yield `public get ${verb}() {` yield IncIndent yield `const $this = this` yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call.`, params: { args: `The arguments for the bare call`, }, returns: `The ${verb} result`, }) yield `bare(args: BareCallArgs & AppClientCallCoreParams ${ includeCompilation ? '& AppClientCompilationParams ' : '' }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<undefined>> {` yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`) yield '},' } else { const uniqueName = methodSignatureToUniqueName[methodSig] const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig) yield* jsDoc({ description: `${description} using the ${methodSig} ABI method.`, params: { args: `The arguments for the smart contract call`, params: `Any additional parameters for the call`, }, returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${ includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {` yield* indent( `return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier( uniqueName, )}(args, params)))`, ) yield '},' } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* clearState({ app }: GeneratorContext): DocumentParts { yield* jsDoc({ description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`, params: { args: `The arguments for the bare call`, }, returns: `The clear_state result`, }) yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent yield `return this.appClient.clearState(args)` yield DecIndentAndCloseBlock yield NewLine } function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { for (const method of app.contract.methods) { const methodSignature = algokit.getABIMethodSignature(method) const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]) // Skip methods which don't support a no_op call config if (!callConfig.callMethods.includes(methodSignature)) continue yield* jsDoc({ description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`, abiDescription: method.desc, params: { args: `The arguments for the contract call`, params: `Any additional parameters for the call`, }, returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name yield `return this.call(${name}CallFactory.${methodName}(args, params)${ outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}` })` yield DecIndent yield '}' yield NewLine } } function* getStateMethods({ app, name }: GeneratorContext): DocumentParts { const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared) const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared) if (globalStateValues?.length || localStateValues?.length) { yield* jsDoc({ description: 'Extracts a binary state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'A BinaryState instance containing the state value, or undefined if the key was not found', }) yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if (!('valueRaw' in value))` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`) yield `return {` yield IncIndent yield `asString(): string {` yield* indent(`return value.value`) yield `},` yield `asByteArray(): Uint8Array {` yield* indent(`return value.valueRaw`) yield `}` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Extracts a integer state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'An IntegerState instance containing the state value, or undefined if the key was not found', }) yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if ('valueRaw' in value)` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`) yield `return {` yield IncIndent yield `asBigInt() {` yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`) yield `},` yield `asNumber(): number {` yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`) yield `},` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (globalStateValues?.length) { yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`) yield `public async getGlobalState(): Promise<${name}['state']['global']> {` yield IncIndent yield `const state = await this.appClient.getGlobalState()` yield `return {` yield IncIndent for (const stateValue of globalStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (localStateValues?.length) { yield* jsDoc({ description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`, params: { account: `The address of the account for which to read local state from`, }, }) yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {` yield IncIndent yield `const state = await this.appClient.getLocalState(account)` yield `return {` yield IncIndent for (const stateValue of localStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } }
src/client/call-client.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-factory.ts", "retrieved_chunk": " yield IncIndent\n yield* opMethods(ctx)\n for (const method of ctx.app.contract.methods) {\n yield* callFactoryMethod(ctx, method)\n }\n yield DecIndent\n yield '}'\n}\nfunction* opMethods(ctx: GeneratorContext): DocumentParts {\n const { app, callConfig } = ctx", "score": 0.8229930400848389 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " yield `const client = this`\n yield `const atc = new AtomicTransactionComposer()`\n yield `let promiseChain:Promise<unknown> = Promise.resolve()`\n yield `const resultMappers: Array<undefined | ((x: any) => any)> = []`\n yield `return {`\n yield IncIndent\n yield* callComposerNoops(ctx)\n yield* callComposerOperationMethods(ctx, callConfig.updateMethods, 'update', true)\n yield* callComposerOperationMethods(ctx, callConfig.deleteMethods, 'delete')\n yield* callComposerOperationMethods(ctx, callConfig.optInMethods, 'optIn')", "score": 0.8188560009002686 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " yield IncIndent\n yield `...result,`\n yield `returns: result.returns?.map((val, i) => resultMappers[i] !== undefined ? resultMappers[i]!(val.returnValue) : val.returnValue)`\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield DecIndent\n yield `} as unknown as ${name}Composer`\n yield DecIndentAndCloseBlock\n}\nfunction* callComposerNoops({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {", "score": 0.808659553527832 }, { "filename": "src/client/generate.ts", "retrieved_chunk": " yield NewLine\n yield* utilityTypes()\n yield NewLine\n yield* appTypes(ctx)\n yield* deployTypes(ctx)\n yield NewLine\n // Write a call factory\n yield* callFactory(ctx)\n yield NewLine\n // Write a client", "score": 0.8031531572341919 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " yield `return this`\n yield DecIndent\n yield '},'\n }\n}\nfunction* callComposerClearState(): DocumentParts {\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.clearState({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))`\n yield `resultMappers.push(undefined)`", "score": 0.7905499339103699 } ]
typescript
yield* composeMethod(ctx) yield DecIndentAndCloseBlock }
import * as algokit from '@algorandfoundation/algokit-utils' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, indent, inline, jsDoc, NewLine } from '../output/writer' import { makeSafeMethodIdentifier, makeSafeTypeIdentifier } from '../util/sanitization' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { GeneratorContext } from './generator-context' import { getCreateOnCompleteOptions } from './deploy-types' import { composeMethod } from './call-composer' export function* callClient(ctx: GeneratorContext): DocumentParts { const { app, name } = ctx yield* jsDoc(`A client to make calls to the ${app.contract.name} smart contract`) yield `export class ${makeSafeTypeIdentifier(app.contract.name)}Client {` yield IncIndent yield* jsDoc(`The underlying \`ApplicationClient\` for when you want to have more flexibility`) yield 'public readonly appClient: ApplicationClient' yield NewLine yield `private readonly sender: SendTransactionFrom | undefined` yield NewLine yield* jsDoc({ description: `Creates a new instance of \`${makeSafeTypeIdentifier(app.contract.name)}Client\``, params: { appDetails: 'appDetails The details to identify the app to deploy', algod: 'An algod client instance', }, }) yield `constructor(appDetails: AppDetails, private algod: Algodv2) {` yield IncIndent yield `this.sender = appDetails.sender` yield 'this.appClient = algokit.getAppClient({' yield* indent('...appDetails,', 'app: APP_SPEC') yield '}, algod)' yield DecIndent yield '}' yield NewLine yield* jsDoc({ description: 'Checks for decode errors on the AppCallTransactionResult and maps the return value to the specified generic type', params: { result: 'The AppCallTransactionResult to be mapped', returnValueFormatter: 'An optional delegate to format the return value if required', }, returns: 'The smart contract response with an updated return value', }) yield* inline( `protected mapReturnValue<TReturn>`, `(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `, `AppCallTransactionResultOfType<TReturn> {`, ) yield IncIndent yield `if(result.return?.decodeError) {` yield* indent(`throw result.return.decodeError`) yield `}` yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined` yield IncIndent yield `? returnValueFormatter(result.return.returnValue)` yield `: result.return?.returnValue as TReturn | undefined` yield `return { ...result, return: returnValue }` yield DecIndent yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP', params: { typedCallParams: 'An object containing the method signature, args, and any other relevant parameters', returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type', }, returns: 'The result of the smart contract call', }) yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {` yield IncIndent yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)` yield DecIndentAndCloseBlock yield NewLine yield* opMethods(ctx) yield* clearState(ctx) yield* noopMethods(ctx) yield* getStateMethods(ctx) yield* composeMethod(ctx) yield DecIndentAndCloseBlock } function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig, name } = ctx yield* jsDoc({ description: `Idempotently deploys the ${app.contract.name} smart contract.`, params: { params: 'The arguments for the contract calls and any additional parameters for the call', }, returns: 'The deployment result', }) yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {` yield IncIndent if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)` if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)` if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)` yield `return this.appClient.deploy({` yield IncIndent yield `...params,` if (callConfig.updateMethods.length) yield 'updateArgs,' if (callConfig.deleteMethods.length) yield 'deleteArgs,' if (callConfig.createMethods.length) { yield 'createArgs,' yield `createOnCompleteAction: createArgs?.onCompleteAction,` } yield DecIndent yield `})` yield DecIndentAndCloseBlock yield NewLine yield* operationMethod(ctx, `Creates a new instance of the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true) yield* operationMethod( ctx, `Updates an existing instance of the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Deletes an existing instance of the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod( ctx, `Opts the user into an existing instance of the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn', ) yield* operationMethod( ctx, `Makes a close out call to an existing instance of the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName, name }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} methods`) yield `public get ${verb}() {` yield IncIndent yield `const $this = this` yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call.`, params: { args: `The arguments for the bare call`, }, returns: `The ${verb} result`, }) yield `bare(args: BareCallArgs & AppClientCallCoreParams ${ includeCompilation ? '& AppClientCompilationParams ' : '' }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<undefined>> {` yield* indent(`return $this.appClient.${verb}(args) as unknown as Promise<AppCallTransactionResultOfType<undefined>>`) yield '},' } else { const uniqueName = methodSignatureToUniqueName[methodSig] const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig) yield* jsDoc({ description: `${description} using the ${methodSig} ABI method.`, params: { args: `The arguments for the smart contract call`, params: `Any additional parameters for the call`, }, returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `
async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${
includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${ onComplete?.isOptional !== false ? ' = {}' : '' }): Promise<AppCallTransactionResultOfType<MethodReturn<'${methodSig}'>>> {` yield* indent( `return $this.mapReturnValue(await $this.appClient.${verb}(${name}CallFactory.${verb}.${makeSafeMethodIdentifier( uniqueName, )}(args, params)))`, ) yield '},' } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* clearState({ app }: GeneratorContext): DocumentParts { yield* jsDoc({ description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`, params: { args: `The arguments for the bare call`, }, returns: `The clear_state result`, }) yield `public clearState(args: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent yield `return this.appClient.clearState(args)` yield DecIndentAndCloseBlock yield NewLine } function* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts { for (const method of app.contract.methods) { const methodSignature = algokit.getABIMethodSignature(method) const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]) // Skip methods which don't support a no_op call config if (!callConfig.callMethods.includes(methodSignature)) continue yield* jsDoc({ description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`, abiDescription: method.desc, params: { args: `The arguments for the contract call`, params: `Any additional parameters for the call`, }, returns: `The result of the call${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`, }) yield `public ${methodName}(args: MethodArgs<'${methodSignature}'>, params: AppClientCallCoreParams & CoreAppCallArgs = {}) {` yield IncIndent const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name yield `return this.call(${name}CallFactory.${methodName}(args, params)${ outputTypeName === undefined ? '' : `, ${makeSafeTypeIdentifier(outputTypeName)}` })` yield DecIndent yield '}' yield NewLine } } function* getStateMethods({ app, name }: GeneratorContext): DocumentParts { const globalStateValues = app.schema.global?.declared && Object.values(app.schema.global?.declared) const localStateValues = app.schema.local?.declared && Object.values(app.schema.local?.declared) if (globalStateValues?.length || localStateValues?.length) { yield* jsDoc({ description: 'Extracts a binary state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'A BinaryState instance containing the state value, or undefined if the key was not found', }) yield `private static getBinaryState(state: AppState, key: string): BinaryState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if (!('valueRaw' in value))` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received an int when expected a byte array\`)`) yield `return {` yield IncIndent yield `asString(): string {` yield* indent(`return value.value`) yield `},` yield `asByteArray(): Uint8Array {` yield* indent(`return value.valueRaw`) yield `}` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine yield* jsDoc({ description: 'Extracts a integer state value out of an AppState dictionary', params: { state: 'The state dictionary containing the state value', key: 'The key of the state value', }, returns: 'An IntegerState instance containing the state value, or undefined if the key was not found', }) yield `private static getIntegerState(state: AppState, key: string): IntegerState | undefined {` yield IncIndent yield `const value = state[key]` yield `if (!value) return undefined` yield `if ('valueRaw' in value)` yield* indent(`throw new Error(\`Failed to parse state value for \${key}; received a byte array when expected a number\`)`) yield `return {` yield IncIndent yield `asBigInt() {` yield* indent(`return typeof value.value === 'bigint' ? value.value : BigInt(value.value)`) yield `},` yield `asNumber(): number {` yield* indent(`return typeof value.value === 'bigint' ? Number(value.value) : value.value`) yield `},` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (globalStateValues?.length) { yield* jsDoc(`Returns the smart contract's global state wrapped in a strongly typed accessor with options to format the stored value`) yield `public async getGlobalState(): Promise<${name}['state']['global']> {` yield IncIndent yield `const state = await this.appClient.getGlobalState()` yield `return {` yield IncIndent for (const stateValue of globalStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } if (localStateValues?.length) { yield* jsDoc({ description: `Returns the smart contract's local state wrapped in a strongly typed accessor with options to format the stored value`, params: { account: `The address of the account for which to read local state from`, }, }) yield `public async getLocalState(account: string | SendTransactionFrom): Promise<${name}['state']['local']> {` yield IncIndent yield `const state = await this.appClient.getLocalState(account)` yield `return {` yield IncIndent for (const stateValue of localStateValues) { yield `get ${stateValue.key}() {` if (stateValue.type === 'uint64') { yield* indent(`return ${name}Client.getIntegerState(state, '${stateValue.key}')`) } else { yield* indent(`return ${name}Client.getBinaryState(state, '${stateValue.key}')`) } yield '},' } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } }
src/client/call-client.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method.`,\n params: {\n args: `The arguments for the smart contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''", "score": 0.9147236347198486 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,", "score": 0.8820228576660156 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,\n params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })", "score": 0.8708629012107849 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": "function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) {\n const methodSignature = algokit.getABIMethodSignature(method)\n if (!callConfig.callMethods.includes(methodSignature)) return\n yield* jsDoc({\n description: `Constructs a no op call for the ${methodSignature} ABI method`,\n abiDescription: method.desc,\n params: {\n args: `Any args for the contract call`,\n params: `Any additional parameters for the call`,\n },", "score": 0.8605846166610718 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " params: {\n args: `The arguments for the bare call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}): ${name}Composer<[...TReturns, undefined]>`\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]", "score": 0.8541682958602905 } ]
typescript
async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${
import { pascalCase } from 'change-case' import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application' export const BARE_CALL = Symbol('bare') export type MethodIdentifier = string | typeof BARE_CALL export type MethodList = Array<MethodIdentifier> export type CallConfigSummary = { createMethods: MethodList callMethods: MethodList deleteMethods: MethodList updateMethods: MethodList optInMethods: MethodList closeOutMethods: MethodList } export const getCallConfigSummary = (app: AlgoAppSpec) => { const result: CallConfigSummary = { createMethods: [], callMethods: [], deleteMethods: [], updateMethods: [], optInMethods: [], closeOutMethods: [], } if (app.bare_call_config) { addToConfig(result, BARE_CALL, app.bare_call_config) } if (app.hints) { for (const [method, hints] of Object.entries(app.hints)) { if (hints.call_config) { addToConfig(result, method, hints.call_config) } } } return result } export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => { const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config if (!callConfig) { return '' } const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE' return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }` } const getCreateOnCompleteTypes = (config: CallConfig) => { return Object.keys(config) .map((oc) => oc as keyof CallConfig) .filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE') .map((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') } const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => { if (hasCall(config.no_op)) { result.callMethods.push(method) } if ( hasCreate(config.no_op) || hasCreate(config.opt_in) || hasCreate(config.close_out) || hasCreate(config.update_application) || hasCreate(config.delete_application) ) { result.createMethods.push(method) } if (hasCall(config.delete_application)) { result.deleteMethods.push(method) } if (hasCall(config.update_application)) { result.updateMethods.push(method) } if (hasCall(config.opt_in)) { result.optInMethods.push(method) } if (hasCall(config.close_out)) { result.closeOutMethods.push(method) } }
const hasCall = (config: CallConfigValue | undefined) => {
return config === 'CALL' || config === 'ALL' } const hasCreate = (config: CallConfigValue | undefined) => { return config === 'CREATE' || config === 'ALL' }
src/client/helpers/get-call-config-summary.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-composer.ts", "retrieved_chunk": " for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {`\n yield IncIndent\n yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))`\n const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name\n yield `resultMappers.push(${outputTypeName ?? 'undefined'})`", "score": 0.7599795460700989 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " if (callConfig.updateMethods.length) yield `const updateArgs = params.updateCall?.(${name}CallFactory.update)`\n if (callConfig.deleteMethods.length) yield `const deleteArgs = params.deleteCall?.(${name}CallFactory.delete)`\n yield `return this.appClient.deploy({`\n yield IncIndent\n yield `...params,`\n if (callConfig.updateMethods.length) yield 'updateArgs,'\n if (callConfig.deleteMethods.length) yield 'deleteArgs,'\n if (callConfig.createMethods.length) {\n yield 'createArgs,'\n yield `createOnCompleteAction: createArgs?.onCompleteAction,`", "score": 0.741858184337616 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)", "score": 0.7371730804443359 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " yield `const client = this`\n yield `const atc = new AtomicTransactionComposer()`\n yield `let promiseChain:Promise<unknown> = Promise.resolve()`\n yield `const resultMappers: Array<undefined | ((x: any) => any)> = []`\n yield `return {`\n yield IncIndent\n yield* callComposerNoops(ctx)\n yield* callComposerOperationMethods(ctx, callConfig.updateMethods, 'update', true)\n yield* callComposerOperationMethods(ctx, callConfig.deleteMethods, 'delete')\n yield* callComposerOperationMethods(ctx, callConfig.optInMethods, 'optIn')", "score": 0.7325021028518677 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,", "score": 0.7295215129852295 } ]
typescript
const hasCall = (config: CallConfigValue | undefined) => {
import { HTMLElement, parse } from "node-html-parser" import { addSegment } from "../segments" import { parseTimestamp, TimestampFormatter } from "../timestamp" import { Segment } from "../types" /** * Regular expression to detect `<html>` tag */ const PATTERN_HTML_TAG = /^< *html.*?>/i /** * Regular expression to detect transcript data where `<time>` is followed by `<p>` */ const PATTERN_HTML_TIME_P = /(?<time><time>\d[\d:.,]*?<\/time>)[ \t\r\n]*?(?<body><p>.*?<\/p>)/i /** * Regular expression to detect transcript data where `<p>` is followed by `<time>` */ const PATTERN_HTML_P_TIME = /(?<body><p>.*?<\/p>)[ \t\r\n]*?(?<time><time>\d[\d:.,]*?<\/time>)/i type HTMLSegmentPart = { cite: string time: string text: string } /** * Determines if the value of data is a valid HTML transcript format * * @param data The transcript data * @returns True: data is valid HTML transcript format */ export const isHTML = (data: string): boolean => { return ( data.startsWith("<!--") || PATTERN_HTML_TAG.test(data) || PATTERN_HTML_TIME_P.test(data) || PATTERN_HTML_P_TIME.test(data) ) } /** * Updates HTML Segment parts if expected HTML segment * * @param element HTML segment to check * @param segmentPart Current segment parts * @returns Updated HTML Segment part and segment data for next segment (if fields encountered) */ const updateSegmentPartFromElement = ( element: HTMLElement, segmentPart: HTMLSegmentPart ): { current: HTMLSegmentPart next: HTMLSegmentPart } => { const currentSegmentPart = segmentPart const nextSegmentPart: HTMLSegmentPart = { cite: "", time: "", text: "", } if (element.tagName === "CITE") { if (currentSegmentPart.cite === "") { currentSegmentPart.cite = element.innerHTML } else { nextSegmentPart.cite = element.innerHTML } } else if (element.tagName === "TIME") { if (currentSegmentPart.time === "") { currentSegmentPart.time = element.innerHTML } else { nextSegmentPart.time = element.innerHTML } } else if (element.tagName === "P") { if (currentSegmentPart.text === "") { currentSegmentPart.text = element.innerHTML } else { nextSegmentPart.text = element.innerHTML } } return { current: currentSegmentPart, next: nextSegmentPart } } /** * Create Segment from HTML segment parts * * @param segmentPart HTML segment data * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines` * @returns Created segment */ const createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => { const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker
const startTime = parseTimestamp(segmentPart.time) return {
startTime, startTimeFormatted: TimestampFormatter.format(startTime), endTime: 0, endTimeFormatted: TimestampFormatter.format(0), speaker: calculatedSpeaker.replace(":", "").trimEnd(), body: segmentPart.text, } } /** * Parse HTML data and create {@link Segment} for each segment data found in data * * @param elements HTML elements containing transcript data * @returns Segments created from HTML data */ const getSegmentsFromHTMLElements = (elements: Array<HTMLElement>): Array<Segment> => { let outSegments: Array<Segment> = [] let lastSpeaker = "" let segmentPart: HTMLSegmentPart = { cite: "", time: "", text: "", } let nextSegmentPart: HTMLSegmentPart = { cite: "", time: "", text: "", } elements.forEach((element, count) => { const segmentParts = updateSegmentPartFromElement(element, segmentPart) segmentPart = segmentParts.current nextSegmentPart = segmentParts.next if ( count === elements.length - 1 || Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === "").length !== 3 ) { // time is required if (segmentPart.time === "") { console.warn(`Segment ${count} does not contain time information, ignoring`) } else { const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker) lastSpeaker = segment.speaker // update endTime of previous Segment const totalSegments = outSegments.length if (totalSegments > 0) { outSegments[totalSegments - 1].endTime = segment.startTime outSegments[totalSegments - 1].endTimeFormatted = TimestampFormatter.format( outSegments[totalSegments - 1].endTime ) } outSegments = addSegment(segment, outSegments) } // clear segmentPart = nextSegmentPart nextSegmentPart = { cite: "", time: "", text: "", } } }) return outSegments } /** * Parse HTML data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid HTML format */ export const parseHTML = (data: string): Array<Segment> => { const dataTrimmed = data.trim() if (!isHTML(dataTrimmed)) { throw new TypeError(`Data is not valid HTML format`) } const html = parse(data) let root: HTMLElement const htmlElements = html.getElementsByTagName("html") if (htmlElements.length === 0) { root = html } else { const htmlElement = htmlElements[0] const bodyElements = htmlElement.getElementsByTagName("body") if (bodyElements.length > 0) { // eslint-disable-next-line prefer-destructuring root = bodyElements[0] } else { root = htmlElement } } return getSegmentsFromHTMLElements(root.childNodes as Array<HTMLElement>) }
src/formats/html.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/srt.ts", "retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)", "score": 0.9248071312904358 }, { "filename": "src/segments.ts", "retrieved_chunk": " *\n * @param newSegment segment before any rules options to it\n * @param priorSegment prior parsed segment\n * @param lastSpeaker last speaker name.\n * Used when speaker in segment has been removed via {@link Options.speakerChange} rule\n * @returns the updated segment info\n */\nconst doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {\n const {\n combineEqualTimes,", "score": 0.8867471218109131 }, { "filename": "src/segments.ts", "retrieved_chunk": " *\n * @param newSegment segment before any rules options to it\n * @param lastSpeaker last speaker name.\n * Used when speaker in segment has been removed via {@link Options.speakerChange} rule\n * @returns the updated segment info\n */\nconst doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {\n const { speakerChange } = Options\n let result: CombineResult = {\n segment: newSegment,", "score": 0.8854274749755859 }, { "filename": "src/segments.ts", "retrieved_chunk": " * - `body`: body of priorSegment with body of newSegment separated with space\n *\n * @param newSegment segment being created\n * @param priorSegment prior parsed segment\n * @param lastSpeaker last speaker name.\n * Used when speaker in segment has been removed via {@link Options.speakerChange} rule\n * @returns result of combination.\n * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true.\n */\nconst doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => {", "score": 0.8841699957847595 }, { "filename": "src/segments.ts", "retrieved_chunk": " * Apply any options to the current segment\n *\n * @param newSegment segment before any rules options to it\n * @param priorSegment prior parsed segment. For the first segment, this shall be undefined.\n * @param lastSpeaker last speaker name.\n * Used when speaker in segment has been removed via {@link Options.speakerChange} rule\n * @returns the updated segment info\n */\nconst applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {\n if (!Options.optionsSet()) {", "score": 0.8789759874343872 } ]
typescript
const startTime = parseTimestamp(segmentPart.time) return {
import { pascalCase } from 'change-case' import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application' export const BARE_CALL = Symbol('bare') export type MethodIdentifier = string | typeof BARE_CALL export type MethodList = Array<MethodIdentifier> export type CallConfigSummary = { createMethods: MethodList callMethods: MethodList deleteMethods: MethodList updateMethods: MethodList optInMethods: MethodList closeOutMethods: MethodList } export const getCallConfigSummary = (app: AlgoAppSpec) => { const result: CallConfigSummary = { createMethods: [], callMethods: [], deleteMethods: [], updateMethods: [], optInMethods: [], closeOutMethods: [], } if (app.bare_call_config) { addToConfig(result, BARE_CALL, app.bare_call_config) } if (app.hints) { for (const [method, hints] of Object.entries(app.hints)) { if (hints.call_config) { addToConfig(result, method, hints.call_config) } } } return result } export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => { const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config if (!callConfig) { return '' } const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE' return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }` } const getCreateOnCompleteTypes = (config: CallConfig) => { return Object.keys(config) .map((oc) => oc as keyof CallConfig) .filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE') .map((oc) => `
'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') }
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => { if (hasCall(config.no_op)) { result.callMethods.push(method) } if ( hasCreate(config.no_op) || hasCreate(config.opt_in) || hasCreate(config.close_out) || hasCreate(config.update_application) || hasCreate(config.delete_application) ) { result.createMethods.push(method) } if (hasCall(config.delete_application)) { result.deleteMethods.push(method) } if (hasCall(config.update_application)) { result.updateMethods.push(method) } if (hasCall(config.opt_in)) { result.optInMethods.push(method) } if (hasCall(config.close_out)) { result.closeOutMethods.push(method) } } const hasCall = (config: CallConfigValue | undefined) => { return config === 'CALL' || config === 'ALL' } const hasCreate = (config: CallConfigValue | undefined) => { return config === 'CREATE' || config === 'ALL' }
src/client/helpers/get-call-config-summary.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " ? `(${Object.entries(callConfig)\n .filter(([_, value]) => value === 'ALL' || value === 'CREATE')\n .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])\n .join(' | ')})`\n : {}\n return {\n type: onCompleteType,\n isOptional: hasNoOp,\n }\n}", "score": 0.8556250929832458 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)", "score": 0.761310338973999 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " if (method === BARE_CALL) {\n yield `| (TypedCallParams<undefined> & ${onComplete.type})`\n } else {\n yield `| (TypedCallParams<'${method}'> & ${onComplete.type})`\n }\n }\n yield DecIndent\n }\n if (callConfig.updateMethods.length > 0) {\n yield* jsDoc(`A factory for available 'update' calls`)", "score": 0.7452731132507324 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig", "score": 0.7377219200134277 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${", "score": 0.7353641390800476 } ]
typescript
'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') }
import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent } from '../output/writer' import { GeneratorContext } from './generator-context' import * as algokit from '@algorandfoundation/algokit-utils' import { makeSafeMethodIdentifier } from '../util/sanitization' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { getCreateOnCompleteOptions } from './deploy-types' export function* composeMethod(ctx: GeneratorContext): DocumentParts { const { name, callConfig } = ctx yield `public compose(): ${name}Composer {` yield IncIndent yield `const client = this` yield `const atc = new AtomicTransactionComposer()` yield `let promiseChain:Promise<unknown> = Promise.resolve()` yield `const resultMappers: Array<undefined | ((x: any) => any)> = []` yield `return {` yield IncIndent yield* callComposerNoops(ctx) yield* callComposerOperationMethods(ctx, callConfig.updateMethods, 'update', true) yield* callComposerOperationMethods(ctx, callConfig.deleteMethods, 'delete') yield* callComposerOperationMethods(ctx, callConfig.optInMethods, 'optIn') yield* callComposerOperationMethods(ctx, callConfig.closeOutMethods, 'closeOut') yield* callComposerClearState() yield `addTransaction(txn: TransactionWithSigner | TransactionToSign | Transaction | Promise<SendTransactionResult>, defaultSender?: SendTransactionFrom) {` yield IncIndent yield 'promiseChain = promiseChain.then(async () => atc.addTransaction(await algokit.getTransactionWithSigner(txn, defaultSender ??' + ' client.sender)))' yield 'return this' yield DecIndent yield '},' yield `async atc() {` yield IncIndent yield 'await promiseChain' yield 'return atc' yield DecIndent yield '},' yield `async execute() {` yield IncIndent yield `await promiseChain` yield `const result = await algokit.sendAtomicTransactionComposer({ atc, sendParams: {} }, client.algod)` yield `return {` yield IncIndent yield `...result,` yield `returns: result.returns?.map((val, i) => resultMappers[i] !== undefined ? resultMappers[i]!(val.returnValue) : val.returnValue)` yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield DecIndent yield `} as unknown as ${name}Composer` yield DecIndentAndCloseBlock }
function* callComposerNoops({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
for (const method of app.contract.methods) { const methodSignature = algokit.getABIMethodSignature(method) const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]) // Skip methods which don't support a no_op call config if (!callConfig.callMethods.includes(methodSignature)) continue yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs) {` yield IncIndent yield `promiseChain = promiseChain.then(() => client.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))` const outputTypeName = app.hints?.[methodSignature]?.structs?.output?.name yield `resultMappers.push(${outputTypeName ?? 'undefined'})` yield `return this` yield DecIndent yield '},' } } function* callComposerClearState(): DocumentParts { yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs) {` yield IncIndent yield `promiseChain = promiseChain.then(() => client.clearState({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))` yield `resultMappers.push(undefined)` yield `return this` yield DecIndent yield '},' } function* callComposerOperationMethods( { app, methodSignatureToUniqueName }: GeneratorContext, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield `get ${verb}() {` yield IncIndent yield `const $this = this` yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${ includeCompilation ? '& AppClientCompilationParams ' : '' }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}) {` yield IncIndent yield `promiseChain = promiseChain.then(() => client.${verb}.bare({...args, sendParams: {...args?.sendParams, skipSending: true, atc}}))` yield `resultMappers.push(undefined)` yield `return $this` yield DecIndent yield '},' } else { const uniqueName = methodSignatureToUniqueName[methodSig] const methodName = makeSafeMethodIdentifier(uniqueName) yield `${methodName}(args: MethodArgs<'${methodSig}'>, params${ onComplete?.isOptional !== false ? '?' : '' }: AppClientCallCoreParams${includeCompilation ? ' & AppClientCompilationParams' : ''}${ onComplete?.type ? ` & ${onComplete.type}` : '' }) {` yield IncIndent yield `promiseChain = promiseChain.then(() => client.${verb}.${methodName}(args, {...params, sendParams: {...params?.sendParams, skipSending: true, atc}}))` const outputTypeName = app.hints?.[methodSig]?.structs?.output?.name yield `resultMappers.push(${outputTypeName ?? 'undefined'})` yield `return $this` yield DecIndent yield '},' } } yield DecIndentAndCloseBlock yield DecIndent yield '},' } }
src/client/call-composer.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-client.ts", "retrieved_chunk": " yield `const returnValue = result.return?.returnValue !== undefined && returnValueFormatter !== undefined`\n yield IncIndent\n yield `? returnValueFormatter(result.return.returnValue)`\n yield `: result.return?.returnValue as TReturn | undefined`\n yield `return { ...result, return: returnValue }`\n yield DecIndent\n yield DecIndentAndCloseBlock\n yield NewLine\n yield* jsDoc({\n description: 'Calls the ABI method with the matching signature using an onCompletion code of NO_OP',", "score": 0.8312321305274963 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " }\n }\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield NewLine\n }\n}\nfunction* clearState({ app }: GeneratorContext): DocumentParts {\n yield* jsDoc({\n description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,", "score": 0.818513035774231 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " })\n yield* inline(\n `protected mapReturnValue<TReturn>`,\n `(result: AppCallTransactionResult, returnValueFormatter?: (value: any) => TReturn): `,\n `AppCallTransactionResultOfType<TReturn> {`,\n )\n yield IncIndent\n yield `if(result.return?.decodeError) {`\n yield* indent(`throw result.return.decodeError`)\n yield `}`", "score": 0.8066788911819458 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " yield IncIndent\n yield* opMethods(ctx)\n for (const method of ctx.app.contract.methods) {\n yield* callFactoryMethod(ctx, method)\n }\n yield DecIndent\n yield '}'\n}\nfunction* opMethods(ctx: GeneratorContext): DocumentParts {\n const { app, callConfig } = ctx", "score": 0.8058680891990662 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " yield `atc(): Promise<AtomicTransactionComposer>`\n yield* jsDoc({\n description: 'Executes the transaction group and returns an array of results',\n })\n yield `execute(): Promise<${name}ComposerResults<TReturns>>`\n yield DecIndentAndCloseBlock\n yield `export type ${name}ComposerResults<TReturns extends [...any[]]> = {`\n yield IncIndent\n yield `returns: TReturns`\n yield `groupId: string`", "score": 0.7969914674758911 } ]
typescript
function* callComposerNoops({ app, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {
import { HTMLElement, parse } from "node-html-parser" import { addSegment } from "../segments" import { parseTimestamp, TimestampFormatter } from "../timestamp" import { Segment } from "../types" /** * Regular expression to detect `<html>` tag */ const PATTERN_HTML_TAG = /^< *html.*?>/i /** * Regular expression to detect transcript data where `<time>` is followed by `<p>` */ const PATTERN_HTML_TIME_P = /(?<time><time>\d[\d:.,]*?<\/time>)[ \t\r\n]*?(?<body><p>.*?<\/p>)/i /** * Regular expression to detect transcript data where `<p>` is followed by `<time>` */ const PATTERN_HTML_P_TIME = /(?<body><p>.*?<\/p>)[ \t\r\n]*?(?<time><time>\d[\d:.,]*?<\/time>)/i type HTMLSegmentPart = { cite: string time: string text: string } /** * Determines if the value of data is a valid HTML transcript format * * @param data The transcript data * @returns True: data is valid HTML transcript format */ export const isHTML = (data: string): boolean => { return ( data.startsWith("<!--") || PATTERN_HTML_TAG.test(data) || PATTERN_HTML_TIME_P.test(data) || PATTERN_HTML_P_TIME.test(data) ) } /** * Updates HTML Segment parts if expected HTML segment * * @param element HTML segment to check * @param segmentPart Current segment parts * @returns Updated HTML Segment part and segment data for next segment (if fields encountered) */ const updateSegmentPartFromElement = ( element: HTMLElement, segmentPart: HTMLSegmentPart ): { current: HTMLSegmentPart next: HTMLSegmentPart } => { const currentSegmentPart = segmentPart const nextSegmentPart: HTMLSegmentPart = { cite: "", time: "", text: "", } if (element.tagName === "CITE") { if (currentSegmentPart.cite === "") { currentSegmentPart.cite = element.innerHTML } else { nextSegmentPart.cite = element.innerHTML } } else if (element.tagName === "TIME") { if (currentSegmentPart.time === "") { currentSegmentPart.time = element.innerHTML } else { nextSegmentPart.time = element.innerHTML } } else if (element.tagName === "P") { if (currentSegmentPart.text === "") { currentSegmentPart.text = element.innerHTML } else { nextSegmentPart.text = element.innerHTML } } return { current: currentSegmentPart, next: nextSegmentPart } } /** * Create Segment from HTML segment parts * * @param segmentPart HTML segment data * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines` * @returns Created segment */ const createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => { const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker const startTime = parseTimestamp(segmentPart.time) return { startTime, startTimeFormatted: TimestampFormatter.format(startTime), endTime: 0, endTimeFormatted: TimestampFormatter.format(0), speaker: calculatedSpeaker.replace(":", "").trimEnd(), body: segmentPart.text, } } /** * Parse HTML data and create {@link Segment} for each segment data found in data * * @param elements HTML elements containing transcript data * @returns Segments created from HTML data */ const getSegmentsFromHTMLElements = (elements: Array<HTMLElement>): Array<Segment> => { let outSegments: Array<Segment> = [] let lastSpeaker = "" let segmentPart: HTMLSegmentPart = { cite: "", time: "", text: "", } let nextSegmentPart: HTMLSegmentPart = { cite: "", time: "", text: "", } elements.forEach((element, count) => { const segmentParts = updateSegmentPartFromElement(element, segmentPart) segmentPart = segmentParts.current nextSegmentPart = segmentParts.next if ( count === elements.length - 1 || Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === "").length !== 3 ) { // time is required if (segmentPart.time === "") { console.warn(`Segment ${count} does not contain time information, ignoring`) } else { const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker) lastSpeaker = segment.speaker // update endTime of previous Segment const totalSegments = outSegments.length if (totalSegments > 0) { outSegments[totalSegments - 1].endTime = segment.startTime outSegments[totalSegments - 1].endTimeFormatted = TimestampFormatter.format( outSegments[totalSegments - 1].endTime ) }
outSegments = addSegment(segment, outSegments) }
// clear segmentPart = nextSegmentPart nextSegmentPart = { cite: "", time: "", text: "", } } }) return outSegments } /** * Parse HTML data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid HTML format */ export const parseHTML = (data: string): Array<Segment> => { const dataTrimmed = data.trim() if (!isHTML(dataTrimmed)) { throw new TypeError(`Data is not valid HTML format`) } const html = parse(data) let root: HTMLElement const htmlElements = html.getElementsByTagName("html") if (htmlElements.length === 0) { root = html } else { const htmlElement = htmlElements[0] const bodyElements = htmlElement.getElementsByTagName("body") if (bodyElements.length > 0) { // eslint-disable-next-line prefer-destructuring root = bodyElements[0] } else { root = htmlElement } } return getSegmentsFromHTMLElements(root.childNodes as Array<HTMLElement>) }
src/formats/html.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/json.ts", "retrieved_chunk": "const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => {\n let outSegments: Array<Segment> = []\n data.segments.forEach((segment) => {\n outSegments = addSegment(\n {\n startTime: segment.startTime,\n startTimeFormatted: TimestampFormatter.format(segment.startTime),\n endTime: segment.endTime,\n endTimeFormatted: TimestampFormatter.format(segment.endTime),\n speaker: segment.speaker,", "score": 0.8277792930603027 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " segmentLines = [] // clear buffer\n } else {\n segmentLines.push(line)\n }\n })\n // handle data when trailing line not included\n if (segmentLines.length !== 0) {\n try {\n outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)\n lastSpeaker = outSegments[outSegments.length - 1].speaker", "score": 0.8237043023109436 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " // handle consecutive multiple blank lines\n if (segmentLines.length !== 0) {\n try {\n outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)\n lastSpeaker = outSegments[outSegments.length - 1].speaker\n } catch (e) {\n console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`)\n console.error(segmentLines)\n }\n }", "score": 0.823665976524353 }, { "filename": "src/segments.ts", "retrieved_chunk": " * - `endTimeFormatted`: from last segment\n * - `speaker`: from first segment\n * - `body`: combination of all segments\n */\nconst joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {\n const newSegment = { ...segments[0] }\n segments.slice(1).forEach((segment) => {\n newSegment.endTime = segment.endTime\n newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)\n newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)", "score": 0.8174929618835449 }, { "filename": "src/segments.ts", "retrieved_chunk": " let lastSpeaker: string\n if (speakerChange) {\n lastSpeaker = getLastSpeaker(priorSegment, outSegments)\n }\n const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)\n if (newSegmentInfo.replace && outSegments.length > 0) {\n outSegments[outSegments.length - 1] = newSegmentInfo.segment\n } else {\n outSegments.push(newSegmentInfo.segment)\n }", "score": 0.7945225834846497 } ]
typescript
outSegments = addSegment(segment, outSegments) }
import { Request, Response, Router } from "express"; const router = Router(); import routes from "./routes"; import { rateLimit } from "express-rate-limit"; const resetPasswordLimiter = rateLimit({ windowMs: 60 * 60, // 1 hour max: 5, // 5 requests standardHeaders: true, legacyHeaders: false, message: { "message": "Too many requests, try again later.", "code": "RATE_LIMITED" } }) router.get("/", async (req: Request, res: Response) => { routes.index(req, res); }) router.get("/account", async (req: Request, res: Response) => { routes.account.index(req, res); }) router.get("/account/change-password", async (req: Request, res: Response) => { routes.account["change-password"](req, res); }) router.get("/account/reset-password", async (req: Request, res: Response) => { routes.account["reset-password"](req, res); }) router.post("/api/auth/forgot-password", async (req: Request, res: Response) => { routes.api.auth["forgot-password"](req, res); }) router.post("/api/auth/login", async (req: Request, res: Response) => { routes.api.auth.login(req, res); }) router.delete("/api/posts", async (req: Request, res: Response) => { routes.api.posts(req, res); }) router.get("/api/posts", async (req: Request, res: Response) => { routes.api.posts(req, res); }) router.patch("/api/posts", async (req: Request, res: Response) => { routes.api.posts(req, res); }) router.put("/api/posts", async (req: Request, res: Response) => { routes.api.posts(req, res); }) router.patch("/api/user/password", async (req: Request, res: Response) => { routes.api.user.password(req, res); }) router.put("/api/user/password", resetPasswordLimiter, async (req: Request, res: Response) => { routes.api.user.password(req, res); }) router.get("/api/users", async (req: Request, res: Response) => { routes.api.users(req, res); }) router.get("/auth/forgot-password", async (req: Request, res: Response) => { routes.auth["forgot-password"](req, res); }) router.get("/auth/login", async (req: Request, res: Response) => { routes.auth.login(req, res); }) router.get("/auth/logout", async (req: Request, res: Response) => { routes.auth.logout(req, res); }) router.get("/author/:username", async (req: Request, res: Response) => {
routes.author(req, res);
}) router.get("/authors", async (req: Request, res: Response) => { routes.authors(req, res); }) router.get("/dashboard", async (req: Request, res: Response) => { routes.dashboard(req, res); }) router.get("/post/create", async (req: Request, res: Response) => { routes.post.create(req, res); }) router.get("/post/delete/:id", async (req: Request, res: Response) => { routes.post.delete(req, res); }) router.get("/post/edit/:id", async (req: Request, res: Response) => { routes.post.edit(req, res); }) router.get("/post/:id", async (req: Request, res: Response) => { routes.post.index(req, res); }) router.get("*", async (req: Request, res: Response) => { routes[404](req, res); }) export default router;
src/util/router.ts
wdhdev-blog-171008f
[ { "filename": "src/endpoints/dashboard.ts", "retrieved_chunk": "import { Request, Response } from \"express\";\nimport gravatar from \"gravatar-url\";\nimport Post from \"../models/Post\";\nexport default async (req: Request & any, res: Response) => {\n if(!req.session.loggedIn) return res.status(401).redirect(\"/auth/login\");\n res.status(200).render(\"dashboard\", {\n avatar: gravatar(req.session.email),\n firstName: req.session.firstName,\n username: req.session.username,\n posts: (await Post.find({ author: req.session.username })).reverse()", "score": 0.8190897703170776 }, { "filename": "src/endpoints/author.ts", "retrieved_chunk": "import { Request, Response } from \"express\";\nimport gravatar from \"gravatar-url\";\nimport moment from \"moment\";\nimport Post from \"../models/Post\";\nimport User from \"../models/User\";\nexport default async (req: Request, res: Response) => {\n if(!await User.findOne({ username: req.params.username })) return res.status(404).render(\"errors/404\");\n const user = await User.findOne({ username: req.params.username });\n res.status(200).render(\"author\", {\n author: {", "score": 0.8082053661346436 }, { "filename": "src/endpoints/404.ts", "retrieved_chunk": "import { Request, Response } from \"express\";\nexport default async (req: Request, res: Response) => {\n res.status(404).render(\"errors/404\");\n}", "score": 0.7867433428764343 }, { "filename": "src/endpoints/index.ts", "retrieved_chunk": "import { Request, Response } from \"express\";\nimport moment from \"moment\";\nimport Post from \"../models/Post\";\nexport default async (req: Request & any, res: Response) => {\n res.status(200).render(\"index\", {\n posts: (await Post.find()).reverse(),\n session: {\n loggedIn: req.session.loggedIn\n },\n moment: moment", "score": 0.7576981782913208 }, { "filename": "src/util/routes.ts", "retrieved_chunk": " password: require(\"../endpoints/api/user/password\")\n },\n users: apiUsers\n },\n auth: {\n \"forgot-password\": require(\"../endpoints/auth/forgot-password\"),\n login: require(\"../endpoints/auth/login\"),\n logout: require(\"../endpoints/auth/logout\")\n },\n author: author,", "score": 0.7168889045715332 } ]
typescript
routes.author(req, res);
import { addSegment } from "../segments" import { parseSpeaker } from "../speaker" import { TimestampFormatter } from "../timestamp" import { Segment } from "../types" /** * Define a segment/cue used in the JSONTranscript format */ export type JSONSegment = { /** * Time (in seconds) when segment starts */ startTime: number /** * Time (in seconds) when segment ends */ endTime: number /** * Name of speaker for `body` */ speaker?: string /** * Text of transcript for segment */ body: string } /** * Define the JSON transcript format */ export type JSONTranscript = { /** * Version of file format */ version: string /** * Segment data */ segments: Array<JSONSegment> } /** * Define the JSON transcript Segment format */ export type SubtitleSegment = { /** * Time (in milliseconds) when segment starts */ start: number /** * Time (in milliseconds) when segment ends */ end: number /** * Text of transcript for segment */ text: string } /** * Determines if the value of data is a valid JSON transcript format * * @param data The transcript data * @returns True: data is valid JSON transcript format */ export const isJSON = (data: string): boolean => { return (data.startsWith("{") && data.endsWith("}")) || (data.startsWith("[") && data.endsWith("]")) } /** * Parse JSON data where segments are in the `segments` Array and in the {@link JSONSegment} format * * @param data Parsed JSON data * @returns An array of Segments from the parsed data */ const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => { let outSegments: Array<Segment> = [] data.segments.forEach((segment) => {
outSegments = addSegment( {
startTime: segment.startTime, startTimeFormatted: TimestampFormatter.format(segment.startTime), endTime: segment.endTime, endTimeFormatted: TimestampFormatter.format(segment.endTime), speaker: segment.speaker, body: segment.body, }, outSegments ) }) return outSegments } /** * Parse JSON data where top level item is a dict/object * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When JSON data does not match one of the valid formats */ const parseDictJSON = (data: object): Array<Segment> => { let outSegments: Array<Segment> = [] if (Object.keys(data).length === 0) { return outSegments } if ("segments" in data) { outSegments = parseDictSegmentsJSON(data as JSONTranscript) } else { throw new TypeError(`Unknown JSON dict transcript format`) } return outSegments } /** * Convert {@link SubtitleSegment} to the {@link Segment} format used here * * @param data Segment parsed from JSON data * @returns Segment representing `data`. * Returns {@link undefined} when data does not match {@link SubtitleSegment} format. */ const getSegmentFromSubtitle = (data: SubtitleSegment): Segment => { if ("start" in data && "end" in data && "text" in data) { const { speaker, message } = parseSpeaker(data.text) const startTime = data.start / 1000 const endTime = data.end / 1000 const segment: Segment = { startTime, startTimeFormatted: TimestampFormatter.format(startTime), endTime, endTimeFormatted: TimestampFormatter.format(endTime), speaker, body: message, } if (Number.isNaN(segment.startTime)) { console.warn(`Computed start time is NaN: ${segment.startTime}`) return undefined } if (Number.isNaN(segment.endTime)) { console.warn(`Computed end time is NaN: ${segment.endTime}`) return undefined } return segment } return undefined } /** * Parse JSON data where items in data are in the {@link SubtitleSegment} format * * @param data Parsed JSON data * @returns An array of Segments from the parsed data * @throws {TypeError} When item in `data` does not match the {@link SubtitleSegment} format */ const parseListJSONSubtitle = (data: Array<SubtitleSegment>): Array<Segment> => { let outSegments: Array<Segment> = [] let lastSpeaker = "" data.forEach((subtitle, count) => { const subtitleSegment = getSegmentFromSubtitle(subtitle) if (subtitleSegment !== undefined) { lastSpeaker = subtitleSegment.speaker ? subtitleSegment.speaker : lastSpeaker subtitleSegment.speaker = lastSpeaker outSegments = addSegment(subtitleSegment, outSegments) } else { throw new TypeError(`Unable to parse segment for item ${count}`) } }) return outSegments } /** * Parse JSON data where top level item is an Array * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When JSON data does not match one of the valid formats */ const parseListJSON = (data: Array<unknown>): Array<Segment> => { let outSegments: Array<Segment> = [] if (data.length === 0) { return outSegments } const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment) if (subtitleSegment !== undefined) { outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>) } else { throw new TypeError(`Unknown JSON list transcript format`) } return outSegments } /** * Parse JSON data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid JSON format */ export const parseJSON = (data: string): Array<Segment> => { const dataTrimmed = data.trim() let outSegments: Array<Segment> = [] if (!isJSON(dataTrimmed)) { throw new TypeError(`Data is not valid JSON format`) } let parsed: object | Array<unknown> try { parsed = JSON.parse(data) } catch (e) { throw new TypeError(`Data is not valid JSON: ${e}`) } if (parsed.constructor === Object) { outSegments = parseDictJSON(parsed) } else if (parsed.constructor === Array) { outSegments = parseListJSON(parsed) } return outSegments }
src/formats/json.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/index.ts", "retrieved_chunk": "}\n/**\n * Convert the data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @param transcriptFormat The format of the data.\n * @returns An Array of Segment objects from the parsed data\n * @throws {TypeError} When `transcriptFormat` is unknown\n */\nexport const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => {", "score": 0.8999952077865601 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " * Parse HTML data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid HTML format\n */\nexport const parseHTML = (data: string): Array<Segment> => {\n const dataTrimmed = data.trim()\n if (!isHTML(dataTrimmed)) {\n throw new TypeError(`Data is not valid HTML format`)", "score": 0.89971923828125 }, { "filename": "src/formats/vtt.ts", "retrieved_chunk": " * @returns True: data is valid VTT transcript format\n */\nexport const isVTT = (data: string): boolean => {\n return data.startsWith(\"WEBVTT\")\n}\n/**\n * Parse VTT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data", "score": 0.8867429494857788 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " return false\n }\n}\n/**\n * Parse SRT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid SRT format\n */", "score": 0.8760507106781006 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)", "score": 0.8752103447914124 } ]
typescript
outSegments = addSegment( {
import { Options } from "./options" import { TimestampFormatter } from "./timestamp" import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types" /** * Regular Expression for detecting punctuation that should not be prefixed with a space */ const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/ /** * Regular Expression for detecting space characters at the end of a string */ const PATTERN_TRAILING_SPACE = /^ *$/ /** * Remove any trailing space characters from data * * @param data text to trim * @returns text with any trailing space character removed */ const trimEndSpace = (data: string): string => { return data.replace(PATTERN_TRAILING_SPACE, "") } /** * Append `addition` to `body` with the character(s) specified. * * If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data. * * @param body Current body text * @param addition Additional text to add to `body` * @param separator Character(s) to use to separate data. If undefined, uses `\n`. * @returns Combined data */ const joinBody = (body: string, addition: string, separator: string = undefined): string => { if (body) { let separatorToUse = separator || "\n" if (PATTERN_PUNCTUATIONS.exec(addition)) { separatorToUse = "" } return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}` } return trimEndSpace(addition) } /** * Combine one or more {@link Segment} * * @param segments Array of Segment objects to combine * @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`. * @returns Combined segment where: * * - `startTime`: from first segment * - `startTimeFormatted`: from first segment * - `endTime`: from last segment * - `endTimeFormatted`: from last segment * - `speaker`: from first segment * - `body`: combination of all segments */ const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => { const newSegment = { ...segments[0] } segments.slice(1).forEach((segment) => { newSegment.endTime = segment.endTime newSegment.endTimeFormatted
= TimestampFormatter.format(segment.endTime) newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator) }) return newSegment }
/** * Type returned from combine functions */ type CombineResult = { /** * The updated segment with any changes applied */ segment: Segment /** * If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of * appending a new segment */ replace: boolean /** * Indicates if the combine rule was applied */ combined: boolean } /** * Checks if the new and prior segments have the same speaker. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker and combining body results in new body shorter than * max length * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH} * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSegments = ( newSegment: Segment, priorSegment: Segment, maxLength: number, lastSpeaker: string ): CombineResult => { if (priorSegment === undefined) { return { segment: newSegment, replace: false, combined: false, } } const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH if ( (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) && joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength ) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker, startTime and endTime. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with value of separator argument * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param separator string to use to combine body values. If undefined, uses "\n" * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineEqualTimes = ( newSegment: Segment, priorSegment: Segment, separator: string, lastSpeaker: string ): CombineResult => { const combineEqualTimesSeparator = separator || "\n" if ( newSegment.startTime === priorSegment.startTime && newSegment.endTime === priorSegment.endTime && (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) ) { return { segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from newSegment if different from priorSegment else undefined * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (priorSegment === undefined) { if (newSegment.speaker === lastSpeaker) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } if (newSegment.speaker === undefined) { return result } if ( newSegment.speaker === "" || newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker ) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } /** * Determine how {@link Options.speakerChange is applied based an past options being applied} * * @param currentResult current result object from any prior options * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const applyOptionsAndDoSpeakerChange = ( currentResult: CombineResult, priorSegment: Segment, lastSpeaker: string ): CombineResult => { const { combineSegments, combineEqualTimes } = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else if (combineEqualTimes) { if (result.combined && result.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } if (result) { result = { segment: result.segment, replace: currentResult.replace || result.replace, combined: currentResult.combined || result.combined, } } return result } /** * Apply convert rules when no prior segment exits. * * NOTE: not all rules applicable when no prior segment * * @param newSegment segment before any rules options to it * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => { const { speakerChange } = Options let result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (speakerChange) { result = doSpeakerChange(result.segment, undefined, lastSpeaker) } return result } /** * Apply convert rules when prior segment exits. * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const { combineEqualTimes, combineEqualTimesSeparator, combineSegments, combineSegmentsLength, combineSpeaker, speakerChange, } = Options let result: CombineResult = { segment: { ...newSegment }, replace: false, combined: false, } let combinedSpeaker = false if (combineSpeaker) { result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker) combinedSpeaker = result.combined } if (!combinedSpeaker && combineEqualTimes) { result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker) } if (!combinedSpeaker && combineSegments) { let combineResult if (combineEqualTimes && result.combined) { combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker) } else { combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker) } if (combineResult) { result = { segment: combineResult.segment, replace: result.replace || combineResult.replace, combined: result.combined || combineResult.combined, } } } if (speakerChange) { result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker) } return result } /** * Apply any options to the current segment * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => { if (!Options.optionsSet()) { return { segment: newSegment, replace: false, combined: false, } } let result: CombineResult // if no prior segment, limited additional checking if (priorSegment === undefined) { result = doCombineNoPrior(newSegment, lastSpeaker) } else { result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker) } return result } /** * Get the last speaker name from the previously parsed segments * * @param priorSegment prior parsed segment * @param priorSegments array of all previous segments * @returns the name of the last speaker */ const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => { let lastSpeaker if (priorSegment) { lastSpeaker = priorSegment.speaker } if (lastSpeaker === undefined && priorSegments.length > 0) { lastSpeaker = priorSegments[0].speaker for (let i = priorSegments.length - 1; i > 0; i--) { if (priorSegments[i].speaker !== undefined) { lastSpeaker = priorSegments[i].speaker break } } } return lastSpeaker } /** * Helper for adding segment to or updating last segment in array of segments * * @param newSegment segment to add or replace * @param priorSegments array of all previous segments * @returns updated array of segments with new segment added or last segment updated (per options) */ export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => { const { speakerChange } = Options const outSegments = priorSegments || [] const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined // don't worry about identifying the last speaker if speaker is not being removed by speakerChange let lastSpeaker: string if (speakerChange) { lastSpeaker = getLastSpeaker(priorSegment, outSegments) } const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker) if (newSegmentInfo.replace && outSegments.length > 0) { outSegments[outSegments.length - 1] = newSegmentInfo.segment } else { outSegments.push(newSegmentInfo.segment) } return outSegments }
src/segments.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/json.ts", "retrieved_chunk": "const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => {\n let outSegments: Array<Segment> = []\n data.segments.forEach((segment) => {\n outSegments = addSegment(\n {\n startTime: segment.startTime,\n startTimeFormatted: TimestampFormatter.format(segment.startTime),\n endTime: segment.endTime,\n endTimeFormatted: TimestampFormatter.format(segment.endTime),\n speaker: segment.speaker,", "score": 0.8698302507400513 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " const timestampParts = timestampLine.split(\"-->\")\n if (timestampParts.length !== 2) {\n throw new Error(`SRT timestamp line contains more than 2 --> separators`)\n }\n const startTime = parseTimestamp(timestampParts[0].trim())\n const endTime = parseTimestamp(timestampParts[1].trim())\n let bodyLines = lines.slice(2)\n const emptyLineIndex = bodyLines.findIndex((v) => v.trim() === \"\")\n if (emptyLineIndex > 0) {\n bodyLines = bodyLines.slice(0, emptyLineIndex)", "score": 0.8059980869293213 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === \"\").length !== 3\n ) {\n // time is required\n if (segmentPart.time === \"\") {\n console.warn(`Segment ${count} does not contain time information, ignoring`)\n } else {\n const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker)\n lastSpeaker = segment.speaker\n // update endTime of previous Segment\n const totalSegments = outSegments.length", "score": 0.8055864572525024 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {\n const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker\n const startTime = parseTimestamp(segmentPart.time)\n return {\n startTime,\n startTimeFormatted: TimestampFormatter.format(startTime),\n endTime: 0,", "score": 0.7897049188613892 }, { "filename": "src/formats/json.ts", "retrieved_chunk": " startTimeFormatted: TimestampFormatter.format(startTime),\n endTime,\n endTimeFormatted: TimestampFormatter.format(endTime),\n speaker,\n body: message,\n }\n if (Number.isNaN(segment.startTime)) {\n console.warn(`Computed start time is NaN: ${segment.startTime}`)\n return undefined\n }", "score": 0.7893865704536438 } ]
typescript
= TimestampFormatter.format(segment.endTime) newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator) }) return newSegment }
import { Options } from "./options" import { TimestampFormatter } from "./timestamp" import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types" /** * Regular Expression for detecting punctuation that should not be prefixed with a space */ const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/ /** * Regular Expression for detecting space characters at the end of a string */ const PATTERN_TRAILING_SPACE = /^ *$/ /** * Remove any trailing space characters from data * * @param data text to trim * @returns text with any trailing space character removed */ const trimEndSpace = (data: string): string => { return data.replace(PATTERN_TRAILING_SPACE, "") } /** * Append `addition` to `body` with the character(s) specified. * * If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data. * * @param body Current body text * @param addition Additional text to add to `body` * @param separator Character(s) to use to separate data. If undefined, uses `\n`. * @returns Combined data */ const joinBody = (body: string, addition: string, separator: string = undefined): string => { if (body) { let separatorToUse = separator || "\n" if (PATTERN_PUNCTUATIONS.exec(addition)) { separatorToUse = "" } return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}` } return trimEndSpace(addition) } /** * Combine one or more {@link Segment} * * @param segments Array of Segment objects to combine * @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`. * @returns Combined segment where: * * - `startTime`: from first segment * - `startTimeFormatted`: from first segment * - `endTime`: from last segment * - `endTimeFormatted`: from last segment * - `speaker`: from first segment * - `body`: combination of all segments */ const joinSegments = (segments:
Array<Segment>, bodySeparator: string = undefined): Segment => {
const newSegment = { ...segments[0] } segments.slice(1).forEach((segment) => { newSegment.endTime = segment.endTime newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime) newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator) }) return newSegment } /** * Type returned from combine functions */ type CombineResult = { /** * The updated segment with any changes applied */ segment: Segment /** * If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of * appending a new segment */ replace: boolean /** * Indicates if the combine rule was applied */ combined: boolean } /** * Checks if the new and prior segments have the same speaker. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker and combining body results in new body shorter than * max length * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH} * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSegments = ( newSegment: Segment, priorSegment: Segment, maxLength: number, lastSpeaker: string ): CombineResult => { if (priorSegment === undefined) { return { segment: newSegment, replace: false, combined: false, } } const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH if ( (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) && joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength ) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker, startTime and endTime. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with value of separator argument * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param separator string to use to combine body values. If undefined, uses "\n" * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineEqualTimes = ( newSegment: Segment, priorSegment: Segment, separator: string, lastSpeaker: string ): CombineResult => { const combineEqualTimesSeparator = separator || "\n" if ( newSegment.startTime === priorSegment.startTime && newSegment.endTime === priorSegment.endTime && (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) ) { return { segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from newSegment if different from priorSegment else undefined * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (priorSegment === undefined) { if (newSegment.speaker === lastSpeaker) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } if (newSegment.speaker === undefined) { return result } if ( newSegment.speaker === "" || newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker ) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } /** * Determine how {@link Options.speakerChange is applied based an past options being applied} * * @param currentResult current result object from any prior options * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const applyOptionsAndDoSpeakerChange = ( currentResult: CombineResult, priorSegment: Segment, lastSpeaker: string ): CombineResult => { const { combineSegments, combineEqualTimes } = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else if (combineEqualTimes) { if (result.combined && result.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } if (result) { result = { segment: result.segment, replace: currentResult.replace || result.replace, combined: currentResult.combined || result.combined, } } return result } /** * Apply convert rules when no prior segment exits. * * NOTE: not all rules applicable when no prior segment * * @param newSegment segment before any rules options to it * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => { const { speakerChange } = Options let result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (speakerChange) { result = doSpeakerChange(result.segment, undefined, lastSpeaker) } return result } /** * Apply convert rules when prior segment exits. * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const { combineEqualTimes, combineEqualTimesSeparator, combineSegments, combineSegmentsLength, combineSpeaker, speakerChange, } = Options let result: CombineResult = { segment: { ...newSegment }, replace: false, combined: false, } let combinedSpeaker = false if (combineSpeaker) { result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker) combinedSpeaker = result.combined } if (!combinedSpeaker && combineEqualTimes) { result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker) } if (!combinedSpeaker && combineSegments) { let combineResult if (combineEqualTimes && result.combined) { combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker) } else { combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker) } if (combineResult) { result = { segment: combineResult.segment, replace: result.replace || combineResult.replace, combined: result.combined || combineResult.combined, } } } if (speakerChange) { result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker) } return result } /** * Apply any options to the current segment * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => { if (!Options.optionsSet()) { return { segment: newSegment, replace: false, combined: false, } } let result: CombineResult // if no prior segment, limited additional checking if (priorSegment === undefined) { result = doCombineNoPrior(newSegment, lastSpeaker) } else { result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker) } return result } /** * Get the last speaker name from the previously parsed segments * * @param priorSegment prior parsed segment * @param priorSegments array of all previous segments * @returns the name of the last speaker */ const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => { let lastSpeaker if (priorSegment) { lastSpeaker = priorSegment.speaker } if (lastSpeaker === undefined && priorSegments.length > 0) { lastSpeaker = priorSegments[0].speaker for (let i = priorSegments.length - 1; i > 0; i--) { if (priorSegments[i].speaker !== undefined) { lastSpeaker = priorSegments[i].speaker break } } } return lastSpeaker } /** * Helper for adding segment to or updating last segment in array of segments * * @param newSegment segment to add or replace * @param priorSegments array of all previous segments * @returns updated array of segments with new segment added or last segment updated (per options) */ export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => { const { speakerChange } = Options const outSegments = priorSegments || [] const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined // don't worry about identifying the last speaker if speaker is not being removed by speakerChange let lastSpeaker: string if (speakerChange) { lastSpeaker = getLastSpeaker(priorSegment, outSegments) } const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker) if (newSegmentInfo.replace && outSegments.length > 0) { outSegments[outSegments.length - 1] = newSegmentInfo.segment } else { outSegments.push(newSegmentInfo.segment) } return outSegments }
src/segments.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/json.ts", "retrieved_chunk": " */\n startTime: number\n /**\n * Time (in seconds) when segment ends\n */\n endTime: number\n /**\n * Name of speaker for `body`\n */\n speaker?: string", "score": 0.8906786441802979 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)", "score": 0.8835345506668091 }, { "filename": "src/types.ts", "retrieved_chunk": " endTime: number\n /**\n * Time when segment ends formatted as a string in the format HH:mm:SS.fff\n */\n endTimeFormatted: string\n /**\n * Name of speaker for `body`\n */\n speaker?: string\n /**", "score": 0.8701815009117126 }, { "filename": "src/types.ts", "retrieved_chunk": " * Time (in seconds) when segment starts\n */\n startTime: number\n /**\n * Time when segment starts formatted as a string in the format HH:mm:SS.fff\n */\n startTimeFormatted: string\n /**\n * Time (in seconds) when segment ends\n */", "score": 0.8689671754837036 }, { "filename": "src/options.ts", "retrieved_chunk": " */\n combineEqualTimesSeparator?: string\n /**\n * Combine segments where speaker is the same and concatenated `body` fits in the {@link combineSegmentsLength}\n *\n * Can be used with {@link combineEqualTimes}. The {@link combineSegments} rule is applied first.\n *\n * Can be used with {@link speakerChange}. The {@link speakerChange} rule is applied last.\n *\n * Cannot be used with {@link combineSpeaker}", "score": 0.8615144491195679 } ]
typescript
Array<Segment>, bodySeparator: string = undefined): Segment => {
import { addSegment } from "../segments" import { parseSpeaker } from "../speaker" import { TimestampFormatter } from "../timestamp" import { Segment } from "../types" /** * Define a segment/cue used in the JSONTranscript format */ export type JSONSegment = { /** * Time (in seconds) when segment starts */ startTime: number /** * Time (in seconds) when segment ends */ endTime: number /** * Name of speaker for `body` */ speaker?: string /** * Text of transcript for segment */ body: string } /** * Define the JSON transcript format */ export type JSONTranscript = { /** * Version of file format */ version: string /** * Segment data */ segments: Array<JSONSegment> } /** * Define the JSON transcript Segment format */ export type SubtitleSegment = { /** * Time (in milliseconds) when segment starts */ start: number /** * Time (in milliseconds) when segment ends */ end: number /** * Text of transcript for segment */ text: string } /** * Determines if the value of data is a valid JSON transcript format * * @param data The transcript data * @returns True: data is valid JSON transcript format */ export const isJSON = (data: string): boolean => { return (data.startsWith("{") && data.endsWith("}")) || (data.startsWith("[") && data.endsWith("]")) } /** * Parse JSON data where segments are in the `segments` Array and in the {@link JSONSegment} format * * @param data Parsed JSON data * @returns An array of Segments from the parsed data */ const parseDictSegmentsJSON = (data
: JSONTranscript): Array<Segment> => {
let outSegments: Array<Segment> = [] data.segments.forEach((segment) => { outSegments = addSegment( { startTime: segment.startTime, startTimeFormatted: TimestampFormatter.format(segment.startTime), endTime: segment.endTime, endTimeFormatted: TimestampFormatter.format(segment.endTime), speaker: segment.speaker, body: segment.body, }, outSegments ) }) return outSegments } /** * Parse JSON data where top level item is a dict/object * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When JSON data does not match one of the valid formats */ const parseDictJSON = (data: object): Array<Segment> => { let outSegments: Array<Segment> = [] if (Object.keys(data).length === 0) { return outSegments } if ("segments" in data) { outSegments = parseDictSegmentsJSON(data as JSONTranscript) } else { throw new TypeError(`Unknown JSON dict transcript format`) } return outSegments } /** * Convert {@link SubtitleSegment} to the {@link Segment} format used here * * @param data Segment parsed from JSON data * @returns Segment representing `data`. * Returns {@link undefined} when data does not match {@link SubtitleSegment} format. */ const getSegmentFromSubtitle = (data: SubtitleSegment): Segment => { if ("start" in data && "end" in data && "text" in data) { const { speaker, message } = parseSpeaker(data.text) const startTime = data.start / 1000 const endTime = data.end / 1000 const segment: Segment = { startTime, startTimeFormatted: TimestampFormatter.format(startTime), endTime, endTimeFormatted: TimestampFormatter.format(endTime), speaker, body: message, } if (Number.isNaN(segment.startTime)) { console.warn(`Computed start time is NaN: ${segment.startTime}`) return undefined } if (Number.isNaN(segment.endTime)) { console.warn(`Computed end time is NaN: ${segment.endTime}`) return undefined } return segment } return undefined } /** * Parse JSON data where items in data are in the {@link SubtitleSegment} format * * @param data Parsed JSON data * @returns An array of Segments from the parsed data * @throws {TypeError} When item in `data` does not match the {@link SubtitleSegment} format */ const parseListJSONSubtitle = (data: Array<SubtitleSegment>): Array<Segment> => { let outSegments: Array<Segment> = [] let lastSpeaker = "" data.forEach((subtitle, count) => { const subtitleSegment = getSegmentFromSubtitle(subtitle) if (subtitleSegment !== undefined) { lastSpeaker = subtitleSegment.speaker ? subtitleSegment.speaker : lastSpeaker subtitleSegment.speaker = lastSpeaker outSegments = addSegment(subtitleSegment, outSegments) } else { throw new TypeError(`Unable to parse segment for item ${count}`) } }) return outSegments } /** * Parse JSON data where top level item is an Array * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When JSON data does not match one of the valid formats */ const parseListJSON = (data: Array<unknown>): Array<Segment> => { let outSegments: Array<Segment> = [] if (data.length === 0) { return outSegments } const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment) if (subtitleSegment !== undefined) { outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>) } else { throw new TypeError(`Unknown JSON list transcript format`) } return outSegments } /** * Parse JSON data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid JSON format */ export const parseJSON = (data: string): Array<Segment> => { const dataTrimmed = data.trim() let outSegments: Array<Segment> = [] if (!isJSON(dataTrimmed)) { throw new TypeError(`Data is not valid JSON format`) } let parsed: object | Array<unknown> try { parsed = JSON.parse(data) } catch (e) { throw new TypeError(`Data is not valid JSON: ${e}`) } if (parsed.constructor === Object) { outSegments = parseDictJSON(parsed) } else if (parsed.constructor === Array) { outSegments = parseListJSON(parsed) } return outSegments }
src/formats/json.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/html.ts", "retrieved_chunk": " * Parse HTML data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid HTML format\n */\nexport const parseHTML = (data: string): Array<Segment> => {\n const dataTrimmed = data.trim()\n if (!isHTML(dataTrimmed)) {\n throw new TypeError(`Data is not valid HTML format`)", "score": 0.8575702905654907 }, { "filename": "src/formats/vtt.ts", "retrieved_chunk": " * @returns True: data is valid VTT transcript format\n */\nexport const isVTT = (data: string): boolean => {\n return data.startsWith(\"WEBVTT\")\n}\n/**\n * Parse VTT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data", "score": 0.8549968600273132 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " endTimeFormatted: TimestampFormatter.format(0),\n speaker: calculatedSpeaker.replace(\":\", \"\").trimEnd(),\n body: segmentPart.text,\n }\n}\n/**\n * Parse HTML data and create {@link Segment} for each segment data found in data\n *\n * @param elements HTML elements containing transcript data\n * @returns Segments created from HTML data", "score": 0.8372952342033386 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " return false\n }\n}\n/**\n * Parse SRT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid SRT format\n */", "score": 0.8357065320014954 }, { "filename": "src/index.ts", "retrieved_chunk": "}\n/**\n * Convert the data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @param transcriptFormat The format of the data.\n * @returns An Array of Segment objects from the parsed data\n * @throws {TypeError} When `transcriptFormat` is unknown\n */\nexport const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => {", "score": 0.8321675658226013 } ]
typescript
: JSONTranscript): Array<Segment> => {
import { isHTML, parseHTML } from "./formats/html" import { isJSON, parseJSON } from "./formats/json" import { isSRT, parseSRT } from "./formats/srt" import { isVTT, parseVTT } from "./formats/vtt" import { Segment, TranscriptFormat } from "./types" export { Segment, TranscriptFormat } from "./types" export { TimestampFormatter, FormatterCallback } from "./timestamp" export { Options, IOptions } from "./options" /** * Determines the format of transcript by inspecting the data * * @param data The transcript data * @returns The determined transcript format * @throws {TypeError} Cannot determine format of data or error parsing data */ export const determineFormat = (data: string): TranscriptFormat => { const normalizedData = data.trim() if (isVTT(normalizedData)) { return TranscriptFormat.VTT } if (isJSON(normalizedData)) { return TranscriptFormat.JSON } if (isHTML(normalizedData)) { return TranscriptFormat.HTML } if (isSRT(normalizedData)) { return TranscriptFormat.SRT } throw new TypeError(`Cannot determine format for data`) } /** * Convert the data to an Array of {@link Segment} * * @param data The transcript data * @param transcriptFormat The format of the data. * @returns An Array of Segment objects from the parsed data * @throws {TypeError} When `transcriptFormat` is unknown */
export const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => {
const format = transcriptFormat ?? determineFormat(data) const normalizedData = data.trimStart() let outSegments: Array<Segment> = [] switch (format) { case TranscriptFormat.HTML: outSegments = parseHTML(normalizedData) break case TranscriptFormat.JSON: outSegments = parseJSON(normalizedData) break case TranscriptFormat.SRT: outSegments = parseSRT(normalizedData) break case TranscriptFormat.VTT: outSegments = parseVTT(normalizedData) break default: throw new TypeError(`Unknown transcript format: ${format}`) } return outSegments }
src/index.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/json.ts", "retrieved_chunk": "/**\n * Parse JSON data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid JSON format\n */\nexport const parseJSON = (data: string): Array<Segment> => {\n const dataTrimmed = data.trim()\n let outSegments: Array<Segment> = []", "score": 0.9519936442375183 }, { "filename": "src/formats/json.ts", "retrieved_chunk": "/**\n * Parse JSON data where top level item is an Array\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When JSON data does not match one of the valid formats\n */\nconst parseListJSON = (data: Array<unknown>): Array<Segment> => {\n let outSegments: Array<Segment> = []\n if (data.length === 0) {", "score": 0.9382960796356201 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " return false\n }\n}\n/**\n * Parse SRT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid SRT format\n */", "score": 0.9308939576148987 }, { "filename": "src/formats/vtt.ts", "retrieved_chunk": " * @returns True: data is valid VTT transcript format\n */\nexport const isVTT = (data: string): boolean => {\n return data.startsWith(\"WEBVTT\")\n}\n/**\n * Parse VTT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data", "score": 0.925401508808136 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " * Parse HTML data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid HTML format\n */\nexport const parseHTML = (data: string): Array<Segment> => {\n const dataTrimmed = data.trim()\n if (!isHTML(dataTrimmed)) {\n throw new TypeError(`Data is not valid HTML format`)", "score": 0.92527836561203 } ]
typescript
export const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => {
import { ContractMethod } from '../schema/application' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer' import { isSafeVariableIdentifier, makeSafeMethodIdentifier, makeSafePropertyIdentifier } from '../util/sanitization' import * as algokit from '@algorandfoundation/algokit-utils' import { GeneratorContext } from './generator-context' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { getCreateOnCompleteOptions } from './deploy-types' export function* callFactory(ctx: GeneratorContext): DocumentParts { yield* jsDoc('Exposes methods for constructing all available smart contract calls') yield `export abstract class ${ctx.name}CallFactory {` yield IncIndent yield* opMethods(ctx) for (const method of ctx.app.contract.methods) { yield* callFactoryMethod(ctx, method) } yield DecIndent yield '}' } function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig } = ctx yield* operationMethod( ctx, `Constructs a create call for the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true, ) yield* operationMethod( ctx, `Constructs an update call for the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Constructs a delete call for the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod(ctx, `Constructs an opt in call for the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn') yield* operationMethod( ctx, `Constructs a close out call for the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} call factories`) yield `static get ${verb}() {` yield IncIndent yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call`, params: { params: `Any parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: true, name: 'bare', paramTypes: `BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs${ includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`, }) } else { const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)! const uniqueName = methodSignatureToUniqueName[methodSig] yield* jsDoc({ description: `${description} using the ${methodSig} ABI method`, params: { args: `Any args for the contract call`, params: `Any additional parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: true, name:
makeSafeMethodIdentifier(uniqueName), signature: methodSig, args: method.args, paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${
onComplete?.type ? ` & ${onComplete.type}` : '' }${onComplete?.isOptional !== false ? ' = {}' : ''}`, }) } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) { const methodSignature = algokit.getABIMethodSignature(method) if (!callConfig.callMethods.includes(methodSignature)) return yield* jsDoc({ description: `Constructs a no op call for the ${methodSignature} ABI method`, abiDescription: method.desc, params: { args: `Any args for the contract call`, params: `Any additional parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: false, name: makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]), signature: methodSignature, args: method.args, paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs', }) } function* factoryMethod({ isNested, name, signature, args, paramTypes, }: | { isNested: boolean name?: string signature?: undefined args?: undefined paramTypes: string } | { isNested: boolean name?: string signature: string args: Array<{ name: string }> paramTypes: string }) { yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {` yield IncIndent yield `return {` yield IncIndent if (signature) { yield `method: '${signature}' as const,` yield `methodArgs: Array.isArray(args) ? args : [${args .map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`)) .join(', ')}],` } else { yield `method: undefined,` yield `methodArgs: undefined,` } yield '...params,' yield DecIndent yield '}' yield DecIndent yield `}${isNested ? ',' : ''}` }
src/client/call-factory.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " params: {\n args: `The arguments for the bare call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${\n includeCompilation ? '& AppClientCompilationParams ' : ''\n }& CoreAppCallArgs${onComplete?.type ? ` & ${onComplete.type}` : ''}): ${name}Composer<[...TReturns, undefined]>`\n } else {\n const uniqueName = methodSignatureToUniqueName[methodSig]", "score": 0.8674784898757935 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " params: {\n typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',\n returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',\n },\n returns: 'The result of the smart contract call',\n })\n yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`\n yield IncIndent\n yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`\n yield DecIndentAndCloseBlock", "score": 0.8596199750900269 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method.`,\n params: {\n args: `The arguments for the smart contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params${\n onComplete?.isOptional !== false ? '?' : ''", "score": 0.8536465167999268 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, undefined]>`\n yield NewLine\n}\nfunction* callComposerTypeNoops({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config", "score": 0.8527089357376099 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " yield* jsDoc({\n description: `Idempotently deploys the ${app.contract.name} smart contract.`,\n params: {\n params: 'The arguments for the contract calls and any additional parameters for the call',\n },\n returns: 'The deployment result',\n })\n yield `public deploy(params: ${name}DeployArgs & AppClientDeployCoreParams = {}): ReturnType<ApplicationClient['deploy']> {`\n yield IncIndent\n if (callConfig.createMethods.length) yield `const createArgs = params.createCall?.(${name}CallFactory.create)`", "score": 0.8447268009185791 } ]
typescript
makeSafeMethodIdentifier(uniqueName), signature: methodSig, args: method.args, paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${
import { addSegment } from "../segments" import { parseSpeaker } from "../speaker" import { parseTimestamp, TimestampFormatter } from "../timestamp" import { PATTERN_LINE_SEPARATOR, Segment } from "../types" /** * Define a segment/cue parsed from SRT file */ export type SRTSegment = { /** * Cue number */ index: number /** * Time (in seconds) when segment starts */ startTime: number /** * Time (in seconds) when segment ends */ endTime: number /** * Name of speaker for `body` */ speaker: string /** * Text of transcript for segment */ body: string } /** * Parse lines looking for data to be SRT format * * @param lines Lines containing SRT data * @returns Parsed segment * @throws {Error} When no non-empty strings in `lines` * @throws {Error} When the minimum required number of lines is not received * @throws {Error} When segment lines does not start with a number * @throws {Error} When second segment line does not follow the timestamp format */ export const parseSRTSegment = (lines: Array<string>): SRTSegment => { do { if (lines.length === 0) { throw new Error("SRT segment lines empty") } else if (lines[0].trim() === "") { lines.shift() } else { break } } while (lines.length > 0) if (lines.length < 3) { throw new Error(`SRT requires at least 3 lines, ${lines.length} received`) } const index = parseInt(lines[0], 10) if (!index) { throw new Error(`First line of SRT segment is not a number`) } const timestampLine = lines[1] if (!timestampLine.includes("-->")) { throw new Error(`SRT timestamp line does not include --> separator`) } const timestampParts = timestampLine.split("-->") if (timestampParts.length !== 2) { throw new Error(`SRT timestamp line contains more than 2 --> separators`) } const startTime = parseTimestamp(timestampParts[0].trim()) const endTime = parseTimestamp(timestampParts[1].trim()) let bodyLines = lines.slice(2) const emptyLineIndex = bodyLines.findIndex((v) => v.trim() === "") if (emptyLineIndex > 0) { bodyLines = bodyLines.slice(0, emptyLineIndex) } const { speaker, message } = parseSpeaker(bodyLines.shift()) bodyLines = [message].concat(bodyLines) return { startTime, endTime, speaker, body: bodyLines.join("\n"), index, } } /** * Create Segment from lines containing an SRT segment/cue * * @param segmentLines Lines containing SRT data * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines` * @returns Created segment */ const createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => { const srtSegment = parseSRTSegment(segmentLines) const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker return { startTime: srtSegment.startTime, startTimeFormatted: TimestampFormatter.format(srtSegment.startTime), endTime: srtSegment.endTime, endTimeFormatted: TimestampFormatter.format(srtSegment.endTime), speaker: calculatedSpeaker, body: srtSegment.body, } } /** * Determines if the value of data is a valid SRT transcript format * * @param data The transcript data * @returns True: data is valid SRT transcript format */ export const isSRT = (data: string): boolean => { try { return parseSRTSegment(
data.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined } catch (e) {
return false } } /** * Parse SRT data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid SRT format */ export const parseSRT = (data: string): Array<Segment> => { if (!isSRT(data)) { throw new TypeError(`Data is not valid SRT format`) } let outSegments: Array<Segment> = [] let lastSpeaker = "" let segmentLines = [] data.split(PATTERN_LINE_SEPARATOR).forEach((line, count) => { // separator line found, handle previous data if (line.trim() === "") { // handle consecutive multiple blank lines if (segmentLines.length !== 0) { try { outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments) lastSpeaker = outSegments[outSegments.length - 1].speaker } catch (e) { console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`) console.error(segmentLines) } } segmentLines = [] // clear buffer } else { segmentLines.push(line) } }) // handle data when trailing line not included if (segmentLines.length !== 0) { try { outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments) lastSpeaker = outSegments[outSegments.length - 1].speaker } catch (e) { console.error(`Error parsing final SRT segment lines: ${e}`) console.error(segmentLines) } } return outSegments }
src/formats/srt.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/vtt.ts", "retrieved_chunk": " * @returns True: data is valid VTT transcript format\n */\nexport const isVTT = (data: string): boolean => {\n return data.startsWith(\"WEBVTT\")\n}\n/**\n * Parse VTT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data", "score": 0.9339286088943481 }, { "filename": "src/formats/html.ts", "retrieved_chunk": "}\n/**\n * Determines if the value of data is a valid HTML transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid HTML transcript format\n */\nexport const isHTML = (data: string): boolean => {\n return (\n data.startsWith(\"<!--\") ||", "score": 0.9193258285522461 }, { "filename": "src/index.ts", "retrieved_chunk": " *\n * @param data The transcript data\n * @returns The determined transcript format\n * @throws {TypeError} Cannot determine format of data or error parsing data\n */\nexport const determineFormat = (data: string): TranscriptFormat => {\n const normalizedData = data.trim()\n if (isVTT(normalizedData)) {\n return TranscriptFormat.VTT\n }", "score": 0.9063123464584351 }, { "filename": "src/formats/json.ts", "retrieved_chunk": "/**\n * Parse JSON data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid JSON format\n */\nexport const parseJSON = (data: string): Array<Segment> => {\n const dataTrimmed = data.trim()\n let outSegments: Array<Segment> = []", "score": 0.9000354409217834 }, { "filename": "src/formats/json.ts", "retrieved_chunk": " /**\n * Text of transcript for segment\n */\n text: string\n}\n/**\n * Determines if the value of data is a valid JSON transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid JSON transcript format", "score": 0.8974952697753906 } ]
typescript
data.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined } catch (e) {
import { isHTML, parseHTML } from "./formats/html" import { isJSON, parseJSON } from "./formats/json" import { isSRT, parseSRT } from "./formats/srt" import { isVTT, parseVTT } from "./formats/vtt" import { Segment, TranscriptFormat } from "./types" export { Segment, TranscriptFormat } from "./types" export { TimestampFormatter, FormatterCallback } from "./timestamp" export { Options, IOptions } from "./options" /** * Determines the format of transcript by inspecting the data * * @param data The transcript data * @returns The determined transcript format * @throws {TypeError} Cannot determine format of data or error parsing data */ export const determineFormat = (data: string): TranscriptFormat => { const normalizedData = data.trim() if (isVTT(normalizedData)) { return TranscriptFormat.VTT } if (isJSON(normalizedData)) { return TranscriptFormat.JSON } if (isHTML(normalizedData)) { return TranscriptFormat.HTML } if (isSRT(normalizedData)) { return TranscriptFormat.SRT } throw new TypeError(`Cannot determine format for data`) } /** * Convert the data to an Array of {@link Segment} * * @param data The transcript data * @param transcriptFormat The format of the data. * @returns An Array of Segment objects from the parsed data * @throws {TypeError} When `transcriptFormat` is unknown */ export const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => { const format = transcriptFormat ?? determineFormat(data) const normalizedData = data.trimStart() let outSegments: Array<Segment> = [] switch (format) { case TranscriptFormat.HTML: outSegments = parseHTML(normalizedData) break case TranscriptFormat.JSON: outSegments = parseJSON(normalizedData) break case TranscriptFormat.SRT: outSegments = parseSRT(normalizedData) break case TranscriptFormat.VTT:
outSegments = parseVTT(normalizedData) break default: throw new TypeError(`Unknown transcript format: ${format}`) }
return outSegments }
src/index.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/json.ts", "retrieved_chunk": " return outSegments\n }\n const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment)\n if (subtitleSegment !== undefined) {\n outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>)\n } else {\n throw new TypeError(`Unknown JSON list transcript format`)\n }\n return outSegments\n}", "score": 0.8299300670623779 }, { "filename": "src/formats/json.ts", "retrieved_chunk": " outSegments = parseDictSegmentsJSON(data as JSONTranscript)\n } else {\n throw new TypeError(`Unknown JSON dict transcript format`)\n }\n return outSegments\n}\n/**\n * Convert {@link SubtitleSegment} to the {@link Segment} format used here\n *\n * @param data Segment parsed from JSON data", "score": 0.8252943754196167 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": "/**\n * Determines if the value of data is a valid SRT transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid SRT transcript format\n */\nexport const isSRT = (data: string): boolean => {\n try {\n return parseSRTSegment(data.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined\n } catch (e) {", "score": 0.8094252347946167 }, { "filename": "src/formats/json.ts", "retrieved_chunk": " * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When JSON data does not match one of the valid formats\n */\nconst parseDictJSON = (data: object): Array<Segment> => {\n let outSegments: Array<Segment> = []\n if (Object.keys(data).length === 0) {\n return outSegments\n }\n if (\"segments\" in data) {", "score": 0.8070967197418213 }, { "filename": "src/formats/vtt.ts", "retrieved_chunk": " * @throws {TypeError} When `data` is not valid VTT format\n */\nexport const parseVTT = (data: string): Array<Segment> => {\n if (!isVTT(data)) {\n throw new TypeError(`Data is not valid VTT format`)\n }\n // format is similar enough to SRT to be parsed by the same parser\n // Remove WEBVTT header first\n return parseSRT(data.substring(WEBVTT_HEADER.length).trimStart())\n}", "score": 0.804999053478241 } ]
typescript
outSegments = parseVTT(normalizedData) break default: throw new TypeError(`Unknown transcript format: ${format}`) }
import { addSegment } from "../segments" import { parseSpeaker } from "../speaker" import { parseTimestamp, TimestampFormatter } from "../timestamp" import { PATTERN_LINE_SEPARATOR, Segment } from "../types" /** * Define a segment/cue parsed from SRT file */ export type SRTSegment = { /** * Cue number */ index: number /** * Time (in seconds) when segment starts */ startTime: number /** * Time (in seconds) when segment ends */ endTime: number /** * Name of speaker for `body` */ speaker: string /** * Text of transcript for segment */ body: string } /** * Parse lines looking for data to be SRT format * * @param lines Lines containing SRT data * @returns Parsed segment * @throws {Error} When no non-empty strings in `lines` * @throws {Error} When the minimum required number of lines is not received * @throws {Error} When segment lines does not start with a number * @throws {Error} When second segment line does not follow the timestamp format */ export const parseSRTSegment = (lines: Array<string>): SRTSegment => { do { if (lines.length === 0) { throw new Error("SRT segment lines empty") } else if (lines[0].trim() === "") { lines.shift() } else { break } } while (lines.length > 0) if (lines.length < 3) { throw new Error(`SRT requires at least 3 lines, ${lines.length} received`) } const index = parseInt(lines[0], 10) if (!index) { throw new Error(`First line of SRT segment is not a number`) } const timestampLine = lines[1] if (!timestampLine.includes("-->")) { throw new Error(`SRT timestamp line does not include --> separator`) } const timestampParts = timestampLine.split("-->") if (timestampParts.length !== 2) { throw new Error(`SRT timestamp line contains more than 2 --> separators`) } const startTime = parseTimestamp(timestampParts[0].trim()) const endTime = parseTimestamp(timestampParts[1].trim()) let bodyLines = lines.slice(2) const emptyLineIndex = bodyLines.findIndex((v) => v.trim() === "") if (emptyLineIndex > 0) { bodyLines = bodyLines.slice(0, emptyLineIndex) } const {
speaker, message } = parseSpeaker(bodyLines.shift()) bodyLines = [message].concat(bodyLines) return {
startTime, endTime, speaker, body: bodyLines.join("\n"), index, } } /** * Create Segment from lines containing an SRT segment/cue * * @param segmentLines Lines containing SRT data * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines` * @returns Created segment */ const createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => { const srtSegment = parseSRTSegment(segmentLines) const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker return { startTime: srtSegment.startTime, startTimeFormatted: TimestampFormatter.format(srtSegment.startTime), endTime: srtSegment.endTime, endTimeFormatted: TimestampFormatter.format(srtSegment.endTime), speaker: calculatedSpeaker, body: srtSegment.body, } } /** * Determines if the value of data is a valid SRT transcript format * * @param data The transcript data * @returns True: data is valid SRT transcript format */ export const isSRT = (data: string): boolean => { try { return parseSRTSegment(data.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined } catch (e) { return false } } /** * Parse SRT data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid SRT format */ export const parseSRT = (data: string): Array<Segment> => { if (!isSRT(data)) { throw new TypeError(`Data is not valid SRT format`) } let outSegments: Array<Segment> = [] let lastSpeaker = "" let segmentLines = [] data.split(PATTERN_LINE_SEPARATOR).forEach((line, count) => { // separator line found, handle previous data if (line.trim() === "") { // handle consecutive multiple blank lines if (segmentLines.length !== 0) { try { outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments) lastSpeaker = outSegments[outSegments.length - 1].speaker } catch (e) { console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`) console.error(segmentLines) } } segmentLines = [] // clear buffer } else { segmentLines.push(line) } }) // handle data when trailing line not included if (segmentLines.length !== 0) { try { outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments) lastSpeaker = outSegments[outSegments.length - 1].speaker } catch (e) { console.error(`Error parsing final SRT segment lines: ${e}`) console.error(segmentLines) } } return outSegments }
src/formats/srt.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/segments.ts", "retrieved_chunk": " * - `endTimeFormatted`: from last segment\n * - `speaker`: from first segment\n * - `body`: combination of all segments\n */\nconst joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {\n const newSegment = { ...segments[0] }\n segments.slice(1).forEach((segment) => {\n newSegment.endTime = segment.endTime\n newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)\n newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)", "score": 0.7983818054199219 }, { "filename": "src/speaker.ts", "retrieved_chunk": " * @returns The speaker (if found) and the remaining string\n */\nexport const parseSpeaker = (data: string): { speaker: string; message: string } => {\n let speaker = \"\"\n let message = data\n const speakerMatch = PATTERN_SPEAKER.exec(data)\n if (speakerMatch !== null) {\n speaker = speakerMatch.groups.speaker\n message = speakerMatch.groups.body\n }", "score": 0.7869088649749756 }, { "filename": "src/timestamp.ts", "retrieved_chunk": " }\n const match = PATTERN_TIMESTAMP.exec(value.trim())\n if (match === null) {\n throw new TypeError(`Not enough separator fields in timestamp string`)\n }\n const { time } = match.groups\n const splits = time.split(\":\")\n const splitLength = splits.length\n let timestamp = 0\n if (splitLength === 3) {", "score": 0.7797060012817383 }, { "filename": "src/segments.ts", "retrieved_chunk": "const joinBody = (body: string, addition: string, separator: string = undefined): string => {\n if (body) {\n let separatorToUse = separator || \"\\n\"\n if (PATTERN_PUNCTUATIONS.exec(addition)) {\n separatorToUse = \"\"\n }\n return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}`\n }\n return trimEndSpace(addition)\n}", "score": 0.7614209055900574 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === \"\").length !== 3\n ) {\n // time is required\n if (segmentPart.time === \"\") {\n console.warn(`Segment ${count} does not contain time information, ignoring`)\n } else {\n const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker)\n lastSpeaker = segment.speaker\n // update endTime of previous Segment\n const totalSegments = outSegments.length", "score": 0.754920244216919 } ]
typescript
speaker, message } = parseSpeaker(bodyLines.shift()) bodyLines = [message].concat(bodyLines) return {
import { Options } from "./options" import { TimestampFormatter } from "./timestamp" import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types" /** * Regular Expression for detecting punctuation that should not be prefixed with a space */ const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/ /** * Regular Expression for detecting space characters at the end of a string */ const PATTERN_TRAILING_SPACE = /^ *$/ /** * Remove any trailing space characters from data * * @param data text to trim * @returns text with any trailing space character removed */ const trimEndSpace = (data: string): string => { return data.replace(PATTERN_TRAILING_SPACE, "") } /** * Append `addition` to `body` with the character(s) specified. * * If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data. * * @param body Current body text * @param addition Additional text to add to `body` * @param separator Character(s) to use to separate data. If undefined, uses `\n`. * @returns Combined data */ const joinBody = (body: string, addition: string, separator: string = undefined): string => { if (body) { let separatorToUse = separator || "\n" if (PATTERN_PUNCTUATIONS.exec(addition)) { separatorToUse = "" } return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}` } return trimEndSpace(addition) } /** * Combine one or more {@link Segment} * * @param segments Array of Segment objects to combine * @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`. * @returns Combined segment where: * * - `startTime`: from first segment * - `startTimeFormatted`: from first segment * - `endTime`: from last segment * - `endTimeFormatted`: from last segment * - `speaker`: from first segment * - `body`: combination of all segments */ const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => { const newSegment = { ...segments[0] } segments.slice(1).forEach((segment) => { newSegment.endTime = segment.endTime newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime) newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator) }) return newSegment } /** * Type returned from combine functions */ type CombineResult = { /** * The updated segment with any changes applied */ segment: Segment /** * If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of * appending a new segment */ replace: boolean /** * Indicates if the combine rule was applied */ combined: boolean } /** * Checks if the new and prior segments have the same speaker. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker and combining body results in new body shorter than * max length * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH} * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSegments = ( newSegment: Segment, priorSegment: Segment, maxLength: number, lastSpeaker: string ): CombineResult => { if (priorSegment === undefined) { return { segment: newSegment, replace: false, combined: false, } } const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH if ( (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) && joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength ) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker, startTime and endTime. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with value of separator argument * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param separator string to use to combine body values. If undefined, uses "\n" * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineEqualTimes = ( newSegment: Segment, priorSegment: Segment, separator: string, lastSpeaker: string ): CombineResult => { const combineEqualTimesSeparator = separator || "\n" if ( newSegment.startTime === priorSegment.startTime && newSegment.endTime === priorSegment.endTime && (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) ) { return { segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from newSegment if different from priorSegment else undefined * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (priorSegment === undefined) { if (newSegment.speaker === lastSpeaker) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } if (newSegment.speaker === undefined) { return result } if ( newSegment.speaker === "" || newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker ) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } /** * Determine how {@link Options.speakerChange is applied based an past options being applied} * * @param currentResult current result object from any prior options * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const applyOptionsAndDoSpeakerChange = ( currentResult: CombineResult, priorSegment: Segment, lastSpeaker: string ): CombineResult => { const { combineSegments, combineEqualTimes
} = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined) } else if (combineEqualTimes) { if (result.combined && result.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } if (result) { result = { segment: result.segment, replace: currentResult.replace || result.replace, combined: currentResult.combined || result.combined, } } return result } /** * Apply convert rules when no prior segment exits. * * NOTE: not all rules applicable when no prior segment * * @param newSegment segment before any rules options to it * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => { const { speakerChange } = Options let result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (speakerChange) { result = doSpeakerChange(result.segment, undefined, lastSpeaker) } return result } /** * Apply convert rules when prior segment exits. * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const { combineEqualTimes, combineEqualTimesSeparator, combineSegments, combineSegmentsLength, combineSpeaker, speakerChange, } = Options let result: CombineResult = { segment: { ...newSegment }, replace: false, combined: false, } let combinedSpeaker = false if (combineSpeaker) { result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker) combinedSpeaker = result.combined } if (!combinedSpeaker && combineEqualTimes) { result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker) } if (!combinedSpeaker && combineSegments) { let combineResult if (combineEqualTimes && result.combined) { combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker) } else { combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker) } if (combineResult) { result = { segment: combineResult.segment, replace: result.replace || combineResult.replace, combined: result.combined || combineResult.combined, } } } if (speakerChange) { result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker) } return result } /** * Apply any options to the current segment * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => { if (!Options.optionsSet()) { return { segment: newSegment, replace: false, combined: false, } } let result: CombineResult // if no prior segment, limited additional checking if (priorSegment === undefined) { result = doCombineNoPrior(newSegment, lastSpeaker) } else { result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker) } return result } /** * Get the last speaker name from the previously parsed segments * * @param priorSegment prior parsed segment * @param priorSegments array of all previous segments * @returns the name of the last speaker */ const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => { let lastSpeaker if (priorSegment) { lastSpeaker = priorSegment.speaker } if (lastSpeaker === undefined && priorSegments.length > 0) { lastSpeaker = priorSegments[0].speaker for (let i = priorSegments.length - 1; i > 0; i--) { if (priorSegments[i].speaker !== undefined) { lastSpeaker = priorSegments[i].speaker break } } } return lastSpeaker } /** * Helper for adding segment to or updating last segment in array of segments * * @param newSegment segment to add or replace * @param priorSegments array of all previous segments * @returns updated array of segments with new segment added or last segment updated (per options) */ export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => { const { speakerChange } = Options const outSegments = priorSegments || [] const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined // don't worry about identifying the last speaker if speaker is not being removed by speakerChange let lastSpeaker: string if (speakerChange) { lastSpeaker = getLastSpeaker(priorSegment, outSegments) } const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker) if (newSegmentInfo.replace && outSegments.length > 0) { outSegments[outSegments.length - 1] = newSegmentInfo.segment } else { outSegments.push(newSegmentInfo.segment) } return outSegments }
src/segments.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/options.ts", "retrieved_chunk": " public optionsSet = (): boolean => {\n const { combineEqualTimes, combineSegments, combineSpeaker, speakerChange } = this\n return combineEqualTimes || combineSegments || combineSpeaker || speakerChange\n }\n}\nexport const Options = new OptionsManager()", "score": 0.8703833818435669 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " * @returns Updated HTML Segment part and segment data for next segment (if fields encountered)\n */\nconst updateSegmentPartFromElement = (\n element: HTMLElement,\n segmentPart: HTMLSegmentPart\n): {\n current: HTMLSegmentPart\n next: HTMLSegmentPart\n} => {\n const currentSegmentPart = segmentPart", "score": 0.8349043726921082 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {\n const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker\n const startTime = parseTimestamp(segmentPart.time)\n return {\n startTime,\n startTimeFormatted: TimestampFormatter.format(startTime),\n endTime: 0,", "score": 0.8293571472167969 }, { "filename": "src/options.ts", "retrieved_chunk": " public getOptionByName = (name: string): boolean | string | number => {\n let actual\n switch (name) {\n case \"combineEqualTimes\":\n actual = this.combineEqualTimes\n break\n case \"combineEqualTimesSeparator\":\n actual = this.combineEqualTimesSeparator\n break\n case \"combineSegments\":", "score": 0.8200302720069885 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " */\nconst getSegmentsFromHTMLElements = (elements: Array<HTMLElement>): Array<Segment> => {\n let outSegments: Array<Segment> = []\n let lastSpeaker = \"\"\n let segmentPart: HTMLSegmentPart = {\n cite: \"\",\n time: \"\",\n text: \"\",\n }\n let nextSegmentPart: HTMLSegmentPart = {", "score": 0.8194385170936584 } ]
typescript
} = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) {
import { addSegment } from "../segments" import { parseSpeaker } from "../speaker" import { parseTimestamp, TimestampFormatter } from "../timestamp" import { PATTERN_LINE_SEPARATOR, Segment } from "../types" /** * Define a segment/cue parsed from SRT file */ export type SRTSegment = { /** * Cue number */ index: number /** * Time (in seconds) when segment starts */ startTime: number /** * Time (in seconds) when segment ends */ endTime: number /** * Name of speaker for `body` */ speaker: string /** * Text of transcript for segment */ body: string } /** * Parse lines looking for data to be SRT format * * @param lines Lines containing SRT data * @returns Parsed segment * @throws {Error} When no non-empty strings in `lines` * @throws {Error} When the minimum required number of lines is not received * @throws {Error} When segment lines does not start with a number * @throws {Error} When second segment line does not follow the timestamp format */ export const parseSRTSegment = (lines: Array<string>): SRTSegment => { do { if (lines.length === 0) { throw new Error("SRT segment lines empty") } else if (lines[0].trim() === "") { lines.shift() } else { break } } while (lines.length > 0) if (lines.length < 3) { throw new Error(`SRT requires at least 3 lines, ${lines.length} received`) } const index = parseInt(lines[0], 10) if (!index) { throw new Error(`First line of SRT segment is not a number`) } const timestampLine = lines[1] if (!timestampLine.includes("-->")) { throw new Error(`SRT timestamp line does not include --> separator`) } const timestampParts = timestampLine.split("-->") if (timestampParts.length !== 2) { throw new Error(`SRT timestamp line contains more than 2 --> separators`) } const startTime = parseTimestamp(timestampParts[0].trim()) const endTime = parseTimestamp(timestampParts[1].trim()) let bodyLines = lines.slice(2) const emptyLineIndex = bodyLines.findIndex((v) => v.trim() === "") if (emptyLineIndex > 0) { bodyLines = bodyLines.slice(0, emptyLineIndex) } const { speaker, message } =
parseSpeaker(bodyLines.shift()) bodyLines = [message].concat(bodyLines) return {
startTime, endTime, speaker, body: bodyLines.join("\n"), index, } } /** * Create Segment from lines containing an SRT segment/cue * * @param segmentLines Lines containing SRT data * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines` * @returns Created segment */ const createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => { const srtSegment = parseSRTSegment(segmentLines) const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker return { startTime: srtSegment.startTime, startTimeFormatted: TimestampFormatter.format(srtSegment.startTime), endTime: srtSegment.endTime, endTimeFormatted: TimestampFormatter.format(srtSegment.endTime), speaker: calculatedSpeaker, body: srtSegment.body, } } /** * Determines if the value of data is a valid SRT transcript format * * @param data The transcript data * @returns True: data is valid SRT transcript format */ export const isSRT = (data: string): boolean => { try { return parseSRTSegment(data.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined } catch (e) { return false } } /** * Parse SRT data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid SRT format */ export const parseSRT = (data: string): Array<Segment> => { if (!isSRT(data)) { throw new TypeError(`Data is not valid SRT format`) } let outSegments: Array<Segment> = [] let lastSpeaker = "" let segmentLines = [] data.split(PATTERN_LINE_SEPARATOR).forEach((line, count) => { // separator line found, handle previous data if (line.trim() === "") { // handle consecutive multiple blank lines if (segmentLines.length !== 0) { try { outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments) lastSpeaker = outSegments[outSegments.length - 1].speaker } catch (e) { console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`) console.error(segmentLines) } } segmentLines = [] // clear buffer } else { segmentLines.push(line) } }) // handle data when trailing line not included if (segmentLines.length !== 0) { try { outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments) lastSpeaker = outSegments[outSegments.length - 1].speaker } catch (e) { console.error(`Error parsing final SRT segment lines: ${e}`) console.error(segmentLines) } } return outSegments }
src/formats/srt.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/segments.ts", "retrieved_chunk": " * - `endTimeFormatted`: from last segment\n * - `speaker`: from first segment\n * - `body`: combination of all segments\n */\nconst joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {\n const newSegment = { ...segments[0] }\n segments.slice(1).forEach((segment) => {\n newSegment.endTime = segment.endTime\n newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)\n newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)", "score": 0.7917432188987732 }, { "filename": "src/speaker.ts", "retrieved_chunk": " * @returns The speaker (if found) and the remaining string\n */\nexport const parseSpeaker = (data: string): { speaker: string; message: string } => {\n let speaker = \"\"\n let message = data\n const speakerMatch = PATTERN_SPEAKER.exec(data)\n if (speakerMatch !== null) {\n speaker = speakerMatch.groups.speaker\n message = speakerMatch.groups.body\n }", "score": 0.7844660878181458 }, { "filename": "src/timestamp.ts", "retrieved_chunk": " }\n const match = PATTERN_TIMESTAMP.exec(value.trim())\n if (match === null) {\n throw new TypeError(`Not enough separator fields in timestamp string`)\n }\n const { time } = match.groups\n const splits = time.split(\":\")\n const splitLength = splits.length\n let timestamp = 0\n if (splitLength === 3) {", "score": 0.774243950843811 }, { "filename": "src/segments.ts", "retrieved_chunk": "const joinBody = (body: string, addition: string, separator: string = undefined): string => {\n if (body) {\n let separatorToUse = separator || \"\\n\"\n if (PATTERN_PUNCTUATIONS.exec(addition)) {\n separatorToUse = \"\"\n }\n return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}`\n }\n return trimEndSpace(addition)\n}", "score": 0.7558278441429138 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === \"\").length !== 3\n ) {\n // time is required\n if (segmentPart.time === \"\") {\n console.warn(`Segment ${count} does not contain time information, ignoring`)\n } else {\n const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker)\n lastSpeaker = segment.speaker\n // update endTime of previous Segment\n const totalSegments = outSegments.length", "score": 0.7471626400947571 } ]
typescript
parseSpeaker(bodyLines.shift()) bodyLines = [message].concat(bodyLines) return {
import { pascalCase } from 'change-case' import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application' export const BARE_CALL = Symbol('bare') export type MethodIdentifier = string | typeof BARE_CALL export type MethodList = Array<MethodIdentifier> export type CallConfigSummary = { createMethods: MethodList callMethods: MethodList deleteMethods: MethodList updateMethods: MethodList optInMethods: MethodList closeOutMethods: MethodList } export const getCallConfigSummary = (app: AlgoAppSpec) => { const result: CallConfigSummary = { createMethods: [], callMethods: [], deleteMethods: [], updateMethods: [], optInMethods: [], closeOutMethods: [], } if (app.bare_call_config) { addToConfig(result, BARE_CALL, app.bare_call_config) } if (app.hints) { for (const [method, hints] of Object.entries(app.hints)) { if (hints.call_config) { addToConfig(result, method, hints.call_config) } } } return result } export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => { const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config if (!callConfig) { return '' } const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE' return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }` } const getCreateOnCompleteTypes = (config: CallConfig) => { return Object.keys(config) .map((oc) => oc as keyof CallConfig) .filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE') .map
((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') }
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => { if (hasCall(config.no_op)) { result.callMethods.push(method) } if ( hasCreate(config.no_op) || hasCreate(config.opt_in) || hasCreate(config.close_out) || hasCreate(config.update_application) || hasCreate(config.delete_application) ) { result.createMethods.push(method) } if (hasCall(config.delete_application)) { result.deleteMethods.push(method) } if (hasCall(config.update_application)) { result.updateMethods.push(method) } if (hasCall(config.opt_in)) { result.optInMethods.push(method) } if (hasCall(config.close_out)) { result.closeOutMethods.push(method) } } const hasCall = (config: CallConfigValue | undefined) => { return config === 'CALL' || config === 'ALL' } const hasCreate = (config: CallConfigValue | undefined) => { return config === 'CREATE' || config === 'ALL' }
src/client/helpers/get-call-config-summary.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " ? `(${Object.entries(callConfig)\n .filter(([_, value]) => value === 'ALL' || value === 'CREATE')\n .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])\n .join(' | ')})`\n : {}\n return {\n type: onCompleteType,\n isOptional: hasNoOp,\n }\n}", "score": 0.8591002821922302 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)", "score": 0.7622721195220947 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " if (method === BARE_CALL) {\n yield `| (TypedCallParams<undefined> & ${onComplete.type})`\n } else {\n yield `| (TypedCallParams<'${method}'> & ${onComplete.type})`\n }\n }\n yield DecIndent\n }\n if (callConfig.updateMethods.length > 0) {\n yield* jsDoc(`A factory for available 'update' calls`)", "score": 0.7422328591346741 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig", "score": 0.737211287021637 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,", "score": 0.7346992492675781 } ]
typescript
((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') }
import { isHTML, parseHTML } from "./formats/html" import { isJSON, parseJSON } from "./formats/json" import { isSRT, parseSRT } from "./formats/srt" import { isVTT, parseVTT } from "./formats/vtt" import { Segment, TranscriptFormat } from "./types" export { Segment, TranscriptFormat } from "./types" export { TimestampFormatter, FormatterCallback } from "./timestamp" export { Options, IOptions } from "./options" /** * Determines the format of transcript by inspecting the data * * @param data The transcript data * @returns The determined transcript format * @throws {TypeError} Cannot determine format of data or error parsing data */ export const determineFormat = (data: string): TranscriptFormat => { const normalizedData = data.trim() if (isVTT(normalizedData)) { return TranscriptFormat.VTT } if (isJSON(normalizedData)) { return TranscriptFormat.JSON } if (isHTML(normalizedData)) { return TranscriptFormat.HTML } if (isSRT(normalizedData)) { return TranscriptFormat.SRT } throw new TypeError(`Cannot determine format for data`) } /** * Convert the data to an Array of {@link Segment} * * @param data The transcript data * @param transcriptFormat The format of the data. * @returns An Array of Segment objects from the parsed data * @throws {TypeError} When `transcriptFormat` is unknown */ export const convertFile = (data: string, transcriptFormat: TranscriptFormat = undefined): Array<Segment> => { const format = transcriptFormat ?? determineFormat(data) const normalizedData = data.trimStart() let outSegments: Array<Segment> = [] switch (format) { case TranscriptFormat.HTML: outSegments = parseHTML(normalizedData) break case TranscriptFormat.JSON: outSegments = parseJSON(normalizedData) break case TranscriptFormat.SRT: outSegments = parseSRT(normalizedData) break case TranscriptFormat.VTT: outSegments
= parseVTT(normalizedData) break default: throw new TypeError(`Unknown transcript format: ${format}`) }
return outSegments }
src/index.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/json.ts", "retrieved_chunk": " outSegments = parseDictSegmentsJSON(data as JSONTranscript)\n } else {\n throw new TypeError(`Unknown JSON dict transcript format`)\n }\n return outSegments\n}\n/**\n * Convert {@link SubtitleSegment} to the {@link Segment} format used here\n *\n * @param data Segment parsed from JSON data", "score": 0.8535631895065308 }, { "filename": "src/formats/json.ts", "retrieved_chunk": " return outSegments\n }\n const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment)\n if (subtitleSegment !== undefined) {\n outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>)\n } else {\n throw new TypeError(`Unknown JSON list transcript format`)\n }\n return outSegments\n}", "score": 0.8393954038619995 }, { "filename": "src/formats/vtt.ts", "retrieved_chunk": " * @throws {TypeError} When `data` is not valid VTT format\n */\nexport const parseVTT = (data: string): Array<Segment> => {\n if (!isVTT(data)) {\n throw new TypeError(`Data is not valid VTT format`)\n }\n // format is similar enough to SRT to be parsed by the same parser\n // Remove WEBVTT header first\n return parseSRT(data.substring(WEBVTT_HEADER.length).trimStart())\n}", "score": 0.8368765115737915 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": "/**\n * Determines if the value of data is a valid SRT transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid SRT transcript format\n */\nexport const isSRT = (data: string): boolean => {\n try {\n return parseSRTSegment(data.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined\n } catch (e) {", "score": 0.8316891193389893 }, { "filename": "src/formats/json.ts", "retrieved_chunk": " * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When JSON data does not match one of the valid formats\n */\nconst parseDictJSON = (data: object): Array<Segment> => {\n let outSegments: Array<Segment> = []\n if (Object.keys(data).length === 0) {\n return outSegments\n }\n if (\"segments\" in data) {", "score": 0.8271493911743164 } ]
typescript
= parseVTT(normalizedData) break default: throw new TypeError(`Unknown transcript format: ${format}`) }
import { addSegment } from "../segments" import { parseSpeaker } from "../speaker" import { TimestampFormatter } from "../timestamp" import { Segment } from "../types" /** * Define a segment/cue used in the JSONTranscript format */ export type JSONSegment = { /** * Time (in seconds) when segment starts */ startTime: number /** * Time (in seconds) when segment ends */ endTime: number /** * Name of speaker for `body` */ speaker?: string /** * Text of transcript for segment */ body: string } /** * Define the JSON transcript format */ export type JSONTranscript = { /** * Version of file format */ version: string /** * Segment data */ segments: Array<JSONSegment> } /** * Define the JSON transcript Segment format */ export type SubtitleSegment = { /** * Time (in milliseconds) when segment starts */ start: number /** * Time (in milliseconds) when segment ends */ end: number /** * Text of transcript for segment */ text: string } /** * Determines if the value of data is a valid JSON transcript format * * @param data The transcript data * @returns True: data is valid JSON transcript format */ export const isJSON = (data: string): boolean => { return (data.startsWith("{") && data.endsWith("}")) || (data.startsWith("[") && data.endsWith("]")) } /** * Parse JSON data where segments are in the `segments` Array and in the {@link JSONSegment} format * * @param data Parsed JSON data * @returns An array of Segments from the parsed data */ const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => { let outSegments: Array<Segment> = [] data.segments.forEach((segment) => { outSegments = addSegment( { startTime: segment.startTime, startTimeFormatted: TimestampFormatter.format(segment.startTime), endTime: segment.endTime, endTimeFormatted: TimestampFormatter.format(segment.endTime), speaker: segment.speaker, body: segment.body, }, outSegments ) }) return outSegments } /** * Parse JSON data where top level item is a dict/object * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When JSON data does not match one of the valid formats */ const parseDictJSON = (data: object): Array<Segment> => { let outSegments: Array<Segment> = [] if (Object.keys(data).length === 0) { return outSegments } if ("segments" in data) { outSegments = parseDictSegmentsJSON(data as JSONTranscript) } else { throw new TypeError(`Unknown JSON dict transcript format`) } return outSegments } /** * Convert {@link SubtitleSegment} to the {@link Segment} format used here * * @param data Segment parsed from JSON data * @returns Segment representing `data`. * Returns {@link undefined} when data does not match {@link SubtitleSegment} format. */ const getSegmentFromSubtitle = (data: SubtitleSegment): Segment => { if ("start" in data && "end" in data && "text" in data) { const { speaker, message } = parseSpeaker(data.text) const startTime = data.start / 1000 const endTime = data.end / 1000 const segment: Segment = { startTime, startTimeFormatted: TimestampFormatter.format(startTime), endTime, endTimeFormatted: TimestampFormatter.format(endTime), speaker, body: message, }
if (Number.isNaN(segment.startTime)) {
console.warn(`Computed start time is NaN: ${segment.startTime}`) return undefined } if (Number.isNaN(segment.endTime)) { console.warn(`Computed end time is NaN: ${segment.endTime}`) return undefined } return segment } return undefined } /** * Parse JSON data where items in data are in the {@link SubtitleSegment} format * * @param data Parsed JSON data * @returns An array of Segments from the parsed data * @throws {TypeError} When item in `data` does not match the {@link SubtitleSegment} format */ const parseListJSONSubtitle = (data: Array<SubtitleSegment>): Array<Segment> => { let outSegments: Array<Segment> = [] let lastSpeaker = "" data.forEach((subtitle, count) => { const subtitleSegment = getSegmentFromSubtitle(subtitle) if (subtitleSegment !== undefined) { lastSpeaker = subtitleSegment.speaker ? subtitleSegment.speaker : lastSpeaker subtitleSegment.speaker = lastSpeaker outSegments = addSegment(subtitleSegment, outSegments) } else { throw new TypeError(`Unable to parse segment for item ${count}`) } }) return outSegments } /** * Parse JSON data where top level item is an Array * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When JSON data does not match one of the valid formats */ const parseListJSON = (data: Array<unknown>): Array<Segment> => { let outSegments: Array<Segment> = [] if (data.length === 0) { return outSegments } const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment) if (subtitleSegment !== undefined) { outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>) } else { throw new TypeError(`Unknown JSON list transcript format`) } return outSegments } /** * Parse JSON data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid JSON format */ export const parseJSON = (data: string): Array<Segment> => { const dataTrimmed = data.trim() let outSegments: Array<Segment> = [] if (!isJSON(dataTrimmed)) { throw new TypeError(`Data is not valid JSON format`) } let parsed: object | Array<unknown> try { parsed = JSON.parse(data) } catch (e) { throw new TypeError(`Data is not valid JSON: ${e}`) } if (parsed.constructor === Object) { outSegments = parseDictJSON(parsed) } else if (parsed.constructor === Array) { outSegments = parseListJSON(parsed) } return outSegments }
src/formats/json.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/html.ts", "retrieved_chunk": " * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {\n const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker\n const startTime = parseTimestamp(segmentPart.time)\n return {\n startTime,\n startTimeFormatted: TimestampFormatter.format(startTime),\n endTime: 0,", "score": 0.8782147169113159 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker\n return {\n startTime: srtSegment.startTime,\n startTimeFormatted: TimestampFormatter.format(srtSegment.startTime),\n endTime: srtSegment.endTime,\n endTimeFormatted: TimestampFormatter.format(srtSegment.endTime),\n speaker: calculatedSpeaker,\n body: srtSegment.body,\n }\n}", "score": 0.8759233355522156 }, { "filename": "src/segments.ts", "retrieved_chunk": " * - `endTimeFormatted`: from last segment\n * - `speaker`: from first segment\n * - `body`: combination of all segments\n */\nconst joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {\n const newSegment = { ...segments[0] }\n segments.slice(1).forEach((segment) => {\n newSegment.endTime = segment.endTime\n newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)\n newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)", "score": 0.8597558736801147 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " }\n const { speaker, message } = parseSpeaker(bodyLines.shift())\n bodyLines = [message].concat(bodyLines)\n return {\n startTime,\n endTime,\n speaker,\n body: bodyLines.join(\"\\n\"),\n index,\n }", "score": 0.8514482975006104 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === \"\").length !== 3\n ) {\n // time is required\n if (segmentPart.time === \"\") {\n console.warn(`Segment ${count} does not contain time information, ignoring`)\n } else {\n const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker)\n lastSpeaker = segment.speaker\n // update endTime of previous Segment\n const totalSegments = outSegments.length", "score": 0.8385748863220215 } ]
typescript
if (Number.isNaN(segment.startTime)) {
import { addSegment } from "../segments" import { parseSpeaker } from "../speaker" import { TimestampFormatter } from "../timestamp" import { Segment } from "../types" /** * Define a segment/cue used in the JSONTranscript format */ export type JSONSegment = { /** * Time (in seconds) when segment starts */ startTime: number /** * Time (in seconds) when segment ends */ endTime: number /** * Name of speaker for `body` */ speaker?: string /** * Text of transcript for segment */ body: string } /** * Define the JSON transcript format */ export type JSONTranscript = { /** * Version of file format */ version: string /** * Segment data */ segments: Array<JSONSegment> } /** * Define the JSON transcript Segment format */ export type SubtitleSegment = { /** * Time (in milliseconds) when segment starts */ start: number /** * Time (in milliseconds) when segment ends */ end: number /** * Text of transcript for segment */ text: string } /** * Determines if the value of data is a valid JSON transcript format * * @param data The transcript data * @returns True: data is valid JSON transcript format */ export const isJSON = (data: string): boolean => { return (data.startsWith("{") && data.endsWith("}")) || (data.startsWith("[") && data.endsWith("]")) } /** * Parse JSON data where segments are in the `segments` Array and in the {@link JSONSegment} format * * @param data Parsed JSON data * @returns An array of Segments from the parsed data */ const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => { let outSegments: Array<Segment> = [] data.segments.forEach((segment) => { outSegments = addSegment( { startTime: segment.startTime, startTimeFormatted: TimestampFormatter.format(segment.startTime), endTime: segment.endTime, endTimeFormatted: TimestampFormatter.format(segment.endTime), speaker: segment.speaker, body: segment.body, }, outSegments ) }) return outSegments } /** * Parse JSON data where top level item is a dict/object * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When JSON data does not match one of the valid formats */ const parseDictJSON = (data: object): Array<Segment> => { let outSegments: Array<Segment> = [] if (Object.keys(data).length === 0) { return outSegments } if ("segments" in data) { outSegments = parseDictSegmentsJSON(data as JSONTranscript) } else { throw new TypeError(`Unknown JSON dict transcript format`) } return outSegments } /** * Convert {@link SubtitleSegment} to the {@link Segment} format used here * * @param data Segment parsed from JSON data * @returns Segment representing `data`. * Returns {@link undefined} when data does not match {@link SubtitleSegment} format. */ const getSegmentFromSubtitle = (data: SubtitleSegment): Segment => { if ("start" in data && "end" in data && "text" in data) { const { speaker, message } = parseSpeaker(data.text) const startTime = data.start / 1000 const endTime = data.end / 1000 const segment: Segment = { startTime, startTimeFormatted: TimestampFormatter.format(startTime), endTime, endTimeFormatted: TimestampFormatter.format(endTime), speaker, body: message, } if (Number.isNaN(segment.startTime)) { console.warn(`Computed start time is NaN: ${segment.startTime}`) return undefined } if (Number.isNaN(segment.endTime)) { console.warn(`Computed end time is NaN: ${segment.endTime}`) return undefined } return segment } return undefined } /** * Parse JSON data where items in data are in the {@link SubtitleSegment} format * * @param data Parsed JSON data * @returns An array of Segments from the parsed data * @throws {TypeError} When item in `data` does not match the {@link SubtitleSegment} format */ const parseListJSONSubtitle = (data: Array<SubtitleSegment>): Array<Segment> => { let outSegments: Array<Segment> = [] let lastSpeaker = "" data.forEach((subtitle, count) => { const subtitleSegment = getSegmentFromSubtitle(subtitle) if (subtitleSegment !== undefined) { lastSpeaker = subtitleSegment
.speaker ? subtitleSegment.speaker : lastSpeaker subtitleSegment.speaker = lastSpeaker outSegments = addSegment(subtitleSegment, outSegments) } else {
throw new TypeError(`Unable to parse segment for item ${count}`) } }) return outSegments } /** * Parse JSON data where top level item is an Array * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When JSON data does not match one of the valid formats */ const parseListJSON = (data: Array<unknown>): Array<Segment> => { let outSegments: Array<Segment> = [] if (data.length === 0) { return outSegments } const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment) if (subtitleSegment !== undefined) { outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>) } else { throw new TypeError(`Unknown JSON list transcript format`) } return outSegments } /** * Parse JSON data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid JSON format */ export const parseJSON = (data: string): Array<Segment> => { const dataTrimmed = data.trim() let outSegments: Array<Segment> = [] if (!isJSON(dataTrimmed)) { throw new TypeError(`Data is not valid JSON format`) } let parsed: object | Array<unknown> try { parsed = JSON.parse(data) } catch (e) { throw new TypeError(`Data is not valid JSON: ${e}`) } if (parsed.constructor === Object) { outSegments = parseDictJSON(parsed) } else if (parsed.constructor === Array) { outSegments = parseListJSON(parsed) } return outSegments }
src/formats/json.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/html.ts", "retrieved_chunk": " Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === \"\").length !== 3\n ) {\n // time is required\n if (segmentPart.time === \"\") {\n console.warn(`Segment ${count} does not contain time information, ignoring`)\n } else {\n const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker)\n lastSpeaker = segment.speaker\n // update endTime of previous Segment\n const totalSegments = outSegments.length", "score": 0.8879562616348267 }, { "filename": "src/segments.ts", "retrieved_chunk": " let lastSpeaker: string\n if (speakerChange) {\n lastSpeaker = getLastSpeaker(priorSegment, outSegments)\n }\n const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker)\n if (newSegmentInfo.replace && outSegments.length > 0) {\n outSegments[outSegments.length - 1] = newSegmentInfo.segment\n } else {\n outSegments.push(newSegmentInfo.segment)\n }", "score": 0.8593938946723938 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " // handle consecutive multiple blank lines\n if (segmentLines.length !== 0) {\n try {\n outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)\n lastSpeaker = outSegments[outSegments.length - 1].speaker\n } catch (e) {\n console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`)\n console.error(segmentLines)\n }\n }", "score": 0.8505445718765259 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " segmentLines = [] // clear buffer\n } else {\n segmentLines.push(line)\n }\n })\n // handle data when trailing line not included\n if (segmentLines.length !== 0) {\n try {\n outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments)\n lastSpeaker = outSegments[outSegments.length - 1].speaker", "score": 0.8494851589202881 }, { "filename": "src/segments.ts", "retrieved_chunk": " * - `endTimeFormatted`: from last segment\n * - `speaker`: from first segment\n * - `body`: combination of all segments\n */\nconst joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {\n const newSegment = { ...segments[0] }\n segments.slice(1).forEach((segment) => {\n newSegment.endTime = segment.endTime\n newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)\n newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)", "score": 0.8477992415428162 } ]
typescript
.speaker ? subtitleSegment.speaker : lastSpeaker subtitleSegment.speaker = lastSpeaker outSegments = addSegment(subtitleSegment, outSegments) } else {
import { addSegment } from "../segments" import { parseSpeaker } from "../speaker" import { TimestampFormatter } from "../timestamp" import { Segment } from "../types" /** * Define a segment/cue used in the JSONTranscript format */ export type JSONSegment = { /** * Time (in seconds) when segment starts */ startTime: number /** * Time (in seconds) when segment ends */ endTime: number /** * Name of speaker for `body` */ speaker?: string /** * Text of transcript for segment */ body: string } /** * Define the JSON transcript format */ export type JSONTranscript = { /** * Version of file format */ version: string /** * Segment data */ segments: Array<JSONSegment> } /** * Define the JSON transcript Segment format */ export type SubtitleSegment = { /** * Time (in milliseconds) when segment starts */ start: number /** * Time (in milliseconds) when segment ends */ end: number /** * Text of transcript for segment */ text: string } /** * Determines if the value of data is a valid JSON transcript format * * @param data The transcript data * @returns True: data is valid JSON transcript format */ export const isJSON = (data: string): boolean => { return (data.startsWith("{") && data.endsWith("}")) || (data.startsWith("[") && data.endsWith("]")) } /** * Parse JSON data where segments are in the `segments` Array and in the {@link JSONSegment} format * * @param data Parsed JSON data * @returns An array of Segments from the parsed data */ const parseDictSegmentsJSON = (data: JSONTranscript): Array<Segment> => { let outSegments: Array<Segment> = [] data.segments.forEach((segment) => { outSegments = addSegment( { startTime: segment.startTime, startTimeFormatted: TimestampFormatter.format(segment.startTime), endTime: segment.endTime, endTimeFormatted: TimestampFormatter.format(segment.endTime), speaker: segment.speaker, body: segment.body, }, outSegments ) }) return outSegments } /** * Parse JSON data where top level item is a dict/object * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When JSON data does not match one of the valid formats */ const parseDictJSON = (data: object): Array<Segment> => { let outSegments: Array<Segment> = [] if (Object.keys(data).length === 0) { return outSegments } if ("segments" in data) { outSegments = parseDictSegmentsJSON(data as JSONTranscript) } else { throw new TypeError(`Unknown JSON dict transcript format`) } return outSegments } /** * Convert {@link SubtitleSegment} to the {@link Segment} format used here * * @param data Segment parsed from JSON data * @returns Segment representing `data`. * Returns {@link undefined} when data does not match {@link SubtitleSegment} format. */ const getSegmentFromSubtitle = (data: SubtitleSegment): Segment => { if ("start" in data && "end" in data && "text" in data) { const { speaker, message } = parseSpeaker(data.text) const startTime = data.start / 1000 const endTime = data.end / 1000 const segment: Segment = { startTime, startTimeFormatted: TimestampFormatter.format(startTime), endTime, endTimeFormatted: TimestampFormatter.format(endTime), speaker, body: message, } if (Number.isNaN(segment.startTime)) { console.warn(`Computed start time is NaN: ${segment.startTime}`) return undefined }
if (Number.isNaN(segment.endTime)) {
console.warn(`Computed end time is NaN: ${segment.endTime}`) return undefined } return segment } return undefined } /** * Parse JSON data where items in data are in the {@link SubtitleSegment} format * * @param data Parsed JSON data * @returns An array of Segments from the parsed data * @throws {TypeError} When item in `data` does not match the {@link SubtitleSegment} format */ const parseListJSONSubtitle = (data: Array<SubtitleSegment>): Array<Segment> => { let outSegments: Array<Segment> = [] let lastSpeaker = "" data.forEach((subtitle, count) => { const subtitleSegment = getSegmentFromSubtitle(subtitle) if (subtitleSegment !== undefined) { lastSpeaker = subtitleSegment.speaker ? subtitleSegment.speaker : lastSpeaker subtitleSegment.speaker = lastSpeaker outSegments = addSegment(subtitleSegment, outSegments) } else { throw new TypeError(`Unable to parse segment for item ${count}`) } }) return outSegments } /** * Parse JSON data where top level item is an Array * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When JSON data does not match one of the valid formats */ const parseListJSON = (data: Array<unknown>): Array<Segment> => { let outSegments: Array<Segment> = [] if (data.length === 0) { return outSegments } const subtitleSegment = getSegmentFromSubtitle(data[0] as SubtitleSegment) if (subtitleSegment !== undefined) { outSegments = parseListJSONSubtitle(data as Array<SubtitleSegment>) } else { throw new TypeError(`Unknown JSON list transcript format`) } return outSegments } /** * Parse JSON data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid JSON format */ export const parseJSON = (data: string): Array<Segment> => { const dataTrimmed = data.trim() let outSegments: Array<Segment> = [] if (!isJSON(dataTrimmed)) { throw new TypeError(`Data is not valid JSON format`) } let parsed: object | Array<unknown> try { parsed = JSON.parse(data) } catch (e) { throw new TypeError(`Data is not valid JSON: ${e}`) } if (parsed.constructor === Object) { outSegments = parseDictJSON(parsed) } else if (parsed.constructor === Array) { outSegments = parseListJSON(parsed) } return outSegments }
src/formats/json.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/html.ts", "retrieved_chunk": " Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === \"\").length !== 3\n ) {\n // time is required\n if (segmentPart.time === \"\") {\n console.warn(`Segment ${count} does not contain time information, ignoring`)\n } else {\n const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker)\n lastSpeaker = segment.speaker\n // update endTime of previous Segment\n const totalSegments = outSegments.length", "score": 0.8188626766204834 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": " const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker\n return {\n startTime: srtSegment.startTime,\n startTimeFormatted: TimestampFormatter.format(srtSegment.startTime),\n endTime: srtSegment.endTime,\n endTimeFormatted: TimestampFormatter.format(srtSegment.endTime),\n speaker: calculatedSpeaker,\n body: srtSegment.body,\n }\n}", "score": 0.8167852759361267 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {\n const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker\n const startTime = parseTimestamp(segmentPart.time)\n return {\n startTime,\n startTimeFormatted: TimestampFormatter.format(startTime),\n endTime: 0,", "score": 0.8061220049858093 }, { "filename": "src/segments.ts", "retrieved_chunk": " * - `endTimeFormatted`: from last segment\n * - `speaker`: from first segment\n * - `body`: combination of all segments\n */\nconst joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => {\n const newSegment = { ...segments[0] }\n segments.slice(1).forEach((segment) => {\n newSegment.endTime = segment.endTime\n newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime)\n newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator)", "score": 0.8024798631668091 }, { "filename": "src/segments.ts", "retrieved_chunk": " newSegment.startTime === priorSegment.startTime &&\n newSegment.endTime === priorSegment.endTime &&\n (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker)\n ) {\n return {\n segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator),\n replace: true,\n combined: true,\n }\n }", "score": 0.7745472192764282 } ]
typescript
if (Number.isNaN(segment.endTime)) {
import { Options } from "./options" import { TimestampFormatter } from "./timestamp" import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types" /** * Regular Expression for detecting punctuation that should not be prefixed with a space */ const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/ /** * Regular Expression for detecting space characters at the end of a string */ const PATTERN_TRAILING_SPACE = /^ *$/ /** * Remove any trailing space characters from data * * @param data text to trim * @returns text with any trailing space character removed */ const trimEndSpace = (data: string): string => { return data.replace(PATTERN_TRAILING_SPACE, "") } /** * Append `addition` to `body` with the character(s) specified. * * If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data. * * @param body Current body text * @param addition Additional text to add to `body` * @param separator Character(s) to use to separate data. If undefined, uses `\n`. * @returns Combined data */ const joinBody = (body: string, addition: string, separator: string = undefined): string => { if (body) { let separatorToUse = separator || "\n" if (PATTERN_PUNCTUATIONS.exec(addition)) { separatorToUse = "" } return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}` } return trimEndSpace(addition) } /** * Combine one or more {@link Segment} * * @param segments Array of Segment objects to combine * @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`. * @returns Combined segment where: * * - `startTime`: from first segment * - `startTimeFormatted`: from first segment * - `endTime`: from last segment * - `endTimeFormatted`: from last segment * - `speaker`: from first segment * - `body`: combination of all segments */ const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => { const newSegment = { ...segments[0] } segments.slice(1).forEach((segment) => { newSegment.endTime = segment.endTime newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime) newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator) }) return newSegment } /** * Type returned from combine functions */ type CombineResult = { /** * The updated segment with any changes applied */ segment: Segment /** * If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of * appending a new segment */ replace: boolean /** * Indicates if the combine rule was applied */ combined: boolean } /** * Checks if the new and prior segments have the same speaker. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker and combining body results in new body shorter than * max length * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH} * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSegments = ( newSegment: Segment, priorSegment: Segment, maxLength: number, lastSpeaker: string ): CombineResult => { if (priorSegment === undefined) { return { segment: newSegment, replace: false, combined: false, } } const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH if ( (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) && joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength ) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker, startTime and endTime. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with value of separator argument * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param separator string to use to combine body values. If undefined, uses "\n" * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineEqualTimes = ( newSegment: Segment, priorSegment: Segment, separator: string, lastSpeaker: string ): CombineResult => { const combineEqualTimesSeparator = separator || "\n" if ( newSegment.startTime === priorSegment.startTime && newSegment.endTime === priorSegment.endTime && (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) ) { return { segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from newSegment if different from priorSegment else undefined * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (priorSegment === undefined) { if (newSegment.speaker === lastSpeaker) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } if (newSegment.speaker === undefined) { return result } if ( newSegment.speaker === "" || newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker ) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } /** * Determine how {@link Options.speakerChange is applied based an past options being applied} * * @param currentResult current result object from any prior options * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const applyOptionsAndDoSpeakerChange = ( currentResult: CombineResult, priorSegment: Segment, lastSpeaker: string ): CombineResult => { const { combineSegments, combineEqualTimes } = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else if (combineEqualTimes) { if (result.combined && result.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } if (result) { result = { segment: result.segment, replace: currentResult.replace || result.replace, combined: currentResult.combined || result.combined, } } return result } /** * Apply convert rules when no prior segment exits. * * NOTE: not all rules applicable when no prior segment * * @param newSegment segment before any rules options to it * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => {
const { speakerChange } = Options let result: CombineResult = {
segment: newSegment, replace: false, combined: false, } if (speakerChange) { result = doSpeakerChange(result.segment, undefined, lastSpeaker) } return result } /** * Apply convert rules when prior segment exits. * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const { combineEqualTimes, combineEqualTimesSeparator, combineSegments, combineSegmentsLength, combineSpeaker, speakerChange, } = Options let result: CombineResult = { segment: { ...newSegment }, replace: false, combined: false, } let combinedSpeaker = false if (combineSpeaker) { result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker) combinedSpeaker = result.combined } if (!combinedSpeaker && combineEqualTimes) { result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker) } if (!combinedSpeaker && combineSegments) { let combineResult if (combineEqualTimes && result.combined) { combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker) } else { combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker) } if (combineResult) { result = { segment: combineResult.segment, replace: result.replace || combineResult.replace, combined: result.combined || combineResult.combined, } } } if (speakerChange) { result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker) } return result } /** * Apply any options to the current segment * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => { if (!Options.optionsSet()) { return { segment: newSegment, replace: false, combined: false, } } let result: CombineResult // if no prior segment, limited additional checking if (priorSegment === undefined) { result = doCombineNoPrior(newSegment, lastSpeaker) } else { result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker) } return result } /** * Get the last speaker name from the previously parsed segments * * @param priorSegment prior parsed segment * @param priorSegments array of all previous segments * @returns the name of the last speaker */ const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => { let lastSpeaker if (priorSegment) { lastSpeaker = priorSegment.speaker } if (lastSpeaker === undefined && priorSegments.length > 0) { lastSpeaker = priorSegments[0].speaker for (let i = priorSegments.length - 1; i > 0; i--) { if (priorSegments[i].speaker !== undefined) { lastSpeaker = priorSegments[i].speaker break } } } return lastSpeaker } /** * Helper for adding segment to or updating last segment in array of segments * * @param newSegment segment to add or replace * @param priorSegments array of all previous segments * @returns updated array of segments with new segment added or last segment updated (per options) */ export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => { const { speakerChange } = Options const outSegments = priorSegments || [] const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined // don't worry about identifying the last speaker if speaker is not being removed by speakerChange let lastSpeaker: string if (speakerChange) { lastSpeaker = getLastSpeaker(priorSegment, outSegments) } const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker) if (newSegmentInfo.replace && outSegments.length > 0) { outSegments[outSegments.length - 1] = newSegmentInfo.segment } else { outSegments.push(newSegmentInfo.segment) } return outSegments }
src/segments.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/options.ts", "retrieved_chunk": " *\n * Note: If this is enabled, {@link combineEqualTimes} and {@link combineSegments} will not be applied.\n *\n * Warning: if the transcript does not contain speaker information, resulting segment will contain entire transcript text.\n */\n combineSpeaker?: boolean\n /**\n * Only include {@link Segment.speaker} when speaker changes\n *\n * May be used in combination with {@link combineSpeaker}, {@link combineEqualTimes}, or {@link combineSegments}", "score": 0.8924808502197266 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)", "score": 0.8899815678596497 }, { "filename": "src/options.ts", "retrieved_chunk": " */\n combineEqualTimesSeparator?: string\n /**\n * Combine segments where speaker is the same and concatenated `body` fits in the {@link combineSegmentsLength}\n *\n * Can be used with {@link combineEqualTimes}. The {@link combineSegments} rule is applied first.\n *\n * Can be used with {@link speakerChange}. The {@link speakerChange} rule is applied last.\n *\n * Cannot be used with {@link combineSpeaker}", "score": 0.8890674710273743 }, { "filename": "src/options.ts", "retrieved_chunk": " /**\n * Combine consecutive segments from the same speaker.\n *\n * Note: If this is enabled, {@link combineEqualTimes} and {@link combineSegments} will not be applied.\n *\n * Warning: if the transcript does not contain speaker information, resulting segment will contain entire transcript text.\n */\n public combineSpeaker = false\n /**\n * Only include {@link Segment.speaker} when speaker changes", "score": 0.8875471949577332 }, { "filename": "src/options.ts", "retrieved_chunk": " static _instance: OptionsManager\n /**\n * Combine segments if the {@link Segment.startTime}, {@link Segment.endTime}, and {@link Segment.speaker} match\n * between the current and prior segments\n *\n * Can be used with {@link combineSegments}. The {@link combineEqualTimes} rule is applied first.\n *\n * Can be used with {@link speakerChange}. The {@link speakerChange} rule is applied last.\n *\n * Cannot be used with {@link combineSpeaker}", "score": 0.8827266693115234 } ]
typescript
const { speakerChange } = Options let result: CombineResult = {
import { Options } from "./options" import { TimestampFormatter } from "./timestamp" import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types" /** * Regular Expression for detecting punctuation that should not be prefixed with a space */ const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/ /** * Regular Expression for detecting space characters at the end of a string */ const PATTERN_TRAILING_SPACE = /^ *$/ /** * Remove any trailing space characters from data * * @param data text to trim * @returns text with any trailing space character removed */ const trimEndSpace = (data: string): string => { return data.replace(PATTERN_TRAILING_SPACE, "") } /** * Append `addition` to `body` with the character(s) specified. * * If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data. * * @param body Current body text * @param addition Additional text to add to `body` * @param separator Character(s) to use to separate data. If undefined, uses `\n`. * @returns Combined data */ const joinBody = (body: string, addition: string, separator: string = undefined): string => { if (body) { let separatorToUse = separator || "\n" if (PATTERN_PUNCTUATIONS.exec(addition)) { separatorToUse = "" } return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}` } return trimEndSpace(addition) } /** * Combine one or more {@link Segment} * * @param segments Array of Segment objects to combine * @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`. * @returns Combined segment where: * * - `startTime`: from first segment * - `startTimeFormatted`: from first segment * - `endTime`: from last segment * - `endTimeFormatted`: from last segment * - `speaker`: from first segment * - `body`: combination of all segments */ const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => { const newSegment = { ...segments[0] } segments.slice(1).forEach((segment) => { newSegment.endTime = segment.endTime newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime) newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator) }) return newSegment } /** * Type returned from combine functions */ type CombineResult = { /** * The updated segment with any changes applied */ segment: Segment /** * If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of * appending a new segment */ replace: boolean /** * Indicates if the combine rule was applied */ combined: boolean } /** * Checks if the new and prior segments have the same speaker. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker and combining body results in new body shorter than * max length * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH} * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSegments = ( newSegment: Segment, priorSegment: Segment, maxLength: number, lastSpeaker: string ): CombineResult => { if (priorSegment === undefined) { return { segment: newSegment, replace: false, combined: false, } } const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH if ( (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) && joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength ) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker, startTime and endTime. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with value of separator argument * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param separator string to use to combine body values. If undefined, uses "\n" * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineEqualTimes = ( newSegment: Segment, priorSegment: Segment, separator: string, lastSpeaker: string ): CombineResult => { const combineEqualTimesSeparator = separator || "\n" if ( newSegment.startTime === priorSegment.startTime && newSegment.endTime === priorSegment.endTime && (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) ) { return { segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from newSegment if different from priorSegment else undefined * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (priorSegment === undefined) { if (newSegment.speaker === lastSpeaker) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } if (newSegment.speaker === undefined) { return result } if ( newSegment.speaker === "" || newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker ) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } /** * Determine how {@link Options.speakerChange is applied based an past options being applied} * * @param currentResult current result object from any prior options * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const applyOptionsAndDoSpeakerChange = ( currentResult: CombineResult, priorSegment: Segment, lastSpeaker: string ): CombineResult => { const { combineSegments, combineEqualTimes } = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else if (combineEqualTimes) { if (result.combined && result.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } if (result) { result = { segment: result.segment, replace: currentResult.replace || result.replace, combined: currentResult.combined || result.combined, } } return result } /** * Apply convert rules when no prior segment exits. * * NOTE: not all rules applicable when no prior segment * * @param newSegment segment before any rules options to it * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => { const { speakerChange } = Options let result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (speakerChange) { result = doSpeakerChange(result.segment, undefined, lastSpeaker) } return result } /** * Apply convert rules when prior segment exits. * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const { combineEqualTimes, combineEqualTimesSeparator, combineSegments, combineSegmentsLength, combineSpeaker, speakerChange, } = Options let result: CombineResult = { segment: { ...newSegment }, replace: false, combined: false, } let combinedSpeaker = false if (combineSpeaker) { result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker) combinedSpeaker = result.combined } if (!combinedSpeaker && combineEqualTimes) { result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker) } if (!combinedSpeaker && combineSegments) { let combineResult if (combineEqualTimes && result.combined) { combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker) } else { combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker) } if (combineResult) { result = { segment: combineResult.segment, replace: result.replace || combineResult.replace, combined: result.combined || combineResult.combined, } } } if (speakerChange) { result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker) } return result } /** * Apply any options to the current segment * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => {
if (!Options.optionsSet()) {
return { segment: newSegment, replace: false, combined: false, } } let result: CombineResult // if no prior segment, limited additional checking if (priorSegment === undefined) { result = doCombineNoPrior(newSegment, lastSpeaker) } else { result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker) } return result } /** * Get the last speaker name from the previously parsed segments * * @param priorSegment prior parsed segment * @param priorSegments array of all previous segments * @returns the name of the last speaker */ const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => { let lastSpeaker if (priorSegment) { lastSpeaker = priorSegment.speaker } if (lastSpeaker === undefined && priorSegments.length > 0) { lastSpeaker = priorSegments[0].speaker for (let i = priorSegments.length - 1; i > 0; i--) { if (priorSegments[i].speaker !== undefined) { lastSpeaker = priorSegments[i].speaker break } } } return lastSpeaker } /** * Helper for adding segment to or updating last segment in array of segments * * @param newSegment segment to add or replace * @param priorSegments array of all previous segments * @returns updated array of segments with new segment added or last segment updated (per options) */ export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => { const { speakerChange } = Options const outSegments = priorSegments || [] const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined // don't worry about identifying the last speaker if speaker is not being removed by speakerChange let lastSpeaker: string if (speakerChange) { lastSpeaker = getLastSpeaker(priorSegment, outSegments) } const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker) if (newSegmentInfo.replace && outSegments.length > 0) { outSegments[outSegments.length - 1] = newSegmentInfo.segment } else { outSegments.push(newSegmentInfo.segment) } return outSegments }
src/segments.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/srt.ts", "retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)", "score": 0.893816351890564 }, { "filename": "src/options.ts", "retrieved_chunk": " *\n * Note: If this is enabled, {@link combineEqualTimes} and {@link combineSegments} will not be applied.\n *\n * Warning: if the transcript does not contain speaker information, resulting segment will contain entire transcript text.\n */\n combineSpeaker?: boolean\n /**\n * Only include {@link Segment.speaker} when speaker changes\n *\n * May be used in combination with {@link combineSpeaker}, {@link combineEqualTimes}, or {@link combineSegments}", "score": 0.8874194025993347 }, { "filename": "src/options.ts", "retrieved_chunk": " /**\n * Combine consecutive segments from the same speaker.\n *\n * Note: If this is enabled, {@link combineEqualTimes} and {@link combineSegments} will not be applied.\n *\n * Warning: if the transcript does not contain speaker information, resulting segment will contain entire transcript text.\n */\n public combineSpeaker = false\n /**\n * Only include {@link Segment.speaker} when speaker changes", "score": 0.8868798017501831 }, { "filename": "src/options.ts", "retrieved_chunk": " static _instance: OptionsManager\n /**\n * Combine segments if the {@link Segment.startTime}, {@link Segment.endTime}, and {@link Segment.speaker} match\n * between the current and prior segments\n *\n * Can be used with {@link combineSegments}. The {@link combineEqualTimes} rule is applied first.\n *\n * Can be used with {@link speakerChange}. The {@link speakerChange} rule is applied last.\n *\n * Cannot be used with {@link combineSpeaker}", "score": 0.881013035774231 }, { "filename": "src/options.ts", "retrieved_chunk": " */\n combineEqualTimesSeparator?: string\n /**\n * Combine segments where speaker is the same and concatenated `body` fits in the {@link combineSegmentsLength}\n *\n * Can be used with {@link combineEqualTimes}. The {@link combineSegments} rule is applied first.\n *\n * Can be used with {@link speakerChange}. The {@link speakerChange} rule is applied last.\n *\n * Cannot be used with {@link combineSpeaker}", "score": 0.8807547092437744 } ]
typescript
if (!Options.optionsSet()) {
import { Options } from "./options" import { TimestampFormatter } from "./timestamp" import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types" /** * Regular Expression for detecting punctuation that should not be prefixed with a space */ const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/ /** * Regular Expression for detecting space characters at the end of a string */ const PATTERN_TRAILING_SPACE = /^ *$/ /** * Remove any trailing space characters from data * * @param data text to trim * @returns text with any trailing space character removed */ const trimEndSpace = (data: string): string => { return data.replace(PATTERN_TRAILING_SPACE, "") } /** * Append `addition` to `body` with the character(s) specified. * * If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data. * * @param body Current body text * @param addition Additional text to add to `body` * @param separator Character(s) to use to separate data. If undefined, uses `\n`. * @returns Combined data */ const joinBody = (body: string, addition: string, separator: string = undefined): string => { if (body) { let separatorToUse = separator || "\n" if (PATTERN_PUNCTUATIONS.exec(addition)) { separatorToUse = "" } return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}` } return trimEndSpace(addition) } /** * Combine one or more {@link Segment} * * @param segments Array of Segment objects to combine * @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`. * @returns Combined segment where: * * - `startTime`: from first segment * - `startTimeFormatted`: from first segment * - `endTime`: from last segment * - `endTimeFormatted`: from last segment * - `speaker`: from first segment * - `body`: combination of all segments */ const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => { const newSegment = { ...segments[0] } segments.slice(1).forEach((segment) => { newSegment.endTime = segment.endTime newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime) newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator) }) return newSegment } /** * Type returned from combine functions */ type CombineResult = { /** * The updated segment with any changes applied */ segment: Segment /** * If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of * appending a new segment */ replace: boolean /** * Indicates if the combine rule was applied */ combined: boolean } /** * Checks if the new and prior segments have the same speaker. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker and combining body results in new body shorter than * max length * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH} * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSegments = ( newSegment: Segment, priorSegment: Segment, maxLength: number, lastSpeaker: string ): CombineResult => { if (priorSegment === undefined) { return { segment: newSegment, replace: false, combined: false, } } const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH if ( (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) && joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength ) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker, startTime and endTime. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with value of separator argument * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param separator string to use to combine body values. If undefined, uses "\n" * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineEqualTimes = ( newSegment: Segment, priorSegment: Segment, separator: string, lastSpeaker: string ): CombineResult => { const combineEqualTimesSeparator = separator || "\n" if ( newSegment.startTime === priorSegment.startTime && newSegment.endTime === priorSegment.endTime && (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) ) { return { segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from newSegment if different from priorSegment else undefined * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (priorSegment === undefined) { if (newSegment.speaker === lastSpeaker) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } if (newSegment.speaker === undefined) { return result } if ( newSegment.speaker === "" || newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker ) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } /** * Determine how {@link Options.speakerChange is applied based an past options being applied} * * @param currentResult current result object from any prior options * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const applyOptionsAndDoSpeakerChange = ( currentResult: CombineResult, priorSegment: Segment, lastSpeaker: string ): CombineResult => {
const { combineSegments, combineEqualTimes } = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined) } else if (combineEqualTimes) { if (result.combined && result.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } if (result) { result = { segment: result.segment, replace: currentResult.replace || result.replace, combined: currentResult.combined || result.combined, } } return result } /** * Apply convert rules when no prior segment exits. * * NOTE: not all rules applicable when no prior segment * * @param newSegment segment before any rules options to it * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => { const { speakerChange } = Options let result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (speakerChange) { result = doSpeakerChange(result.segment, undefined, lastSpeaker) } return result } /** * Apply convert rules when prior segment exits. * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const { combineEqualTimes, combineEqualTimesSeparator, combineSegments, combineSegmentsLength, combineSpeaker, speakerChange, } = Options let result: CombineResult = { segment: { ...newSegment }, replace: false, combined: false, } let combinedSpeaker = false if (combineSpeaker) { result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker) combinedSpeaker = result.combined } if (!combinedSpeaker && combineEqualTimes) { result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker) } if (!combinedSpeaker && combineSegments) { let combineResult if (combineEqualTimes && result.combined) { combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker) } else { combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker) } if (combineResult) { result = { segment: combineResult.segment, replace: result.replace || combineResult.replace, combined: result.combined || combineResult.combined, } } } if (speakerChange) { result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker) } return result } /** * Apply any options to the current segment * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => { if (!Options.optionsSet()) { return { segment: newSegment, replace: false, combined: false, } } let result: CombineResult // if no prior segment, limited additional checking if (priorSegment === undefined) { result = doCombineNoPrior(newSegment, lastSpeaker) } else { result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker) } return result } /** * Get the last speaker name from the previously parsed segments * * @param priorSegment prior parsed segment * @param priorSegments array of all previous segments * @returns the name of the last speaker */ const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => { let lastSpeaker if (priorSegment) { lastSpeaker = priorSegment.speaker } if (lastSpeaker === undefined && priorSegments.length > 0) { lastSpeaker = priorSegments[0].speaker for (let i = priorSegments.length - 1; i > 0; i--) { if (priorSegments[i].speaker !== undefined) { lastSpeaker = priorSegments[i].speaker break } } } return lastSpeaker } /** * Helper for adding segment to or updating last segment in array of segments * * @param newSegment segment to add or replace * @param priorSegments array of all previous segments * @returns updated array of segments with new segment added or last segment updated (per options) */ export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => { const { speakerChange } = Options const outSegments = priorSegments || [] const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined // don't worry about identifying the last speaker if speaker is not being removed by speakerChange let lastSpeaker: string if (speakerChange) { lastSpeaker = getLastSpeaker(priorSegment, outSegments) } const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker) if (newSegmentInfo.replace && outSegments.length > 0) { outSegments[outSegments.length - 1] = newSegmentInfo.segment } else { outSegments.push(newSegmentInfo.segment) } return outSegments }
src/segments.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/options.ts", "retrieved_chunk": " public optionsSet = (): boolean => {\n const { combineEqualTimes, combineSegments, combineSpeaker, speakerChange } = this\n return combineEqualTimes || combineSegments || combineSpeaker || speakerChange\n }\n}\nexport const Options = new OptionsManager()", "score": 0.8641073107719421 }, { "filename": "src/options.ts", "retrieved_chunk": " public getOptionByName = (name: string): boolean | string | number => {\n let actual\n switch (name) {\n case \"combineEqualTimes\":\n actual = this.combineEqualTimes\n break\n case \"combineEqualTimesSeparator\":\n actual = this.combineEqualTimesSeparator\n break\n case \"combineSegments\":", "score": 0.8178215622901917 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " * @returns Updated HTML Segment part and segment data for next segment (if fields encountered)\n */\nconst updateSegmentPartFromElement = (\n element: HTMLElement,\n segmentPart: HTMLSegmentPart\n): {\n current: HTMLSegmentPart\n next: HTMLSegmentPart\n} => {\n const currentSegmentPart = segmentPart", "score": 0.8175160884857178 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {\n const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker\n const startTime = parseTimestamp(segmentPart.time)\n return {\n startTime,\n startTimeFormatted: TimestampFormatter.format(startTime),\n endTime: 0,", "score": 0.816723108291626 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " Object.keys(nextSegmentPart).filter((x) => nextSegmentPart[x] === \"\").length !== 3\n ) {\n // time is required\n if (segmentPart.time === \"\") {\n console.warn(`Segment ${count} does not contain time information, ignoring`)\n } else {\n const segment = createSegmentFromSegmentPart(segmentPart, lastSpeaker)\n lastSpeaker = segment.speaker\n // update endTime of previous Segment\n const totalSegments = outSegments.length", "score": 0.816576361656189 } ]
typescript
const { combineSegments, combineEqualTimes } = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) {
import { pascalCase } from 'change-case' import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application' export const BARE_CALL = Symbol('bare') export type MethodIdentifier = string | typeof BARE_CALL export type MethodList = Array<MethodIdentifier> export type CallConfigSummary = { createMethods: MethodList callMethods: MethodList deleteMethods: MethodList updateMethods: MethodList optInMethods: MethodList closeOutMethods: MethodList } export const getCallConfigSummary = (app: AlgoAppSpec) => { const result: CallConfigSummary = { createMethods: [], callMethods: [], deleteMethods: [], updateMethods: [], optInMethods: [], closeOutMethods: [], } if (app.bare_call_config) { addToConfig(result, BARE_CALL, app.bare_call_config) } if (app.hints) { for (const [method, hints] of Object.entries(app.hints)) { if (hints.call_config) { addToConfig(result, method, hints.call_config) } } } return result } export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => { const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config if (!callConfig) { return '' } const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE' return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }` } const getCreateOnCompleteTypes = (config: CallConfig) => { return Object.keys(config) .map((oc) => oc as keyof CallConfig) .filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE')
.map((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') }
const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => { if (hasCall(config.no_op)) { result.callMethods.push(method) } if ( hasCreate(config.no_op) || hasCreate(config.opt_in) || hasCreate(config.close_out) || hasCreate(config.update_application) || hasCreate(config.delete_application) ) { result.createMethods.push(method) } if (hasCall(config.delete_application)) { result.deleteMethods.push(method) } if (hasCall(config.update_application)) { result.updateMethods.push(method) } if (hasCall(config.opt_in)) { result.optInMethods.push(method) } if (hasCall(config.close_out)) { result.closeOutMethods.push(method) } } const hasCall = (config: CallConfigValue | undefined) => { return config === 'CALL' || config === 'ALL' } const hasCreate = (config: CallConfigValue | undefined) => { return config === 'CREATE' || config === 'ALL' }
src/client/helpers/get-call-config-summary.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " ? `(${Object.entries(callConfig)\n .filter(([_, value]) => value === 'ALL' || value === 'CREATE')\n .map(([oc]) => OnCompleteCodeMap[oc as keyof CallConfig])\n .join(' | ')})`\n : {}\n return {\n type: onCompleteType,\n isOptional: hasNoOp,\n }\n}", "score": 0.8623319864273071 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)", "score": 0.7673401236534119 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig", "score": 0.7541170120239258 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " if (method === BARE_CALL) {\n yield `| (TypedCallParams<undefined> & ${onComplete.type})`\n } else {\n yield `| (TypedCallParams<'${method}'> & ${onComplete.type})`\n }\n }\n yield DecIndent\n }\n if (callConfig.updateMethods.length > 0) {\n yield* jsDoc(`A factory for available 'update' calls`)", "score": 0.748624324798584 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${", "score": 0.7481231689453125 } ]
typescript
.map((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') }
import { Options } from "./options" import { TimestampFormatter } from "./timestamp" import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types" /** * Regular Expression for detecting punctuation that should not be prefixed with a space */ const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/ /** * Regular Expression for detecting space characters at the end of a string */ const PATTERN_TRAILING_SPACE = /^ *$/ /** * Remove any trailing space characters from data * * @param data text to trim * @returns text with any trailing space character removed */ const trimEndSpace = (data: string): string => { return data.replace(PATTERN_TRAILING_SPACE, "") } /** * Append `addition` to `body` with the character(s) specified. * * If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data. * * @param body Current body text * @param addition Additional text to add to `body` * @param separator Character(s) to use to separate data. If undefined, uses `\n`. * @returns Combined data */ const joinBody = (body: string, addition: string, separator: string = undefined): string => { if (body) { let separatorToUse = separator || "\n" if (PATTERN_PUNCTUATIONS.exec(addition)) { separatorToUse = "" } return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}` } return trimEndSpace(addition) } /** * Combine one or more {@link Segment} * * @param segments Array of Segment objects to combine * @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`. * @returns Combined segment where: * * - `startTime`: from first segment * - `startTimeFormatted`: from first segment * - `endTime`: from last segment * - `endTimeFormatted`: from last segment * - `speaker`: from first segment * - `body`: combination of all segments */ const joinSegments =
(segments: Array<Segment>, bodySeparator: string = undefined): Segment => {
const newSegment = { ...segments[0] } segments.slice(1).forEach((segment) => { newSegment.endTime = segment.endTime newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime) newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator) }) return newSegment } /** * Type returned from combine functions */ type CombineResult = { /** * The updated segment with any changes applied */ segment: Segment /** * If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of * appending a new segment */ replace: boolean /** * Indicates if the combine rule was applied */ combined: boolean } /** * Checks if the new and prior segments have the same speaker. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker and combining body results in new body shorter than * max length * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH} * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSegments = ( newSegment: Segment, priorSegment: Segment, maxLength: number, lastSpeaker: string ): CombineResult => { if (priorSegment === undefined) { return { segment: newSegment, replace: false, combined: false, } } const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH if ( (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) && joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength ) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker, startTime and endTime. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with value of separator argument * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param separator string to use to combine body values. If undefined, uses "\n" * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineEqualTimes = ( newSegment: Segment, priorSegment: Segment, separator: string, lastSpeaker: string ): CombineResult => { const combineEqualTimesSeparator = separator || "\n" if ( newSegment.startTime === priorSegment.startTime && newSegment.endTime === priorSegment.endTime && (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) ) { return { segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from newSegment if different from priorSegment else undefined * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (priorSegment === undefined) { if (newSegment.speaker === lastSpeaker) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } if (newSegment.speaker === undefined) { return result } if ( newSegment.speaker === "" || newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker ) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } /** * Determine how {@link Options.speakerChange is applied based an past options being applied} * * @param currentResult current result object from any prior options * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const applyOptionsAndDoSpeakerChange = ( currentResult: CombineResult, priorSegment: Segment, lastSpeaker: string ): CombineResult => { const { combineSegments, combineEqualTimes } = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else if (combineEqualTimes) { if (result.combined && result.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } if (result) { result = { segment: result.segment, replace: currentResult.replace || result.replace, combined: currentResult.combined || result.combined, } } return result } /** * Apply convert rules when no prior segment exits. * * NOTE: not all rules applicable when no prior segment * * @param newSegment segment before any rules options to it * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => { const { speakerChange } = Options let result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (speakerChange) { result = doSpeakerChange(result.segment, undefined, lastSpeaker) } return result } /** * Apply convert rules when prior segment exits. * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const { combineEqualTimes, combineEqualTimesSeparator, combineSegments, combineSegmentsLength, combineSpeaker, speakerChange, } = Options let result: CombineResult = { segment: { ...newSegment }, replace: false, combined: false, } let combinedSpeaker = false if (combineSpeaker) { result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker) combinedSpeaker = result.combined } if (!combinedSpeaker && combineEqualTimes) { result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker) } if (!combinedSpeaker && combineSegments) { let combineResult if (combineEqualTimes && result.combined) { combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker) } else { combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker) } if (combineResult) { result = { segment: combineResult.segment, replace: result.replace || combineResult.replace, combined: result.combined || combineResult.combined, } } } if (speakerChange) { result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker) } return result } /** * Apply any options to the current segment * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => { if (!Options.optionsSet()) { return { segment: newSegment, replace: false, combined: false, } } let result: CombineResult // if no prior segment, limited additional checking if (priorSegment === undefined) { result = doCombineNoPrior(newSegment, lastSpeaker) } else { result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker) } return result } /** * Get the last speaker name from the previously parsed segments * * @param priorSegment prior parsed segment * @param priorSegments array of all previous segments * @returns the name of the last speaker */ const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => { let lastSpeaker if (priorSegment) { lastSpeaker = priorSegment.speaker } if (lastSpeaker === undefined && priorSegments.length > 0) { lastSpeaker = priorSegments[0].speaker for (let i = priorSegments.length - 1; i > 0; i--) { if (priorSegments[i].speaker !== undefined) { lastSpeaker = priorSegments[i].speaker break } } } return lastSpeaker } /** * Helper for adding segment to or updating last segment in array of segments * * @param newSegment segment to add or replace * @param priorSegments array of all previous segments * @returns updated array of segments with new segment added or last segment updated (per options) */ export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => { const { speakerChange } = Options const outSegments = priorSegments || [] const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined // don't worry about identifying the last speaker if speaker is not being removed by speakerChange let lastSpeaker: string if (speakerChange) { lastSpeaker = getLastSpeaker(priorSegment, outSegments) } const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker) if (newSegmentInfo.replace && outSegments.length > 0) { outSegments[outSegments.length - 1] = newSegmentInfo.segment } else { outSegments.push(newSegmentInfo.segment) } return outSegments }
src/segments.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/json.ts", "retrieved_chunk": " */\n startTime: number\n /**\n * Time (in seconds) when segment ends\n */\n endTime: number\n /**\n * Name of speaker for `body`\n */\n speaker?: string", "score": 0.8904497623443604 }, { "filename": "src/formats/srt.ts", "retrieved_chunk": "}\n/**\n * Create Segment from lines containing an SRT segment/cue\n *\n * @param segmentLines Lines containing SRT data\n * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => {\n const srtSegment = parseSRTSegment(segmentLines)", "score": 0.8842461705207825 }, { "filename": "src/types.ts", "retrieved_chunk": " endTime: number\n /**\n * Time when segment ends formatted as a string in the format HH:mm:SS.fff\n */\n endTimeFormatted: string\n /**\n * Name of speaker for `body`\n */\n speaker?: string\n /**", "score": 0.8698705434799194 }, { "filename": "src/types.ts", "retrieved_chunk": " * Time (in seconds) when segment starts\n */\n startTime: number\n /**\n * Time when segment starts formatted as a string in the format HH:mm:SS.fff\n */\n startTimeFormatted: string\n /**\n * Time (in seconds) when segment ends\n */", "score": 0.8691223859786987 }, { "filename": "src/options.ts", "retrieved_chunk": " */\n combineEqualTimesSeparator?: string\n /**\n * Combine segments where speaker is the same and concatenated `body` fits in the {@link combineSegmentsLength}\n *\n * Can be used with {@link combineEqualTimes}. The {@link combineSegments} rule is applied first.\n *\n * Can be used with {@link speakerChange}. The {@link speakerChange} rule is applied last.\n *\n * Cannot be used with {@link combineSpeaker}", "score": 0.8655099272727966 } ]
typescript
(segments: Array<Segment>, bodySeparator: string = undefined): Segment => {
import { Options } from "./options" import { TimestampFormatter } from "./timestamp" import { DEFAULT_COMBINE_SEGMENTS_LENGTH, Segment } from "./types" /** * Regular Expression for detecting punctuation that should not be prefixed with a space */ const PATTERN_PUNCTUATIONS = /^ *[.,?!}\]>) *$]/ /** * Regular Expression for detecting space characters at the end of a string */ const PATTERN_TRAILING_SPACE = /^ *$/ /** * Remove any trailing space characters from data * * @param data text to trim * @returns text with any trailing space character removed */ const trimEndSpace = (data: string): string => { return data.replace(PATTERN_TRAILING_SPACE, "") } /** * Append `addition` to `body` with the character(s) specified. * * If `addition` matches the {@link PATTERN_PUNCTUATIONS} pattern, no character is added before the additional data. * * @param body Current body text * @param addition Additional text to add to `body` * @param separator Character(s) to use to separate data. If undefined, uses `\n`. * @returns Combined data */ const joinBody = (body: string, addition: string, separator: string = undefined): string => { if (body) { let separatorToUse = separator || "\n" if (PATTERN_PUNCTUATIONS.exec(addition)) { separatorToUse = "" } return `${trimEndSpace(body)}${separatorToUse}${trimEndSpace(addition)}` } return trimEndSpace(addition) } /** * Combine one or more {@link Segment} * * @param segments Array of Segment objects to combine * @param bodySeparator Character(s) to use to separate body data. If undefined, uses `\n`. * @returns Combined segment where: * * - `startTime`: from first segment * - `startTimeFormatted`: from first segment * - `endTime`: from last segment * - `endTimeFormatted`: from last segment * - `speaker`: from first segment * - `body`: combination of all segments */ const joinSegments = (segments: Array<Segment>, bodySeparator: string = undefined): Segment => { const newSegment = { ...segments[0] } segments.slice(1).forEach((segment) => { newSegment.endTime = segment.endTime newSegment.endTimeFormatted = TimestampFormatter.format(segment.endTime) newSegment.body = joinBody(newSegment.body, segment.body, bodySeparator) }) return newSegment } /** * Type returned from combine functions */ type CombineResult = { /** * The updated segment with any changes applied */ segment: Segment /** * If true, the {@link segment} contains a {@link Segment} that should replace the prior segment instead of * appending a new segment */ replace: boolean /** * Indicates if the combine rule was applied */ combined: boolean } /** * Checks if the new and prior segments have the same speaker. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSpeaker = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { if (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker and combining body results in new body shorter than * max length * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param maxLength maximum allowed length of combined body. If undefined, uses {@link DEFAULT_COMBINE_SEGMENTS_LENGTH} * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineSegments = ( newSegment: Segment, priorSegment: Segment, maxLength: number, lastSpeaker: string ): CombineResult => { if (priorSegment === undefined) { return { segment: newSegment, replace: false, combined: false, } } const combineSegmentsLength = maxLength || DEFAULT_COMBINE_SEGMENTS_LENGTH if ( (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) && joinBody(priorSegment.body, newSegment.body, " ").length <= combineSegmentsLength ) { return { segment: joinSegments([priorSegment, newSegment], " "), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker, startTime and endTime. * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from priorSegment * - `body`: body of priorSegment with body of newSegment separated with value of separator argument * * @param newSegment segment being created * @param priorSegment prior parsed segment * @param separator string to use to combine body values. If undefined, uses "\n" * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} and {@link CombineResult.combined} set to true. */ const doCombineEqualTimes = ( newSegment: Segment, priorSegment: Segment, separator: string, lastSpeaker: string ): CombineResult => { const combineEqualTimesSeparator = separator || "\n" if ( newSegment.startTime === priorSegment.startTime && newSegment.endTime === priorSegment.endTime && (newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker) ) { return { segment: joinSegments([priorSegment, newSegment], combineEqualTimesSeparator), replace: true, combined: true, } } return { segment: newSegment, replace: false, combined: false, } } /** * Checks if the new and prior segments have the same speaker. If so, sets the speaker value to undefined * * If so, combines segments where: * - `startTime`: from priorSegment * - `startTimeFormatted`: from priorSegment * - `endTime`: from newSegment * - `endTimeFormatted`: from newSegment * - `speaker`: from newSegment if different from priorSegment else undefined * - `body`: body of priorSegment with body of newSegment separated with space * * @param newSegment segment being created * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const doSpeakerChange = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (priorSegment === undefined) { if (newSegment.speaker === lastSpeaker) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } if (newSegment.speaker === undefined) { return result } if ( newSegment.speaker === "" || newSegment.speaker === priorSegment.speaker || newSegment.speaker === lastSpeaker ) { const segment: Segment = { ...newSegment } segment.speaker = undefined return { segment, replace: false, combined: true, } } return result } /** * Determine how {@link Options.speakerChange is applied based an past options being applied} * * @param currentResult current result object from any prior options * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * @returns result of combination. * If segments were combined, {@link CombineResult.replace} set to false and {@link CombineResult.combined} set to true. */ const applyOptionsAndDoSpeakerChange = ( currentResult: CombineResult, priorSegment: Segment, lastSpeaker: string ): CombineResult => { const
{ combineSegments, combineEqualTimes } = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) {
result = doSpeakerChange(currentResult.segment, undefined, undefined) } else if (combineEqualTimes) { if (result.combined && result.replace) { result = doSpeakerChange(currentResult.segment, undefined, undefined) } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } } else { result = doSpeakerChange(currentResult.segment, priorSegment, lastSpeaker) } if (result) { result = { segment: result.segment, replace: currentResult.replace || result.replace, combined: currentResult.combined || result.combined, } } return result } /** * Apply convert rules when no prior segment exits. * * NOTE: not all rules applicable when no prior segment * * @param newSegment segment before any rules options to it * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineNoPrior = (newSegment: Segment, lastSpeaker: string): CombineResult => { const { speakerChange } = Options let result: CombineResult = { segment: newSegment, replace: false, combined: false, } if (speakerChange) { result = doSpeakerChange(result.segment, undefined, lastSpeaker) } return result } /** * Apply convert rules when prior segment exits. * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const doCombineWithPrior = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string): CombineResult => { const { combineEqualTimes, combineEqualTimesSeparator, combineSegments, combineSegmentsLength, combineSpeaker, speakerChange, } = Options let result: CombineResult = { segment: { ...newSegment }, replace: false, combined: false, } let combinedSpeaker = false if (combineSpeaker) { result = doCombineSpeaker(result.segment, priorSegment, lastSpeaker) combinedSpeaker = result.combined } if (!combinedSpeaker && combineEqualTimes) { result = doCombineEqualTimes(result.segment, priorSegment, combineEqualTimesSeparator, lastSpeaker) } if (!combinedSpeaker && combineSegments) { let combineResult if (combineEqualTimes && result.combined) { combineResult = doCombineSegments(result.segment, undefined, combineSegmentsLength, lastSpeaker) } else { combineResult = doCombineSegments(result.segment, priorSegment, combineSegmentsLength, lastSpeaker) } if (combineResult) { result = { segment: combineResult.segment, replace: result.replace || combineResult.replace, combined: result.combined || combineResult.combined, } } } if (speakerChange) { result = applyOptionsAndDoSpeakerChange(result, priorSegment, lastSpeaker) } return result } /** * Apply any options to the current segment * * @param newSegment segment before any rules options to it * @param priorSegment prior parsed segment. For the first segment, this shall be undefined. * @param lastSpeaker last speaker name. * Used when speaker in segment has been removed via {@link Options.speakerChange} rule * @returns the updated segment info */ const applyOptions = (newSegment: Segment, priorSegment: Segment, lastSpeaker: string = undefined): CombineResult => { if (!Options.optionsSet()) { return { segment: newSegment, replace: false, combined: false, } } let result: CombineResult // if no prior segment, limited additional checking if (priorSegment === undefined) { result = doCombineNoPrior(newSegment, lastSpeaker) } else { result = doCombineWithPrior(newSegment, priorSegment, lastSpeaker) } return result } /** * Get the last speaker name from the previously parsed segments * * @param priorSegment prior parsed segment * @param priorSegments array of all previous segments * @returns the name of the last speaker */ const getLastSpeaker = (priorSegment: Segment, priorSegments: Array<Segment>): string => { let lastSpeaker if (priorSegment) { lastSpeaker = priorSegment.speaker } if (lastSpeaker === undefined && priorSegments.length > 0) { lastSpeaker = priorSegments[0].speaker for (let i = priorSegments.length - 1; i > 0; i--) { if (priorSegments[i].speaker !== undefined) { lastSpeaker = priorSegments[i].speaker break } } } return lastSpeaker } /** * Helper for adding segment to or updating last segment in array of segments * * @param newSegment segment to add or replace * @param priorSegments array of all previous segments * @returns updated array of segments with new segment added or last segment updated (per options) */ export const addSegment = (newSegment: Segment, priorSegments: Array<Segment>): Array<Segment> => { const { speakerChange } = Options const outSegments = priorSegments || [] const priorSegment = outSegments.length > 0 ? outSegments[outSegments.length - 1] : undefined // don't worry about identifying the last speaker if speaker is not being removed by speakerChange let lastSpeaker: string if (speakerChange) { lastSpeaker = getLastSpeaker(priorSegment, outSegments) } const newSegmentInfo = applyOptions(newSegment, priorSegment, lastSpeaker) if (newSegmentInfo.replace && outSegments.length > 0) { outSegments[outSegments.length - 1] = newSegmentInfo.segment } else { outSegments.push(newSegmentInfo.segment) } return outSegments }
src/segments.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/options.ts", "retrieved_chunk": " public optionsSet = (): boolean => {\n const { combineEqualTimes, combineSegments, combineSpeaker, speakerChange } = this\n return combineEqualTimes || combineSegments || combineSpeaker || speakerChange\n }\n}\nexport const Options = new OptionsManager()", "score": 0.8734367489814758 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " * @returns Updated HTML Segment part and segment data for next segment (if fields encountered)\n */\nconst updateSegmentPartFromElement = (\n element: HTMLElement,\n segmentPart: HTMLSegmentPart\n): {\n current: HTMLSegmentPart\n next: HTMLSegmentPart\n} => {\n const currentSegmentPart = segmentPart", "score": 0.837794303894043 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines`\n * @returns Created segment\n */\nconst createSegmentFromSegmentPart = (segmentPart: HTMLSegmentPart, lastSpeaker: string): Segment => {\n const calculatedSpeaker = segmentPart.cite ? segmentPart.cite : lastSpeaker\n const startTime = parseTimestamp(segmentPart.time)\n return {\n startTime,\n startTimeFormatted: TimestampFormatter.format(startTime),\n endTime: 0,", "score": 0.8293864727020264 }, { "filename": "src/formats/html.ts", "retrieved_chunk": " */\nconst getSegmentsFromHTMLElements = (elements: Array<HTMLElement>): Array<Segment> => {\n let outSegments: Array<Segment> = []\n let lastSpeaker = \"\"\n let segmentPart: HTMLSegmentPart = {\n cite: \"\",\n time: \"\",\n text: \"\",\n }\n let nextSegmentPart: HTMLSegmentPart = {", "score": 0.8233482837677002 }, { "filename": "src/options.ts", "retrieved_chunk": " public getOptionByName = (name: string): boolean | string | number => {\n let actual\n switch (name) {\n case \"combineEqualTimes\":\n actual = this.combineEqualTimes\n break\n case \"combineEqualTimesSeparator\":\n actual = this.combineEqualTimesSeparator\n break\n case \"combineSegments\":", "score": 0.8228318691253662 } ]
typescript
{ combineSegments, combineEqualTimes } = Options let result = currentResult if (combineSegments && currentResult.combined && currentResult.replace) {
import { addSegment } from "../segments" import { parseSpeaker } from "../speaker" import { parseTimestamp, TimestampFormatter } from "../timestamp" import { PATTERN_LINE_SEPARATOR, Segment } from "../types" /** * Define a segment/cue parsed from SRT file */ export type SRTSegment = { /** * Cue number */ index: number /** * Time (in seconds) when segment starts */ startTime: number /** * Time (in seconds) when segment ends */ endTime: number /** * Name of speaker for `body` */ speaker: string /** * Text of transcript for segment */ body: string } /** * Parse lines looking for data to be SRT format * * @param lines Lines containing SRT data * @returns Parsed segment * @throws {Error} When no non-empty strings in `lines` * @throws {Error} When the minimum required number of lines is not received * @throws {Error} When segment lines does not start with a number * @throws {Error} When second segment line does not follow the timestamp format */ export const parseSRTSegment = (lines: Array<string>): SRTSegment => { do { if (lines.length === 0) { throw new Error("SRT segment lines empty") } else if (lines[0].trim() === "") { lines.shift() } else { break } } while (lines.length > 0) if (lines.length < 3) { throw new Error(`SRT requires at least 3 lines, ${lines.length} received`) } const index = parseInt(lines[0], 10) if (!index) { throw new Error(`First line of SRT segment is not a number`) } const timestampLine = lines[1] if (!timestampLine.includes("-->")) { throw new Error(`SRT timestamp line does not include --> separator`) } const timestampParts = timestampLine.split("-->") if (timestampParts.length !== 2) { throw new Error(`SRT timestamp line contains more than 2 --> separators`) } const startTime = parseTimestamp(timestampParts[0].trim()) const endTime = parseTimestamp(timestampParts[1].trim()) let bodyLines = lines.slice(2) const emptyLineIndex = bodyLines.findIndex((v) => v.trim() === "") if (emptyLineIndex > 0) { bodyLines = bodyLines.slice(0, emptyLineIndex) } const { speaker, message } = parseSpeaker(bodyLines.shift()) bodyLines = [message].concat(bodyLines) return { startTime, endTime, speaker, body: bodyLines.join("\n"), index, } } /** * Create Segment from lines containing an SRT segment/cue * * @param segmentLines Lines containing SRT data * @param lastSpeaker Name of last speaker. Will be used if no speaker found in `segmentLines` * @returns Created segment */ const createSegmentFromSRTLines = (segmentLines: Array<string>, lastSpeaker: string): Segment => { const srtSegment = parseSRTSegment(segmentLines) const calculatedSpeaker = srtSegment.speaker ? srtSegment.speaker : lastSpeaker return { startTime: srtSegment.startTime, startTimeFormatted: TimestampFormatter.format(srtSegment.startTime), endTime: srtSegment.endTime, endTimeFormatted: TimestampFormatter.format(srtSegment.endTime), speaker: calculatedSpeaker, body: srtSegment.body, } } /** * Determines if the value of data is a valid SRT transcript format * * @param data The transcript data * @returns True: data is valid SRT transcript format */ export const isSRT = (data: string): boolean => { try { return parseSRTSegment(data
.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined } catch (e) {
return false } } /** * Parse SRT data to an Array of {@link Segment} * * @param data The transcript data * @returns An array of Segments from the parsed data * @throws {TypeError} When `data` is not valid SRT format */ export const parseSRT = (data: string): Array<Segment> => { if (!isSRT(data)) { throw new TypeError(`Data is not valid SRT format`) } let outSegments: Array<Segment> = [] let lastSpeaker = "" let segmentLines = [] data.split(PATTERN_LINE_SEPARATOR).forEach((line, count) => { // separator line found, handle previous data if (line.trim() === "") { // handle consecutive multiple blank lines if (segmentLines.length !== 0) { try { outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments) lastSpeaker = outSegments[outSegments.length - 1].speaker } catch (e) { console.error(`Error parsing SRT segment lines (source line ${count}): ${e}`) console.error(segmentLines) } } segmentLines = [] // clear buffer } else { segmentLines.push(line) } }) // handle data when trailing line not included if (segmentLines.length !== 0) { try { outSegments = addSegment(createSegmentFromSRTLines(segmentLines, lastSpeaker), outSegments) lastSpeaker = outSegments[outSegments.length - 1].speaker } catch (e) { console.error(`Error parsing final SRT segment lines: ${e}`) console.error(segmentLines) } } return outSegments }
src/formats/srt.ts
stevencrader-transcriptator-75faa70
[ { "filename": "src/formats/vtt.ts", "retrieved_chunk": " * @returns True: data is valid VTT transcript format\n */\nexport const isVTT = (data: string): boolean => {\n return data.startsWith(\"WEBVTT\")\n}\n/**\n * Parse VTT data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data", "score": 0.9346697330474854 }, { "filename": "src/formats/html.ts", "retrieved_chunk": "}\n/**\n * Determines if the value of data is a valid HTML transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid HTML transcript format\n */\nexport const isHTML = (data: string): boolean => {\n return (\n data.startsWith(\"<!--\") ||", "score": 0.9202126264572144 }, { "filename": "src/index.ts", "retrieved_chunk": " *\n * @param data The transcript data\n * @returns The determined transcript format\n * @throws {TypeError} Cannot determine format of data or error parsing data\n */\nexport const determineFormat = (data: string): TranscriptFormat => {\n const normalizedData = data.trim()\n if (isVTT(normalizedData)) {\n return TranscriptFormat.VTT\n }", "score": 0.9063345193862915 }, { "filename": "src/formats/json.ts", "retrieved_chunk": "/**\n * Parse JSON data to an Array of {@link Segment}\n *\n * @param data The transcript data\n * @returns An array of Segments from the parsed data\n * @throws {TypeError} When `data` is not valid JSON format\n */\nexport const parseJSON = (data: string): Array<Segment> => {\n const dataTrimmed = data.trim()\n let outSegments: Array<Segment> = []", "score": 0.900697648525238 }, { "filename": "src/formats/json.ts", "retrieved_chunk": " /**\n * Text of transcript for segment\n */\n text: string\n}\n/**\n * Determines if the value of data is a valid JSON transcript format\n *\n * @param data The transcript data\n * @returns True: data is valid JSON transcript format", "score": 0.8987265229225159 } ]
typescript
.split(PATTERN_LINE_SEPARATOR).slice(0, 20)) !== undefined } catch (e) {
import { ContractMethod } from '../schema/application' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer' import { isSafeVariableIdentifier, makeSafeMethodIdentifier, makeSafePropertyIdentifier } from '../util/sanitization' import * as algokit from '@algorandfoundation/algokit-utils' import { GeneratorContext } from './generator-context' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { getCreateOnCompleteOptions } from './deploy-types' export function* callFactory(ctx: GeneratorContext): DocumentParts { yield* jsDoc('Exposes methods for constructing all available smart contract calls') yield `export abstract class ${ctx.name}CallFactory {` yield IncIndent yield* opMethods(ctx) for (const method of ctx.app.contract.methods) { yield* callFactoryMethod(ctx, method) } yield DecIndent yield '}' } function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig } = ctx yield* operationMethod( ctx, `Constructs a create call for the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true, ) yield* operationMethod( ctx, `Constructs an update call for the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Constructs a delete call for the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod(ctx, `Constructs an opt in call for the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn') yield* operationMethod( ctx, `Constructs a close out call for the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} call factories`) yield `static get ${verb}() {` yield IncIndent yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call`, params: { params: `Any parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: true, name: 'bare', paramTypes: `BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs${ includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`, }) } else { const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)! const uniqueName = methodSignatureToUniqueName[methodSig] yield* jsDoc({ description: `${description} using the ${methodSig} ABI method`, params: { args: `Any args for the contract call`, params: `Any additional parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: true, name: makeSafeMethodIdentifier(uniqueName), signature: methodSig, args: method.args, paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${ onComplete?.type ? ` & ${onComplete.type}` : '' }${onComplete?.isOptional !== false ? ' = {}' : ''}`, }) } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) { const methodSignature = algokit.getABIMethodSignature(method) if (!callConfig.callMethods.includes(methodSignature)) return yield* jsDoc({ description: `Constructs a no op call for the ${methodSignature} ABI method`,
abiDescription: method.desc, params: {
args: `Any args for the contract call`, params: `Any additional parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: false, name: makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]), signature: methodSignature, args: method.args, paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs', }) } function* factoryMethod({ isNested, name, signature, args, paramTypes, }: | { isNested: boolean name?: string signature?: undefined args?: undefined paramTypes: string } | { isNested: boolean name?: string signature: string args: Array<{ name: string }> paramTypes: string }) { yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {` yield IncIndent yield `return {` yield IncIndent if (signature) { yield `method: '${signature}' as const,` yield `methodArgs: Array.isArray(args) ? args : [${args .map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`)) .join(', ')}],` } else { yield `method: undefined,` yield `methodArgs: undefined,` } yield '...params,' yield DecIndent yield '}' yield DecIndent yield `}${isNested ? ',' : ''}` }
src/client/call-factory.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-client.ts", "retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,", "score": 0.9372422695159912 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, undefined]>`\n yield NewLine\n}\nfunction* callComposerTypeNoops({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config", "score": 0.9025052785873413 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method.`,\n params: {\n args: `The arguments for the smart contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The ${verb} result${method?.returns?.desc ? `: ${method.returns.desc}` : ''}`,\n })\n yield `async ${makeSafeMethodIdentifier(uniqueName)}(args: MethodArgs<'${methodSig}'>, params: AppClientCallCoreParams${", "score": 0.8525069952011108 }, { "filename": "src/client/generator-context.ts", "retrieved_chunk": "export const createGeneratorContext = (app: AlgoAppSpec) => ({\n app,\n name: makeSafeTypeIdentifier(app.contract.name),\n callConfig: getCallConfigSummary(app),\n methodSignatureToUniqueName: app.contract.methods.reduce((acc, cur) => {\n const signature = algokit.getABIMethodSignature(cur)\n acc[signature] = app.contract.methods.some((m) => m.name === cur.name && m !== cur) ? signature : cur.name\n return acc\n }, {} as Record<string, string>),\n})", "score": 0.8515468835830688 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,\n params: {\n args: `The arguments for the contract call`,\n params: `Any additional parameters for the call`,\n },\n returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })", "score": 0.8513742685317993 } ]
typescript
abiDescription: method.desc, params: {
import { pascalCase } from 'change-case' import { AlgoAppSpec, CallConfig, CallConfigValue } from '../../schema/application' export const BARE_CALL = Symbol('bare') export type MethodIdentifier = string | typeof BARE_CALL export type MethodList = Array<MethodIdentifier> export type CallConfigSummary = { createMethods: MethodList callMethods: MethodList deleteMethods: MethodList updateMethods: MethodList optInMethods: MethodList closeOutMethods: MethodList } export const getCallConfigSummary = (app: AlgoAppSpec) => { const result: CallConfigSummary = { createMethods: [], callMethods: [], deleteMethods: [], updateMethods: [], optInMethods: [], closeOutMethods: [], } if (app.bare_call_config) { addToConfig(result, BARE_CALL, app.bare_call_config) } if (app.hints) { for (const [method, hints] of Object.entries(app.hints)) { if (hints.call_config) { addToConfig(result, method, hints.call_config) } } } return result } export const getCreateOnComplete = (app: AlgoAppSpec, method: MethodIdentifier) => { const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config if (!callConfig) { return '' } const hasNoOp = callConfig.no_op === 'ALL' || callConfig.no_op === 'CREATE' return `{ onCompleteAction${hasNoOp ? '?' : ''}: ${getCreateOnCompleteTypes(callConfig)} }` } const getCreateOnCompleteTypes =
(config: CallConfig) => {
return Object.keys(config) .map((oc) => oc as keyof CallConfig) .filter((oc) => config[oc] === 'ALL' || config[oc] === 'CREATE') .map((oc) => `'${oc}' | OnApplicationComplete.${pascalCase(oc)}OC`) .join(' | ') } const addToConfig = (result: CallConfigSummary, method: MethodIdentifier, config: CallConfig) => { if (hasCall(config.no_op)) { result.callMethods.push(method) } if ( hasCreate(config.no_op) || hasCreate(config.opt_in) || hasCreate(config.close_out) || hasCreate(config.update_application) || hasCreate(config.delete_application) ) { result.createMethods.push(method) } if (hasCall(config.delete_application)) { result.deleteMethods.push(method) } if (hasCall(config.update_application)) { result.updateMethods.push(method) } if (hasCall(config.opt_in)) { result.optInMethods.push(method) } if (hasCall(config.close_out)) { result.closeOutMethods.push(method) } } const hasCall = (config: CallConfigValue | undefined) => { return config === 'CALL' || config === 'ALL' } const hasCreate = (config: CallConfigValue | undefined) => { return config === 'CREATE' || config === 'ALL' }
src/client/helpers/get-call-config-summary.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer'\nimport { makeSafeTypeIdentifier } from '../util/sanitization'\nimport { BARE_CALL, MethodIdentifier } from './helpers/get-call-config-summary'\nimport { GeneratorContext } from './generator-context'\nimport { AlgoAppSpec, CallConfig } from '../schema/application'\nimport { OnCompleteCodeMap } from './utility-types'\nexport function getCreateOnCompleteOptions(method: MethodIdentifier, app: AlgoAppSpec) {\n const callConfig = method === BARE_CALL ? app.bare_call_config : app.hints?.[method]?.call_config\n const hasNoOp = callConfig?.no_op === 'ALL' || callConfig?.no_op === 'CREATE'\n const onCompleteType = callConfig", "score": 0.8597382307052612 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, undefined]>`\n yield NewLine\n}\nfunction* callComposerTypeNoops({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config", "score": 0.831175684928894 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": "export function* deployTypes({ app, callConfig }: GeneratorContext): DocumentParts {\n const name = makeSafeTypeIdentifier(app.contract.name)\n if (callConfig.createMethods.length > 0) {\n yield* jsDoc(`A factory for available 'create' calls`)\n yield `export type ${name}CreateCalls = (typeof ${name}CallFactory)['create']`\n yield* jsDoc('Defines supported create methods for this smart contract')\n yield `export type ${name}CreateCallParams =`\n yield IncIndent\n for (const method of callConfig.createMethods) {\n const onComplete = getCreateOnCompleteOptions(method, app)", "score": 0.8280135989189148 }, { "filename": "src/client/call-composer.ts", "retrieved_chunk": " if (methods.length) {\n yield `get ${verb}() {`\n yield IncIndent\n yield `const $this = this`\n yield `return {`\n yield IncIndent\n for (const methodSig of methods) {\n const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined\n if (methodSig === BARE_CALL) {\n yield `bare(args${onComplete?.isOptional !== false ? '?' : ''}: BareCallArgs & AppClientCallCoreParams ${", "score": 0.8245471715927124 }, { "filename": "src/client/call-factory.ts", "retrieved_chunk": " includeCompilation ? ' & AppClientCompilationParams' : ''\n }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`,\n })\n } else {\n const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)!\n const uniqueName = methodSignatureToUniqueName[methodSig]\n yield* jsDoc({\n description: `${description} using the ${methodSig} ABI method`,\n params: {\n args: `Any args for the contract call`,", "score": 0.813549280166626 } ]
typescript
(config: CallConfig) => {
import { ContractMethod } from '../schema/application' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer' import { isSafeVariableIdentifier, makeSafeMethodIdentifier, makeSafePropertyIdentifier } from '../util/sanitization' import * as algokit from '@algorandfoundation/algokit-utils' import { GeneratorContext } from './generator-context' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { getCreateOnCompleteOptions } from './deploy-types' export function* callFactory(ctx: GeneratorContext): DocumentParts { yield* jsDoc('Exposes methods for constructing all available smart contract calls') yield `export abstract class ${ctx.name}CallFactory {` yield IncIndent yield* opMethods(ctx) for (const method of ctx.app.contract.methods) { yield* callFactoryMethod(ctx, method) } yield DecIndent yield '}' } function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig } = ctx yield* operationMethod( ctx, `Constructs a create call for the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true, ) yield* operationMethod( ctx, `Constructs an update call for the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Constructs a delete call for the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod(ctx, `Constructs an opt in call for the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn') yield* operationMethod( ctx, `Constructs a close out call for the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} call factories`) yield `static get ${verb}() {` yield IncIndent yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call`, params: { params: `Any parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: true, name: 'bare', paramTypes: `BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs${ includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`, }) } else { const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)! const uniqueName = methodSignatureToUniqueName[methodSig] yield* jsDoc({ description: `${description} using the ${methodSig} ABI method`, params: { args: `Any args for the contract call`, params: `Any additional parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: true, name: makeSafeMethodIdentifier(uniqueName), signature: methodSig, args: method.args, paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${ onComplete?.type ? ` & ${onComplete.type}` : '' }${onComplete?.isOptional !== false ? ' = {}' : ''}`, }) } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) { const
methodSignature = algokit.getABIMethodSignature(method) if (!callConfig.callMethods.includes(methodSignature)) return yield* jsDoc({
description: `Constructs a no op call for the ${methodSignature} ABI method`, abiDescription: method.desc, params: { args: `Any args for the contract call`, params: `Any additional parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: false, name: makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]), signature: methodSignature, args: method.args, paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs', }) } function* factoryMethod({ isNested, name, signature, args, paramTypes, }: | { isNested: boolean name?: string signature?: undefined args?: undefined paramTypes: string } | { isNested: boolean name?: string signature: string args: Array<{ name: string }> paramTypes: string }) { yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {` yield IncIndent yield `return {` yield IncIndent if (signature) { yield `method: '${signature}' as const,` yield `methodArgs: Array.isArray(args) ? args : [${args .map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`)) .join(', ')}],` } else { yield `method: undefined,` yield `methodArgs: undefined,` } yield '...params,' yield DecIndent yield '}' yield DecIndent yield `}${isNested ? ',' : ''}` }
src/client/call-factory.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, undefined]>`\n yield NewLine\n}\nfunction* callComposerTypeNoops({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config", "score": 0.8895571231842041 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,", "score": 0.884052038192749 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " yield* operationMethod(\n ctx,\n `Makes a close out call to an existing instance of the ${app.contract.name} smart contract`,\n callConfig.closeOutMethods,\n 'closeOut',\n )\n}\nfunction* operationMethod(\n { app, methodSignatureToUniqueName, name }: GeneratorContext,\n description: string,", "score": 0.8390679359436035 }, { "filename": "src/client/deploy-types.ts", "retrieved_chunk": " if (callConfig.deleteMethods.length) {\n yield* jsDoc('A delegate which takes a delete call factory and returns the delete call params for this smart contract')\n yield `deleteCall?: (callFactory: ${name}DeleteCalls) => ${name}DeleteCallParams`\n }\n yield DecIndentAndCloseBlock\n yield NewLine\n}", "score": 0.8351424336433411 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " }\n }\n yield DecIndentAndCloseBlock\n yield DecIndentAndCloseBlock\n yield NewLine\n }\n}\nfunction* clearState({ app }: GeneratorContext): DocumentParts {\n yield* jsDoc({\n description: `Makes a clear_state call to an existing instance of the ${app.contract.name} smart contract.`,", "score": 0.8302486538887024 } ]
typescript
methodSignature = algokit.getABIMethodSignature(method) if (!callConfig.callMethods.includes(methodSignature)) return yield* jsDoc({
import { ContractMethod } from '../schema/application' import { DecIndent, DecIndentAndCloseBlock, DocumentParts, IncIndent, jsDoc, NewLine } from '../output/writer' import { isSafeVariableIdentifier, makeSafeMethodIdentifier, makeSafePropertyIdentifier } from '../util/sanitization' import * as algokit from '@algorandfoundation/algokit-utils' import { GeneratorContext } from './generator-context' import { BARE_CALL, MethodList } from './helpers/get-call-config-summary' import { getCreateOnCompleteOptions } from './deploy-types' export function* callFactory(ctx: GeneratorContext): DocumentParts { yield* jsDoc('Exposes methods for constructing all available smart contract calls') yield `export abstract class ${ctx.name}CallFactory {` yield IncIndent yield* opMethods(ctx) for (const method of ctx.app.contract.methods) { yield* callFactoryMethod(ctx, method) } yield DecIndent yield '}' } function* opMethods(ctx: GeneratorContext): DocumentParts { const { app, callConfig } = ctx yield* operationMethod( ctx, `Constructs a create call for the ${app.contract.name} smart contract`, callConfig.createMethods, 'create', true, ) yield* operationMethod( ctx, `Constructs an update call for the ${app.contract.name} smart contract`, callConfig.updateMethods, 'update', true, ) yield* operationMethod(ctx, `Constructs a delete call for the ${app.contract.name} smart contract`, callConfig.deleteMethods, 'delete') yield* operationMethod(ctx, `Constructs an opt in call for the ${app.contract.name} smart contract`, callConfig.optInMethods, 'optIn') yield* operationMethod( ctx, `Constructs a close out call for the ${app.contract.name} smart contract`, callConfig.closeOutMethods, 'closeOut', ) } function* operationMethod( { app, methodSignatureToUniqueName }: GeneratorContext, description: string, methods: MethodList, verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete', includeCompilation?: boolean, ): DocumentParts { if (methods.length) { yield* jsDoc(`Gets available ${verb} call factories`) yield `static get ${verb}() {` yield IncIndent yield `return {` yield IncIndent for (const methodSig of methods) { const onComplete = verb === 'create' ? getCreateOnCompleteOptions(methodSig, app) : undefined if (methodSig === BARE_CALL) { yield* jsDoc({ description: `${description} using a bare call`, params: { params: `Any parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: true, name: 'bare', paramTypes: `BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs${ includeCompilation ? ' & AppClientCompilationParams' : '' }${onComplete?.type ? ` & ${onComplete.type}` : ''}${onComplete?.isOptional !== false ? ' = {}' : ''}`, }) } else { const method = app.contract.methods.find((m) => algokit.getABIMethodSignature(m) === methodSig)! const uniqueName = methodSignatureToUniqueName[methodSig] yield* jsDoc({ description: `${description} using the ${methodSig} ABI method`, params: { args: `Any args for the contract call`, params: `Any additional parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: true, name: makeSafeMethodIdentifier(uniqueName), signature: methodSig, args: method.args, paramTypes: `AppClientCallCoreParams & CoreAppCallArgs${includeCompilation ? ' & AppClientCompilationParams' : ''}${ onComplete?.type ? ` & ${onComplete.type}` : '' }${onComplete?.isOptional !== false ? ' = {}' : ''}`, }) } } yield DecIndentAndCloseBlock yield DecIndentAndCloseBlock yield NewLine } } function* callFactoryMethod({ methodSignatureToUniqueName, callConfig }: GeneratorContext, method: ContractMethod) { const methodSignature = algokit.getABIMethodSignature(method) if (!callConfig.callMethods.includes(methodSignature)) return yield* jsDoc({ description: `Constructs a no op call for the ${methodSignature} ABI method`, abiDescription: method.desc, params: { args: `Any args for the contract call`, params: `Any additional parameters for the call`, }, returns: `A TypedCallParams object for the call`, }) yield* factoryMethod({ isNested: false, name: makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature]), signature: methodSignature, args
: method.args, paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs', }) }
function* factoryMethod({ isNested, name, signature, args, paramTypes, }: | { isNested: boolean name?: string signature?: undefined args?: undefined paramTypes: string } | { isNested: boolean name?: string signature: string args: Array<{ name: string }> paramTypes: string }) { yield `${isNested ? '' : 'static '}${name}(${signature === undefined ? '' : `args: MethodArgs<'${signature}'>, `}params: ${paramTypes}) {` yield IncIndent yield `return {` yield IncIndent if (signature) { yield `method: '${signature}' as const,` yield `methodArgs: Array.isArray(args) ? args : [${args .map((a) => (isSafeVariableIdentifier(a.name) ? `args.${a.name}` : `args['${makeSafePropertyIdentifier(a.name)}']`)) .join(', ')}],` } else { yield `method: undefined,` yield `methodArgs: undefined,` } yield '...params,' yield DecIndent yield '}' yield DecIndent yield `}${isNested ? ',' : ''}` }
src/client/call-factory.ts
algorandfoundation-algokit-client-generator-ts-2de43ed
[ { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " returns: `The typed transaction composer so you can fluently chain multiple calls or call execute to execute all queued up transactions`,\n })\n yield `clearState(args?: BareCallArgs & AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, undefined]>`\n yield NewLine\n}\nfunction* callComposerTypeNoops({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config", "score": 0.8433563709259033 }, { "filename": "src/client/call-composer-types.ts", "retrieved_chunk": " yield `${methodName}(args: MethodArgs<'${methodSignature}'>, params?: AppClientCallCoreParams & CoreAppCallArgs): ${name}Composer<[...TReturns, MethodReturn<'${methodSignature}'>]>`\n yield NewLine\n }\n}\nfunction* callComposerOperationMethodType(\n { app, methodSignatureToUniqueName, name }: GeneratorContext,\n description: string,\n methods: MethodList,\n verb: 'create' | 'update' | 'optIn' | 'closeOut' | 'delete',\n includeCompilation?: boolean,", "score": 0.8285996913909912 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": "}\nfunction* noopMethods({ app, name, callConfig, methodSignatureToUniqueName }: GeneratorContext): DocumentParts {\n for (const method of app.contract.methods) {\n const methodSignature = algokit.getABIMethodSignature(method)\n const methodName = makeSafeMethodIdentifier(methodSignatureToUniqueName[methodSignature])\n // Skip methods which don't support a no_op call config\n if (!callConfig.callMethods.includes(methodSignature)) continue\n yield* jsDoc({\n description: `Calls the ${algokit.getABIMethodSignature(method)} ABI method.`,\n abiDescription: method.desc,", "score": 0.8259260654449463 }, { "filename": "src/client/call-client.ts", "retrieved_chunk": " params: {\n typedCallParams: 'An object containing the method signature, args, and any other relevant parameters',\n returnValueFormatter: 'An optional delegate which when provided will be used to map non-undefined return values to the target type',\n },\n returns: 'The result of the smart contract call',\n })\n yield `public async call<TSignature extends keyof ${name}['methods']>(typedCallParams: TypedCallParams<TSignature>, returnValueFormatter?: (value: any) => MethodReturn<TSignature>) {`\n yield IncIndent\n yield `return this.mapReturnValue<MethodReturn<TSignature>>(await this.appClient.call(typedCallParams), returnValueFormatter)`\n yield DecIndentAndCloseBlock", "score": 0.8184549808502197 }, { "filename": "src/client/generator-context.ts", "retrieved_chunk": "export const createGeneratorContext = (app: AlgoAppSpec) => ({\n app,\n name: makeSafeTypeIdentifier(app.contract.name),\n callConfig: getCallConfigSummary(app),\n methodSignatureToUniqueName: app.contract.methods.reduce((acc, cur) => {\n const signature = algokit.getABIMethodSignature(cur)\n acc[signature] = app.contract.methods.some((m) => m.name === cur.name && m !== cur) ? signature : cur.name\n return acc\n }, {} as Record<string, string>),\n})", "score": 0.8180853128433228 } ]
typescript
: method.args, paramTypes: 'AppClientCallCoreParams & CoreAppCallArgs', }) }
import { readFileSync } from 'fs'; import path from 'path'; import db from '../helpers/mysql'; type MODERATION_LIST = Record<string, string[] | JSON>; const CACHE_PATH = path.resolve(__dirname, `../../${process.env.MODERATION_LIST_PATH || 'data'}`); const FIELDS = new Map<keyof MODERATION_LIST, Record<string, string>>([ ['flaggedLinks', { action: 'flag', type: 'link' }], ['flaggedProposals', { action: 'flag', type: 'proposal' }], ['flaggedSpaces', { action: 'flag', type: 'space' }], ['flaggedIps', { action: 'flag', type: 'ip' }], ['verifiedSpaces', { action: 'verify', type: 'space' }], ['verifiedTokens', { file: 'verifiedTokens.json' }] ]); export function readFile(filename: string) { return parseFileContent( readFileSync(path.join(CACHE_PATH, filename), { encoding: 'utf8' }), filename.split('.')[1] ); } function parseFileContent(content: string, parser: string): MODERATION_LIST[keyof MODERATION_LIST] { switch (parser) { case 'txt': return content.split('\n').filter(value => value !== ''); case 'json': return JSON.parse(content); default: throw new Error('Invalid file type'); } } export default async function getModerationList(fields = Array.from(FIELDS.keys())) { const list: Partial<MODERATION_LIST> = {}; const reverseMapping: Record<string, keyof MODERATION_LIST> = {}; const queryWhereStatement: string[] = []; let queryWhereArgs: string[] = []; fields.forEach(field => { if (FIELDS.has(field)) { const args = FIELDS.get(field) as Record<string, string>; if (!args.file) { list[field] = []; reverseMapping[`${args.action}-${args.type}`] = field; queryWhereStatement.push(`(action = ? AND type = ?)`); queryWhereArgs = queryWhereArgs.concat([args.action, args.type]); } else { list[field] = readFile(args.file); } } }); if (queryWhereStatement.length > 0) {
const dbResults = await db.queryAsync( `SELECT * FROM moderation WHERE ${queryWhereStatement.join(' OR ')}`, queryWhereArgs );
dbResults.forEach(row => { (list[reverseMapping[`${row.action}-${row.type}`]] as string[]).push(row.value as string); }); } return list; }
src/lib/moderationList.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/api.ts", "retrieved_chunk": " return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});\nrouter.get('/moderation', async (req, res) => {\n const { list } = req.query;\n try {\n res.json(await getModerationList(list ? (list as string).split(',') : undefined));\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', '');", "score": 0.7663889527320862 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": " orderBy,\n orderDirection,\n first,\n skip,\n created_gte\n }\n });\n return votes;\n}\nexport async function fetchSpace(id: string) {", "score": 0.7490741610527039 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": "export async function fetchVotes(\n id: string,\n { first = 1000, skip = 0, orderBy = 'created_gte', orderDirection = 'asc', created_gte = 0 } = {}\n) {\n const {\n data: { votes }\n }: { data: { votes: Vote[] } } = await client.query({\n query: VOTES_QUERY,\n variables: {\n id,", "score": 0.7450106739997864 }, { "filename": "src/helpers/utils.ts", "retrieved_chunk": " error: {\n code: errorCode,\n message: errorMessage\n },\n id\n });\n}\nexport async function sleep(time: number) {\n return new Promise(resolve => {\n setTimeout(resolve, time);", "score": 0.7366712093353271 }, { "filename": "src/lib/votesReport.ts", "retrieved_chunk": " const pageSize = 1000;\n let resultsSize = 0;\n const maxPage = 5;\n do {\n let newVotes = await fetchVotes(this.id, {\n first: pageSize,\n skip: page * pageSize,\n created_gte: createdPivot,\n orderBy: 'created',\n orderDirection: 'asc'", "score": 0.7345423698425293 } ]
typescript
const dbResults = await db.queryAsync( `SELECT * FROM moderation WHERE ${queryWhereStatement.join(' OR ')}`, queryWhereArgs );
import express from 'express'; import { capture } from './helpers/sentry'; import { rpcError, rpcSuccess, storageEngine } from './helpers/utils'; import getModerationList from './lib/moderationList'; import VotesReport from './lib/votesReport'; import mintPayload from './lib/nftClaimer/mint'; import deployPayload from './lib/nftClaimer/deploy'; import { queue, getProgress } from './lib/queue'; import { snapshotFee } from './lib/nftClaimer/utils'; const router = express.Router(); router.post('/votes/:id', async (req, res) => { const { id } = req.params; const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR)); try { const file = await votesReport.getCache(); if (file) { res.header('Content-Type', 'text/csv'); res.attachment(votesReport.filename); return res.end(file); } try { await votesReport.isCacheable(); queue(votesReport); return rpcSuccess(res.status(202), getProgress(id).toString(), id); } catch (e: any) { capture(e); rpcError(res, e, id); } } catch (e) { capture(e); return rpcError(res, 'INTERNAL_ERROR', id); } }); router.get('/moderation', async (req, res) => { const { list } = req.query; try { res.json(await getModerationList(list ? (list as string).split(',') : undefined)); } catch (e) { capture(e); return rpcError(res, 'INTERNAL_ERROR', ''); } }); router.get('/nft-claimer', async (req, res) => { try { return res.json({ snapshotFee: await snapshotFee() }); } catch (e: any) { capture(e); return rpcError(res, e, ''); } }); router.post('/nft-claimer/deploy', async (req, res) => { const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body; try { return res.json( await deployPayload({ spaceOwner: address, id, maxSupply, mintPrice, proposerFee, salt, spaceTreasury }) ); } catch (e: any) { capture(e); return rpcError(res, e, salt); } }); router.post('/nft-claimer/mint', async (req, res) => { const { proposalAuthor, address, id, salt } = req.body; try {
return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt }));
} catch (e: any) { capture(e); return rpcError(res, e, salt); } }); export default router;
src/api.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/sentryTunnel.ts", "retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;", "score": 0.8198671936988831 }, { "filename": "src/webhook.ts", "retrieved_chunk": " return rpcError(res, 'Invalid Request', id);\n }\n try {\n processVotesReport(id, event);\n return rpcSuccess(res, 'Webhook received', id);\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});", "score": 0.813991367816925 }, { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": "const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;\nexport default async function payload(input: {\n proposalAuthor: string;\n recipient: string;\n id: string;\n salt: string;\n}) {\n const params = await validateMintInput(input);\n const proposal = await fetchProposal(params.id);\n validateProposal(proposal, params.proposalAuthor);", "score": 0.8055596351623535 }, { "filename": "src/index.ts", "retrieved_chunk": "app.use('/', sentryTunnel);\napp.get('/', (req, res) => {\n const commit = process.env.COMMIT_HASH || '';\n const v = commit ? `${version}#${commit.substring(0, 7)}` : version;\n return res.json({\n name,\n version: v\n });\n});\nfallbackLogger(app);", "score": 0.7987772822380066 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " };\n}\nexport async function validateMintInput(params: any) {\n validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient });\n validateNumbers({\n salt: params.salt\n });\n return {\n proposalAuthor: getAddress(params.proposalAuthor),\n recipient: getAddress(params.recipient),", "score": 0.7948652505874634 } ]
typescript
return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt }));
import { sleep } from '../helpers/utils'; import { capture } from '../helpers/sentry'; import Cache from './cache'; const queues = new Set<Cache>(); const processingItems = new Map<string, Cache>(); async function processItem(cacheable: Cache) { console.log(`[queue] Processing queue item: ${cacheable}`); try { processingItems.set(cacheable.id, cacheable); await cacheable.createCache(); } catch (e) { capture(e); console.error(`[queue] Error while processing item`, e); } finally { queues.delete(cacheable); processingItems.delete(cacheable.id); } } export function queue(cacheable: Cache) { queues.add(cacheable); return queues.size; } export function getProgress(id: string) { if (processingItems.has(id)) { return processingItems.get(id)?.generationProgress as number; } return 0; } async function run() { try { console.log(`[queue] Poll queue (found ${queues.size} items)`); queues.forEach(async cacheable => { if (processingItems.has(cacheable.id)) { console.log( `[queue] Skip: ${cacheable} is currently being processed, progress: ${processingItems.get( cacheable.id )?.generationProgress}%` ); return; } processItem(cacheable); }); } catch (e) { capture(e); } finally { await
sleep(15e3);
await run(); } } run();
src/lib/queue.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/helpers/utils.ts", "retrieved_chunk": " error: {\n code: errorCode,\n message: errorMessage\n },\n id\n });\n}\nexport async function sleep(time: number) {\n return new Promise(resolve => {\n setTimeout(resolve, time);", "score": 0.8468602895736694 }, { "filename": "src/lib/storage/aws.ts", "retrieved_chunk": " stream.once('error', reject);\n });\n } catch (e: any) {\n if (e['$metadata']?.httpStatusCode !== 404) {\n capture(e);\n console.error('[storage:aws] File fetch failed', e);\n }\n return false;\n }\n }", "score": 0.844527006149292 }, { "filename": "src/sentryTunnel.ts", "retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;", "score": 0.832481861114502 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " );\n return contract.snapshotFee();\n } catch (e: any) {\n capture(e);\n throw 'Unable to retrieve the snapshotFee';\n }\n}", "score": 0.8124344348907471 }, { "filename": "src/api.ts", "retrieved_chunk": " try {\n await votesReport.isCacheable();\n queue(votesReport);\n return rpcSuccess(res.status(202), getProgress(id).toString(), id);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, id);\n }\n } catch (e) {\n capture(e);", "score": 0.7872987985610962 } ]
typescript
sleep(15e3);
import { splitSignature } from '@ethersproject/bytes'; import { fetchProposal, Space } from '../../helpers/snapshot'; import { validateProposal, getProposalContract, signer, numberizeProposalId, validateMintInput, mintingAllowed } from './utils'; import abi from './spaceCollectionImplementationAbi.json'; import { FormatTypes, Interface } from '@ethersproject/abi'; const MintType = { Mint: [ { name: 'proposer', type: 'address' }, { name: 'recipient', type: 'address' }, { name: 'proposalId', type: 'uint256' }, { name: 'salt', type: 'uint256' } ] }; const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK; export default async function payload(input: { proposalAuthor: string; recipient: string; id: string; salt: string; }) { const params = await validateMintInput(input); const proposal = await fetchProposal(params.id); validateProposal(proposal, params.proposalAuthor); const spaceId = proposal?.space.id as string; const verifyingContract = await getProposalContract(spaceId); if (!mintingAllowed(proposal?.space as Space)) { throw new Error('Space has closed minting'); } const message = { proposer: params.proposalAuthor, recipient: params.recipient, proposalId: numberizeProposalId(params.id), salt: BigInt(params.salt) }; return { signature: await generateSignature(verifyingContract, spaceId, message), contractAddress: verifyingContract, spaceId: proposal?.space.id, ...message, salt: params.salt, abi:
new Interface(abi).getFunction('mint').format(FormatTypes.full) };
} async function generateSignature( verifyingContract: string, domain: string, message: Record<string, string | bigint> ) { return splitSignature( await signer._signTypedData( { name: domain, version: '0.1', chainId: NFT_CLAIMER_NETWORK, verifyingContract }, MintType, message ) ); }
src/lib/nftClaimer/mint.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": " const result = {\n initializer,\n salt: params.salt,\n abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full),\n verifyingContract: VERIFYING_CONTRACT,\n implementation: IMPLEMENTATION_ADDRESS,\n signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt)\n };\n console.debug('Signer', signer.address);\n console.debug('Payload', result);", "score": 0.8781619071960449 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": " // the smart contract version\n // NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting\n // from the smart contract\n const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);\n const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`;\n console.debug('Initializer params', params);\n return result;\n}\nasync function generateSignature(implementation: string, initializer: string, salt: string) {\n const params = {", "score": 0.7623715400695801 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": " const params = [\n args.spaceId,\n '0.1',\n args.maxSupply,\n BigInt(args.mintPrice),\n args.proposerFee,\n getAddress(args.spaceTreasury),\n getAddress(args.spaceOwner)\n ];\n // This encodeFunctionData should ignore the last 4 params compared to", "score": 0.7620365619659424 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": "export default async function payload(input: {\n spaceOwner: string;\n id: string;\n maxSupply: string;\n mintPrice: string;\n proposerFee: string;\n salt: string;\n spaceTreasury: string;\n}) {\n const params = await validateDeployInput(input);", "score": 0.7546498775482178 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": " domain: {\n name: 'SpaceCollectionFactory',\n version: '0.1',\n chainId: NFT_CLAIMER_NETWORK,\n verifyingContract: VERIFYING_CONTRACT\n },\n types: DeployType,\n value: {\n implementation,\n initializer,", "score": 0.7495125532150269 } ]
typescript
new Interface(abi).getFunction('mint').format(FormatTypes.full) };
import express from 'express'; import { capture } from './helpers/sentry'; import { rpcError, rpcSuccess, storageEngine } from './helpers/utils'; import getModerationList from './lib/moderationList'; import VotesReport from './lib/votesReport'; import mintPayload from './lib/nftClaimer/mint'; import deployPayload from './lib/nftClaimer/deploy'; import { queue, getProgress } from './lib/queue'; import { snapshotFee } from './lib/nftClaimer/utils'; const router = express.Router(); router.post('/votes/:id', async (req, res) => { const { id } = req.params; const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR)); try { const file = await votesReport.getCache(); if (file) { res.header('Content-Type', 'text/csv'); res.attachment(votesReport.filename); return res.end(file); } try { await votesReport.isCacheable(); queue(votesReport); return rpcSuccess(res.status(202), getProgress(id).toString(), id); } catch (e: any) { capture(e); rpcError(res, e, id); } } catch (e) { capture(e); return rpcError(res, 'INTERNAL_ERROR', id); } }); router.get('/moderation', async (req, res) => { const { list } = req.query; try { res.json(await getModerationList(list ? (list as string).split(',') : undefined)); } catch (e) { capture(e); return rpcError(res, 'INTERNAL_ERROR', ''); } }); router.get('/nft-claimer', async (req, res) => { try { return res.json({ snapshotFee: await snapshotFee() }); } catch (e: any) { capture(e); return rpcError(res, e, ''); } }); router.post('/nft-claimer/deploy', async (req, res) => { const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body; try { return res.json(
await deployPayload({
spaceOwner: address, id, maxSupply, mintPrice, proposerFee, salt, spaceTreasury }) ); } catch (e: any) { capture(e); return rpcError(res, e, salt); } }); router.post('/nft-claimer/mint', async (req, res) => { const { proposalAuthor, address, id, salt } = req.body; try { return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt })); } catch (e: any) { capture(e); return rpcError(res, e, salt); } }); export default router;
src/api.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/sentryTunnel.ts", "retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;", "score": 0.819848358631134 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " throw new Error(`proposerFee should not be greater than ${100 - sFee}`);\n }\n return true;\n}\nexport async function validateDeployInput(params: any) {\n validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury });\n validateNumbers({\n maxSupply: params.maxSupply,\n proposerFee: params.proposerFee,\n mintPrice: params.mintPrice,", "score": 0.815828800201416 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": "export default async function payload(input: {\n spaceOwner: string;\n id: string;\n maxSupply: string;\n mintPrice: string;\n proposerFee: string;\n salt: string;\n spaceTreasury: string;\n}) {\n const params = await validateDeployInput(input);", "score": 0.8102716207504272 }, { "filename": "src/index.ts", "retrieved_chunk": "app.use('/', sentryTunnel);\napp.get('/', (req, res) => {\n const commit = process.env.COMMIT_HASH || '';\n const v = commit ? `${version}#${commit.substring(0, 7)}` : version;\n return res.json({\n name,\n version: v\n });\n});\nfallbackLogger(app);", "score": 0.7986003160476685 }, { "filename": "src/webhook.ts", "retrieved_chunk": " return rpcError(res, 'Invalid Request', id);\n }\n try {\n processVotesReport(id, event);\n return rpcSuccess(res, 'Webhook received', id);\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});", "score": 0.7886384725570679 } ]
typescript
await deployPayload({
import { getAddress } from '@ethersproject/address'; import { splitSignature } from '@ethersproject/bytes'; import { FormatTypes, Interface } from '@ethersproject/abi'; import { fetchSpace } from '../../helpers/snapshot'; import { signer, validateDeployInput, validateSpace } from './utils'; import spaceCollectionAbi from './spaceCollectionImplementationAbi.json'; import spaceFactoryAbi from './spaceFactoryAbi.json'; const DeployType = { Deploy: [ { name: 'implementation', type: 'address' }, { name: 'initializer', type: 'bytes' }, { name: 'salt', type: 'uint256' } ] }; const VERIFYING_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string); const IMPLEMENTATION_ADDRESS = getAddress( process.env.NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS as string ); const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK; const INITIALIZE_SELECTOR = process.env.NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR; export default async function payload(input: { spaceOwner: string; id: string; maxSupply: string; mintPrice: string; proposerFee: string; salt: string; spaceTreasury: string; }) { const params = await validateDeployInput(input); const space = await fetchSpace(params.id); await validateSpace(params.spaceOwner, space); const initializer = getInitializer({ spaceOwner: params.spaceOwner, spaceId: space?.id as string, maxSupply: params.maxSupply, mintPrice: params.mintPrice, proposerFee: params.proposerFee, spaceTreasury: params.spaceTreasury }); const result = { initializer, salt: params.salt, abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full), verifyingContract: VERIFYING_CONTRACT, implementation: IMPLEMENTATION_ADDRESS, signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt) }; console.debug('Signer', signer.address); console.debug('Payload', result); return result; } function getInitializer(args: { spaceId: string; maxSupply: number; mintPrice: string; proposerFee: number; spaceTreasury: string; spaceOwner: string; }) { const params = [ args.spaceId, '0.1', args.maxSupply, BigInt(args.mintPrice), args.proposerFee, getAddress(args.spaceTreasury), getAddress(args.spaceOwner) ]; // This encodeFunctionData should ignore the last 4 params compared to // the smart contract version // NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting // from the smart contract
const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);
const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`; console.debug('Initializer params', params); return result; } async function generateSignature(implementation: string, initializer: string, salt: string) { const params = { domain: { name: 'SpaceCollectionFactory', version: '0.1', chainId: NFT_CLAIMER_NETWORK, verifyingContract: VERIFYING_CONTRACT }, types: DeployType, value: { implementation, initializer, salt: BigInt(salt) } }; return splitSignature(await signer._signTypedData(params.domain, params.types, params.value)); }
src/lib/nftClaimer/deploy.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " }\n });\n return true;\n}\nexport async function validateProposerFee(fee: number) {\n if (fee < 0 || fee > 100) {\n throw new Error('proposerFee should be between 0 and 100');\n }\n const sFee = await snapshotFee();\n if (sFee + fee > 100) {", "score": 0.801716685295105 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " throw new Error(`proposerFee should not be greater than ${100 - sFee}`);\n }\n return true;\n}\nexport async function validateDeployInput(params: any) {\n validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury });\n validateNumbers({\n maxSupply: params.maxSupply,\n proposerFee: params.proposerFee,\n mintPrice: params.mintPrice,", "score": 0.7992876172065735 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " ...params\n };\n}\nexport async function snapshotFee(): Promise<number> {\n try {\n const provider = snapshot.utils.getProvider(NFT_CLAIMER_NETWORK);\n const contract = new Contract(\n DEPLOY_CONTRACT,\n ['function snapshotFee() public view returns (uint8)'],\n provider", "score": 0.7977546453475952 }, { "filename": "src/api.ts", "retrieved_chunk": "router.post('/nft-claimer/deploy', async (req, res) => {\n const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body;\n try {\n return res.json(\n await deployPayload({\n spaceOwner: address,\n id,\n maxSupply,\n mintPrice,\n proposerFee,", "score": 0.7872875928878784 }, { "filename": "src/api.ts", "retrieved_chunk": " const { proposalAuthor, address, id, salt } = req.body;\n try {\n return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt }));\n } catch (e: any) {\n capture(e);\n return rpcError(res, e, salt);\n }\n});\nexport default router;", "score": 0.769209623336792 } ]
typescript
const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);
import express from 'express'; import { capture } from './helpers/sentry'; import { rpcError, rpcSuccess, storageEngine } from './helpers/utils'; import getModerationList from './lib/moderationList'; import VotesReport from './lib/votesReport'; import mintPayload from './lib/nftClaimer/mint'; import deployPayload from './lib/nftClaimer/deploy'; import { queue, getProgress } from './lib/queue'; import { snapshotFee } from './lib/nftClaimer/utils'; const router = express.Router(); router.post('/votes/:id', async (req, res) => { const { id } = req.params; const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR)); try { const file = await votesReport.getCache(); if (file) { res.header('Content-Type', 'text/csv'); res.attachment(votesReport.filename); return res.end(file); } try { await votesReport.isCacheable(); queue(votesReport); return rpcSuccess(res.status(202), getProgress(id).toString(), id); } catch (e: any) { capture(e); rpcError(res, e, id); } } catch (e) { capture(e); return rpcError(res, 'INTERNAL_ERROR', id); } }); router.get('/moderation', async (req, res) => { const { list } = req.query; try { res.json(await getModerationList(list ? (list as string).split(',') : undefined)); } catch (e) { capture(e); return rpcError(res, 'INTERNAL_ERROR', ''); } }); router.get('/nft-claimer', async (req, res) => { try { return res.json(
{ snapshotFee: await snapshotFee() });
} catch (e: any) { capture(e); return rpcError(res, e, ''); } }); router.post('/nft-claimer/deploy', async (req, res) => { const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body; try { return res.json( await deployPayload({ spaceOwner: address, id, maxSupply, mintPrice, proposerFee, salt, spaceTreasury }) ); } catch (e: any) { capture(e); return rpcError(res, e, salt); } }); router.post('/nft-claimer/mint', async (req, res) => { const { proposalAuthor, address, id, salt } = req.body; try { return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt })); } catch (e: any) { capture(e); return rpcError(res, e, salt); } }); export default router;
src/api.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/sentryTunnel.ts", "retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;", "score": 0.8510158061981201 }, { "filename": "src/webhook.ts", "retrieved_chunk": " return rpcError(res, 'Invalid Request', id);\n }\n try {\n processVotesReport(id, event);\n return rpcSuccess(res, 'Webhook received', id);\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});", "score": 0.8437144756317139 }, { "filename": "src/index.ts", "retrieved_chunk": "app.use('/', sentryTunnel);\napp.get('/', (req, res) => {\n const commit = process.env.COMMIT_HASH || '';\n const v = commit ? `${version}#${commit.substring(0, 7)}` : version;\n return res.json({\n name,\n version: v\n });\n});\nfallbackLogger(app);", "score": 0.7930177450180054 }, { "filename": "src/lib/moderationList.ts", "retrieved_chunk": " switch (parser) {\n case 'txt':\n return content.split('\\n').filter(value => value !== '');\n case 'json':\n return JSON.parse(content);\n default:\n throw new Error('Invalid file type');\n }\n}\nexport default async function getModerationList(fields = Array.from(FIELDS.keys())) {", "score": 0.7771522402763367 }, { "filename": "src/lib/storage/aws.ts", "retrieved_chunk": " stream.once('error', reject);\n });\n } catch (e: any) {\n if (e['$metadata']?.httpStatusCode !== 404) {\n capture(e);\n console.error('[storage:aws] File fetch failed', e);\n }\n return false;\n }\n }", "score": 0.7633692026138306 } ]
typescript
{ snapshotFee: await snapshotFee() });
import { splitSignature } from '@ethersproject/bytes'; import { fetchProposal, Space } from '../../helpers/snapshot'; import { validateProposal, getProposalContract, signer, numberizeProposalId, validateMintInput, mintingAllowed } from './utils'; import abi from './spaceCollectionImplementationAbi.json'; import { FormatTypes, Interface } from '@ethersproject/abi'; const MintType = { Mint: [ { name: 'proposer', type: 'address' }, { name: 'recipient', type: 'address' }, { name: 'proposalId', type: 'uint256' }, { name: 'salt', type: 'uint256' } ] }; const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK; export default async function payload(input: { proposalAuthor: string; recipient: string; id: string; salt: string; }) { const params = await validateMintInput(input); const proposal = await fetchProposal(params.id); validateProposal(proposal, params.proposalAuthor); const spaceId = proposal?.space.id as string; const verifyingContract = await getProposalContract(spaceId); if (!mintingAllowed(proposal?.space as Space)) { throw new Error('Space has closed minting'); } const message = { proposer: params.proposalAuthor, recipient: params.recipient, proposalId: numberizeProposalId(params.id), salt: BigInt(params.salt) }; return { signature: await generateSignature(verifyingContract, spaceId, message), contractAddress: verifyingContract, spaceId: proposal?.space.id, ...message, salt: params.salt, abi: new
Interface(abi).getFunction('mint').format(FormatTypes.full) };
} async function generateSignature( verifyingContract: string, domain: string, message: Record<string, string | bigint> ) { return splitSignature( await signer._signTypedData( { name: domain, version: '0.1', chainId: NFT_CLAIMER_NETWORK, verifyingContract }, MintType, message ) ); }
src/lib/nftClaimer/mint.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": " const result = {\n initializer,\n salt: params.salt,\n abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full),\n verifyingContract: VERIFYING_CONTRACT,\n implementation: IMPLEMENTATION_ADDRESS,\n signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt)\n };\n console.debug('Signer', signer.address);\n console.debug('Payload', result);", "score": 0.8790849447250366 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": " const params = [\n args.spaceId,\n '0.1',\n args.maxSupply,\n BigInt(args.mintPrice),\n args.proposerFee,\n getAddress(args.spaceTreasury),\n getAddress(args.spaceOwner)\n ];\n // This encodeFunctionData should ignore the last 4 params compared to", "score": 0.7653781175613403 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": " // the smart contract version\n // NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting\n // from the smart contract\n const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);\n const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`;\n console.debug('Initializer params', params);\n return result;\n}\nasync function generateSignature(implementation: string, initializer: string, salt: string) {\n const params = {", "score": 0.7642171382904053 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": "export default async function payload(input: {\n spaceOwner: string;\n id: string;\n maxSupply: string;\n mintPrice: string;\n proposerFee: string;\n salt: string;\n spaceTreasury: string;\n}) {\n const params = await validateDeployInput(input);", "score": 0.7585638761520386 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": " domain: {\n name: 'SpaceCollectionFactory',\n version: '0.1',\n chainId: NFT_CLAIMER_NETWORK,\n verifyingContract: VERIFYING_CONTRACT\n },\n types: DeployType,\n value: {\n implementation,\n initializer,", "score": 0.7526058554649353 } ]
typescript
Interface(abi).getFunction('mint').format(FormatTypes.full) };
import { fetchProposal, fetchVotes, Proposal, Vote } from '../helpers/snapshot'; import type { IStorage } from './storage/types'; import Cache from './cache'; class VotesReport extends Cache { proposal?: Proposal | null; constructor(id: string, storage: IStorage) { super(id, storage); this.filename = `snapshot-votes-report-${this.id}.csv`; } async isCacheable() { this.proposal = await fetchProposal(this.id); if (!this.proposal || this.proposal.state !== 'closed') { return Promise.reject('RECORD_NOT_FOUND'); } return true; } getContent = async () => { this.isCacheable(); const votes = await this.fetchAllVotes(); let content = ''; console.log(`[votes-report] Generating report for ${this.id}`); const headers = [ 'address', votes.length === 0 || typeof votes[0].choice === 'number' ? 'choice' : this.proposal && this.proposal.choices.map((_choice, index) => `choice.${index + 1}`), 'voting_power', 'timestamp', 'author_ipfs_hash', 'reason' ].flat(); content += headers.join(','); content += `\n${votes.map(vote => this.#formatCsvLine(vote)).join('\n')}`; console.log(`[votes-report] Report for ${this.id} ready with ${votes.length} items`); return content; }; fetchAllVotes = async () => { let votes: Vote[] = []; let page = 0; let createdPivot = 0; const pageSize = 1000; let resultsSize = 0; const maxPage = 5; do { let newVotes
= await fetchVotes(this.id, {
first: pageSize, skip: page * pageSize, created_gte: createdPivot, orderBy: 'created', orderDirection: 'asc' }); resultsSize = newVotes.length; if (page === 0 && createdPivot > 0) { // Loosely assuming that there will never be more than 1000 duplicates const existingIpfs = votes.slice(-pageSize).map(vote => vote.ipfs); newVotes = newVotes.filter(vote => { return !existingIpfs.includes(vote.ipfs); }); } if (page === maxPage) { page = 0; createdPivot = newVotes[newVotes.length - 1].created; } else { page++; } votes = votes.concat(newVotes); this.generationProgress = Number( ((votes.length / (this.proposal?.votes as number)) * 100).toFixed(2) ); } while (resultsSize === pageSize); return votes; }; toString() { return `VotesReport#${this.id}`; } #formatCsvLine = (vote: Vote) => { let choices: Vote['choice'][] = []; if (typeof vote.choice !== 'number' && this.proposal) { choices = Array.from({ length: this.proposal.choices.length }); for (const [key, value] of Object.entries(vote.choice)) { choices[parseInt(key) - 1] = value; } } else { choices.push(vote.choice); } return [ vote.voter, ...choices, vote.vp, vote.created, vote.ipfs, `"${vote.reason.replace(/(\r\n|\n|\r)/gm, '')}"` ] .flat() .join(','); }; } export default VotesReport;
src/lib/votesReport.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": "export async function fetchVotes(\n id: string,\n { first = 1000, skip = 0, orderBy = 'created_gte', orderDirection = 'asc', created_gte = 0 } = {}\n) {\n const {\n data: { votes }\n }: { data: { votes: Vote[] } } = await client.query({\n query: VOTES_QUERY,\n variables: {\n id,", "score": 0.8286073803901672 }, { "filename": "src/helpers/utils.ts", "retrieved_chunk": " error: {\n code: errorCode,\n message: errorMessage\n },\n id\n });\n}\nexport async function sleep(time: number) {\n return new Promise(resolve => {\n setTimeout(resolve, time);", "score": 0.7841697931289673 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": " orderBy,\n orderDirection,\n first,\n skip,\n created_gte\n }\n });\n return votes;\n}\nexport async function fetchSpace(id: string) {", "score": 0.784142017364502 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " }\n });\n return true;\n}\nexport async function validateProposerFee(fee: number) {\n if (fee < 0 || fee > 100) {\n throw new Error('proposerFee should be between 0 and 100');\n }\n const sFee = await snapshotFee();\n if (sFee + fee > 100) {", "score": 0.7533484697341919 }, { "filename": "src/lib/cache.ts", "retrieved_chunk": " this.generationProgress = 0;\n }\n async getContent(): Promise<string | Buffer> {\n return '';\n }\n getCache() {\n return this.storage.get(this.filename);\n }\n async isCacheable() {\n return true;", "score": 0.7380979061126709 } ]
typescript
= await fetchVotes(this.id, {
import express from 'express'; import { capture } from './helpers/sentry'; import { rpcError, rpcSuccess, storageEngine } from './helpers/utils'; import getModerationList from './lib/moderationList'; import VotesReport from './lib/votesReport'; import mintPayload from './lib/nftClaimer/mint'; import deployPayload from './lib/nftClaimer/deploy'; import { queue, getProgress } from './lib/queue'; import { snapshotFee } from './lib/nftClaimer/utils'; const router = express.Router(); router.post('/votes/:id', async (req, res) => { const { id } = req.params; const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR)); try { const file = await votesReport.getCache(); if (file) { res.header('Content-Type', 'text/csv'); res.attachment(votesReport.filename); return res.end(file); } try { await votesReport.isCacheable(); queue(votesReport); return rpcSuccess(res.status(202), getProgress(id).toString(), id); } catch (e: any) { capture(e); rpcError(res, e, id); } } catch (e) { capture(e); return rpcError(res, 'INTERNAL_ERROR', id); } }); router.get('/moderation', async (req, res) => { const { list } = req.query; try { res.json(await getModerationList(list ? (list as string).split(',') : undefined)); } catch (e) { capture(e); return rpcError(res, 'INTERNAL_ERROR', ''); } }); router.get('/nft-claimer', async (req, res) => { try {
return res.json({ snapshotFee: await snapshotFee() });
} catch (e: any) { capture(e); return rpcError(res, e, ''); } }); router.post('/nft-claimer/deploy', async (req, res) => { const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body; try { return res.json( await deployPayload({ spaceOwner: address, id, maxSupply, mintPrice, proposerFee, salt, spaceTreasury }) ); } catch (e: any) { capture(e); return rpcError(res, e, salt); } }); router.post('/nft-claimer/mint', async (req, res) => { const { proposalAuthor, address, id, salt } = req.body; try { return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt })); } catch (e: any) { capture(e); return rpcError(res, e, salt); } }); export default router;
src/api.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/webhook.ts", "retrieved_chunk": " return rpcError(res, 'Invalid Request', id);\n }\n try {\n processVotesReport(id, event);\n return rpcSuccess(res, 'Webhook received', id);\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});", "score": 0.854074239730835 }, { "filename": "src/sentryTunnel.ts", "retrieved_chunk": " if (status !== 200) {\n console.debug(await response.text());\n }\n return res.sendStatus(status);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, '');\n }\n});\nexport default router;", "score": 0.8532869815826416 }, { "filename": "src/index.ts", "retrieved_chunk": "app.use('/', sentryTunnel);\napp.get('/', (req, res) => {\n const commit = process.env.COMMIT_HASH || '';\n const v = commit ? `${version}#${commit.substring(0, 7)}` : version;\n return res.json({\n name,\n version: v\n });\n});\nfallbackLogger(app);", "score": 0.7971667051315308 }, { "filename": "src/lib/moderationList.ts", "retrieved_chunk": " switch (parser) {\n case 'txt':\n return content.split('\\n').filter(value => value !== '');\n case 'json':\n return JSON.parse(content);\n default:\n throw new Error('Invalid file type');\n }\n}\nexport default async function getModerationList(fields = Array.from(FIELDS.keys())) {", "score": 0.7732870578765869 }, { "filename": "src/lib/storage/aws.ts", "retrieved_chunk": " stream.once('error', reject);\n });\n } catch (e: any) {\n if (e['$metadata']?.httpStatusCode !== 404) {\n capture(e);\n console.error('[storage:aws] File fetch failed', e);\n }\n return false;\n }\n }", "score": 0.7607709169387817 } ]
typescript
return res.json({ snapshotFee: await snapshotFee() });
import { fetchProposal, fetchVotes, Proposal, Vote } from '../helpers/snapshot'; import type { IStorage } from './storage/types'; import Cache from './cache'; class VotesReport extends Cache { proposal?: Proposal | null; constructor(id: string, storage: IStorage) { super(id, storage); this.filename = `snapshot-votes-report-${this.id}.csv`; } async isCacheable() { this.proposal = await fetchProposal(this.id); if (!this.proposal || this.proposal.state !== 'closed') { return Promise.reject('RECORD_NOT_FOUND'); } return true; } getContent = async () => { this.isCacheable(); const votes = await this.fetchAllVotes(); let content = ''; console.log(`[votes-report] Generating report for ${this.id}`); const headers = [ 'address', votes.length === 0 || typeof votes[0].choice === 'number' ? 'choice' : this.proposal && this.proposal.choices.map((_choice, index) => `choice.${index + 1}`), 'voting_power', 'timestamp', 'author_ipfs_hash', 'reason' ].flat(); content += headers.join(','); content += `\n${votes.map(vote => this.#formatCsvLine(vote)).join('\n')}`; console.log(`[votes-report] Report for ${this.id} ready with ${votes.length} items`); return content; }; fetchAllVotes = async () => { let votes: Vote[] = []; let page = 0; let createdPivot = 0; const pageSize = 1000; let resultsSize = 0; const maxPage = 5; do { let newVotes = await fetchVotes(this.id, { first: pageSize, skip: page * pageSize, created_gte: createdPivot, orderBy: 'created', orderDirection: 'asc' }); resultsSize = newVotes.length; if (page === 0 && createdPivot > 0) { // Loosely assuming that there will never be more than 1000 duplicates const existingIpfs = votes.slice(-pageSize).map(vote => vote.ipfs); newVotes = newVotes.filter(vote => { return !existingIpfs.includes(vote.ipfs); }); } if (page === maxPage) { page = 0; createdPivot = newVotes[newVotes.length - 1].created; } else { page++; } votes = votes.concat(newVotes); this.generationProgress = Number(
((votes.length / (this.proposal?.votes as number)) * 100).toFixed(2) );
} while (resultsSize === pageSize); return votes; }; toString() { return `VotesReport#${this.id}`; } #formatCsvLine = (vote: Vote) => { let choices: Vote['choice'][] = []; if (typeof vote.choice !== 'number' && this.proposal) { choices = Array.from({ length: this.proposal.choices.length }); for (const [key, value] of Object.entries(vote.choice)) { choices[parseInt(key) - 1] = value; } } else { choices.push(vote.choice); } return [ vote.voter, ...choices, vote.vp, vote.created, vote.ipfs, `"${vote.reason.replace(/(\r\n|\n|\r)/gm, '')}"` ] .flat() .join(','); }; } export default VotesReport;
src/lib/votesReport.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/api.ts", "retrieved_chunk": " try {\n await votesReport.isCacheable();\n queue(votesReport);\n return rpcSuccess(res.status(202), getProgress(id).toString(), id);\n } catch (e: any) {\n capture(e);\n rpcError(res, e, id);\n }\n } catch (e) {\n capture(e);", "score": 0.6548415422439575 }, { "filename": "src/lib/queue.ts", "retrieved_chunk": " console.log(`[queue] Poll queue (found ${queues.size} items)`);\n queues.forEach(async cacheable => {\n if (processingItems.has(cacheable.id)) {\n console.log(\n `[queue] Skip: ${cacheable} is currently being processed, progress: ${processingItems.get(\n cacheable.id\n )?.generationProgress}%`\n );\n return;\n }", "score": 0.6444291472434998 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": "export async function fetchVotes(\n id: string,\n { first = 1000, skip = 0, orderBy = 'created_gte', orderDirection = 'asc', created_gte = 0 } = {}\n) {\n const {\n data: { votes }\n }: { data: { votes: Vote[] } } = await client.query({\n query: VOTES_QUERY,\n variables: {\n id,", "score": 0.6390635371208191 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": " orderBy,\n orderDirection,\n first,\n skip,\n created_gte\n }\n });\n return votes;\n}\nexport async function fetchSpace(id: string) {", "score": 0.6385693550109863 }, { "filename": "src/api.ts", "retrieved_chunk": "router.post('/votes/:id', async (req, res) => {\n const { id } = req.params;\n const votesReport = new VotesReport(id, storageEngine(process.env.VOTE_REPORT_SUBDIR));\n try {\n const file = await votesReport.getCache();\n if (file) {\n res.header('Content-Type', 'text/csv');\n res.attachment(votesReport.filename);\n return res.end(file);\n }", "score": 0.6379936933517456 } ]
typescript
((votes.length / (this.proposal?.votes as number)) * 100).toFixed(2) );
import { fetchProposal, fetchVotes, Proposal, Vote } from '../helpers/snapshot'; import type { IStorage } from './storage/types'; import Cache from './cache'; class VotesReport extends Cache { proposal?: Proposal | null; constructor(id: string, storage: IStorage) { super(id, storage); this.filename = `snapshot-votes-report-${this.id}.csv`; } async isCacheable() { this.proposal = await fetchProposal(this.id); if (!this.proposal || this.proposal.state !== 'closed') { return Promise.reject('RECORD_NOT_FOUND'); } return true; } getContent = async () => { this.isCacheable(); const votes = await this.fetchAllVotes(); let content = ''; console.log(`[votes-report] Generating report for ${this.id}`); const headers = [ 'address', votes.length === 0 || typeof votes[0].choice === 'number' ? 'choice' : this.proposal && this.proposal.choices.map((_choice, index) => `choice.${index + 1}`), 'voting_power', 'timestamp', 'author_ipfs_hash', 'reason' ].flat(); content += headers.join(','); content += `\n${votes.map(vote => this.#formatCsvLine(vote)).join('\n')}`; console.log(`[votes-report] Report for ${this.id} ready with ${votes.length} items`); return content; }; fetchAllVotes = async () => { let votes: Vote[] = []; let page = 0; let createdPivot = 0; const pageSize = 1000; let resultsSize = 0; const maxPage = 5; do { let newVotes = await fetchVotes(this.id, { first: pageSize, skip: page * pageSize, created_gte: createdPivot, orderBy: 'created', orderDirection: 'asc' }); resultsSize = newVotes.length; if (page === 0 && createdPivot > 0) { // Loosely assuming that there will never be more than 1000 duplicates const existingIpfs = votes.slice(-pageSize).map(vote => vote.ipfs);
newVotes = newVotes.filter(vote => {
return !existingIpfs.includes(vote.ipfs); }); } if (page === maxPage) { page = 0; createdPivot = newVotes[newVotes.length - 1].created; } else { page++; } votes = votes.concat(newVotes); this.generationProgress = Number( ((votes.length / (this.proposal?.votes as number)) * 100).toFixed(2) ); } while (resultsSize === pageSize); return votes; }; toString() { return `VotesReport#${this.id}`; } #formatCsvLine = (vote: Vote) => { let choices: Vote['choice'][] = []; if (typeof vote.choice !== 'number' && this.proposal) { choices = Array.from({ length: this.proposal.choices.length }); for (const [key, value] of Object.entries(vote.choice)) { choices[parseInt(key) - 1] = value; } } else { choices.push(vote.choice); } return [ vote.voter, ...choices, vote.vp, vote.created, vote.ipfs, `"${vote.reason.replace(/(\r\n|\n|\r)/gm, '')}"` ] .flat() .join(','); }; } export default VotesReport;
src/lib/votesReport.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": "export async function fetchVotes(\n id: string,\n { first = 1000, skip = 0, orderBy = 'created_gte', orderDirection = 'asc', created_gte = 0 } = {}\n) {\n const {\n data: { votes }\n }: { data: { votes: Vote[] } } = await client.query({\n query: VOTES_QUERY,\n variables: {\n id,", "score": 0.7784358263015747 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": " orderBy,\n orderDirection,\n first,\n skip,\n created_gte\n }\n });\n return votes;\n}\nexport async function fetchSpace(id: string) {", "score": 0.7673511505126953 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " }\n });\n return true;\n}\nexport async function validateProposerFee(fee: number) {\n if (fee < 0 || fee > 100) {\n throw new Error('proposerFee should be between 0 and 100');\n }\n const sFee = await snapshotFee();\n if (sFee + fee > 100) {", "score": 0.7328266501426697 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": " orderDirection: $orderDirection\n ) {\n ipfs\n voter\n choice\n vp\n reason\n created\n }\n }", "score": 0.7317767143249512 }, { "filename": "src/helpers/utils.ts", "retrieved_chunk": " error: {\n code: errorCode,\n message: errorMessage\n },\n id\n });\n}\nexport async function sleep(time: number) {\n return new Promise(resolve => {\n setTimeout(resolve, time);", "score": 0.7186305522918701 } ]
typescript
newVotes = newVotes.filter(vote => {
import { gql, ApolloClient, InMemoryCache, HttpLink } from '@apollo/client/core'; import fetch from 'cross-fetch'; import snapshot from '@snapshot-labs/snapshot.js'; import { CID } from 'multiformats/cid'; import { Wallet } from '@ethersproject/wallet'; import { Contract } from '@ethersproject/contracts'; import { getAddress, isAddress } from '@ethersproject/address'; import { BigNumber } from '@ethersproject/bignumber'; import { capture } from '../../helpers/sentry'; import type { Proposal, Space } from '../../helpers/snapshot'; const requiredEnvKeys = [ 'NFT_CLAIMER_PRIVATE_KEY', 'NFT_CLAIMER_NETWORK', 'NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT', 'NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS', 'NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR', 'NFT_CLAIMER_SUBGRAPH_URL' ]; const HUB_NETWORK = process.env.HUB_URL === 'https://hub.snapshot.org' ? '1' : '5'; const DEPLOY_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string); const NFT_CLAIMER_NETWORK = parseInt(process.env.NFT_CLAIMER_NETWORK as string); const missingEnvKeys: string[] = []; requiredEnvKeys.forEach(key => { if (!process.env[key]) { missingEnvKeys.push(key); } }); if (missingEnvKeys.length > 0) { throw new Error( `NFT Claimer not configured properly, missing env keys: ${missingEnvKeys.join(', ')}` ); } export const signer = new Wallet(process.env.NFT_CLAIMER_PRIVATE_KEY as string); export async function mintingAllowed(space: Space) { return (await getSpaceCollection(space.id)).enabled; } export async function validateSpace(address: string, space: Space | null) { if (!space) { throw new Error('RECORD_NOT_FOUND'); } if (NFT_CLAIMER_NETWORK !== 5 && !(await isSpaceOwner(space.id, address))) { throw new Error('Address is not the space owner'); } const contract = await getSpaceCollection(space.id); if (contract) { throw new Error(`SpaceCollection contract already exist (${contract.id})`); } } async function isSpaceOwner(spaceId: string, address: string) { return (await snapshot.utils.getSpaceController(spaceId, HUB_NETWORK)) === getAddress(address); } export function validateProposal(proposal: Proposal | null, proposer: string) { if (!proposal) { throw new Error('RECORD_NOT_FOUND'); }
if (getAddress(proposer) !== getAddress(proposal.author)) {
throw new Error('Proposal author is not matching'); } if (!mintingAllowed(proposal.space)) { throw new Error('Space has not allowed minting'); } } export async function getProposalContract(spaceId: string) { const contract = await getSpaceCollection(spaceId); if (!contract) { throw new Error(`SpaceCollection contract is not found for space ${spaceId}`); } return contract.id; } const client = new ApolloClient({ link: new HttpLink({ uri: process.env.NFT_CLAIMER_SUBGRAPH_URL, fetch }), cache: new InMemoryCache({ addTypename: false }), defaultOptions: { query: { fetchPolicy: 'no-cache' } } }); const SPACE_COLLECTION_QUERY = gql` query SpaceCollections($spaceId: String) { spaceCollections(where: { spaceId: $spaceId }, first: 1) { id enabled } } `; type SpaceCollection = { id: string; enabled: boolean; }; export async function getSpaceCollection(spaceId: string) { const { data: { spaceCollections } }: { data: { spaceCollections: SpaceCollection[] } } = await client.query({ query: SPACE_COLLECTION_QUERY, variables: { spaceId } }); return spaceCollections[0]; } export function numberizeProposalId(id: string) { return BigNumber.from(id.startsWith('0x') ? id : CID.parse(id).bytes).toString(); } export function validateAddresses(addresses: Record<string, string>) { Object.entries(addresses).forEach(([key, value]) => { if (!isAddress(value)) { throw new Error(`Value for ${key} is not a valid address (${value})`); } }); return true; } function validateNumbers(numbers: Record<string, string>) { Object.entries(numbers).forEach(([key, value]) => { try { BigNumber.from(value).toString(); } catch (e: any) { throw new Error(`Value for ${key} is not a valid number (${value})`); } }); return true; } export async function validateProposerFee(fee: number) { if (fee < 0 || fee > 100) { throw new Error('proposerFee should be between 0 and 100'); } const sFee = await snapshotFee(); if (sFee + fee > 100) { throw new Error(`proposerFee should not be greater than ${100 - sFee}`); } return true; } export async function validateDeployInput(params: any) { validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury }); validateNumbers({ maxSupply: params.maxSupply, proposerFee: params.proposerFee, mintPrice: params.mintPrice, salt: params.salt }); await validateProposerFee(parseInt(params.proposerFee)); return { spaceOwner: getAddress(params.spaceOwner), spaceTreasury: getAddress(params.spaceTreasury), proposerFee: parseInt(params.proposerFee), maxSupply: parseInt(params.maxSupply), mintPrice: parseInt(params.mintPrice), ...params }; } export async function validateMintInput(params: any) { validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient }); validateNumbers({ salt: params.salt }); return { proposalAuthor: getAddress(params.proposalAuthor), recipient: getAddress(params.recipient), ...params }; } export async function snapshotFee(): Promise<number> { try { const provider = snapshot.utils.getProvider(NFT_CLAIMER_NETWORK); const contract = new Contract( DEPLOY_CONTRACT, ['function snapshotFee() public view returns (uint8)'], provider ); return contract.snapshotFee(); } catch (e: any) { capture(e); throw 'Unable to retrieve the snapshotFee'; } }
src/lib/nftClaimer/utils.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": " const spaceId = proposal?.space.id as string;\n const verifyingContract = await getProposalContract(spaceId);\n if (!mintingAllowed(proposal?.space as Space)) {\n throw new Error('Space has closed minting');\n }\n const message = {\n proposer: params.proposalAuthor,\n recipient: params.recipient,\n proposalId: numberizeProposalId(params.id),\n salt: BigInt(params.salt)", "score": 0.7989802956581116 }, { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": "const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;\nexport default async function payload(input: {\n proposalAuthor: string;\n recipient: string;\n id: string;\n salt: string;\n}) {\n const params = await validateMintInput(input);\n const proposal = await fetchProposal(params.id);\n validateProposal(proposal, params.proposalAuthor);", "score": 0.7951214909553528 }, { "filename": "src/lib/votesReport.ts", "retrieved_chunk": " this.proposal = await fetchProposal(this.id);\n if (!this.proposal || this.proposal.state !== 'closed') {\n return Promise.reject('RECORD_NOT_FOUND');\n }\n return true;\n }\n getContent = async () => {\n this.isCacheable();\n const votes = await this.fetchAllVotes();\n let content = '';", "score": 0.7802345752716064 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": "`;\nconst SPACE_QUERY = gql`\n query Space($id: String) {\n space(id: $id) {\n id\n network\n }\n }\n`;\nexport async function fetchProposal(id: string) {", "score": 0.7402406334877014 }, { "filename": "src/api.ts", "retrieved_chunk": " const { proposalAuthor, address, id, salt } = req.body;\n try {\n return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt }));\n } catch (e: any) {\n capture(e);\n return rpcError(res, e, salt);\n }\n});\nexport default router;", "score": 0.7220563888549805 } ]
typescript
if (getAddress(proposer) !== getAddress(proposal.author)) {
import { gql, ApolloClient, InMemoryCache, HttpLink } from '@apollo/client/core'; import fetch from 'cross-fetch'; import snapshot from '@snapshot-labs/snapshot.js'; import { CID } from 'multiformats/cid'; import { Wallet } from '@ethersproject/wallet'; import { Contract } from '@ethersproject/contracts'; import { getAddress, isAddress } from '@ethersproject/address'; import { BigNumber } from '@ethersproject/bignumber'; import { capture } from '../../helpers/sentry'; import type { Proposal, Space } from '../../helpers/snapshot'; const requiredEnvKeys = [ 'NFT_CLAIMER_PRIVATE_KEY', 'NFT_CLAIMER_NETWORK', 'NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT', 'NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS', 'NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR', 'NFT_CLAIMER_SUBGRAPH_URL' ]; const HUB_NETWORK = process.env.HUB_URL === 'https://hub.snapshot.org' ? '1' : '5'; const DEPLOY_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string); const NFT_CLAIMER_NETWORK = parseInt(process.env.NFT_CLAIMER_NETWORK as string); const missingEnvKeys: string[] = []; requiredEnvKeys.forEach(key => { if (!process.env[key]) { missingEnvKeys.push(key); } }); if (missingEnvKeys.length > 0) { throw new Error( `NFT Claimer not configured properly, missing env keys: ${missingEnvKeys.join(', ')}` ); } export const signer = new Wallet(process.env.NFT_CLAIMER_PRIVATE_KEY as string); export async function mintingAllowed(space: Space) { return (await getSpaceCollection(space.id)).enabled; } export async function validateSpace(address: string, space: Space | null) { if (!space) { throw new Error('RECORD_NOT_FOUND'); } if (NFT_CLAIMER_NETWORK !== 5 && !(await isSpaceOwner(space.id, address))) { throw new Error('Address is not the space owner'); } const contract = await getSpaceCollection(space.id); if (contract) { throw new Error(`SpaceCollection contract already exist (${contract.id})`); } } async function isSpaceOwner(spaceId: string, address: string) { return (await snapshot.utils.getSpaceController(spaceId, HUB_NETWORK)) === getAddress(address); } export function validateProposal(proposal: Proposal | null, proposer: string) { if (!proposal) { throw new Error('RECORD_NOT_FOUND'); } if (getAddress(proposer) !== getAddress(proposal.author)) { throw new Error('Proposal author is not matching'); }
if (!mintingAllowed(proposal.space)) {
throw new Error('Space has not allowed minting'); } } export async function getProposalContract(spaceId: string) { const contract = await getSpaceCollection(spaceId); if (!contract) { throw new Error(`SpaceCollection contract is not found for space ${spaceId}`); } return contract.id; } const client = new ApolloClient({ link: new HttpLink({ uri: process.env.NFT_CLAIMER_SUBGRAPH_URL, fetch }), cache: new InMemoryCache({ addTypename: false }), defaultOptions: { query: { fetchPolicy: 'no-cache' } } }); const SPACE_COLLECTION_QUERY = gql` query SpaceCollections($spaceId: String) { spaceCollections(where: { spaceId: $spaceId }, first: 1) { id enabled } } `; type SpaceCollection = { id: string; enabled: boolean; }; export async function getSpaceCollection(spaceId: string) { const { data: { spaceCollections } }: { data: { spaceCollections: SpaceCollection[] } } = await client.query({ query: SPACE_COLLECTION_QUERY, variables: { spaceId } }); return spaceCollections[0]; } export function numberizeProposalId(id: string) { return BigNumber.from(id.startsWith('0x') ? id : CID.parse(id).bytes).toString(); } export function validateAddresses(addresses: Record<string, string>) { Object.entries(addresses).forEach(([key, value]) => { if (!isAddress(value)) { throw new Error(`Value for ${key} is not a valid address (${value})`); } }); return true; } function validateNumbers(numbers: Record<string, string>) { Object.entries(numbers).forEach(([key, value]) => { try { BigNumber.from(value).toString(); } catch (e: any) { throw new Error(`Value for ${key} is not a valid number (${value})`); } }); return true; } export async function validateProposerFee(fee: number) { if (fee < 0 || fee > 100) { throw new Error('proposerFee should be between 0 and 100'); } const sFee = await snapshotFee(); if (sFee + fee > 100) { throw new Error(`proposerFee should not be greater than ${100 - sFee}`); } return true; } export async function validateDeployInput(params: any) { validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury }); validateNumbers({ maxSupply: params.maxSupply, proposerFee: params.proposerFee, mintPrice: params.mintPrice, salt: params.salt }); await validateProposerFee(parseInt(params.proposerFee)); return { spaceOwner: getAddress(params.spaceOwner), spaceTreasury: getAddress(params.spaceTreasury), proposerFee: parseInt(params.proposerFee), maxSupply: parseInt(params.maxSupply), mintPrice: parseInt(params.mintPrice), ...params }; } export async function validateMintInput(params: any) { validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient }); validateNumbers({ salt: params.salt }); return { proposalAuthor: getAddress(params.proposalAuthor), recipient: getAddress(params.recipient), ...params }; } export async function snapshotFee(): Promise<number> { try { const provider = snapshot.utils.getProvider(NFT_CLAIMER_NETWORK); const contract = new Contract( DEPLOY_CONTRACT, ['function snapshotFee() public view returns (uint8)'], provider ); return contract.snapshotFee(); } catch (e: any) { capture(e); throw 'Unable to retrieve the snapshotFee'; } }
src/lib/nftClaimer/utils.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": " const spaceId = proposal?.space.id as string;\n const verifyingContract = await getProposalContract(spaceId);\n if (!mintingAllowed(proposal?.space as Space)) {\n throw new Error('Space has closed minting');\n }\n const message = {\n proposer: params.proposalAuthor,\n recipient: params.recipient,\n proposalId: numberizeProposalId(params.id),\n salt: BigInt(params.salt)", "score": 0.8236645460128784 }, { "filename": "src/lib/votesReport.ts", "retrieved_chunk": " this.proposal = await fetchProposal(this.id);\n if (!this.proposal || this.proposal.state !== 'closed') {\n return Promise.reject('RECORD_NOT_FOUND');\n }\n return true;\n }\n getContent = async () => {\n this.isCacheable();\n const votes = await this.fetchAllVotes();\n let content = '';", "score": 0.7993423938751221 }, { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": "const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;\nexport default async function payload(input: {\n proposalAuthor: string;\n recipient: string;\n id: string;\n salt: string;\n}) {\n const params = await validateMintInput(input);\n const proposal = await fetchProposal(params.id);\n validateProposal(proposal, params.proposalAuthor);", "score": 0.7883367538452148 }, { "filename": "src/api.ts", "retrieved_chunk": " const { proposalAuthor, address, id, salt } = req.body;\n try {\n return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt }));\n } catch (e: any) {\n capture(e);\n return rpcError(res, e, salt);\n }\n});\nexport default router;", "score": 0.7257614731788635 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": " const space = await fetchSpace(params.id);\n await validateSpace(params.spaceOwner, space);\n const initializer = getInitializer({\n spaceOwner: params.spaceOwner,\n spaceId: space?.id as string,\n maxSupply: params.maxSupply,\n mintPrice: params.mintPrice,\n proposerFee: params.proposerFee,\n spaceTreasury: params.spaceTreasury\n });", "score": 0.7111112475395203 } ]
typescript
if (!mintingAllowed(proposal.space)) {
import { getAddress } from '@ethersproject/address'; import { splitSignature } from '@ethersproject/bytes'; import { FormatTypes, Interface } from '@ethersproject/abi'; import { fetchSpace } from '../../helpers/snapshot'; import { signer, validateDeployInput, validateSpace } from './utils'; import spaceCollectionAbi from './spaceCollectionImplementationAbi.json'; import spaceFactoryAbi from './spaceFactoryAbi.json'; const DeployType = { Deploy: [ { name: 'implementation', type: 'address' }, { name: 'initializer', type: 'bytes' }, { name: 'salt', type: 'uint256' } ] }; const VERIFYING_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string); const IMPLEMENTATION_ADDRESS = getAddress( process.env.NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS as string ); const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK; const INITIALIZE_SELECTOR = process.env.NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR; export default async function payload(input: { spaceOwner: string; id: string; maxSupply: string; mintPrice: string; proposerFee: string; salt: string; spaceTreasury: string; }) { const params = await validateDeployInput(input); const space = await fetchSpace(params.id); await validateSpace(params.spaceOwner, space); const initializer = getInitializer({ spaceOwner: params.spaceOwner, spaceId: space?.id as string, maxSupply: params.maxSupply, mintPrice: params.mintPrice, proposerFee: params.proposerFee, spaceTreasury: params.spaceTreasury }); const result = { initializer, salt: params.salt, abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full), verifyingContract: VERIFYING_CONTRACT, implementation: IMPLEMENTATION_ADDRESS, signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt) }; console.debug('Signer', signer.address); console.debug('Payload', result); return result; } function getInitializer(args: { spaceId: string; maxSupply: number; mintPrice: string; proposerFee: number; spaceTreasury: string; spaceOwner: string; }) { const params = [ args.spaceId, '0.1', args.maxSupply, BigInt(args.mintPrice), args.proposerFee, getAddress(args.spaceTreasury), getAddress(args.spaceOwner) ]; // This encodeFunctionData should ignore the last 4 params compared to // the smart contract version // NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting // from the smart contract const initializer = new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params); const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`; console.debug('Initializer params', params); return result; } async function generateSignature(implementation: string, initializer: string, salt: string) { const params = { domain: { name: 'SpaceCollectionFactory', version: '0.1', chainId: NFT_CLAIMER_NETWORK, verifyingContract: VERIFYING_CONTRACT }, types: DeployType, value: { implementation, initializer, salt: BigInt(salt) } }; return splitSignature
(await signer._signTypedData(params.domain, params.types, params.value));
}
src/lib/nftClaimer/deploy.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": "async function generateSignature(\n verifyingContract: string,\n domain: string,\n message: Record<string, string | bigint>\n) {\n return splitSignature(\n await signer._signTypedData(\n {\n name: domain,\n version: '0.1',", "score": 0.850871741771698 }, { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": " };\n return {\n signature: await generateSignature(verifyingContract, spaceId, message),\n contractAddress: verifyingContract,\n spaceId: proposal?.space.id,\n ...message,\n salt: params.salt,\n abi: new Interface(abi).getFunction('mint').format(FormatTypes.full)\n };\n}", "score": 0.7963764667510986 }, { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": "const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;\nexport default async function payload(input: {\n proposalAuthor: string;\n recipient: string;\n id: string;\n salt: string;\n}) {\n const params = await validateMintInput(input);\n const proposal = await fetchProposal(params.id);\n validateProposal(proposal, params.proposalAuthor);", "score": 0.7795897722244263 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": " const {\n data: { proposal }\n }: { data: { proposal: Proposal | null } } = await client.query({\n query: PROPOSAL_QUERY,\n variables: {\n id\n }\n });\n return proposal;\n}", "score": 0.7684253454208374 }, { "filename": "src/api.ts", "retrieved_chunk": " const { proposalAuthor, address, id, salt } = req.body;\n try {\n return res.json(await mintPayload({ proposalAuthor, recipient: address, id, salt }));\n } catch (e: any) {\n capture(e);\n return rpcError(res, e, salt);\n }\n});\nexport default router;", "score": 0.7487391829490662 } ]
typescript
(await signer._signTypedData(params.domain, params.types, params.value));
import { readFileSync } from 'fs'; import path from 'path'; import db from '../helpers/mysql'; type MODERATION_LIST = Record<string, string[] | JSON>; const CACHE_PATH = path.resolve(__dirname, `../../${process.env.MODERATION_LIST_PATH || 'data'}`); const FIELDS = new Map<keyof MODERATION_LIST, Record<string, string>>([ ['flaggedLinks', { action: 'flag', type: 'link' }], ['flaggedProposals', { action: 'flag', type: 'proposal' }], ['flaggedSpaces', { action: 'flag', type: 'space' }], ['flaggedIps', { action: 'flag', type: 'ip' }], ['verifiedSpaces', { action: 'verify', type: 'space' }], ['verifiedTokens', { file: 'verifiedTokens.json' }] ]); export function readFile(filename: string) { return parseFileContent( readFileSync(path.join(CACHE_PATH, filename), { encoding: 'utf8' }), filename.split('.')[1] ); } function parseFileContent(content: string, parser: string): MODERATION_LIST[keyof MODERATION_LIST] { switch (parser) { case 'txt': return content.split('\n').filter(value => value !== ''); case 'json': return JSON.parse(content); default: throw new Error('Invalid file type'); } } export default async function getModerationList(fields = Array.from(FIELDS.keys())) { const list: Partial<MODERATION_LIST> = {}; const reverseMapping: Record<string, keyof MODERATION_LIST> = {}; const queryWhereStatement: string[] = []; let queryWhereArgs: string[] = []; fields.forEach(field => { if (FIELDS.has(field)) { const args = FIELDS.get(field) as Record<string, string>; if (!args.file) { list[field] = []; reverseMapping[`${args.action}-${args.type}`] = field; queryWhereStatement.push(`(action = ? AND type = ?)`); queryWhereArgs = queryWhereArgs.concat([args.action, args.type]); } else { list[field] = readFile(args.file); } } }); if (queryWhereStatement.length > 0) { const dbResults =
await db.queryAsync( `SELECT * FROM moderation WHERE ${queryWhereStatement.join(' OR ')}`, queryWhereArgs );
dbResults.forEach(row => { (list[reverseMapping[`${row.action}-${row.type}`]] as string[]).push(row.value as string); }); } return list; }
src/lib/moderationList.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/api.ts", "retrieved_chunk": " return rpcError(res, 'INTERNAL_ERROR', id);\n }\n});\nrouter.get('/moderation', async (req, res) => {\n const { list } = req.query;\n try {\n res.json(await getModerationList(list ? (list as string).split(',') : undefined));\n } catch (e) {\n capture(e);\n return rpcError(res, 'INTERNAL_ERROR', '');", "score": 0.7636735439300537 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": "export async function fetchVotes(\n id: string,\n { first = 1000, skip = 0, orderBy = 'created_gte', orderDirection = 'asc', created_gte = 0 } = {}\n) {\n const {\n data: { votes }\n }: { data: { votes: Vote[] } } = await client.query({\n query: VOTES_QUERY,\n variables: {\n id,", "score": 0.7588352560997009 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": " orderBy,\n orderDirection,\n first,\n skip,\n created_gte\n }\n });\n return votes;\n}\nexport async function fetchSpace(id: string) {", "score": 0.7568310499191284 }, { "filename": "src/helpers/utils.ts", "retrieved_chunk": " error: {\n code: errorCode,\n message: errorMessage\n },\n id\n });\n}\nexport async function sleep(time: number) {\n return new Promise(resolve => {\n setTimeout(resolve, time);", "score": 0.756824254989624 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " enabled: boolean;\n};\nexport async function getSpaceCollection(spaceId: string) {\n const {\n data: { spaceCollections }\n }: { data: { spaceCollections: SpaceCollection[] } } = await client.query({\n query: SPACE_COLLECTION_QUERY,\n variables: {\n spaceId\n }", "score": 0.7481226921081543 } ]
typescript
await db.queryAsync( `SELECT * FROM moderation WHERE ${queryWhereStatement.join(' OR ')}`, queryWhereArgs );
import { gql, ApolloClient, InMemoryCache, HttpLink } from '@apollo/client/core'; import fetch from 'cross-fetch'; import snapshot from '@snapshot-labs/snapshot.js'; import { CID } from 'multiformats/cid'; import { Wallet } from '@ethersproject/wallet'; import { Contract } from '@ethersproject/contracts'; import { getAddress, isAddress } from '@ethersproject/address'; import { BigNumber } from '@ethersproject/bignumber'; import { capture } from '../../helpers/sentry'; import type { Proposal, Space } from '../../helpers/snapshot'; const requiredEnvKeys = [ 'NFT_CLAIMER_PRIVATE_KEY', 'NFT_CLAIMER_NETWORK', 'NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT', 'NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS', 'NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR', 'NFT_CLAIMER_SUBGRAPH_URL' ]; const HUB_NETWORK = process.env.HUB_URL === 'https://hub.snapshot.org' ? '1' : '5'; const DEPLOY_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string); const NFT_CLAIMER_NETWORK = parseInt(process.env.NFT_CLAIMER_NETWORK as string); const missingEnvKeys: string[] = []; requiredEnvKeys.forEach(key => { if (!process.env[key]) { missingEnvKeys.push(key); } }); if (missingEnvKeys.length > 0) { throw new Error( `NFT Claimer not configured properly, missing env keys: ${missingEnvKeys.join(', ')}` ); } export const signer = new Wallet(process.env.NFT_CLAIMER_PRIVATE_KEY as string); export async function mintingAllowed(space: Space) { return (await getSpaceCollection(space.id)).enabled; } export async function validateSpace(address: string, space: Space | null) { if (!space) { throw new Error('RECORD_NOT_FOUND'); } if (NFT_CLAIMER_NETWORK !== 5 && !(await isSpaceOwner(space.id, address))) { throw new Error('Address is not the space owner'); } const contract = await getSpaceCollection(space.id); if (contract) { throw new Error(`SpaceCollection contract already exist (${contract.id})`); } } async function isSpaceOwner(spaceId: string, address: string) { return (await snapshot.utils.getSpaceController(spaceId, HUB_NETWORK)) === getAddress(address); } export function validateProposal(
proposal: Proposal | null, proposer: string) {
if (!proposal) { throw new Error('RECORD_NOT_FOUND'); } if (getAddress(proposer) !== getAddress(proposal.author)) { throw new Error('Proposal author is not matching'); } if (!mintingAllowed(proposal.space)) { throw new Error('Space has not allowed minting'); } } export async function getProposalContract(spaceId: string) { const contract = await getSpaceCollection(spaceId); if (!contract) { throw new Error(`SpaceCollection contract is not found for space ${spaceId}`); } return contract.id; } const client = new ApolloClient({ link: new HttpLink({ uri: process.env.NFT_CLAIMER_SUBGRAPH_URL, fetch }), cache: new InMemoryCache({ addTypename: false }), defaultOptions: { query: { fetchPolicy: 'no-cache' } } }); const SPACE_COLLECTION_QUERY = gql` query SpaceCollections($spaceId: String) { spaceCollections(where: { spaceId: $spaceId }, first: 1) { id enabled } } `; type SpaceCollection = { id: string; enabled: boolean; }; export async function getSpaceCollection(spaceId: string) { const { data: { spaceCollections } }: { data: { spaceCollections: SpaceCollection[] } } = await client.query({ query: SPACE_COLLECTION_QUERY, variables: { spaceId } }); return spaceCollections[0]; } export function numberizeProposalId(id: string) { return BigNumber.from(id.startsWith('0x') ? id : CID.parse(id).bytes).toString(); } export function validateAddresses(addresses: Record<string, string>) { Object.entries(addresses).forEach(([key, value]) => { if (!isAddress(value)) { throw new Error(`Value for ${key} is not a valid address (${value})`); } }); return true; } function validateNumbers(numbers: Record<string, string>) { Object.entries(numbers).forEach(([key, value]) => { try { BigNumber.from(value).toString(); } catch (e: any) { throw new Error(`Value for ${key} is not a valid number (${value})`); } }); return true; } export async function validateProposerFee(fee: number) { if (fee < 0 || fee > 100) { throw new Error('proposerFee should be between 0 and 100'); } const sFee = await snapshotFee(); if (sFee + fee > 100) { throw new Error(`proposerFee should not be greater than ${100 - sFee}`); } return true; } export async function validateDeployInput(params: any) { validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury }); validateNumbers({ maxSupply: params.maxSupply, proposerFee: params.proposerFee, mintPrice: params.mintPrice, salt: params.salt }); await validateProposerFee(parseInt(params.proposerFee)); return { spaceOwner: getAddress(params.spaceOwner), spaceTreasury: getAddress(params.spaceTreasury), proposerFee: parseInt(params.proposerFee), maxSupply: parseInt(params.maxSupply), mintPrice: parseInt(params.mintPrice), ...params }; } export async function validateMintInput(params: any) { validateAddresses({ proposalAuthor: params.proposalAuthor, recipient: params.recipient }); validateNumbers({ salt: params.salt }); return { proposalAuthor: getAddress(params.proposalAuthor), recipient: getAddress(params.recipient), ...params }; } export async function snapshotFee(): Promise<number> { try { const provider = snapshot.utils.getProvider(NFT_CLAIMER_NETWORK); const contract = new Contract( DEPLOY_CONTRACT, ['function snapshotFee() public view returns (uint8)'], provider ); return contract.snapshotFee(); } catch (e: any) { capture(e); throw 'Unable to retrieve the snapshotFee'; } }
src/lib/nftClaimer/utils.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": " const spaceId = proposal?.space.id as string;\n const verifyingContract = await getProposalContract(spaceId);\n if (!mintingAllowed(proposal?.space as Space)) {\n throw new Error('Space has closed minting');\n }\n const message = {\n proposer: params.proposalAuthor,\n recipient: params.recipient,\n proposalId: numberizeProposalId(params.id),\n salt: BigInt(params.salt)", "score": 0.8062654733657837 }, { "filename": "src/helpers/snapshot.ts", "retrieved_chunk": "`;\nconst SPACE_QUERY = gql`\n query Space($id: String) {\n space(id: $id) {\n id\n network\n }\n }\n`;\nexport async function fetchProposal(id: string) {", "score": 0.7708777189254761 }, { "filename": "src/lib/votesReport.ts", "retrieved_chunk": " this.proposal = await fetchProposal(this.id);\n if (!this.proposal || this.proposal.state !== 'closed') {\n return Promise.reject('RECORD_NOT_FOUND');\n }\n return true;\n }\n getContent = async () => {\n this.isCacheable();\n const votes = await this.fetchAllVotes();\n let content = '';", "score": 0.7558376789093018 }, { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": "const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK;\nexport default async function payload(input: {\n proposalAuthor: string;\n recipient: string;\n id: string;\n salt: string;\n}) {\n const params = await validateMintInput(input);\n const proposal = await fetchProposal(params.id);\n validateProposal(proposal, params.proposalAuthor);", "score": 0.754106342792511 }, { "filename": "src/lib/nftClaimer/deploy.ts", "retrieved_chunk": " const space = await fetchSpace(params.id);\n await validateSpace(params.spaceOwner, space);\n const initializer = getInitializer({\n spaceOwner: params.spaceOwner,\n spaceId: space?.id as string,\n maxSupply: params.maxSupply,\n mintPrice: params.mintPrice,\n proposerFee: params.proposerFee,\n spaceTreasury: params.spaceTreasury\n });", "score": 0.7301419377326965 } ]
typescript
proposal: Proposal | null, proposer: string) {
import { getAddress } from '@ethersproject/address'; import { splitSignature } from '@ethersproject/bytes'; import { FormatTypes, Interface } from '@ethersproject/abi'; import { fetchSpace } from '../../helpers/snapshot'; import { signer, validateDeployInput, validateSpace } from './utils'; import spaceCollectionAbi from './spaceCollectionImplementationAbi.json'; import spaceFactoryAbi from './spaceFactoryAbi.json'; const DeployType = { Deploy: [ { name: 'implementation', type: 'address' }, { name: 'initializer', type: 'bytes' }, { name: 'salt', type: 'uint256' } ] }; const VERIFYING_CONTRACT = getAddress(process.env.NFT_CLAIMER_DEPLOY_VERIFYING_CONTRACT as string); const IMPLEMENTATION_ADDRESS = getAddress( process.env.NFT_CLAIMER_DEPLOY_IMPLEMENTATION_ADDRESS as string ); const NFT_CLAIMER_NETWORK = process.env.NFT_CLAIMER_NETWORK; const INITIALIZE_SELECTOR = process.env.NFT_CLAIMER_DEPLOY_INITIALIZE_SELECTOR; export default async function payload(input: { spaceOwner: string; id: string; maxSupply: string; mintPrice: string; proposerFee: string; salt: string; spaceTreasury: string; }) { const params = await validateDeployInput(input); const space = await fetchSpace(params.id); await validateSpace(params.spaceOwner, space); const initializer = getInitializer({ spaceOwner: params.spaceOwner, spaceId: space?.id as string, maxSupply: params.maxSupply, mintPrice: params.mintPrice, proposerFee: params.proposerFee, spaceTreasury: params.spaceTreasury }); const result = { initializer, salt: params.salt, abi: new Interface(spaceFactoryAbi).getFunction('deployProxy').format(FormatTypes.full), verifyingContract: VERIFYING_CONTRACT, implementation: IMPLEMENTATION_ADDRESS, signature: await generateSignature(IMPLEMENTATION_ADDRESS, initializer, params.salt) }; console.debug('Signer', signer.address); console.debug('Payload', result); return result; } function getInitializer(args: { spaceId: string; maxSupply: number; mintPrice: string; proposerFee: number; spaceTreasury: string; spaceOwner: string; }) { const params = [ args.spaceId, '0.1', args.maxSupply, BigInt(args.mintPrice), args.proposerFee, getAddress(args.spaceTreasury), getAddress(args.spaceOwner) ]; // This encodeFunctionData should ignore the last 4 params compared to // the smart contract version // NOTE Do not forget to remove the last 4 params in the ABI when copy/pasting // from the smart contract const initializer
= new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);
const result = `${INITIALIZE_SELECTOR}${initializer.slice(10)}`; console.debug('Initializer params', params); return result; } async function generateSignature(implementation: string, initializer: string, salt: string) { const params = { domain: { name: 'SpaceCollectionFactory', version: '0.1', chainId: NFT_CLAIMER_NETWORK, verifyingContract: VERIFYING_CONTRACT }, types: DeployType, value: { implementation, initializer, salt: BigInt(salt) } }; return splitSignature(await signer._signTypedData(params.domain, params.types, params.value)); }
src/lib/nftClaimer/deploy.ts
snapshot-labs-snapshot-sidekick-800dacf
[ { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " }\n });\n return true;\n}\nexport async function validateProposerFee(fee: number) {\n if (fee < 0 || fee > 100) {\n throw new Error('proposerFee should be between 0 and 100');\n }\n const sFee = await snapshotFee();\n if (sFee + fee > 100) {", "score": 0.8055761456489563 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " ...params\n };\n}\nexport async function snapshotFee(): Promise<number> {\n try {\n const provider = snapshot.utils.getProvider(NFT_CLAIMER_NETWORK);\n const contract = new Contract(\n DEPLOY_CONTRACT,\n ['function snapshotFee() public view returns (uint8)'],\n provider", "score": 0.8041462302207947 }, { "filename": "src/lib/nftClaimer/utils.ts", "retrieved_chunk": " throw new Error(`proposerFee should not be greater than ${100 - sFee}`);\n }\n return true;\n}\nexport async function validateDeployInput(params: any) {\n validateAddresses({ spaceOwner: params.spaceOwner, spaceTreasury: params.spaceTreasury });\n validateNumbers({\n maxSupply: params.maxSupply,\n proposerFee: params.proposerFee,\n mintPrice: params.mintPrice,", "score": 0.7799063920974731 }, { "filename": "src/api.ts", "retrieved_chunk": "router.post('/nft-claimer/deploy', async (req, res) => {\n const { address, id, salt, maxSupply, mintPrice, spaceTreasury, proposerFee } = req.body;\n try {\n return res.json(\n await deployPayload({\n spaceOwner: address,\n id,\n maxSupply,\n mintPrice,\n proposerFee,", "score": 0.7736600637435913 }, { "filename": "src/lib/nftClaimer/mint.ts", "retrieved_chunk": "async function generateSignature(\n verifyingContract: string,\n domain: string,\n message: Record<string, string | bigint>\n) {\n return splitSignature(\n await signer._signTypedData(\n {\n name: domain,\n version: '0.1',", "score": 0.7699474096298218 } ]
typescript
= new Interface(spaceCollectionAbi).encodeFunctionData('initialize', params);