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 transitions
const alpha = 0.2; // Smoothing factor
const newEstimate = sum / heights.size;
return Math.round(
alpha * newEstimate + (1 - alpha) * listMetrics.estimatedRowHeight,
);
}; | // 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)
) {
updates.push([index, measuredHeight]);
}
}
});
if (updates.length === 0) return;
const newHeights = new Map(listMetrics.rowHeights);
updates.forEach(([index, height]) => {
newHeights.set(index, height);
});
// Calculate new estimated height
const newEstimatedHeight = calculateEstimatedHeight(newHeights);
let newTotalHeight = 0;
for (let i = 0; i < data.length; i++) {
newTotalHeight += newHeights.get(i) || newEstimatedHeight;
}
setListMetrics({
rowHeights: newHeights,
totalHeight: newTotalHeight,
estimatedRowHeight: newEstimatedHeight,
});
}; | // 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);
} catch (error) {
if (error instanceof FileSizeLimitError) {
throw error;
} else if (error instanceof Error) {
throw new Error(
`Failed to read or parse file ${file}: ${error.message}`,
);
} else {
throw new Error(
`Failed to read or parse file ${file} - an unknown error occurred`,
);
}
}
}; | /**
* 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("/")[1].split("_epoch_");
return {
sampleId,
epoch: parseInt(epochStr.split(".")[0], 10),
};
});
}; | /**
* 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 new Error(
`Unable to read sample file ${sampleFile} - it is not present in the manifest.`,
);
}
}; | /**
* 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",
eval: evalSpec.eval,
plan: evalSpec.plan,
};
}
}; | /**
* 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[] = [];
const errors: unknown[] = [];
await Promise.all(
summaryFiles.map((filename) =>
queue.enqueue(async () => {
try {
const partialSummary = (await readJSONFile(
filename,
)) as SampleSummary[];
summaries.push(...partialSummary);
} catch (error) {
errors.push(error);
}
}),
),
);
if (errors.length > 0) {
console.error(
`Encountered ${errors.length} errors while reading summary files:`,
errors,
);
}
return summaries;
}; | /**
* 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 signature for ${file}`);
}
offset += 4;
const versionNeeded = view.getUint16(offset, true);
offset += 2;
const bitFlag = view.getUint16(offset, true);
offset += 2;
const compressionMethod = view.getUint16(offset, true);
offset += 2;
offset += 4; // Skip last mod time and date
const crc32 = view.getUint32(offset, true);
offset += 4;
const compressedSize = view.getUint32(offset, true);
offset += 4;
const uncompressedSize = view.getUint32(offset, true);
offset += 4;
const filenameLength = view.getUint16(offset, true);
offset += 2;
const extraFieldLength = view.getUint16(offset, true);
offset += 2;
offset += filenameLength + extraFieldLength;
const data = rawData.subarray(offset, offset + compressedSize);
return {
versionNeeded,
bitFlag,
compressionMethod,
crc32,
compressedSize,
uncompressedSize,
filenameLength,
extraFieldLength,
data,
};
}; | /**
* 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 = view.getUint16(offset + 28, true);
const extraFieldLength = view.getUint16(offset + 30, true);
const fileCommentLength = view.getUint16(offset + 32, true);
const filename = new TextDecoder().decode(
buffer.subarray(
offset + kFileHeaderSize,
offset + kFileHeaderSize + filenameLength,
),
);
// Read 32-bit file offset
let fileOffset = view.getUint32(offset + 42, true);
// If fileOffset is 0xFFFFFFFF, use the ZIP64 extended offset instead
if (fileOffset === 0xffffffff) {
// Move to extra field
let extraOffset = offset + kFileHeaderSize + filenameLength;
// Look through extra fields until we find zip64 extra field
while (
extraOffset <
offset + kFileHeaderSize + filenameLength + extraFieldLength
) {
const tag = view.getUint16(extraOffset, true);
const size = view.getUint16(extraOffset + 2, true);
if (tag === 0x0001) {
// ZIP64 Extra Field - Read 64-bit offset
fileOffset = Number(view.getBigUint64(extraOffset + 4, true));
break;
}
extraOffset += 4 + size; // Move to next extra field
}
}
const entry = {
filename,
compressionMethod: view.getUint16(offset + 10, true),
compressedSize: view.getUint32(offset + 20, true),
uncompressedSize: view.getUint32(offset + 24, true),
fileOffset,
};
entries.set(filename, entry);
offset +=
kFileHeaderSize + filenameLength + extraFieldLength + fileCommentLength;
}
return entries;
}; | /**
* 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.type === "tool") {
if (
Array.isArray(value.content) &&
value.content.some(isContentImage)
) {
return true;
}
}
}
return false;
} | // 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
)[],
): (
| ContentText
| ContentImage
| ContentAudio
| ContentVideo
| ContentTool
)[] => {
if (Array.isArray(output)) {
return output;
} else {
return [
{
type: "tool",
content: [
{
type: "text",
text: String(output),
},
],
},
];
}
}; | /**
* 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 undefined;
}; | // 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);
}
}
return banned;
}; | /**
* 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,
) => {
const coercedValue = coerceValue(
value,
evalDescriptor.scoreDescriptor(scoreLabel),
);
if (isFilteringSupportedForValue(coercedValue)) {
variables[variableName] = coercedValue;
}
};
for (const [scorer, score] of Object.entries(sampleScores || {})) {
addScore(scorer, { scorer, name: scorer }, score.value);
if (typeof score.value === "object") {
for (const [name, value] of Object.entries(score.value)) {
addScore(`${scorer}.${name}`, { scorer, name }, value);
if (!bannedShortNames.has(name)) {
addScore(name, { scorer, name }, value);
}
}
}
}
return variables;
}; | /**
* 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/samplesDescriptor").EvalDescriptor} evalDescriptor
* @param {import("../../types/log").Scores1} sampleScores
* @returns {Object<string, any>}
*/ | 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(scoreLabel);
const scoreType = descriptor?.scoreType;
if (!descriptor) {
items.push({
shortName,
qualifiedName,
canonicalName,
tooltip: undefined,
categories: [],
scoreType,
});
return;
}
var tooltip = `${canonicalName}: ${descriptor.scoreType}`;
var categories: string[] = [];
if (descriptor.min !== undefined || descriptor.max !== undefined) {
const rounded = (num: number) => {
// Additional round-trip to remove trailing zeros.
return parseFloat(num.toPrecision(3)).toString();
};
tooltip += `\nrange: ${rounded(descriptor.min || 0)} to ${rounded(descriptor.max || 0)}`;
}
if (descriptor.categories) {
categories = descriptor.categories.map((cat) => {
const val = (cat as Record<string, unknown>).val;
return valueToString(val);
});
tooltip += `\ncategories: ${categories.join(" ")}`;
}
items.push({
shortName,
qualifiedName,
canonicalName,
tooltip,
categories,
scoreType,
});
}; | /**
* @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 (stream.match(keywordsRegex)) return "keyword";
if (stream.match(mathFunctionsRegex)) return "mathFunction";
if (stream.match(sampleFunctionsRegex)) return "sampleFunction";
if (stream.match(TOKEN_PATTERNS.VARIABLE)) return "variable";
if (stream.match(TOKEN_PATTERNS.RELATION)) return "relation";
if (stream.match(TOKEN_PATTERNS.MISC_OPERATOR)) return "miscOperator";
if (stream.match(TOKEN_PATTERNS.OPERATOR)) return "miscOperator";
stream.next();
return null;
} | // 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:
return decision;
}
}; | /**
* 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 ApplicationIcons.approvals.escalate;
case "modify":
return ApplicationIcons.approvals.modify;
default:
return ApplicationIcons.approve;
}
}; | /**
* 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.subtaskLabel)}></div>
<div className={clsx("text-style-label")}>Output</div>
<Rendered values={input} />
<div className={clsx("text-size-title-secondary", styles.subtaskLabel)}>
<i className={ApplicationIcons.arrows.right} />
</div>
<div>
<Rendered values={result} />
</div>
</div>
);
}; | /**
* 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 values;
}
}; | /**
* 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--;
this.runNext();
}
});
if (this.runningCount < this.concurrentLimit) {
this.runNext();
}
});
} | // 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();
return [
{
label: `Sample ${itemCount}`,
number: itemCount,
index: index,
data: sample,
type: "sample",
},
];
};
}; | /**
* 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 === "string") {
if (order === "asc") {
return String(a.id).localeCompare(String(b.id));
} else {
return String(b.id).localeCompare(String(a.id));
}
} else {
if (order === "asc") {
return Number(a.id) - Number(b.id);
} else {
return Number(b.id) - Number(b.id);
}
}
});
const groupCount = samples.length / sampleDescriptor.evalDescriptor.epochs;
const itemCount = samples.length / groupCount;
const counter = getCounter(itemCount, groupCount, order);
return (
sample: SampleSummary,
index: number,
previousSample?: SampleSummary,
): ListItem[] => {
const results = [];
// Add a separator when the id changes
const lastId = previousSample ? previousSample.id : undefined;
if (sample.id !== lastId) {
counter.incrementGroup();
results.push({
label: `Sample ${itemCount}`,
number: counter.group(),
index: index,
data: `Sample ${counter.group()}`,
type: "separator",
} as SeparatorListItem);
counter.resetItem();
}
counter.incrementItem();
results.push({
label: `Sample ${counter.group()} (Epoch ${counter.item()})`,
number: counter.item(),
index: index,
data: sample,
type: "sample",
} as SampleListItem);
return results;
};
}; | /**
* 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 / groupCount;
const counter = getCounter(itemCount, groupCount, order);
return (
sample: SampleSummary,
index: number,
previousSample?: SampleSummary,
) => {
const results = [];
const lastEpoch = previousSample ? previousSample.epoch : -1;
if (lastEpoch !== sample.epoch) {
counter.incrementGroup();
// Add a separator
results.push({
label: `Epoch ${counter.group()}`,
number: counter.group(),
index: index,
data: `Epoch ${counter.group()}`,
type: "separator",
} as SeparatorListItem);
counter.resetItem();
}
// Compute the index within the epoch
counter.incrementItem();
results.push({
label: `Sample ${counter.item()} (Epoch ${counter.group()})`,
number: counter.item(),
index: index,
data: sample,
type: "sample",
} as SampleListItem);
return results;
};
}; | /**
* 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;
},
incrementItem: () => {
if (order !== "desc") {
itemIndex++;
} else {
itemIndex--;
}
},
incrementGroup: () => {
if (order !== "desc") {
groupIndex++;
} else {
groupIndex--;
}
},
item: () => {
return itemIndex;
},
group: () => {
return groupIndex;
},
};
}; | // 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).isDirectory())
.find(isEnvDir);
if (envDir) {
return getPythonPath(envDir);
}
return null;
} | // 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 interpreter (on all platforms)
const paths = [join(binDir, binary)];
switch (process.platform) {
case "darwin":
break;
case "linux":
// Also check .local/bin on linux
paths.unshift(join(process.env.HOME || "", ".local", "bin", binary));
break;
default:
break;
}
return paths;
}; | // 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: ${version?.raw}` + (version ? `\n${inspectBinPath()?.path}` : "");
}; | // 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 taskTreeItem;
} else {
return undefined;
}
} | // 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, logDir, viewServer));
// show a workspace relative path if this is in the workspace,
// otherwise show the protocol then the last two bits of the path
const relativePath = getRelativeUri(activeWorkspaceFolder().uri, logDir);
if (relativePath) {
tree.description = `./${relativePath}`;
} else {
tree.description = prettyUriPath(logDir);
}
}; | // 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 = findNodeWithUri(child);
if (uri) {
return uri;
}
}
}
return undefined;
}; | // 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: "$(debug-alt) Debug Task",
tooltip: "Debug this evaluation task.",
command: "inspect.debugTask",
arguments: [uri, fn],
},
{
title: "$(play) Run Task",
tooltip: "Execute this evaluation task.",
command: "inspect.runTask",
arguments: [uri, fn],
},
];
}
} | // 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);
}
return false;
}
case "linux":
return binPath && binPath.path.includes(".local/bin");
default:
return false;
}
};
return {
update: (binPath: AbsolutePath | null) => {
// The path info
const env = context.environmentVariableCollection;
env.delete('PATH');
// Actually update the path
const binDir = binPath?.dirname();
if (binDir && filter(binPath)) {
env.append('PATH', `${delimiter}${binDir.path}`);
}
}
};
}; | // 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(activeWorkspacePath(), log_dir);
const logsJson = (logs ? (JSON.parse(logs)) : []) as Array<{ name: string }>;
return JSON.stringify({
log_dir: log_dir.toString(true),
files: logsJson.map(log => ({
...log,
name: Uri.joinPath(workspaceRoot, log.name).toString(true)
}))
});
},
() => {
// Return the original log content
return inspectEvalLogs(activeWorkspacePath());
}
);
return Promise.resolve(response);
} | // 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);
if (useLogViewer) {
const docUri = document.uri.toString();
if (docUri.endsWith(".json")) {
const fileSize = await this.server_.evalLogSize(docUri);
if (fileSize > (1024 * 1000 * 100)) {
log.info(`JSON log file ${document.uri.path} is to large for Inspect View, opening in text editor.`);
useLogViewer = false;
}
}
}
if (useLogViewer) {
// local resource roots
const localResourceRoots: Uri[] = [];
const viewDir = inspectViewPath();
if (viewDir) {
localResourceRoots.push(Uri.file(viewDir.path));
}
Uri.joinPath(this.context_.extensionUri, "assets", "www");
// set webview options
webviewPanel.webview.options = {
enableScripts: true,
enableForms: true,
localResourceRoots
};
// editor panel implementation
this.logviewPanel_ = new LogviewPanel(
webviewPanel as HostWebviewPanel,
this.context_,
this.server_,
"file",
document.uri
);
// set html
const logViewState: LogviewState = {
log_file: document.uri,
log_dir: dirname(document.uri)
};
webviewPanel.webview.html = this.logviewPanel_.getHtml(logViewState);
} else {
const viewColumn = webviewPanel.viewColumn;
await vscode.commands.executeCommand('vscode.openWith', document.uri, 'default', viewColumn);
}
} | // 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: openAIKey, dangerouslyAllowBrowser: true });
if (prompt === "") {
setLlmStatus(LLMStatus.ERROR);
return "Embedding server is down. Please try again later."
}
if (openAIKey !== "") {
return await memoizedOpenAI.chat.completions.create({
messages: [{ role: "user", content: prompt }],
model: "gpt-3.5-turbo-1106",
temperature: 0,
})
.then((res) => {
setLlmStatus(LLMStatus.SUCCESS);
return res.choices[0].message.content
})
.catch((err) => {
setLlmStatus(LLMStatus.ERROR);
return err.toString();
});
} else {
const response = await chatOpenAIBackend(prompt)
if (response === "") {
setLlmStatus(LLMStatus.ERROR);
return "OpenAI is unreachable. Please try again later."
}
setLlmStatus(LLMStatus.SUCCESS);
return response;
}
} | // 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: "@mintplex-labs/openai-assistant-swarm",
},
});
if (!thread) throw new Error("Failed to create thread.");
const mgrAssistant = this.mgrAssistant as Assistant;
const assistants = await this.getAssistants(assistantIds);
// If the user defined a sub-set of assistants we want to reduce scope of known assistants
// so we don't execute tasks outside of the subset.
this.knownAssistantIds = assistants.map((a) => a.id);
const run = await this.client.beta.threads.runs.create(thread.id, {
assistant_id: mgrAssistant.id,
tools: toolsFromAssistants(assistants),
instructions: `${
mgrAssistant.instructions
} Your available assistants and their descriptions are presented between <assistant></assistant> tags with their id and descriptions. Only select assistants that are explicitly listed here.
${assistants.map((assistant: Assistant) => {
return `<assistant>
<agent_id>${assistant.id}</agent_id>
<name>${assistant.name}</name>
<description>${assistant.description ?? assistant.instructions}</description>
</assistant>`;
})},`,
...(!!runOpts ? { ...runOpts } : {}),
});
this.log(`Run created: ${run.id}`);
this.log({ parentThreadPlaygroundLink: this.playgroundLink(run) });
this.emitEvent("poll_event", {
data: {
status: "parent_run_created",
prompt,
playground: this.playgroundLink(run),
run,
},
});
const settledManagerRun = await pollRun(
this.client,
this.logGroup,
this.log,
run,
);
return await this.delegateTaskToChildren(settledManagerRun);
} | /**
* 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.instructions)
.flat();
} else {
instructions = data.instructions;
}
return instructions.map((instruction: DelegationArguments) => {
return {
id: callId,
function: "delegate",
agentId: instruction.agent_id,
args: instruction,
};
});
} | /**
* 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": { "instructions": [ {...} ] } }, { "recipient_name": "functions.delegate", "parameters": { "instructions": [ {... } ] } } ] })
* or
* tool_output({ "instructions": [ {...},{...} ] })
*/ | 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-any
obj[key] = function (...args: any) {
return value.call(obj, ...args)
}
} else {
obj[key] = value
}
}
return obj
} | // 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[] = [];
for (const key in el.shortcut) {
if (key in el.shortcut) {
const [gestureLeft, gestureRight] = el.shortcut[key];
shortcuts.push({
keyCombination: key,
gestureLeft,
gestureRight,
enabled: true,
removable: true
});
}
}
if (shortcuts.length) {
resConfig.push({
name: el.name,
icon: el.icon,
shortcuts
});
}
}
})
return resConfig;
} | /**
* 适配 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);
callbackRef.current = frameCallback;
useEffect(() => {
if (!video) return;
let frameId: number | null;
let requestFrame = requestAnimationFrame; // 处理视频的兼容方法
let cancelFrame = cancelAnimationFrame;
if ("requestVideoFrameCallback" in HTMLVideoElement.prototype) {
const vid = video as HTMLVideoElement & {
requestVideoFrameCallback: typeof requestAnimationFrame;
cancelVideoFrameCallback: typeof cancelAnimationFrame;
};
requestFrame = vid.requestVideoFrameCallback.bind(vid);
cancelFrame = vid.cancelVideoFrameCallback.bind(vid);
}
const callbackFrame = () => {
const videoTime = video.currentTime;
callbackRef.current(videoTime);
frameId = requestFrame(callbackFrame);
};
const eventListeners: VideoEventListenerMap = {
loadeddata() {
requestAnimationFrame(() => callbackRef.current(video.currentTime));
},
play() {
frameId = requestFrame(callbackFrame);
},
pause() {
cancelFrame(frameId ?? 0);
frameId = null;
},
timeupdate() {
if (!frameId) {
requestAnimationFrame(() => callbackRef.current(video.currentTime));
}
},
};
Object.keys(eventListeners).forEach((eventName) => {
const eventListener = eventListeners[eventName as keyof HTMLMediaElementEventMap];
if (eventListener != null) {
video.addEventListener(eventName, eventListener);
}
});
return () => {
cancelFrame(frameId ?? 0);
Object.keys(eventListeners).forEach((eventName) => {
const eventListener =
eventListeners[eventName as keyof HTMLMediaElementEventMap];
if (eventListener != null) {
video.removeEventListener(eventName, eventListener);
}
});
};
}, [video]);
return [video, setVideo];
}; | /**
* 允许开发者在每个视频帧被渲染到屏幕时执行特定的回调函数
* 确保处理操作与视频播放同步
* @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');
}
});
}, [navigate]);
return null;
} | /**
* 打包后相机窗口一直无法加载,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.stringify(object, replacer).replace(/"-?\d+n"/g, match =>
match.slice(1, -1),
);
} | /**
* 用于生成测试用例的结果
*
* @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.blacklist);
}
// TODO: Load or download dependencies if they don't exist.
if (!options?.extractDeps) {
blacklist.push('node_modules');
}
if (blacklist.length > 0) {
ignoreFunctions.push(
util.createIgnoreFunctionByBlacklist(extractedPath, blacklist),
);
}
if (options?.useGitignore) {
// use ".gitignore" to ignore files
// TODO: most repos only have one ".gitignore" in the root directory, thus currently only the root ".gitignore" is used.
// However, there may be more than one ".gitignore".
// ref:https://git-scm.com/docs/gitignore
const gitignorePath = path.join(extractedPath, '.gitignore');
ignoreFunctions.push(util.createIgnoreFunctionByGitignore(gitignorePath));
}
if (!options?.extractDist) {
// ignore files for distribution or minified files
ignoreFunctions.push(util.distIgnoreFunction);
}
// ignore super big files
ignoreFunctions.push(
util.createFileSizeIgnoreFunction(options?.fileSizeLimit),
);
return ignoreFunctions;
} | /**
* 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(scanner);
const reScanSlashToken: ReScanFunction =
scanner.reScanSlashToken.bind(scanner);
const reScanTemplateToken: ReScanFunction = scanner.reScanTemplateToken.bind(
scanner,
) as ReScanFunction;
const reScanItems: ReScanItem[] = [];
if (
!tsSourceFile.parseDiagnostics ||
tsSourceFile.parseDiagnostics.length === 0
) {
util.forEachNode(tsSourceFile, node => {
if (util.shouldReScanGreaterThanToken(node)) {
reScanItems.push({
pos: node.getStart(tsSourceFile, false),
callback: reScanGreaterToken,
});
} else if (util.shouldReScanSlashToken(node)) {
reScanItems.push({
pos: node.getStart(tsSourceFile, false),
callback: reScanSlashToken,
});
} else if (util.shouldReScanTemplateToken(node)) {
reScanItems.push({
pos: node.getStart(tsSourceFile, false),
callback: reScanTemplateToken,
});
}
});
}
const tokens: coref.Token[] = [];
const comments: coref.Comment[] = [];
const locationMap = new Map<bigint, coref.Location>();
let tokenSyntaxKind: ts.SyntaxKind;
let reScanItemIndex = 0;
do {
tokenSyntaxKind = scanner.scan();
if (scanner.getTokenPos() === reScanItems[reScanItemIndex]?.pos) {
reScanItems[reScanItemIndex].callback();
reScanItemIndex++;
}
const startPos = scanner.getTokenPos();
const text = scanner.getTokenText();
const width = text.length;
const endPos = startPos + width;
// skip broken token
if (width === 0) {
continue;
}
const location = util.createLocationByPosition(
tsSourceFile,
startPos,
endPos,
text,
);
// 暂时只将 comment 入库,只记录 comment 的 location 到 locationMap
if (util.isCommentSyntaxKind(tokenSyntaxKind)) {
// 处理 comments
const comment = coref.createComment(
tokenSyntaxKind as coref.CommentSyntaxKind,
location,
);
comments.push(comment);
locationMap.set(location.oid, location);
} else if (ts.isTokenKind(tokenSyntaxKind)) {
// 处理 tokens,除了 comments ( comments 也属于 tokens )
const token = coref.createToken(
tokenSyntaxKind as ts.TokenSyntaxKind,
location,
);
tokens.push(token);
}
} while (tokenSyntaxKind !== ts.SyntaxKind.EndOfFileToken);
return {
tokens,
comments,
locationMap,
};
} | /**
* 抽取 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.parent_oid = node.oid;
childNode.index = index;
childNodes.push(childNode);
index++;
});
return childNodes;
} | /**
* 处理普通节点的子节点,记录子节点的父节点,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,
});
collectChildNodes(childNodes, tsForStatement.condition, {
parent_oid: node.oid,
index: 1,
});
collectChildNodes(childNodes, tsForStatement.incrementor, {
parent_oid: node.oid,
index: 2,
});
collectChildNodes(childNodes, tsForStatement.statement, {
parent_oid: node.oid,
index: 3,
});
return childNodes;
} | /**
* 处理 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 || '';
return classLikeDeclaration;
} | /**
* 访问 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.FunctionDeclaration:
functionLikeDeclaration.name =
(tsFunctionLikeDeclaration as extendedTs.FunctionDeclaration).name
?.text || '';
break;
case ts.SyntaxKind.Constructor:
functionLikeDeclaration.name = '';
break;
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
functionLikeDeclaration.name = (
tsFunctionLikeDeclaration as
| extendedTs.MethodDeclaration
| extendedTs.GetAccessorDeclaration
| extendedTs.SetAccessorDeclaration
).name.getText();
break;
case ts.SyntaxKind.FunctionExpression:
functionLikeDeclaration.name =
(tsFunctionLikeDeclaration as extendedTs.FunctionExpression).name
?.text || '';
break;
case ts.SyntaxKind.ArrowFunction:
functionLikeDeclaration.name = '';
break;
}
const functionEnclosingNodes: coref.FunctionEnclosingNode[] = [];
// 不遍历 tsFunctionLikeDeclaration 本身
util.forEachChild(tsFunctionLikeDeclaration, childNode => {
util.forEachNode(
childNode,
(tsNode: extendedTs.Node) => {
const node = util.ensureCorefAstNode(tsNode);
functionEnclosingNodes.push({
nodeOid: node.oid,
functionOid: functionLikeDeclaration.oid,
});
if (util.isFunctionLikeDeclaration(tsNode)) {
// 不再遍历 FunctionLikeDeclaration 的子节点
return false;
}
},
/*childFirst*/ false,
);
});
return {
functionLikeDeclaration,
functionEnclosingNodes,
};
} | /**
* 访问 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.getTrailingCommentRangesOfNode(
tsNode,
sourceFile,
);
const nodeComments: coref.NodeComment[] = [];
/**
* 根据 ts.CommentRange 和 NodeCommentType 创建 NodeComment 对象
*
* @param commentRange ts.CommentRange 对象
* @param nodeCommentType 节点注释关联类型 NodeCommentType.LEADING 或 NodeCommentType.TRAILING
* @returns NodeComment 对象
*/
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,
);
const commentLocation = util.createLocationByPosition(
sourceFile,
commentStartPos,
commentEndPos,
commentText,
);
const commentOid = coref.computeNodeOid(commentRange.kind, commentLocation);
return coref.createNodeComment(node.oid, commentOid, nodeCommentType);
}
leadingCommentRanges?.forEach(commentRange => {
const nodeComment = createNodeComment(
commentRange,
coref.NodeCommentType.LEADING,
);
nodeComments.push(nodeComment);
});
trailingCommentRanges?.forEach(commentRange => {
const nodeComment = createNodeComment(
commentRange,
coref.NodeCommentType.TRAILING,
);
nodeComments.push(nodeComment);
});
return nodeComments;
} | /**
* 抽取节点与注释的关系
*
* @todo 目前有一种特殊情况没有抽取:一行行内的多行注释,而且该注释不在所在行的开头或结尾。
* 原因是,通过 typescript API (ts.getLeadingCommentRanges 和 ts.getTrailingCommentRanges)
* 获取 AST 节点与注释的关系,这种特殊类型的注释会关联到一些只有语法意义的 Token 节点上
* (如 PunctuationToken标点符号, keyword 等),后续应把注释关联到他们前后更有意义的节点上,
* 如 Identifier,Expression等。
*
* @param tsNode TsNode 节点,增加了自定义属性的 ts.Node 对象
* @returns 节点与注释关系的 NodeComment 数组
*/ | 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,
);
const commentLocation = util.createLocationByPosition(
sourceFile,
commentStartPos,
commentEndPos,
commentText,
);
const commentOid = coref.computeNodeOid(commentRange.kind, commentLocation);
return coref.createNodeComment(node.oid, commentOid, nodeCommentType);
} | /**
* 根据 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 标准中的字符,插入数据库时会报错,需保存转译后的值
*/
/**
* 找到单独出现代理字符的正则表达式,
* 即后面没有 [\uDC00-\uDFFF] 的 [\uD800-\uDBFF] ,
* 或前面没有 [\uD800-\uDBFF] 的 [\uDC00-\uDFFF]
*/
const singleSurrogateRegex =
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
const value = (literalLikeNode as ts.LiteralLikeNode).text;
literal.value =
value.search(singleSurrogateRegex) === -1
? value // 不存在非法字符,使用 literal 的实际值
: literalLikeNode.getText(); // 存在非法字符,使用原始文本
return literal;
} | /**
* 访问 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
)?.$corefModel?.oid;
bindingElement.nameOid = (tsBindingElement.name as extendedTs.Node)
.$corefModel?.oid as bigint;
bindingElement.initializerOid = (
tsBindingElement.initializer as extendedTs.Node
)?.$corefModel?.oid;
return bindingElement;
} | /**
* 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.FunctionLikeDeclaration[] = [];
let functionEnclosingNodes: coref.FunctionEnclosingNode[] = [];
const topLevel = visitTopLevel(tsSourceFile);
const literals: coref.Literal[] = [];
let modifiers: coref.Modifier[] = [];
const cfgEntryNodes: coref.SyntheticCfgNode[] = [
coref.createCfgEntryNode(topLevel.oid),
];
const cfgExitNodes: coref.SyntheticCfgNode[] = [
coref.createCfgExitNode(topLevel.oid),
];
util.forEachNode(tsSourceFile, (tsNode: extendedTs.Node) => {
const childNodes = visitNode(tsNode);
nodes = nodes.concat(childNodes);
const currentNodeComments = visitNodeComments(tsNode);
nodeComments = nodeComments.concat(currentNodeComments);
if (tsNode.kind === ts.SyntaxKind.BindingElement) {
bindingElements.push(
extractBindingElement(tsNode as extendedTs.BindingElement),
);
} else if (ts.isClassLike(tsNode)) {
const classLikeDeclaration = visitClassLikeDeclaration(tsNode);
classLikeDeclarations.push(classLikeDeclaration);
} else if (ts.isFunctionLike(tsNode)) {
if (util.isFunctionLikeDeclaration(tsNode)) {
const {
functionLikeDeclaration,
functionEnclosingNodes: currentFunctionEnclosingNodes,
} = visitFunctionLikeDeclaration(tsNode);
functionEnclosingNodes = functionEnclosingNodes.concat(
currentFunctionEnclosingNodes,
);
functionLikeDeclarations.push(functionLikeDeclaration);
cfgEntryNodes.push(
coref.createCfgEntryNode(functionLikeDeclaration.oid),
);
cfgExitNodes.push(coref.createCfgExitNode(functionLikeDeclaration.oid));
}
} else if (util.isLiteralLikeNode(tsNode)) {
const literal = visitLiteralLikeNode(tsNode);
literals.push(literal);
}
if (util.canHaveModifiers(tsNode)) {
const extractedModifiers = extractModifiers(tsNode);
if (extractedModifiers.length > 0) {
modifiers = modifiers.concat(extractedModifiers);
}
}
});
const locationMap = new Map<bigint, coref.Location>();
// TopLevel 的范围不包含文件开头的注释,因此其 location 信息需要单独记录
locationMap.set(topLevel.location.oid, topLevel.location);
nodes.forEach(node => {
const location = node.location;
locationMap.set(location.oid, location);
});
return {
topLevel,
nodes,
nodeComments,
bindingElements,
classLikeDeclarations,
functionLikeDeclarations,
functionEnclosingNodes,
literals,
modifiers,
cfgEntryNodes,
cfgExitNodes,
locationMap,
};
} | /**
* 抽取 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.forEachNode(tsSourceFile, (tsNode: extendedTs.Node) => {
const symbol = util.createSymbol(tsNode, typeChecker, projectPath);
if (symbol === undefined) {
return;
}
symbolMap.set(symbol.oid, symbol);
nodeSymbolMap.set((tsNode.$corefModel as coref.Node).oid, symbol.oid);
if (tsNode.kind === ts.SyntaxKind.ShorthandPropertyAssignment) {
const valueSymbolOid = util.getShortHandAssignmentValueSymbolOid(
tsNode,
typeChecker,
projectPath,
);
if (valueSymbolOid !== undefined) {
shorthandAssignmentValueSymbolMap.set(
(tsNode.$corefModel as coref.Node).oid,
valueSymbolOid,
);
}
}
});
return {
symbolMap,
nodeSymbolMap,
shorthandAssignmentValueSymbolMap,
};
} | /**
* 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 = visitMayInvokeExpression(
program,
tsNode as extendedTs.MayInvokeExpression,
projectPath,
);
if (callSite) {
callSiteMap.set(callSite.invokeExpression.oid, callSite.callee.oid);
}
}
});
return callSiteMap;
} | /**
* 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 node 可能包含一整行的内容只存在非代码的 Token
for (const token of tokens) {
// 非代码的 Token
if (util.isNonCodeTokenSyntaxKind(token.kind)) {
continue;
}
// 除了非代码的Token,如果一行存在 Token,则认为该行为代码行
const startLine = token.location.start.line;
const endLine = token.location.end.line;
range(startLine, endLine + 1).forEach(value => {
codeLineSet.add(value);
});
}
// 使用 comments 统计代码行数,如果一行存在 comment,则认为该行为注释行
for (const comment of comments) {
const startLine = comment.location.start.line;
const endLine = comment.location.end.line;
range(startLine, endLine + 1).forEach(value => {
commentLineSet.add(value);
});
}
for (const location of locations) {
const startLine = location.start.line;
const endLine = location.end.line;
const lines = endLine - startLine + 1;
const codeLines = range(startLine, endLine + 1).reduce(
(previousValue, currentValue) => {
return codeLineSet.has(currentValue)
? previousValue + 1
: previousValue;
},
0,
);
const commentLines = range(startLine, endLine + 1).reduce(
(previousValue, currentValue) => {
return commentLineSet.has(currentValue)
? previousValue + 1
: previousValue;
},
0,
);
numberOfLinesArray.push({
locationOid: location.oid,
lines,
codeLines,
commentLines,
});
}
return numberOfLinesArray;
} | /**
* 抽取每个 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 {
high = mid - 1;
}
}
return low;
} | /**
* 根据源码 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(node);
if (result) {
return result;
}
}
}
} | /**
* 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.