repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
inspect_ai
github_2023
UKGovernmentBEIS
typescript
ScaleBaseFont
const ScaleBaseFont = (scale: number): string => { return `${kBaseFontSize + scale}rem`; };
/** * Scales the base font size by the provided scale factor. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/appearance/fonts.ts#L9-L11
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
calculateEstimatedHeight
const calculateEstimatedHeight = (heights: Map<number, number>): number => { if (heights.size === 0) return listMetrics.estimatedRowHeight; // Calculate average of measured heights let sum = 0; heights.forEach((height) => { sum += height; }); // Use exponential moving average to smooth t...
// Calculate new estimated height based on measured rows
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/components/VirtualList.tsx#L66-L81
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
measureRows
const measureRows = () => { let updates: [number, number][] = []; rowRefs.current.forEach((element, index) => { if (element) { const measuredHeight = element.offsetHeight; if ( measuredHeight && measuredHeight !== listMetrics.rowHeights.get(index) ) { ...
// Measure rendered rows and update heights if needed
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/components/VirtualList.tsx#L96-L131
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
readJSONFile
const readJSONFile = async ( file: string, maxBytes?: number, ): Promise<Object> => { try { const data = await remoteZipFile.readFile(file, maxBytes); const textDecoder = new TextDecoder("utf-8"); const jsonString = textDecoder.decode(data); return asyncJsonParse(jsonString); }...
/** * Reads and parses a JSON file from the zip. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/logfile/remoteLogFile.ts#L51-L73
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
listSamples
const listSamples = async (): Promise<SampleEntry[]> => { return Array.from(remoteZipFile.centralDirectory.keys()) .filter( (filename) => filename.startsWith("samples/") && filename.endsWith(".json"), ) .map((filename) => { const [sampleId, epochStr] = filename.split("/")...
/** * Lists all samples in the zip file. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/logfile/remoteLogFile.ts#L78-L91
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
readSample
const readSample = async ( sampleId: string, epoch: number, ): Promise<EvalSample> => { const sampleFile = `samples/${sampleId}_epoch_${epoch}.json`; if (remoteZipFile.centralDirectory.has(sampleFile)) { return (await readJSONFile(sampleFile, MAX_BYTES)) as EvalSample; } else { throw n...
/** * Reads a specific sample file. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/logfile/remoteLogFile.ts#L96-L108
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
readHeader
const readHeader = async (): Promise<EvalHeader> => { if (remoteZipFile.centralDirectory.has("header.json")) { return (await readJSONFile("header.json")) as EvalHeader; } else { const evalSpec = (await readJSONFile("_journal/start.json")) as LogStart; return { status: "started", ...
/** * Reads the results.json file. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/logfile/remoteLogFile.ts#L113-L124
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
readFallbackSummaries
const readFallbackSummaries = async (): Promise<SampleSummary[]> => { const summaryFiles = Array.from( remoteZipFile.centralDirectory.keys(), ).filter( (filename) => filename.startsWith("_journal/summaries/") && filename.endsWith(".json"), ); const summaries: SampleSummary[]...
/** * Reads individual summary files when summaries.json is not available. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/logfile/remoteLogFile.ts#L129-L164
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
readSampleSummaries
const readSampleSummaries = async (): Promise<SampleSummary[]> => { if (remoteZipFile.centralDirectory.has("summaries.json")) { return (await readJSONFile("summaries.json")) as SampleSummary[]; } else { return readFallbackSummaries(); } };
/** * Reads all summaries, falling back to individual files if necessary. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/logfile/remoteLogFile.ts#L169-L175
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
decompressAsync
const decompressAsync = async ( data: Uint8Array, opts: AsyncInflateOptions, ): Promise<Uint8Array> => { return new Promise((resolve, reject) => { decompress(data, opts, (err, result) => { if (err) { reject(err); } else { resolve(result); } }); }); };
/** * Asynchronously decompresses the provided data using the specified options. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/logfile/remoteZipFile.ts#L157-L170
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
parseZipFileEntry
const parseZipFileEntry = async ( file: string, rawData: Uint8Array, ): Promise<ZipFileEntry> => { // Parse ZIP entry header const view = new DataView(rawData.buffer); let offset = 0; const signature = view.getUint32(offset, true); if (signature !== 0x04034b50) { throw new Error(`Invalid ZIP entry sig...
/** * Extracts and parses the header and data of a compressed ZIP entry from raw binary data. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/logfile/remoteZipFile.ts#L175-L220
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
parseCentralDirectory
const parseCentralDirectory = (buffer: Uint8Array<ArrayBufferLike>) => { let offset = 0; const view = new DataView(buffer.buffer); const entries = new Map(); while (offset < buffer.length) { // Central Directory signature if (view.getUint32(offset, true) !== 0x02014b50) break; const filenameLength...
/** * Parses the central directory of a ZIP file from the provided buffer and returns a map of entries. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/logfile/remoteZipFile.ts#L226-L283
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
mimeTypeForFormat
const mimeTypeForFormat = (format: Format | Format1): string => { switch (format) { case "mov": return "video/quicktime"; case "wav": return "audio/wav"; case "mp3": return "audio/mpeg"; case "mp4": return "video/mp4"; case "mpeg": return "video/mpeg"; } };
/** * Renders message content based on its type. * Supports rendering strings, images, and tools using specific renderers. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/chat/MessageContent.tsx#L144-L157
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
normalizeContent
const normalizeContent = ( content: ContentText | ContentImage | ContentAudio | ContentVideo | string, ): ContentText | ContentImage | ContentAudio | ContentVideo => { if (typeof content === "string") { return { type: "text", text: content, }; } else { return content; } };
/** * Normalize strings */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/chat/messages.ts#L101-L112
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
isContentImage
function isContentImage( value: | string | number | boolean | ContentText | ContentAudio | ContentImage | ContentVideo | ContentTool, ) { if (value && typeof value === "object") { if (value.type === "image") { return true; } else if (value.ty...
// don't collapse if output includes an image
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/chat/tools/ToolCallView.tsx#L51-L75
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
normalizeContent
const normalizeContent = ( output: | string | number | boolean | ContentText | ContentImage | ContentAudio | ContentVideo | ContentTool | ( | ContentText | ContentImage | ContentAudio | ContentVideo | ContentTool )[], ): ( | ContentTe...
/** * Renders the ToolCallView component. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/chat/tools/ToolCallView.tsx#L108-L147
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
scoreMetadata
const scoreMetadata = ( sample: BasicSampleData, scorer: string, ): Record<string, unknown> | undefined => { if (sample && sample.scores) { const sampleScore = sample.scores[scorer]; if (sampleScore && sampleScore.metadata) { return sampleScore.metadata; } } return undefi...
// Retrieve the metadata for a sample
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/descriptor/samplesDescriptor.tsx#L86-L97
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
coerceValue
const coerceValue = (value: unknown, descriptor: ScoreDescriptor): unknown => { if (descriptor && descriptor.scoreType === kScoreTypeBoolean) { return Boolean(value); } else { return value; } };
/** * Coerces a value to the type expected by the score. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/sample-tools/filters.ts#L28-L34
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
isFilteringSupportedForValue
const isFilteringSupportedForValue = (value: unknown): boolean => ["string", "number", "boolean"].includes(typeof value);
// Whether a particular value is filter-able
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/sample-tools/filters.ts#L37-L38
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
bannedShortScoreNames
const bannedShortScoreNames = (scores: ScoreLabel[]): Set<string> => { const used: Set<string> = new Set(); const banned: Set<string> = new Set(); for (const { scorer, name } of scores) { banned.add(scorer); if (used.has(name)) { banned.add(name); } else { used.add(name); } } retur...
/** * Returns the names of scores that are not allowed to be used as short names in * filter expressions because they are not unique. This should be applied only to * the nested scores, not to the top-level scorer names. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/sample-tools/filters.ts#L45-L57
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
scoreVariables
const scoreVariables = ( evalDescriptor: EvalDescriptor, sampleScores: Scores1, ) => { const bannedShortNames = bannedShortScoreNames(evalDescriptor.scores); const variables: Record<string, unknown> = {}; const addScore = ( variableName: string, scoreLabel: ScoreLabel, value: unknown, ) => { ...
/** * Generates a dictionary of variables that can be used in the filter expression. * High-level scorer metrics can be accessed by name directly. * Child metrics are accessed using dot notation (e.g. `scorer_name.score_name`) or * directly by name when it is unique. * * @param {import("../../samples/descriptor/s...
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/sample-tools/filters.ts#L69-L102
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
addScore
const addScore = ( scoreLabel: ScoreLabel, shortName?: string, qualifiedName?: string, ) => { const canonicalName = shortName || qualifiedName; if (!canonicalName) { throw new Error("Unable to create a canonical name for a score"); } const descriptor = evalDescriptor.scoreDescriptor(...
/** * @param {string | undefined} shortName * @param {string | undefined} qualifiedName * @param {import("../../types").ScoreLabel} scoreLabel */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/sample-tools/filters.ts#L123-L169
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
createWordRegex
const createWordRegex = (words: string[]): RegExp => new RegExp(`^(${words.join("|")})\\b`);
// Utilities
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/sample-tools/sample-filter/tokenize.ts#L25-L26
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
nextToken
function nextToken(stream: StringStream): string | null { // Check patterns in order of specificity if (stream.match(TOKEN_PATTERNS.STRING)) return "string"; if (stream.match(TOKEN_PATTERNS.UNTERMINATED_STRING)) return "unterminatedString"; if (stream.match(TOKEN_PATTERNS.NUMBER)) return "number"; if (str...
// Token recognition
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/sample-tools/sample-filter/tokenize.ts#L43-L59
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
decisionLabel
const decisionLabel = (decision: string): string => { switch (decision) { case "approve": return "Approved"; case "reject": return "Rejected"; case "terminate": return "Terminated"; case "escalate": return "Escalated"; case "modify": return "Modified"; default: ...
/** * Determines the label for a decision */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/transcript/ApprovalEventView.tsx#L31-L46
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
decisionIcon
const decisionIcon = (decision: string): string => { switch (decision) { case "approve": return ApplicationIcons.approvals.approve; case "reject": return ApplicationIcons.approvals.reject; case "terminate": return ApplicationIcons.approvals.terminate; case "escalate": return Ap...
/** * Determines the icon for a decision */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/transcript/ApprovalEventView.tsx#L51-L66
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
SubtaskSummary
const SubtaskSummary: React.FC<SubtaskSummaryProps> = ({ input, result }) => { result = typeof result === "object" ? result : { result }; return ( <div className={clsx(styles.subtaskSummary)}> <div className={clsx("text-style-label")}>Input</div> <div className={clsx("text-size-large", styles.subtas...
/** * Renders the StateEventView component. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/transcript/SubtaskEventView.tsx#L97-L113
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
Rendered
const Rendered: React.FC<RenderedProps> = ({ values }) => { if (Array.isArray(values)) { return values.map((val) => { return <Rendered values={val} />; }); } else if (values && typeof values === "object") { return <MetaDataView entries={values as Record<string, unknown>} />; } else { return ...
/** * Recursively renders content based on the type of `values`. value. */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/samples/transcript/SubtaskEventView.tsx#L123-L133
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
AsyncQueue.enqueue
async enqueue<T>(task: () => Promise<T>): Promise<T> { return new Promise<T>((resolve, reject) => { this.queue.push(async () => { try { const result = await task(); resolve(result); } catch (error) { reject(error); } finally { this.runningCount--...
// Adds a task to the queue and runs it if the concurrency limit allows.
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/utils/queue.ts#L21-L39
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
AsyncQueue.runNext
private runNext(): void { if (this.queue.length > 0 && this.runningCount < this.concurrentLimit) { const task = this.queue.shift(); if (task) { this.runningCount++; task(); } } }
// Runs the next task in the queue if there are available slots for concurrent execution.
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/utils/queue.ts#L42-L50
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
noGrouping
const noGrouping = ( samples: SampleSummary[], order: "asc" | "desc", ): ((sample: SampleSummary, index: number) => ListItem[]) => { const counter = getCounter(samples.length, 1, order); return (sample: SampleSummary, index: number) => { counter.incrementItem(); const itemCount = counter.item(); ret...
/** * Performs no grouping */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/workspace/tabs/grouping.ts#L28-L46
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
groupBySample
const groupBySample = ( samples: SampleSummary[], sampleDescriptor: SamplesDescriptor, order: "asc" | "desc", ): (( sample: SampleSummary, index: number, previousSample?: SampleSummary, ) => ListItem[]) => { // ensure that we are sorted by id samples = samples.sort((a, b) => { if (typeof a.id === "s...
/** * Groups by sample (showing separators for Epochs) */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/workspace/tabs/grouping.ts#L51-L110
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
groupByEpoch
const groupByEpoch = ( samples: SampleSummary[], sampleDescriptor: SamplesDescriptor, order: "asc" | "desc", ): (( sample: SampleSummary, index: number, previousSample?: SampleSummary, ) => ListItem[]) => { const groupCount = sampleDescriptor.evalDescriptor.epochs; const itemCount = samples.length / gro...
/** * Groups by epoch (showing a separator for each sample) */
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/workspace/tabs/grouping.ts#L115-L160
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
getCounter
const getCounter = ( itemCount: number, groupCount: number, order: "asc" | "desc", ) => { let itemIndex = order !== "desc" ? 0 : itemCount + 1; let groupIndex = order !== "desc" ? 0 : groupCount + 1; return { resetItem: () => { itemIndex = order !== "desc" ? 0 : itemCount + 1; }, increment...
// An order aware counter that hides increment/decrement behavior
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/src/inspect_ai/_view/www/src/workspace/tabs/grouping.ts#L163-L195
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
tasksForDocument
const tasksForDocument = async (documentUri: Uri) => { const document = await workspace.openTextDocument(documentUri); const tasks = readTaskData(document); return tasks; };
// Provides a list of task DocumentSymbols for a document
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/components/document.ts#L31-L35
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
findEnvPython
function findEnvPython(directory: AbsolutePath): string | null { const items = fs.readdirSync(directory.path); // Filter only directories and check if any is an environment directory const envDir = items .map((item) => path.join(directory.path, item)) .filter((filePath) => fs.statSync(filePath).isDirecto...
// Helper function to search for Python environment in a given directory
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/core/python/env.ts#L27-L41
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
platformPaths
const platformPaths = (interpreter: PythonInterpreter, binary: string) => { // find the folder that contained the python bin const binDir = interpreter.execCommand && interpreter.execCommand.length > 0 ? dirname(interpreter.execCommand[0]) : ""; // Check in the bin dir next to the python interpre...
// A list of heuristic paths to use if we can't find inspect
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/core/python/exec.ts#L44-L64
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
openLogViewer
const openLogViewer = async () => { await commands.executeCommand( 'vscode.open', uri, <TextDocumentShowOptions>{ preview: true } ); };
// function to open using defualt editor in preview mode
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/openlog.ts#L17-L23
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
updateStatus
const updateStatus = () => { statusItem.name = "Inspect"; const version = inspectVersion(); const versionSummary = version ? `${version.version.toString()}${version.isDeveloperBuild ? '.dev' : ''}` : "(not found)"; statusItem.text = `Inspect: ${versionSummary}`; statusItem.tooltip = `Inspect: ${ver...
// track changes to inspect
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/statusbar.ts#L15-L21
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
ActiveTaskManager.getActiveTaskInfo
public getActiveTaskInfo(): DocumentTaskInfo | undefined { return this.activeTaskInfo_; }
// Get the task information for the current selection
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/active-task/active-task-provider.ts#L96-L98
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
ActiveTaskManager.refresh
public async refresh() { const currentSelection = window.activeTextEditor?.selection; const currentDocument = window.activeTextEditor?.document; await this.updateActiveTaskWithDocument(currentDocument, currentSelection); }
// Refresh the task information for the current editor
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/active-task/active-task-provider.ts#L101-L105
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
ActiveTaskManager.setActiveTaskInfo
setActiveTaskInfo(task?: DocumentTaskInfo) { if (this.activeTaskInfo_ !== task) { this.activeTaskInfo_ = task; this.onActiveTaskChanged_.fire({ activeTaskInfo: this.activeTaskInfo_ }); } }
// Set the task information
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/active-task/active-task-provider.ts#L158-L163
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
findTaskSelection
const findTaskSelection = async (task: string | undefined) => { if (task) { return taskRangeForDocument(task, fileUri); } else { return await firstTaskRangeForDocument(fileUri); } };
// Find the task selection for the document (if any)
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/activity-bar/task-outline-commands.ts#L152-L158
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
findTreeItem
async function findTreeItem( activeTask: DocumentTaskInfo, treeDataProvider: TaskOutLineTreeDataProvider ) { const filePath = activeTask.document.fsPath; const taskName = activeTask.activeTask?.name; const taskTreeItem = await findTask(filePath, treeDataProvider, taskName); if (taskTreeItem) { return ta...
// Find a task in the tree based upon its
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/activity-bar/task-outline-provider.ts#L358-L370
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
updateTree
const updateTree = () => { // see what the active log dir is const preferredLogDir = context.workspaceState.get<string>(kLogListingDir); const logDir = preferredLogDir ? Uri.parse(preferredLogDir) : envManager.getDefaultLogDir(); // set it treeDataProvider.setLogListing(new LogListing(context, logD...
// update the tree based on the current preferred log dir
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/activity-bar/log-listing/log-listing-provider.ts#L45-L61
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
findNodeWithUri
const findNodeWithUri = (node: LogNode): LogNode | undefined => { if (node.type === "file") { return this.uriForNode(node).toString() === uri.toString() ? node : undefined; } else if (node.type === "dir") { for (const child of node.children) { const uri = findNo...
// recursively look for a node that matches the uri
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/activity-bar/log-listing/log-listing.ts#L84-L98
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
createDir
function createDir(name: string, parent?: LogNode): LogNode { return { type: "dir", name, children: [], parent, }; }
// Helper to create a directory node
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/activity-bar/log-listing/log-listing.ts#L171-L178
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
createFileNode
function createFileNode(file: LogFile, parent?: LogNode): LogNode { return { ...file, type: "file", parent, }; }
// Helper to create a file node
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/activity-bar/log-listing/log-listing.ts#L181-L187
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
ensureDirectory
function ensureDirectory(path: string, parent?: LogNode): LogNode { if (dirCache.has(path)) { return dirCache.get(path)!; } const dir = createDir(path, parent); dirCache.set(path, dir); return dir; }
// Helper to ensure directory exists and return it
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/activity-bar/log-listing/log-listing.ts#L190-L198
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
taskCommands
function taskCommands(uri: Uri, fn: string): Command[] { if (isNotebook(uri)) { return [ { title: "$(play) Run Task", tooltip: "Execute this evaluation task.", command: "inspect.runTask", arguments: [uri, fn], }, ]; } else { return [ { title: "$(...
// The Code Lens commands
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/codelens/codelens-provider.ts#L22-L48
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
terminalEnvironment
const terminalEnvironment = (context: ExtensionContext) => { const filter = (binPath: AbsolutePath | null) => { switch (process.platform) { case "win32": { const localPath = process.env['LocalAppData']; if (localPath) { return binPath?.path.startsWith(localPath); ...
// Configures the terminal environment to support inspect. We do this
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/inspect/inspect-manager.ts#L87-L117
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
evalLogs
function evalLogs(log_dir: Uri): Promise<string | undefined> { // Return both the log_dir and the logs const response = withMinimumInspectVersion<string | undefined>( kInspectOpenInspectViewVersion, () => { const workspaceRoot = activeWorkspaceFolder().uri; const logs = inspectEvalLogs(activeWo...
// The eval commands below need to be coordinated in terms of their working directory
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/inspect/inspect-view-server.ts#L256-L280
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
InspectLogReadonlyEditor.openCustomDocument
async openCustomDocument( uri: vscode.Uri, _openContext: vscode.CustomDocumentOpenContext, _token: vscode.CancellationToken ): Promise<vscode.CustomDocument> { return { uri, dispose: () => { } }; }
// eslint-disable-next-line @typescript-eslint/require-await
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/logview/logview-editor.ts#L47-L53
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
InspectLogReadonlyEditor.resolveCustomEditor
async resolveCustomEditor( document: vscode.CustomDocument, webviewPanel: vscode.WebviewPanel, _token: vscode.CancellationToken ): Promise<void> { // check if we should use the log viewer (version check + size threshold) let useLogViewer = hasMinimumInspectVersion(kInspectEvalLogFormatVersion); ...
// eslint-disable-next-line @typescript-eslint/require-await
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/logview/logview-editor.ts#L56-L110
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
resourceUri
const resourceUri = (path: string) => this.panel_.webview .asWebviewUri(Uri.joinPath(viewDirUri, path)) .toString();
// function to resolve resource uri
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/logview/logview-panel.ts#L145-L148
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
InspectSettingsManager.getSettings
public getSettings(): InspectSettings { if (!this.settings_) { this.settings_ = this.readSettings(); } return this.settings_; }
// get the current settings values
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/settings/inspect-settings.ts#L29-L34
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
InspectSettingsManager.setNotifyEvalComplete
public setNotifyEvalComplete(notify: boolean) { const configuration = workspace.getConfiguration(kInspectConfigSection,); void configuration.update(kInspectConfigNotifyEvalComplete, notify, true); }
// write the notification pref
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/settings/inspect-settings.ts#L37-L40
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
InspectSettingsManager.readSettings
private readSettings() { const configuration = workspace.getConfiguration(kInspectConfigSection); const notifyEvalComplete = configuration.get<boolean>(kInspectConfigNotifyEvalComplete); return { notifyEvalComplete: notifyEvalComplete !== undefined ? notifyEvalComplete : true }; }
// Read settings values directly from VS.Code
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/settings/inspect-settings.ts#L44-L50
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
ignorePaths
function ignorePaths() { const ignores: string[] = [".env", "logs/", "__pycache__/"]; return ignores; }
// TODO: Extract this for use adding additional paths (like if the modify env with logdir)
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/providers/workspace/workspace-init.ts#L29-L32
fa64ceab7a943432114e5b8dada495d781b132ea
inspect_ai
github_2023
UKGovernmentBEIS
typescript
MockTextDocument.uri
get uri(): any { return { scheme: "file", path: "test.py" } as Uri; }
// Implement other required interface members with mock values
https://github.com/UKGovernmentBEIS/inspect_ai/blob/fa64ceab7a943432114e5b8dada495d781b132ea/tools/vscode/src/test/codelens-provider.test.ts#L60-L62
fa64ceab7a943432114e5b8dada495d781b132ea
talk2arxiv
github_2023
evanhu1
typescript
getBotReply
const getBotReply = async (message: string, messages: Message[], paper_id: string, setLlmStatus: any, openAIKey: string) => { setLlmStatus(LLMStatus.THINKING); const prompt = await getContextAndConstructPrompt(message, messages, paper_id); console.log(prompt); const memoizedOpenAI = new OpenAI({apiKey: openAIKe...
// const GROBID_SERVER_URL = "http://18.191.167.109:5328";
https://github.com/evanhu1/talk2arxiv/blob/ab0b487217c421a4bf7756d6452c1b6603a2d120/utils/llmtools.tsx#L23-L57
ab0b487217c421a4bf7756d6452c1b6603a2d120
openai-assistant-swarm
github_2023
Mintplex-Labs
typescript
SwarmManager.init
async init() { this.log("Initialization of Swarm Manager is running."); const _ready = await this.findOrUpsertManager(); this.ready = _ready; }
/** * Initializes your account with the primary assistant to execute and delegate to existing assistants */
https://github.com/Mintplex-Labs/openai-assistant-swarm/blob/de7387a2ea0d71b4782adab027063d0f96afb433/src/manager/index.ts#L308-L312
de7387a2ea0d71b4782adab027063d0f96afb433
openai-assistant-swarm
github_2023
Mintplex-Labs
typescript
SwarmManager.allAssistants
async allAssistants(): Promise<Assistant[]> { this.isReady(); return (await _allAssistants(this.assistants, this.log)).filter( (a) => a.id !== this.mgrAssistant?.id, ); }
/** * Returns a list of all assistants connected to this OpenAI apiKey. */
https://github.com/Mintplex-Labs/openai-assistant-swarm/blob/de7387a2ea0d71b4782adab027063d0f96afb433/src/manager/index.ts#L317-L322
de7387a2ea0d71b4782adab027063d0f96afb433
openai-assistant-swarm
github_2023
Mintplex-Labs
typescript
SwarmManager.getAssistants
async getAssistants(assistantIds: string[] = []): Promise<Assistant[]> { this.isReady(); return ( await _getAssistants(this.assistants, this.log, assistantIds) ).filter((a) => a.id !== this.mgrAssistant?.id); }
/** * Returns multiple assistants at once from multiple ids. */
https://github.com/Mintplex-Labs/openai-assistant-swarm/blob/de7387a2ea0d71b4782adab027063d0f96afb433/src/manager/index.ts#L327-L332
de7387a2ea0d71b4782adab027063d0f96afb433
openai-assistant-swarm
github_2023
Mintplex-Labs
typescript
SwarmManager.cleanup
async cleanup() { this.isReady(); if (!this.mgrAssistant) return; await this.assistants.del(this.mgrAssistant.id); this.log( `Primary swarm assistant manager was deleted from OpenAI account.`, ); return; }
/** * Cleanup and remove primary swarm assistant manager from your account. * Only removes the one created with this script using the params defined during creation of class. */
https://github.com/Mintplex-Labs/openai-assistant-swarm/blob/de7387a2ea0d71b4782adab027063d0f96afb433/src/manager/index.ts#L338-L346
de7387a2ea0d71b4782adab027063d0f96afb433
openai-assistant-swarm
github_2023
Mintplex-Labs
typescript
SwarmManager.emitEvent
emitEvent( event: EventTypes, args: ParentResponseEvent | SubRunResponseEvent | PollEvent, ) { this.emitter.emit(event, args); }
/** * Emit informative event from the swarm process running. */
https://github.com/Mintplex-Labs/openai-assistant-swarm/blob/de7387a2ea0d71b4782adab027063d0f96afb433/src/manager/index.ts#L351-L356
de7387a2ea0d71b4782adab027063d0f96afb433
openai-assistant-swarm
github_2023
Mintplex-Labs
typescript
SwarmManager.playgroundLink
playgroundLink(run?: Run | null): string | null { if (!run) return null; return `https://platform.openai.com/playground?assistant=${run.assistant_id}&mode=assistant&thread=${run.thread_id}`; }
/** * Generate the Playground link for an assistant and thread for visualization in the browser. */
https://github.com/Mintplex-Labs/openai-assistant-swarm/blob/de7387a2ea0d71b4782adab027063d0f96afb433/src/manager/index.ts#L361-L364
de7387a2ea0d71b4782adab027063d0f96afb433
openai-assistant-swarm
github_2023
Mintplex-Labs
typescript
SwarmManager.delegateWithPrompt
async delegateWithPrompt( prompt: string, assistantIds: string[] = ["<any>"], runOpts?: RunCreateParams, ): Promise<DelegationResponse> { this.isReady(); const thread = await this.client.beta.threads.create({ messages: [{ role: "user", content: prompt }], metadata: { createdBy:...
/** * Given a single prompt we will create a thread and then find the best option * for assistant execution to complete or fulfill the task. */
https://github.com/Mintplex-Labs/openai-assistant-swarm/blob/de7387a2ea0d71b4782adab027063d0f96afb433/src/manager/index.ts#L370-L426
de7387a2ea0d71b4782adab027063d0f96afb433
openai-assistant-swarm
github_2023
Mintplex-Labs
typescript
parseParallelToolCall
function parseParallelToolCall(toolCall: RequiredActionFunctionToolCall) { let instructions; const callId = toolCall.id; const data = JSON.parse(toolCall.function.arguments); if (data.hasOwnProperty("tool_uses")) { instructions = data.tool_uses .map(({ parameters }: { parameters: any }) => parameters....
/** * Parallel calls can come in two distinct ways - as a list of instructions in a single call * Or bundled in an object called "tool_uses". * Here we can check which response mode is randomly chose and handle each. * multi_tool_use.parallel({ "tool_uses": [ { "recipient_name": "functions.delegate", "parameters":...
https://github.com/Mintplex-Labs/openai-assistant-swarm/blob/de7387a2ea0d71b4782adab027063d0f96afb433/src/utils/toolCalls.ts#L51-L71
de7387a2ea0d71b4782adab027063d0f96afb433
awesome-hands-control
github_2023
RylanBot
typescript
withPrototype
function withPrototype(obj: Record<string, any>) { const protos = Object.getPrototypeOf(obj) for (const [key, value] of Object.entries(protos)) { if (Object.prototype.hasOwnProperty.call(obj, key)) continue if (typeof value === 'function') { // eslint-disable-next-line @typescript-eslint/no-explicit-...
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/RylanBot/awesome-hands-control/blob/dfc4f362d01ea83d2cc85278d52bb9d205c751e3/electron/preload.ts#L8-L23
dfc4f362d01ea83d2cc85278d52bb9d205c751e3
awesome-hands-control
github_2023
RylanBot
typescript
convertConfigFormat
const convertConfigFormat = (config: AppConfig[] | AppConfigV0[]): AppConfig[] => { const resConfig: AppConfig[] = []; config.forEach((el) => { if ('shortcuts' in el) { resConfig.push(el as AppConfig); } else { const shortcuts: Shortcut[] = []; ...
/** * 适配 v1.0.x 之前的配置文件格式 */
https://github.com/RylanBot/awesome-hands-control/blob/dfc4f362d01ea83d2cc85278d52bb9d205c751e3/electron/stores/configStore.ts#L18-L47
dfc4f362d01ea83d2cc85278d52bb9d205c751e3
awesome-hands-control
github_2023
RylanBot
typescript
useVideoFrames
const useVideoFrames = ( // eslint-disable-next-line @typescript-eslint/no-unused-vars frameCallback = (_: number) => { } ): [HTMLVideoElement | null, React.RefCallback<HTMLVideoElement>] => { const [video, setVideo] = useState<HTMLVideoElement | null>(null); const callbackRef = useRef(frameCallback); ...
/** * 允许开发者在每个视频帧被渲染到屏幕时执行特定的回调函数 * 确保处理操作与视频播放同步 * @see https://web.dev/requestvideoframecallback-rvfc/ */
https://github.com/RylanBot/awesome-hands-control/blob/dfc4f362d01ea83d2cc85278d52bb9d205c751e3/src/hooks/useVideoFrames.ts#L12-L82
dfc4f362d01ea83d2cc85278d52bb9d205c751e3
awesome-hands-control
github_2023
RylanBot
typescript
EmptySlot
const EmptySlot: React.FC = () => { const navigate = useNavigate(); useEffect(() => { window.windowApi.identifyWindow((windowName: string) => { if (windowName === 'main') { navigate('/main'); } else if (windowName === 'camera') { navigate('/camera...
/** * 打包后相机窗口一直无法加载,HashRouter 解析失败 * 因此监听来自主进程的信息,判断当前是哪个窗口在加载,然后再进行重定向 *(缺点:页面会有一瞬间的空白) */
https://github.com/RylanBot/awesome-hands-control/blob/dfc4f362d01ea83d2cc85278d52bb9d205c751e3/src/pages/EmptySlot.tsx#L9-L23
dfc4f362d01ea83d2cc85278d52bb9d205c751e3
rise-tools
github_2023
rise-tools
typescript
DynamicSection
const DynamicSection = ({ children }: { children: ReactNode[] }) => { return ( <View> <View> {children.map((_el, idx) => ( <View>{idx}</View> ))} </View> </View> ) }
// Since DynamicSection maps over children, its type should change from static to dynamic
https://github.com/rise-tools/rise-tools/blob/0b3331191e15a85efd3aba27f71cea4a00e71563/packages/react/src/__tests__/jsx-runtime.test.tsx#L104-L114
0b3331191e15a85efd3aba27f71cea4a00e71563
CodeFuse-Query
github_2023
codefuse-ai
typescript
customParseFloat
function customParseFloat(value: string, previous: number): number { const parsedValue = parseFloat(value); if (isNaN(parsedValue)) { throw new InvalidArgumentError('Not a number.'); } return parsedValue; }
/** * Custom float options or arguments parser * * @param value * @param previous * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/index.ts#L28-L36
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
parseFileSizeLimit
function parseFileSizeLimit(value: string, previous: number): number { const parsedValue = customParseFloat(value, previous); if (parsedValue <= 0) { throw new InvalidArgumentError( "The 'fileSizeLimit' should be greater than 0.", ); } return parsedValue; }
/** * Parse file size limit * * @param value * @param previous * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/index.ts#L45-L54
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
generateExpectedObject
function generateExpectedObject(object: any): string { function replacer(key: string, value: any) { if (typeof value === 'bigint') { return value.toString() + 'n'; } else if (value instanceof Map) { return Array.from(value.entries()); } else { return value; } } return JSON.strin...
/** * 用于生成测试用例的结果 * * @param object 原始对象 * @returns 处理了 bigint 类型的 JSON 格式字符串 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/__test__/core/index.test.ts#L20-L34
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
extractTestFile
function extractTestFile(filePath: string): Coref | undefined { const program = ts.createProgram([filePath], compilerOptions); // 使用 getTypeChecker 确保 Node 中的属性都初始化 program.getTypeChecker(); const sourceFile = program.getSourceFile(filePath); return extractFile(sourceFile as ts.SourceFile, program); }
/** * 根据测试文件路径抽取文件 * * @param filePath 测试文件路径 * @returns 抽取的 Coref 数据 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/__test__/core/index.test.ts#L42-L49
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
initIgnoreFunctions
function initIgnoreFunctions( extractedPath: string, options?: ExtractOptions, ): ((fileOrDirPath: string) => coref.IgnoredPath | null)[] { const ignoreFunctions = []; // use blacklist to ignore files let blacklist = DEFAULT_BLACKLIST; if (options?.blacklist) { blacklist = blacklist.concat(options.blac...
/** * Init ignore functions * * @param extractedPath * @param options * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extract-manager.ts#L50-L92
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
createSpawnWorkerFunction
function createSpawnWorkerFunction() { let i = 0; return async () => workers[i++]; }
/** * Create the spawn-worker function * * @returns the spawn-worker function */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extract-manager.ts#L180-L183
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
extractTokensAndComments
function extractTokensAndComments(tsSourceFile: extendedTs.SourceFile) { const code = tsSourceFile.text; const scanner = ts.createScanner( ts.ScriptTarget.Latest, /*skipTrivia*/ false, ts.LanguageVariant.JSX, code, ); const reScanGreaterToken: ReScanFunction = scanner.reScanGreaterToken.bind...
/** * 抽取 Tokens 和 Comments * 因为抽取的 AST 中 不包含 Tokens 和 Comments 信息,因此需要使用 Scanner 重新解析代码来抽取 * * @param tsSourceFile */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L36-L133
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
visitTopLevel
function visitTopLevel(tsSourceFile: extendedTs.SourceFile): coref.TopLevel { return util.ensureCorefAstNode(tsSourceFile) as coref.TopLevel; }
/** * 访问 sourceFile 节点,并返回对应的 TopLevel 对象 * * @param tsSourceFile * @returns TopLevel 对象 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L141-L143
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
processCommonChildNodes
function processCommonChildNodes(tsNode: extendedTs.Node): coref.Node[] { const node = util.ensureCorefAstNode(tsNode); let index = 0; const childNodes: coref.Node[] = []; util.forEachChild(tsNode, (childTsNode: extendedTs.Node) => { const childNode = childTsNode.$corefModel as coref.Node; childNode.pa...
/** * 处理普通节点的子节点,记录子节点的父节点,index 等信息 * 按子节点顺序记录 index * * @param tsNode 父节点 * @returns 子节点数组 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L152-L166
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
collectChildNodes
function collectChildNodes( childNodes: coref.Node[], tsNode: extendedTs.Node | undefined, extra_desc: { parent_oid: bigint; index: number }, ) { const node = tsNode?.$corefModel as coref.Node | undefined; if (node) { childNodes.push({ ...node, ...extra_desc }); } return childNodes; }
/** * 收集 COREF 子节点 * 如果该子节点存在,则保存到 childNodes 中 * * @param childNodes COREF 子节点数组 * @param tsNode extendedTs 子节点 * @param extra_desc 子节点额外的信息 * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L177-L188
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
processForStatementChildNodes
function processForStatementChildNodes( tsForStatement: extendedTs.ForStatement, ): coref.Node[] { const node = util.ensureCorefAstNode(tsForStatement); const childNodes: coref.Node[] = []; collectChildNodes(childNodes, tsForStatement.initializer, { parent_oid: node.oid, index: 0, }); collectChild...
/** * 处理 ForStatement 的子节点,记录子节点的父节点,index 等信息 * 4 种子节点 initializer, condition, incrementor 和 statement 的 index 固定为 0, 1, 2, 3, * 以便在 Godel 库中可以区分。 * * @param tsForStatement * @returns */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L198-L223
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
visitNode
function visitNode(tsNode: extendedTs.Node): coref.Node[] { switch (tsNode.kind) { case ts.SyntaxKind.ForStatement: return processForStatementChildNodes(tsNode as extendedTs.ForStatement); default: return processCommonChildNodes(tsNode); } }
/** * 访问一个 AST Node 节点,记录其所有子节点与之的父子关系,并返回全部子节点 * * @param tsNode AST Node 节点,增加了自定义属性的 ts.Node 对象 * @returns 该节点所有直接子节点对应的 COREF 对象 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L231-L238
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
visitClassLikeDeclaration
function visitClassLikeDeclaration( tsClassLikeDeclaration: extendedTs.ClassLikeDeclaration, ): coref.ClassLikeDeclaration { const classLikeDeclaration = util.ensureCorefAstNode( tsClassLikeDeclaration, ) as coref.ClassLikeDeclaration; classLikeDeclaration.name = tsClassLikeDeclaration.name?.text || ''; r...
/** * 访问 ClassLikeDeclaration 节点,返回对应的 COREF 对象 * * @param tsClassLikeDeclaration extendedTs.ClassLikeDeclaration 节点,增加了自定义属性的 ts.ClassLikeDeclaration 对象 * @returns COREF ClassLikeDeclaration 对象 * * @todo 处理 classLikeDeclaration 的 members, modifiers, heritageClauses, decorators, typeParameters 等 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L248-L256
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
visitFunctionLikeDeclaration
function visitFunctionLikeDeclaration( tsFunctionLikeDeclaration: extendedTs.FunctionLikeDeclaration, ) { const functionLikeDeclaration = util.ensureCorefAstNode( tsFunctionLikeDeclaration, ) as coref.FunctionLikeDeclaration; switch (functionLikeDeclaration.kind) { case ts.SyntaxKind.FunctionDeclaratio...
/** * 访问 FunctionLikeDeclaration 节点,返回对应的 COREF 对象 * @param tsFunctionLikeDeclaration extendedTs.FunctionLikeDeclaration 节点,增加了自定义属性的 ts.FunctionLikeDeclaration 对象 * @returns COREF FunctionLikeDeclaration 对象 * * @todo 处理除了 name,其他的 FunctionLikeDeclaration 的属性 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L265-L326
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
visitNodeComments
function visitNodeComments(tsNode: extendedTs.Node): coref.NodeComment[] { const sourceFile = tsNode.getSourceFile(); const node = tsNode.$corefModel as coref.Node; const leadingCommentRanges = util.getLeadingCommentRangesOfNode( tsNode, sourceFile, ); const trailingCommentRanges = util.getTrailingCom...
/** * 抽取节点与注释的关系 * * @todo 目前有一种特殊情况没有抽取:一行行内的多行注释,而且该注释不在所在行的开头或结尾。 * 原因是,通过 typescript API (ts.getLeadingCommentRanges 和 ts.getTrailingCommentRanges) * 获取 AST 节点与注释的关系,这种特殊类型的注释会关联到一些只有语法意义的 Token 节点上 * (如 PunctuationToken标点符号, keyword 等),后续应把注释关联到他们前后更有意义的节点上, * 如 Identifier,Expression等。 * * @param tsNode T...
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L388-L445
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
createNodeComment
function createNodeComment( commentRange: ts.CommentRange, nodeCommentType: coref.NodeCommentType, ): coref.NodeComment { const commentStartPos = commentRange.pos; const commentEndPos = commentRange.end; const commentText = sourceFile.text.substring( commentStartPos, commentEndPos, ...
/** * 根据 ts.CommentRange 和 NodeCommentType 创建 NodeComment 对象 * * @param commentRange ts.CommentRange 对象 * @param nodeCommentType 节点注释关联类型 NodeCommentType.LEADING 或 NodeCommentType.TRAILING * @returns NodeComment 对象 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L408-L426
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
visitLiteralLikeNode
function visitLiteralLikeNode(literalLikeNode: extendedTs.Node): coref.Literal { const literal = literalLikeNode.$corefModel as coref.Literal; /** * 如果 literal 的值中存在未成对的 UTF-16 代理对(Surrogate Pair)范围的字符, * 则这些字符是非法字符,不对应任何 Unicode 标准中的字符,插入数据库时会报错,需保存转译后的值 */ /** * 找到单独出现代理字符的正则表达式, * 即后面没有 [\uDC0...
/** * 访问 TypeScript literal-like node * @param literalLikeNode literal-like node * @returns 该 literal-like node 对应的 coref.Literal 对象 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L452-L475
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
extractBindingElement
function extractBindingElement( tsBindingElement: extendedTs.BindingElement, ): coref.BindingElement { const bindingElement = util.ensureCorefAstNode( tsBindingElement, ) as coref.BindingElement; bindingElement.propertyNameOid = ( tsBindingElement.propertyName as extendedTs.Node | undefined )?.$corefM...
/** * Extract a BindingElement * * @param tsBindingElement * @returns coref.BindingElement */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L483-L498
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
extractModifiers
function extractModifiers(tsNode: util.HasModifiers): coref.Modifier[] { return tsNode.modifiers ? tsNode.modifiers.map((tsModifier, modifierIndex) => { const modifier = (tsModifier as extendedTs.Modifier).$corefModel; modifier.modifierIndex = modifierIndex; return modifier; }) :...
/** * Extract modifiers * * @param tsNode * @returns COREF modifiers */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L506-L514
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
extractAstNodes
function extractAstNodes(tsSourceFile: extendedTs.SourceFile) { let nodes: coref.Node[] = []; let nodeComments: coref.NodeComment[] = []; const bindingElements: coref.BindingElement[] = []; const classLikeDeclarations: coref.ClassLikeDeclaration[] = []; const functionLikeDeclarations: coref.FunctionLikeDeclar...
/** * 抽取 AST 节点数据 * * @param tsSourceFile * @returns 一个 SourceFile 中 AST 相关的数据 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L522-L604
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
extractSymbols
function extractSymbols( tsSourceFile: extendedTs.SourceFile, typeChecker: ts.TypeChecker, projectPath?: string | undefined, ) { const symbolMap = new Map<bigint, coref.Symbol>(); const nodeSymbolMap = new Map<bigint, bigint>(); const shorthandAssignmentValueSymbolMap = new Map<bigint, bigint>(); util.fo...
/** * Extract symbols and node symbol relations * * @param tsSourceFile * @param projectPath * @returns { symbolMap, nodeSymbols } */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L613-L651
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
extractCallSites
function extractCallSites( program: ts.Program, tsSourceFile: extendedTs.SourceFile, projectPath?: string | undefined, ) { const callSiteMap = new Map<bigint, bigint>(); util.forEachNode(tsSourceFile, (tsNode: extendedTs.Node) => { if (util.isMayInvokeExpression(tsNode)) { const callSite = visitMay...
/** * Extract call sites and the corresponding callees */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L656-L677
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
extractNumberOfLines
function extractNumberOfLines( tokens: coref.Token[], comments: coref.Comment[], locations: coref.Location[], ): coref.NumberOfLines[] { const numberOfLinesArray: coref.NumberOfLines[] = []; const codeLineSet = new Set<number>(); const commentLineSet = new Set<number>(); // 使用 tokens 统计代码行数,因为上层的 AST nod...
/** * 抽取每个 Location 对应的行数,代码行数和注释行数 * * @param tokens * @param comments * @param locations * @returns NumberOfLines 对象数组 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/extractor.ts#L687-L753
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
getLineFromPos
function getLineFromPos(pos: number, lineStarts: readonly number[]): number { let low = 0, high = lineStarts.length - 1; while (low < high) { const mid = high - ((high - low) >> 1); // Get middle, rounding up. const startOfLine = lineStarts[mid]; if (startOfLine <= pos) { low = mid; } else...
/** * 根据源码 string 的位置 index 获取行号 * * @param pos 在源码 string 中的 index * @param lineStarts 每行代码开始的 index * @returns 行号 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/util.ts#L107-L120
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
visitNode
function visitNode<T>( cbNode: (node: ts.Node) => T, node: ts.Node | undefined, ): T | undefined { if (isBrokenNode(node)) { return; } return node && cbNode(node); }
/** * typescript 内部方法 visitNode * * 参考: https://github.com/microsoft/TypeScript/blob/v4.5.5/src/compiler/parser.ts#L38 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/util.ts#L429-L437
c262c419616db680bb8a8a3f91b669f5e961dc81
CodeFuse-Query
github_2023
codefuse-ai
typescript
visitNodes
function visitNodes<T>( cbNode: (node: ts.Node) => T, cbNodes: ((node: ts.NodeArray<ts.Node>) => T | undefined) | undefined, nodes: ts.NodeArray<ts.Node> | undefined, ): T | undefined { if (nodes) { if (cbNodes) { return cbNodes(nodes); } for (const node of nodes) { const result = cbNode...
/** * typescript 内部方法 visitNodes * * 参考: https://github.com/microsoft/TypeScript/blob/v4.5.5/src/compiler/parser.ts#L42 */
https://github.com/codefuse-ai/CodeFuse-Query/blob/c262c419616db680bb8a8a3f91b669f5e961dc81/language/javascript/extractor/src/core/util.ts#L444-L460
c262c419616db680bb8a8a3f91b669f5e961dc81