prefix
stringlengths 82
32.6k
| middle
stringlengths 5
470
| suffix
stringlengths 0
81.2k
| file_path
stringlengths 6
168
| repo_name
stringlengths 16
77
| context
listlengths 5
5
| lang
stringclasses 4
values | ground_truth
stringlengths 5
470
|
---|---|---|---|---|---|---|---|
import { useEffect, useLayoutEffect, useRef } from 'react';
import { PlayIcon } from '@heroicons/react/24/outline';
import MonacoEditor from '@monaco-editor/react';
import { editor } from 'monaco-editor';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import K from './Hotkey';
interface EditorProps {
onRunCode?: (code: string) => void;
showRunButton?: boolean;
}
interface CoreEditorProps extends EditorProps {
onSave: (content: string) => void;
onChange: (value: string) => void;
value: string;
}
const CoreEditor = (props: CoreEditorProps): JSX.Element => {
const ref = useRef<editor.IStandaloneCodeEditor>();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 's') {
e.preventDefault();
const content = ref.current?.getValue();
if (content !== undefined) props.onSave(content);
}
if (e.key === 'F5') {
e.preventDefault();
saveThenRunCode();
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
const saveThenRunCode = () => {
const content = ref.current?.getValue() ?? '';
props.onSave(content);
props.onRunCode?.(content);
};
return (
<section className="windowed h-full w-full">
<MonacoEditor
defaultLanguage="python"
onChange={(value) =>
value !== undefined ? props.onChange(value) : null
}
onMount={(editor) => (ref.current = editor)}
options={{
fontSize: 14,
fontFamily: 'monospace',
smoothScrolling: true,
cursorSmoothCaretAnimation: 'on',
minimap: { enabled: false },
}}
theme="vs-dark"
value={props.value}
/>
{props.showRunButton && (
<div className="absolute bottom-3 right-3 space-x-2">
<Button icon={PlayIcon} onClick={saveThenRunCode}>
Run
<K className="ml-2 text-blue-900/60 ring-blue-900/60" of="F5" />
</Button>
</div>
)}
</section>
);
};
const Editor = (props: EditorProps): JSX.Element | null => {
const { update, save } = useFilesMutations();
| const { name, content } = useFile.Selected(); |
useLayoutEffect(() => {
document.title = `${name ? `${name} | ` : ''}Glide`;
}, [name]);
if (name === undefined || content === undefined) return null;
return (
<CoreEditor
{...props}
onChange={update}
onSave={(newContent) => save(name, newContent)}
value={content}
/>
);
};
export default Editor;
| src/components/Editor.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`mr-2 h-5 w-5 ${props.iconClassName ?? ''}`}\n />\n )}\n {props.children}\n </button>\n )}\n </Menu.Item>\n);\nconst MenuHeader = (props: { children: ReactNode }): JSX.Element => (\n <Menu.Item as=\"p\" className=\"px-2 py-1 text-xs text-slate-400\">",
"score": 0.8524788618087769
},
{
"filename": "src/components/Button.tsx",
"retrieved_chunk": " props.className ?? ''\n }`}\n >\n {Icon && <Icon className=\"-ml-1 mr-2 h-5 w-5\" />}\n {props.children}\n </button>\n );\n};\nexport default Button;",
"score": 0.8311430215835571
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " onClose: () => void;\n}\nconst Library = (props: LibraryProps): JSX.Element => {\n const files = useFile.NamesWithUnsaved();\n const { draft, create } = useFilesMutations();\n return (\n <Transition appear as={Fragment} show={props.open}>\n <Dialog className=\"relative z-40\" onClose={props.onClose}>\n <Transition.Child\n as={Fragment}",
"score": 0.8214114904403687
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">",
"score": 0.8115150928497314
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 0.8052382469177246
}
] | typescript | const { name, content } = useFile.Selected(); |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
| <FileItem
key={name} |
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 0.8651307821273804
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 0.8259509801864624
},
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " <main className=\"h-screen w-screen bg-slate-900 p-3 text-white\">\n <Between\n by={[70, 30]}\n first={\n <div className=\"flex h-full flex-col space-y-3\">\n <Navigator />\n <Editor onRunCode={interpreter.run} showRunButton={!running} />\n </div>\n }\n second={",
"score": 0.8051022291183472
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">",
"score": 0.7951511144638062
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " const [newFileName, setNewFileName] = useState<string>();\n const [editing, setEditing] = useState(false);\n return !editing ? (\n <div\n className=\"min-w-0 rounded-lg p-2 hover:bg-slate-800\"\n onClick={() => setEditing(true)}\n >\n <p className=\"text-md overflow-hidden overflow-ellipsis whitespace-nowrap\">\n {props.initialValue}\n </p>",
"score": 0.7852158546447754
}
] | typescript | <FileItem
key={name} |
import { useState } from 'react';
import { Transition } from '@headlessui/react';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import UnsavedBadge from './UnsavedBadge';
interface RenamableInputProps {
initialValue: string;
onConfirm: (value: string) => void;
}
const RenamableInput = (props: RenamableInputProps): JSX.Element => {
const [newFileName, setNewFileName] = useState<string>();
const [editing, setEditing] = useState(false);
return !editing ? (
<div
className="min-w-0 rounded-lg p-2 hover:bg-slate-800"
onClick={() => setEditing(true)}
>
<p className="text-md overflow-hidden overflow-ellipsis whitespace-nowrap">
{props.initialValue}
</p>
</div>
) : (
<input
autoFocus
className="w-fit rounded-lg bg-slate-800 bg-transparent p-2 outline-none ring-2 ring-slate-600"
onBlur={() => {
let newName = newFileName?.trim();
setEditing(false);
setNewFileName(undefined);
if (
!newName ||
newName === props.initialValue ||
newName.startsWith('.') ||
newName.endsWith('.')
)
return;
/**
* @see https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
*/
newName = newName.replace(/[/\\?%*:|"<>]/g, '_');
props.onConfirm(newName);
}}
onChange={(e) => setNewFileName(e.target.value)}
onFocus={(e) => {
const name = e.target.value;
const extensionLength = name.split('.').pop()?.length ?? 0;
e.target.setSelectionRange(0, name.length - extensionLength - 1);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
e.currentTarget.blur();
}
if (e.key === 'Escape') {
e.preventDefault();
setEditing(false);
setNewFileName(undefined);
}
}}
placeholder={props.initialValue}
type="text"
value={newFileName ?? props.initialValue}
/>
);
};
const FileName = (): JSX.Element => {
const name = useFile.SelectedName();
| const unsaved = useFile.IsUnsavedOf(name); |
const existingNames = useFile.NamesSet();
const { rename } = useFilesMutations();
return (
<div className="flex min-w-0 items-center space-x-3">
{name && (
<RenamableInput
initialValue={name}
onConfirm={(newName) => {
if (!name) return;
if (existingNames.has(newName)) return;
rename(name, newName);
}}
/>
)}
<Transition
enter="transition-transform origin-left duration-75"
enterFrom="scale-0"
enterTo="scale-100"
leave="transition-transform origin-left duration-150"
leaveFrom="scale-100"
leaveTo="scale-0"
show={Boolean(name && unsaved)}
>
<UnsavedBadge />
</Transition>
</div>
);
};
export default FileName;
| src/components/FileName.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">",
"score": 0.8106221556663513
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 0.7662346363067627
},
{
"filename": "src/components/Library.tsx",
"retrieved_chunk": " onClose: () => void;\n}\nconst Library = (props: LibraryProps): JSX.Element => {\n const files = useFile.NamesWithUnsaved();\n const { draft, create } = useFilesMutations();\n return (\n <Transition appear as={Fragment} show={props.open}>\n <Dialog className=\"relative z-40\" onClose={props.onClose}>\n <Transition.Child\n as={Fragment}",
"score": 0.7644537687301636
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " showRunButton?: boolean;\n}\ninterface CoreEditorProps extends EditorProps {\n onSave: (content: string) => void;\n onChange: (value: string) => void;\n value: string;\n}\nconst CoreEditor = (props: CoreEditorProps): JSX.Element => {\n const ref = useRef<editor.IStandaloneCodeEditor>();\n const handleShortcut = (e: KeyboardEvent) => {",
"score": 0.7619379758834839
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": " if (!files?.length) return;\n const file = Array.from(files)[0];\n const reader = new FileReader();\n reader.onload = ({ target }) =>\n props.onUpload?.(file.name, target?.result as string);\n reader.readAsText(file);\n e.target.value = '';\n };\n return (\n <Button",
"score": 0.7548413872718811
}
] | typescript | const unsaved = useFile.IsUnsavedOf(name); |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
<FileItem
key={name}
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
< | Button
icon={PlusIcon} |
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={(name, content) => {
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Button.tsx",
"retrieved_chunk": " props.className ?? ''\n }`}\n >\n {Icon && <Icon className=\"-ml-1 mr-2 h-5 w-5\" />}\n {props.children}\n </button>\n );\n};\nexport default Button;",
"score": 0.8361995220184326
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`mr-2 h-5 w-5 ${props.iconClassName ?? ''}`}\n />\n )}\n {props.children}\n </button>\n )}\n </Menu.Item>\n);\nconst MenuHeader = (props: { children: ReactNode }): JSX.Element => (\n <Menu.Item as=\"p\" className=\"px-2 py-1 text-xs text-slate-400\">",
"score": 0.8354976177215576
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }}\n onClickRestart={props.onRestart}\n />\n </div>\n {props.showStopButton && (\n <div className=\"absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100\">\n <Button icon={StopIcon} onClick={props.onStop}>\n Stop\n </Button>\n </div>",
"score": 0.8341439962387085
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 0.825023353099823
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " Save <K of=\"Mod+S\" />\n </Item>\n )}\n <Item\n className=\"text-slate-400\"\n icon={BuildingLibraryIcon}\n onClick={() => setOpenLibrary(true)}\n >\n Library <K of=\"Mod+O\" />\n </Item>",
"score": 0.8140178918838501
}
] | typescript | Button
icon={PlusIcon} |
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
| promptRef.current?.focusWith(key); |
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
| src/components/Terminal.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " const name = useFile.SelectedName();\n const handleShortcut = (e: KeyboardEvent) => {\n const isMod = isMac ? e.metaKey : e.ctrlKey;\n if (isMod && e.key === 'o') {\n e.preventDefault();\n setOpenLibrary(true);\n }\n };\n useEffect(() => {\n window.addEventListener('keydown', handleShortcut);",
"score": 0.7095301151275635
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " const isMod = navigator.platform.startsWith('Mac') ? e.metaKey : e.ctrlKey;\n if (isMod && e.key === 's') {\n e.preventDefault();\n const content = ref.current?.getValue();\n if (content !== undefined) props.onSave(content);\n }\n if (e.key === 'F5') {\n e.preventDefault();\n saveThenRunCode();\n }",
"score": 0.7025300860404968
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " };\n useEffect(() => {\n window.addEventListener('keydown', handleShortcut);\n return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n const saveThenRunCode = () => {\n const content = ref.current?.getValue() ?? '';\n props.onSave(content);\n props.onRunCode?.(content);\n };",
"score": 0.6878269910812378
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " props.onConfirm(newName);\n }}\n onChange={(e) => setNewFileName(e.target.value)}\n onFocus={(e) => {\n const name = e.target.value;\n const extensionLength = name.split('.').pop()?.length ?? 0;\n e.target.setSelectionRange(0, name.length - extensionLength - 1);\n }}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {",
"score": 0.6729816198348999
},
{
"filename": "src/workers/interpreter.worker.ts",
"retrieved_chunk": "const listeners = {\n initialize: async (newInterruptBuffer?: Uint8Array) => {\n pyodide ??= await preparePyodide();\n if (!newInterruptBuffer) return;\n pyodide.setInterruptBuffer(newInterruptBuffer);\n interruptBuffer = newInterruptBuffer;\n },\n run: async ({ code, exports }: RunExportableData) => {\n pyodide ??= await preparePyodide();\n post.writeln(RUN_CODE);",
"score": 0.6679439544677734
}
] | typescript | promptRef.current?.focusWith(key); |
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
| const promptRef = useRef<ComponentRef<typeof Prompt>>(null); |
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
| src/components/Terminal.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Between.tsx",
"retrieved_chunk": " const { by: sizes } = props;\n const oneRef = useRef<HTMLDivElement>(null);\n const twoRef = useRef<HTMLDivElement>(null);\n const [direction, setDirection] = useState<Direction>('vertical');\n useLayoutEffect(() => {\n const resizeObserver = new ResizeObserver((entries) => {\n if (!entries.length) return;\n const { width } = entries[0].contentRect;\n setDirection(width >= 1024 ? 'horizontal' : 'vertical');\n });",
"score": 0.80745929479599
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": "const Prompt = forwardRef<PromptRef, PromptProps>((props, ref): JSX.Element => {\n const [{ dirty, command }, setCommand] = useState({\n dirty: false,\n command: '',\n });\n const inputRef = useRef<HTMLInputElement>(null);\n const history = useCommandHistory();\n useImperativeHandle(ref, () => ({\n focusWith: (key) => {\n if (key)",
"score": 0.7991982698440552
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " showRunButton?: boolean;\n}\ninterface CoreEditorProps extends EditorProps {\n onSave: (content: string) => void;\n onChange: (value: string) => void;\n value: string;\n}\nconst CoreEditor = (props: CoreEditorProps): JSX.Element => {\n const ref = useRef<editor.IStandaloneCodeEditor>();\n const handleShortcut = (e: KeyboardEvent) => {",
"score": 0.7851308584213257
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": "const FileItem = (props: FileItemProps): JSX.Element => {\n const { select, destroy } = useFilesMutations();\n const selectedFileName = useFile.SelectedName();\n const buttonRef = useRef<HTMLButtonElement>(null);\n useLayoutEffect(() => {\n if (props.name !== selectedFileName) return;\n buttonRef.current?.focus();\n }, [props.name, selectedFileName]);\n return (\n <div className=\"flex items-center space-x-2\">",
"score": 0.7849696278572083
},
{
"filename": "src/components/Item.tsx",
"retrieved_chunk": "import { ComponentProps, ElementType, SVGProps } from 'react';\ninterface ItemProps extends ComponentProps<'div'> {\n icon?: ElementType<SVGProps<SVGSVGElement>>;\n iconClassName?: string;\n labelClassName?: string;\n selected?: boolean;\n}\nconst Item = (props: ItemProps): JSX.Element => {\n const {\n icon: Icon,",
"score": 0.7843518257141113
}
] | typescript | const promptRef = useRef<ComponentRef<typeof Prompt>>(null); |
import { useEffect, useState } from 'react';
import { BuildingLibraryIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import FileName from './FileName';
import K from './Hotkey';
import Item from './Item';
import Library from './Library';
const isMac = navigator.platform.startsWith('Mac');
const Navigator = (): JSX.Element => {
const [openLibrary, setOpenLibrary] = useState(true);
const name = useFile.SelectedName();
const handleShortcut = (e: KeyboardEvent) => {
const isMod = isMac ? e.metaKey : e.ctrlKey;
if (isMod && e.key === 'o') {
e.preventDefault();
setOpenLibrary(true);
}
};
useEffect(() => {
window.addEventListener('keydown', handleShortcut);
return () => window.removeEventListener('keydown', handleShortcut);
}, [handleShortcut]);
return (
<>
<nav className="flex items-center justify-between space-x-2">
<FileName />
<div className="flex flex-row items-center space-x-2">
{name && (
<Item
className="text-slate-400"
onClick={() => {
window.dispatchEvent(
new KeyboardEvent('keydown', {
key: 's',
metaKey: isMac,
ctrlKey: !isMac,
}),
);
}}
>
Save <K of="Mod+S" />
</Item>
)}
<Item
className="text-slate-400"
icon={BuildingLibraryIcon}
onClick={() => setOpenLibrary(true)}
>
Library <K of="Mod+O" />
</Item>
</div>
</nav>
< | Library onClose={() => setOpenLibrary(false)} open={openLibrary} />
</>
); |
};
export default Navigator;
| src/components/Navigator.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 0.8108454346656799
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuItem icon={TrashIcon} onClick={props.onClickClearConsole}>\n Clear output\n </MenuItem>\n </div>\n </Menu.Items>\n </Transition>\n </Menu>\n );\n};\nexport default TerminalMenu;",
"score": 0.7978479862213135
},
{
"filename": "src/components/Button.tsx",
"retrieved_chunk": " props.className ?? ''\n }`}\n >\n {Icon && <Icon className=\"-ml-1 mr-2 h-5 w-5\" />}\n {props.children}\n </button>\n );\n};\nexport default Button;",
"score": 0.7699764966964722
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`mr-2 h-5 w-5 ${props.iconClassName ?? ''}`}\n />\n )}\n {props.children}\n </button>\n )}\n </Menu.Item>\n);\nconst MenuHeader = (props: { children: ReactNode }): JSX.Element => (\n <Menu.Item as=\"p\" className=\"px-2 py-1 text-xs text-slate-400\">",
"score": 0.7625372409820557
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuHeader>Interpreter</MenuHeader>\n <MenuItem icon={ArrowPathIcon} onClick={props.onClickRestart}>\n Restart\n </MenuItem>\n <MenuItem icon={StopIcon} onClick={props.onClickForceStop}>\n Force stop\n </MenuItem>\n </div>\n <div className=\"px-1 py-1\">\n <MenuHeader>Console</MenuHeader>",
"score": 0.7532546520233154
}
] | typescript | Library onClose={() => setOpenLibrary(false)} open={openLibrary} />
</>
); |
import { Fragment } from 'react';
import { Dialog, Transition } from '@headlessui/react';
import { ArrowUpTrayIcon, PlusIcon } from '@heroicons/react/24/outline';
import useFile from '../hooks/useFile';
import useFilesMutations from '../hooks/useFilesMutations';
import Button from './Button';
import FileItem from './FileItem';
import FileUploader from './FileUploader';
interface LibraryProps {
open: boolean;
onClose: () => void;
}
const Library = (props: LibraryProps): JSX.Element => {
const files = useFile.NamesWithUnsaved();
const { draft, create } = useFilesMutations();
return (
<Transition appear as={Fragment} show={props.open}>
<Dialog className="relative z-40" onClose={props.onClose}>
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black bg-opacity-25" />
</Transition.Child>
<div className="fixed inset-0 overflow-y-auto">
<div className="flex min-h-full items-start justify-center px-4 py-10 text-center">
<Transition.Child
as={Fragment}
enter="ease-out duration-100"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="ease-in duration-100"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-slate-800 p-5 text-left align-middle shadow-xl ring-2 ring-slate-700 transition-all">
<div className="flex justify-between">
<Dialog.Title
as="h3"
className="text-lg font-medium leading-6 text-white"
>
Library
</Dialog.Title>
<p className="select-none text-sm text-slate-600">
{__VERSION__}
</p>
</div>
<div className="mt-6 flex flex-col space-y-2">
{files.map(({ name, unsaved }) => (
<FileItem
key={name}
name={name}
onClick={props.onClose}
unsaved={unsaved}
/>
))}
</div>
<div className="mt-10 space-x-2">
<Button
icon={PlusIcon}
onClick={() => {
draft(true);
props.onClose();
}}
>
New File
</Button>
<FileUploader
icon={ArrowUpTrayIcon}
onUpload={ | (name, content) => { |
if (content === null) return;
create(name, content);
props.onClose();
}}
>
Upload
</FileUploader>
</div>
</Dialog.Panel>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
);
};
export default Library;
| src/components/Library.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " Save <K of=\"Mod+S\" />\n </Item>\n )}\n <Item\n className=\"text-slate-400\"\n icon={BuildingLibraryIcon}\n onClick={() => setOpenLibrary(true)}\n >\n Library <K of=\"Mod+O\" />\n </Item>",
"score": 0.8309035301208496
},
{
"filename": "src/components/FileUploader.tsx",
"retrieved_chunk": "import { ChangeEventHandler, ComponentProps } from 'react';\nimport Button from './Button';\ninterface FileUploaderProps extends ComponentProps<typeof Button> {\n onUpload?: (name: string, content: string | null) => void;\n}\nconst FileUploader = (props: FileUploaderProps): JSX.Element => {\n const { onUpload: onUploadFile, ...buttonProps } = props;\n const handleUpload: ChangeEventHandler<HTMLInputElement> = (e) => {\n e.preventDefault();\n const files = e.target.files;",
"score": 0.8013855218887329
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuItem icon={TrashIcon} onClick={props.onClickClearConsole}>\n Clear output\n </MenuItem>\n </div>\n </Menu.Items>\n </Transition>\n </Menu>\n );\n};\nexport default TerminalMenu;",
"score": 0.7816815376281738
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " </div>\n </nav>\n <Library onClose={() => setOpenLibrary(false)} open={openLibrary} />\n </>\n );\n};\nexport default Navigator;",
"score": 0.7778462171554565
},
{
"filename": "src/components/Editor.tsx",
"retrieved_chunk": " <Button icon={PlayIcon} onClick={saveThenRunCode}>\n Run\n <K className=\"ml-2 text-blue-900/60 ring-blue-900/60\" of=\"F5\" />\n </Button>\n </div>\n )}\n </section>\n );\n};\nconst Editor = (props: EditorProps): JSX.Element | null => {",
"score": 0.7765952348709106
}
] | typescript | (name, content) => { |
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
<Prompt
ref={promptRef}
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
< | Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)} |
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
| src/components/Terminal.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " className={`${\n active ? 'bg-blue-200 text-blue-900' : 'text-white'\n } group flex w-full items-center whitespace-nowrap rounded-md p-2 text-sm ${\n props.className ?? ''\n }`}\n onClick={props.onClick}\n >\n {props.icon && (\n <props.icon\n aria-hidden=\"true\"",
"score": 0.8498002290725708
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " {props.children}\n </Menu.Item>\n);\nconst TerminalMenu = (props: TerminalMenuProps): JSX.Element => {\n return (\n <Menu as=\"div\" className=\"relative inline-block text-left\">\n <Menu.Button className=\"rounded-md bg-slate-500 bg-opacity-20 p-2 transition-transform hover:bg-opacity-30 active:scale-95\">\n <Bars3Icon aria-hidden=\"true\" className=\"h-5 w-5\" />\n </Menu.Button>\n <Transition",
"score": 0.8490636348724365
},
{
"filename": "src/components/Item.tsx",
"retrieved_chunk": " } ${props.className ?? ''}`}\n role=\"button\"\n >\n {Icon && (\n <Icon\n className={`w-5 flex-shrink-0 opacity-80 ${\n !selected ? 'group-hover:opacity-90' : ''\n } ${iconClassName ?? ''}`}\n />\n )}",
"score": 0.8425303101539612
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " <MenuHeader>Interpreter</MenuHeader>\n <MenuItem icon={ArrowPathIcon} onClick={props.onClickRestart}>\n Restart\n </MenuItem>\n <MenuItem icon={StopIcon} onClick={props.onClickForceStop}>\n Force stop\n </MenuItem>\n </div>\n <div className=\"px-1 py-1\">\n <MenuHeader>Console</MenuHeader>",
"score": 0.839560866355896
},
{
"filename": "src/components/FileItem.tsx",
"retrieved_chunk": " {props.name}\n </p>\n <div className=\"flex items-center space-x-3 pl-2\">\n {props.unsaved && <UnsavedBadge className=\"group-hover:hidden\" />}\n <div className=\"hidden animate-pulse items-center space-x-1 text-xs opacity-70 group-hover:flex\">\n <p>Open</p>\n <ArrowRightIcon className=\"h-4\" />\n </div>\n </div>\n </button>",
"score": 0.8280808925628662
}
] | typescript | Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)} |
import {
ComponentRef,
forwardRef,
useEffect,
useImperativeHandle,
useLayoutEffect,
useRef,
} from 'react';
import { StopIcon } from '@heroicons/react/24/outline';
import { slate, yellow } from 'tailwindcss/colors';
import { Terminal as Xterm } from 'xterm';
import { CanvasAddon } from 'xterm-addon-canvas';
import { FitAddon } from 'xterm-addon-fit';
import { WebglAddon } from 'xterm-addon-webgl';
import Button from './Button';
import Prompt from './Prompt';
import TerminalMenu from './TerminalMenu';
import 'xterm/css/xterm.css';
interface TerminalRef {
append: (result?: string) => void;
write: (result?: string) => void;
error: (result?: string) => void;
system: (result?: string) => void;
}
interface TerminalProps {
onStop?: () => void;
onReturn?: (line: string) => void;
onRestart?: () => void;
showStopButton?: boolean;
}
const isASCIIPrintable = (character: string): boolean =>
character >= String.fromCharCode(32) && character <= String.fromCharCode(126);
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
/**
* @see https://github.com/xtermjs/xterm.js/pull/4255
*/
const getSafariVersion = (): number => {
if (!isSafari) return 0;
const majorVersion = navigator.userAgent.match(/Version\/(\d+)/);
if (majorVersion === null || majorVersion.length < 2) return 0;
return parseInt(majorVersion[1]);
};
const isWebGL2Compatible = (): boolean => {
const context = document.createElement('canvas').getContext('webgl2');
const isWebGL2Available = Boolean(context);
return isWebGL2Available && (isSafari ? getSafariVersion() >= 16 : true);
};
const Terminal = forwardRef<TerminalRef, TerminalProps>(
(props, ref): JSX.Element => {
const xtermRef = useRef<Xterm>();
const fitAddonRef = useRef<FitAddon>();
const terminalRef = useRef<HTMLDivElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
const promptRef = useRef<ComponentRef<typeof Prompt>>(null);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) return;
const resizeObserver = new ResizeObserver(() =>
fitAddonRef.current?.fit(),
);
resizeObserver.observe(container);
return () => resizeObserver.disconnect();
}, []);
useEffect(() => {
const terminal = terminalRef.current;
if (!terminal) return;
const xterm = new Xterm({
cursorBlink: false,
cursorStyle: 'underline',
fontFamily: 'monospace',
fontSize: 14,
theme: { background: slate[900], cursor: yellow[400] },
disableStdin: true,
});
const fitAddon = new FitAddon();
xterm.loadAddon(fitAddon);
if (isWebGL2Compatible()) {
xterm.loadAddon(new WebglAddon());
} else {
xterm.loadAddon(new CanvasAddon());
}
xterm.onKey(({ key }) => {
if (!(isASCIIPrintable(key) || key >= '\u00a0')) return;
promptRef.current?.focusWith(key);
});
xterm.open(terminal);
fitAddon.fit();
xtermRef.current = xterm;
fitAddonRef.current = fitAddon;
return () => xterm.dispose();
}, []);
const write = (text: string, line = true) => {
const trimmed = text.replace(/\n/g, '\r\n');
const xterm = xtermRef.current;
if (!xterm) return;
const writer = (text: string) =>
line ? xterm.writeln(text) : xterm.write(text);
try {
writer(trimmed);
} catch (error) {
if (!(error instanceof Error)) throw error;
console.log('oops', error.message);
xterm.clear();
writer(trimmed);
}
};
useImperativeHandle(ref, () => ({
append: (result?: string) => write(result ?? ''),
write: (result?: string) => write(result ?? '', false),
error: (result?: string) =>
write('\u001b[31m' + (result ?? '') + '\u001b[0m'),
system: (result?: string) =>
write('\u001b[33m' + (result ?? '') + '\u001b[0m'),
}));
return (
<section ref={containerRef} className="relative h-full w-full">
<div ref={terminalRef} className="windowed h-full" />
<div className="absolute bottom-0 left-0 z-40 flex w-full space-x-2 px-2 pb-2">
| <Prompt
ref={promptRef} |
onReturn={(input) => {
props.onReturn?.(input);
xtermRef.current?.scrollToBottom();
}}
/>
<TerminalMenu
onClickClearConsole={() => xtermRef.current?.clear()}
onClickForceStop={() => {
props.onStop?.();
xtermRef.current?.scrollToBottom();
}}
onClickRestart={props.onRestart}
/>
</div>
{props.showStopButton && (
<div className="absolute right-3 top-3 z-20 space-x-2 opacity-50 hover:opacity-100">
<Button icon={StopIcon} onClick={props.onStop}>
Stop
</Button>
</div>
)}
</section>
);
},
);
Terminal.displayName = 'Terminal';
export default Terminal;
| src/components/Terminal.tsx | NUSSOC-glide-3ab6925 | [
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " setCommand((state) => ({ dirty: true, command: state.command + key }));\n inputRef.current?.focus();\n },\n }));\n return (\n <div className=\"flex w-full items-center rounded-lg bg-slate-800 px-2 text-slate-300 shadow-2xl shadow-slate-900 focus-within:ring-2 focus-within:ring-slate-500\">\n <ChevronRightIcon className=\"h-5\" />\n <div className=\"relative ml-2 w-full\">\n {!command.length && (\n <div className=\"pointer-events-none absolute left-0 top-0 flex h-full w-full items-center overflow-hidden\">",
"score": 0.8214009404182434
},
{
"filename": "src/components/Prompt.tsx",
"retrieved_chunk": " <p className=\"overflow-ellipsis whitespace-nowrap text-sm opacity-50\">\n Python commands go here! More options? →\n </p>\n </div>\n )}\n <input\n ref={inputRef}\n className=\"w-full bg-transparent py-2 pr-2 font-mono text-sm outline-none\"\n onChange={(e) => {\n setCommand({ dirty: true, command: e.target.value });",
"score": 0.8112820386886597
},
{
"filename": "src/components/Navigator.tsx",
"retrieved_chunk": " return () => window.removeEventListener('keydown', handleShortcut);\n }, [handleShortcut]);\n return (\n <>\n <nav className=\"flex items-center justify-between space-x-2\">\n <FileName />\n <div className=\"flex flex-row items-center space-x-2\">\n {name && (\n <Item\n className=\"text-slate-400\"",
"score": 0.794121265411377
},
{
"filename": "src/components/TerminalMenu.tsx",
"retrieved_chunk": " {props.children}\n </Menu.Item>\n);\nconst TerminalMenu = (props: TerminalMenuProps): JSX.Element => {\n return (\n <Menu as=\"div\" className=\"relative inline-block text-left\">\n <Menu.Button className=\"rounded-md bg-slate-500 bg-opacity-20 p-2 transition-transform hover:bg-opacity-30 active:scale-95\">\n <Bars3Icon aria-hidden=\"true\" className=\"h-5 w-5\" />\n </Menu.Button>\n <Transition",
"score": 0.776278018951416
},
{
"filename": "src/components/FileName.tsx",
"retrieved_chunk": " const [newFileName, setNewFileName] = useState<string>();\n const [editing, setEditing] = useState(false);\n return !editing ? (\n <div\n className=\"min-w-0 rounded-lg p-2 hover:bg-slate-800\"\n onClick={() => setEditing(true)}\n >\n <p className=\"text-md overflow-hidden overflow-ellipsis whitespace-nowrap\">\n {props.initialValue}\n </p>",
"score": 0.7704544067382812
}
] | typescript | <Prompt
ref={promptRef} |
import { createCollectionRef } from './createCollectionRef'
import { firestore } from 'firebase-admin'
import { serverTimestamp } from './serverTimestamp'
/**
* Adds a new document to the specified collection in Firestore. If an ID is provided, the document will be set with that ID; otherwise, an ID will be automatically generated.
*
* @param db - The instance of the Firestore database to interact with.
* @param collectionPath - The path of the collection where the document will be added or set.
* @param params - The data of the document to be added or set.
* @param id - Optional. If provided, the document will be set with this ID. If not, an ID will be automatically generated by Firestore.
*
* @returns A reference to the added or set document.
*
* @throws Throws an exception if any error occurs during the document addition or setting process.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { add } from '@skeet-framework/firestore'
*
* const db = firestore();
* const data: User = {
* name: "John Doe",
* age: 30
* };
*
* async function run() {
* try {
* const path = 'Users';
* // Example without providing an ID:
* const docRef1 = await add<User>(db, path, data);
* console.log(`Document added with ID: ${docRef1.id}`);
*
* // Example with providing an ID:
* const customID = 'custom_user_id';
* const docRef2 = await add<User>(db, path, data, customID);
* console.log(`Document set with ID: ${docRef2.id}`);
* } catch (error) {
* console.error(`Error processing document: ${error}`);
* }
* }
*
* run();
* ```
*/
export const addCollectionItem = async <T extends firestore.DocumentData>(
db: firestore.Firestore,
collectionPath: string,
params: T,
id?: string
) => {
try {
| const collectionRef = createCollectionRef<T>(db, collectionPath)
if (id) { |
const docRef = collectionRef.doc(id)
await docRef.set({
...params,
createdAt: serverTimestamp(),
updatedAt: serverTimestamp(),
})
return docRef
} else {
const data = await collectionRef.add({
...params,
createdAt: serverTimestamp(),
updatedAt: serverTimestamp(),
})
if (!data) {
throw new Error('no data')
}
return data
}
} catch (error) {
throw new Error(`Error adding document: ${error}`)
}
}
| src/lib/addCollectionItem.ts | elsoul-skeet-firestore-8c637de | [
{
"filename": "src/lib/updateCollectionItem.ts",
"retrieved_chunk": " */\nexport const updateCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string,\n params: firestore.UpdateData<T>\n): Promise<boolean> => {\n try {\n const docRef = db\n .collection(collectionPath)",
"score": 0.9640660285949707
},
{
"filename": "src/lib/getCollectionItem.ts",
"retrieved_chunk": " * run();\n * ```\n */\nexport const getCollectionItem = async <T>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string\n): Promise<T> => {\n const dataRef = db\n .collection(collectionPath)",
"score": 0.9230747818946838
},
{
"filename": "src/lib/queryCollectionItems.ts",
"retrieved_chunk": " */\nexport const queryCollectionItems = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n conditions: QueryCondition[]\n): Promise<T[]> => {\n try {\n let query: firestore.Query = db\n .collection(collectionPath)\n .withConverter(createFirestoreDataConverter<T>())",
"score": 0.9228736758232117
},
{
"filename": "src/lib/addMultipleCollectionItems.ts",
"retrieved_chunk": " */\nexport const addMultipleCollectionItems = async <\n T extends firestore.DocumentData\n>(\n db: firestore.Firestore,\n collectionPath: string,\n items: T[]\n): Promise<firestore.WriteResult[][]> => {\n const MAX_BATCH_SIZE = 500\n const chunkedItems =",
"score": 0.9216974973678589
},
{
"filename": "src/lib/deleteCollectionItem.ts",
"retrieved_chunk": " * }\n * }\n *\n * run();\n * ```\n */\nexport const deleteCollectionItem = async (\n db: firestore.Firestore,\n collectionPath: string,\n docId: string",
"score": 0.8845782279968262
}
] | typescript | const collectionRef = createCollectionRef<T>(db, collectionPath)
if (id) { |
import { persistor } from '../store';
import { filesActions } from '../store/filesSlice';
import { useAppDispatch } from '../store/hooks';
import { vaultActions } from '../store/vaultSlice';
interface UseFilesMutationsHook {
/**
* For performance reasons, the caller should ensure that the new
* name is not already in use in *both* the files and vault stores.
*/
rename: (from: string, to: string) => void;
save: (name: string, content: string) => void;
destroy: (name: string) => void;
draft: (autoSelect?: boolean) => void;
select: (name: string) => void;
update: (content: string) => void;
create: (name: string, content: string) => void;
}
const useFilesMutations = (): UseFilesMutationsHook => {
const dispatch = useAppDispatch();
return {
save: (name: string, content: string) => {
dispatch(filesActions.updateSelected(content));
dispatch(vaultActions.save({ name, content }));
persistor.flush();
},
rename: (from: string, to: string) => {
if (from === to) return;
dispatch(filesActions.rename({ from, to }));
dispatch(vaultActions.rename({ from, to }));
persistor.flush();
},
destroy: (name: string) => {
dispatch(filesActions.destroy(name));
dispatch(vaultActions.destroy(name));
persistor.flush();
},
draft: (autoSelect?: boolean) => {
| dispatch(filesActions.draft(autoSelect)); |
},
select: (name: string) => {
dispatch(filesActions.select(name));
},
update: (content: string) => {
dispatch(filesActions.updateSelected(content));
},
create: (name: string, content: string) => {
dispatch(filesActions.create({ name, content }));
dispatch(vaultActions.save({ name, content }));
persistor.flush();
},
};
};
export default useFilesMutations;
| src/hooks/useFilesMutations.ts | NUSSOC-glide-3ab6925 | [
{
"filename": "src/store/vaultSlice.ts",
"retrieved_chunk": " const { name, content } = action.payload;\n if (state.files[name] === undefined) state.list.push(name);\n state.files[name] = content;\n },\n destroy: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n delete state.files[name];\n state.list = state.list.filter((file) => file !== name);\n },\n rename: (state, action: PayloadAction<{ from: string; to: string }>) => {",
"score": 0.7932432889938354
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " state.selected = newName;\n },\n updateSelected: (state, action: PayloadAction<string>) => {\n if (state.selected === undefined) return;\n state.files[state.selected] = action.payload;\n },\n destroy: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n delete state.files[name];\n state.list = state.list.filter((file) => file !== name);",
"score": 0.7915632724761963
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " if (state.selected === name) state.selected = undefined;\n },\n select: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n if (state.files[name] === undefined) return;\n state.selected = name;\n },\n rename: (state, action: PayloadAction<{ from: string; to: string }>) => {\n const { from: oldName, to: newName } = action.payload;\n const isOldNameExist = state.files[oldName] !== undefined;",
"score": 0.7673758268356323
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " rehydrate: (\n state,\n action: PayloadAction<Pick<FilesState, 'files' | 'list'>>,\n ) => {\n state.files = action.payload.files;\n state.list = action.payload.list;\n },\n draft: (state, action: PayloadAction<boolean | undefined>) => {\n const name = findSuitableName(\n 'untitled.py',",
"score": 0.7609519958496094
},
{
"filename": "src/store/index.ts",
"retrieved_chunk": " }),\n});\nexport const persistor = persistStore(store, null, () => {\n const vault = store.getState().vault;\n store.dispatch(filesActions.rehydrate(vault));\n});\nexport const getState = store.getState;\nexport type RootState = ReturnType<typeof store.getState>;\nexport type AppDispatch = typeof store.dispatch;",
"score": 0.758548378944397
}
] | typescript | dispatch(filesActions.draft(autoSelect)); |
import { createCollectionRef } from './createCollectionRef'
import { firestore } from 'firebase-admin'
import { serverTimestamp } from './serverTimestamp'
/**
* Adds multiple documents to the specified collection in Firestore.
* This function supports batched writes, and if the number of items exceeds the maximum batch size (500),
* it will split the items into multiple batches and write them sequentially.
*
* @param db - The instance of the Firestore database to use.
* @param collectionPath - The path of the collection to which the documents will be added.
* @param items - An array of document data to be added.
*
* @returns An array of WriteResult arrays corresponding to each batch.
*
* @throws Throws an exception with an error message if an error occurs.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { adds } from '@skeet-framework/firestore'
*
* const db = firestore();
* const users: User[] = [
* { name: "John Doe", age: 30 },
* { name: "Jane Smith", age: 25 },
* // ... more users ...
* ];
*
* async function run() {
* try {
* const path = 'Users'
* const results = await adds<User>(db, path, users);
* console.log(`Added ${users.length} users in ${results.length} batches.`);
* } catch (error) {
* console.error(`Error adding documents: ${error}`);
* }
* }
*
* run();
* ```
*/
export const addMultipleCollectionItems = async <
T extends firestore.DocumentData
>(
db: firestore.Firestore,
collectionPath: string,
items: T[]
): Promise<firestore.WriteResult[][]> => {
const MAX_BATCH_SIZE = 500
const chunkedItems =
items.length > 500 ? chunkArray(items, MAX_BATCH_SIZE) : [items]
const batchResults: firestore.WriteResult[][] = []
for (const chunk of chunkedItems) {
try {
const batch = db.batch()
const | collectionRef = createCollectionRef<T>(db, collectionPath)
chunk.forEach((item) => { |
const docRef = collectionRef.doc()
batch.set(docRef, {
...item,
createdAt: serverTimestamp(),
updatedAt: serverTimestamp(),
})
})
const writeResults = await batch.commit()
batchResults.push(writeResults)
} catch (error) {
throw new Error(`Error adding a batch of documents: ${error}`)
}
}
return batchResults
}
/**
* Helper function to divide an array into chunks of a specified size.
*
* @param array - The array to be divided.
* @param size - The size of each chunk.
*
* @returns An array of chunked arrays.
*/
function chunkArray<T>(array: T[], size: number): T[][] {
const chunked = []
let index = 0
while (index < array.length) {
chunked.push(array.slice(index, size + index))
index += size
}
return chunked
}
| src/lib/addMultipleCollectionItems.ts | elsoul-skeet-firestore-8c637de | [
{
"filename": "src/lib/queryCollectionItems.ts",
"retrieved_chunk": " */\nexport const queryCollectionItems = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n conditions: QueryCondition[]\n): Promise<T[]> => {\n try {\n let query: firestore.Query = db\n .collection(collectionPath)\n .withConverter(createFirestoreDataConverter<T>())",
"score": 0.8042954802513123
},
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": ") => {\n try {\n const collectionRef = createCollectionRef<T>(db, collectionPath)\n if (id) {\n const docRef = collectionRef.doc(id)\n await docRef.set({\n ...params,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n })",
"score": 0.7999973297119141
},
{
"filename": "src/lib/updateCollectionItem.ts",
"retrieved_chunk": " */\nexport const updateCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string,\n params: firestore.UpdateData<T>\n): Promise<boolean> => {\n try {\n const docRef = db\n .collection(collectionPath)",
"score": 0.7861772775650024
},
{
"filename": "src/lib/deleteCollectionItem.ts",
"retrieved_chunk": "): Promise<boolean> => {\n try {\n const docRef = db.collection(collectionPath).doc(docId)\n await docRef.delete()\n return true\n } catch (error) {\n throw new Error(`Error deleting document with ID ${docId}: ${error}`)\n }\n}",
"score": 0.7734431624412537
},
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": " return docRef\n } else {\n const data = await collectionRef.add({\n ...params,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n })\n if (!data) {\n throw new Error('no data')\n }",
"score": 0.7711354494094849
}
] | typescript | collectionRef = createCollectionRef<T>(db, collectionPath)
chunk.forEach((item) => { |
import { firestore } from 'firebase-admin'
import { createFirestoreDataConverter } from './createFirestoreDataConverter'
/**
* Represents a condition for querying Firestore collections.
*/
type QueryCondition = {
field?: string
operator?: firestore.WhereFilterOp
value?: any
orderDirection?: firestore.OrderByDirection // "asc" or "desc"
limit?: number
}
/**
* Queries the specified collection in Firestore based on the provided conditions
* and returns an array of documents that match the conditions.
*
* @param db - The instance of the Firestore database to use.
* @param collectionPath - The path of the collection to be queried.
* @param conditions - An array of conditions to apply to the query.
*
* @returns An array of documents from the collection that match the conditions.
*
* @throws Throws an exception with an error message if an error occurs.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { query } from '@skeet-framework/firestore'
* const db = firestore();
*
* // Simple query to get users over 25 years old
* const simpleConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 }
* ];
*
* // Advanced query to get users over 25 years old, ordered by their names
* const advancedConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 },
* { field: "name", orderDirection: "asc" }
* ];
*
* // Query to get users over 25 years old and limit the results to 5
* const limitedConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 },
* { limit: 5 }
* ];
*
* async function run() {
* try {
* const path = 'Users';
*
* // Using the simple conditions
* const usersByAge = await query<User>(db, path, simpleConditions);
* console.log(`Found ${usersByAge.length} users over 25 years old.`);
*
* // Using the advanced conditions
* const orderedUsers = await query<User>(db, path, advancedConditions);
* console.log(`Found ${orderedUsers.length} users over 25 years old, ordered by name.`);
*
* // Using the limited conditions
* const limitedUsers = await query<User>(db, path, limitedConditions);
* console.log(`Found ${limitedUsers.length} users over 25 years old, limited to 5.`);
*
* } catch (error) {
* console.error(`Error querying collection: ${error}`);
* }
* }
*
* run();
* ```
*/
export const queryCollectionItems = async <T extends firestore.DocumentData>(
db: firestore.Firestore,
collectionPath: string,
conditions: QueryCondition[]
): Promise<T[]> => {
try {
let query: firestore.Query = db
.collection(collectionPath)
| .withConverter(createFirestoreDataConverter<T>())
for (const condition of conditions) { |
if (
condition.field &&
condition.operator &&
condition.value !== undefined
) {
query = query.where(
condition.field,
condition.operator,
condition.value
)
}
if (condition.field && condition.orderDirection) {
query = query.orderBy(condition.field, condition.orderDirection)
}
if (condition.limit !== undefined) {
query = query.limit(condition.limit)
}
}
const snapshot = await query.get()
return snapshot.docs.map((doc) => ({
id: doc.id,
...(doc.data() as T),
}))
} catch (error) {
throw new Error(`Error querying collection: ${error}`)
}
}
| src/lib/queryCollectionItems.ts | elsoul-skeet-firestore-8c637de | [
{
"filename": "src/lib/updateCollectionItem.ts",
"retrieved_chunk": " */\nexport const updateCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string,\n params: firestore.UpdateData<T>\n): Promise<boolean> => {\n try {\n const docRef = db\n .collection(collectionPath)",
"score": 0.9378204941749573
},
{
"filename": "src/lib/addMultipleCollectionItems.ts",
"retrieved_chunk": " */\nexport const addMultipleCollectionItems = async <\n T extends firestore.DocumentData\n>(\n db: firestore.Firestore,\n collectionPath: string,\n items: T[]\n): Promise<firestore.WriteResult[][]> => {\n const MAX_BATCH_SIZE = 500\n const chunkedItems =",
"score": 0.9113553166389465
},
{
"filename": "src/lib/getCollectionItem.ts",
"retrieved_chunk": " * run();\n * ```\n */\nexport const getCollectionItem = async <T>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string\n): Promise<T> => {\n const dataRef = db\n .collection(collectionPath)",
"score": 0.902351975440979
},
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": " * }\n *\n * run();\n * ```\n */\nexport const addCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n params: T,\n id?: string",
"score": 0.8909183740615845
},
{
"filename": "src/lib/queryCollectionItems.d.ts",
"retrieved_chunk": "export declare const queryCollectionItems: <T extends firestore.DocumentData>(db: firestore.Firestore, collectionPath: string, conditions: QueryCondition[]) => Promise<T[]>;\nexport {};",
"score": 0.8648817539215088
}
] | typescript | .withConverter(createFirestoreDataConverter<T>())
for (const condition of conditions) { |
import Express from "express";
import { ErrorCodes } from "../const/errors";
import { sendErrorResponse, sendJSONResponse, isURL } from "../utils";
import dns from "node:dns";
import EmailCache from "../models/EmailCache";
import RateLimiter from "../models/RateLimiter";
const RATE_TIMEOUT = 5000;
const RATE_LIMITER = new RateLimiter(5, RATE_TIMEOUT); // Throttle the requests to prevent overload
function validateEmailSyntax(email: string): boolean {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const maxDomainLength = 255;
const maxLocalPartLength = 64;
const maxEmailLength = maxLocalPartLength + 1 + maxDomainLength;
if (email.length > maxEmailLength) {
return false;
}
const [localPart, domain] = email.split("@");
if (localPart?.length > maxLocalPartLength || domain?.length > maxDomainLength) {
return false;
}
return regex.test(email);
}
function validateEmailDomain(email: string): Promise<boolean> {
if (!validateEmailSyntax(email)) return Promise.resolve(false);
const [mail, tld] = email.split("@");
if (!tld || !isURL(tld)) return Promise.resolve(false);
return new Promise((resolve, reject) => {
dns.resolve(tld, "MX", (err, addresses) => {
if (err) resolve(false);
resolve(addresses?.length > 0)
})
})
}
export default async function (req: Express.Request, res: Express.Response) {
const queryEmail = req.query?.email;
if (RATE_LIMITER.checkIfTimedOut(req)) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.TOO_MANY_REQUESTS,
details: {
retry_after: `${RATE_TIMEOUT} ms`
},
message: "Too many requests. Please try again later",
},
status: 429
});
RATE_LIMITER.resetRequest(req);
return;
}
RATE_LIMITER.logRequest(req);
if (!queryEmail || queryEmail?.length === 0) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.BAD_INPUT,
message: "email is a required argument",
},
status: 400
});
return;
}
| const cachedEmailData = await EmailCache.getEmail(queryEmail as string); |
let emailChecks;
if (cachedEmailData?.length) {
emailChecks = cachedEmailData;
} else {
emailChecks = [
validateEmailSyntax(queryEmail as string),
await validateEmailDomain(queryEmail as string)
]
}
emailChecks = emailChecks as Array<boolean>;
const response = {
data: {
email: queryEmail as string,
valid: emailChecks.every(e => e),
format_valid: emailChecks[0],
domain_valid: emailChecks[1],
},
status: 200
}
if (!cachedEmailData?.length) {
await EmailCache.pushEmail(queryEmail as string, emailChecks as Array<boolean>);
}
sendJSONResponse(res, response)
}
| src/routes/EmailValidate.ts | Aadv1k-ZapMail-fd3be91 | [
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n\t\t\t\treturn;\n\t\t}\n\t\tconst isMailValid = ajv.validate(mailSchema, body);\n\t\tif (!isMailValid) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.BAD_INPUT,",
"score": 0.8392339944839478
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\t\t\tmessage: \"Bad input\",\n\t\t\t\t\t\t\t\tdetails: ajv.errors,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n\t\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\t\tconst receivedMailId = await sendMail(body);\n\t\t\t\tsendJSONResponse(res, {",
"score": 0.8330064415931702
},
{
"filename": "src/server.ts",
"retrieved_chunk": "app.use((err: any, req: any, res: any, next: any) => {\n if (err instanceof SyntaxError) \n\t\t\t\tsendErrorResponse(res as express.Response, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.BAD_INPUT,\n\t\t\t\t\t\t\t\tmessage: \"Bad JSON input\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n return;",
"score": 0.8298938870429993
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\tRATE_LIMITER.logRequest(req);\n\t\tlet body: Mail;\n\t\ttry {\n\t\t\t\tbody = req.body;\n\t\t} catch (err) {\n\t\t\t\tconsole.log(\"DEBUG LOG >>>>> \", err)\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.BAD_INPUT,\n\t\t\t\t\t\t\t\tmessage: \"Invalid JSON data\",",
"score": 0.829392671585083
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tmessageId: receivedMailId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 200,\n\t\t\t\t}, 200)\n\t\t} catch (error) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.INTERNAL_ERROR,\n\t\t\t\t\t\t\t\tmessage: \"Internall error while sending mail\",",
"score": 0.8290349841117859
}
] | typescript | const cachedEmailData = await EmailCache.getEmail(queryEmail as string); |
import {
loadPyodide,
PyodideInterface,
PyProxy,
PyProxyAwaitable,
PyProxyCallable,
PyProxyDict,
} from 'pyodide';
import consoleScript from '../assets/console.py';
/**
* @see https://pyodide.org/en/stable/usage/api/python-api/console.html#pyodide.console.ConsoleFuture.syntax_check
*/
type SyntaxCheck = 'syntax-error' | 'incomplete' | 'complete';
interface Message<T extends Record<string, unknown>> {
type: keyof T;
payload: any;
}
interface RunExportableData {
code: string;
exports?: { name: string; content: string }[];
}
let pyodide: PyodideInterface;
let interruptBuffer: Uint8Array | null;
let await_fut: PyProxyCallable;
let repr_shorten: PyProxyCallable;
let pyconsole: PyProxy;
let clear_console: PyProxyCallable;
let create_console: PyProxyCallable;
const PS1 = '\u001b[32;1m>>> \u001b[0m' as const;
const PS2 = '\u001b[32m... \u001b[0m' as const;
const RUN_CODE = '\u001b[3m\u001b[32m<run code>\u001b[0m' as const;
const post = {
write: (text: string) => postMessage({ type: 'write', payload: text }),
writeln: (line: string) => postMessage({ type: 'writeln', payload: line }),
error: (message: string) => postMessage({ type: 'error', payload: message }),
system: (message: string) =>
postMessage({ type: 'system', payload: message }),
lock: () => postMessage({ type: 'lock' }),
unlock: () => postMessage({ type: 'unlock' }),
prompt: (newLine = true) => post.write(`${newLine ? '\n' : ''}${PS1}`),
promptPending: () => post.write(PS2),
};
const setUpConsole = (globals?: PyProxyDict) => {
pyconsole?.destroy();
pyconsole = create_console(globals);
};
const setUpREPLEnvironment = () => {
const globals = pyodide.globals.get('dict')();
pyodide. | runPython(consoleScript, { globals }); |
repr_shorten = globals.get('repr_shorten');
await_fut = globals.get('await_fut');
create_console = globals.get('create_console');
clear_console = globals.get('clear_console');
setUpConsole();
return globals.get('BANNER') as string;
};
const preparePyodide = async () => {
const newPyodide = await loadPyodide();
newPyodide.setStdout({ batched: post.writeln });
newPyodide.setStderr({ batched: post.error });
pyodide = newPyodide;
if (interruptBuffer) pyodide.setInterruptBuffer(interruptBuffer);
/**
* Replaces Pyodide's `js` import with a stub `object`. This must also be
* paired with some `del sys.modules['js']` in Pyodide's initialisation.
*/
pyodide.registerJsModule('js', {});
const banner = setUpREPLEnvironment();
post.writeln(banner);
post.prompt(false);
post.unlock();
return newPyodide;
};
const prepareExports = (exports?: { name: string; content: string }[]) => {
let newExports = new Set<string>();
exports?.forEach(({ name, content }) => {
pyodide.FS.writeFile(name, content, { encoding: 'utf-8' });
newExports.add(name);
});
const oldExports = pyodide.FS.readdir('.') as string[];
oldExports.forEach((name) => {
if (name === '.' || name === '..' || newExports.has(name)) return;
pyodide.FS.unlink(name);
});
};
/**
* Pyodide may sometimes not catch `RecursionError`s and excessively
* recursive code spills as JavaScript `RangeError`, causing Pyodide to
* fatally crash. We need to restart Pyodide in this case.
* @see https://github.com/pyodide/pyodide/issues/951
*/
const handleRangeErrorAndRestartPyodide = async (error: unknown) => {
if (!(error instanceof RangeError)) return;
post.system(
'\nOops, something happened and we have to restart the interpreter. ' +
"Don't worry, it's not your fault. " +
'You may continue once you see the prompt again.\n',
);
await preparePyodide();
};
const listeners = {
initialize: async (newInterruptBuffer?: Uint8Array) => {
pyodide ??= await preparePyodide();
if (!newInterruptBuffer) return;
pyodide.setInterruptBuffer(newInterruptBuffer);
interruptBuffer = newInterruptBuffer;
},
run: async ({ code, exports }: RunExportableData) => {
pyodide ??= await preparePyodide();
post.writeln(RUN_CODE);
try {
post.lock();
prepareExports(exports);
await pyodide.loadPackagesFromImports(code);
const globals = pyodide.globals.get('dict')();
/**
* `await pyodide.runPythonAsync(code)` is not used because it raises
* an uncatchable `PythonError` when Pyodide emits a `KeyboardInterrupt`.
* @see https://github.com/pyodide/pyodide/issues/2141
*/
const result = pyodide.runPython(code, { globals });
setUpConsole(globals);
post.writeln(result?.toString());
} catch (error) {
if (!(error instanceof Error)) throw error;
post.error(error.message);
handleRangeErrorAndRestartPyodide(error);
} finally {
post.prompt();
post.unlock();
}
},
replClear: async () => {
try {
clear_console(pyconsole);
await await_fut(pyconsole.push(''));
} finally {
post.error('\nKeyboardInterrupt');
post.prompt();
}
},
replInput: async ({ code, exports }: RunExportableData) => {
post.writeln(code);
const future = pyconsole.push(code) as PyProxy;
const status = future.syntax_check as SyntaxCheck;
switch (status) {
case 'syntax-error':
post.error(future.formatted_error.trimEnd());
post.prompt();
return;
case 'incomplete':
post.promptPending();
return;
case 'complete':
break;
default:
throw new Error(`Unexpected type: ${status}`);
}
prepareExports(exports);
const wrapped = await_fut(future) as PyProxyAwaitable;
try {
const [value] = await wrapped;
if (value !== undefined) {
const repr = repr_shorten.callKwargs(value, {
separator: '\n<long output truncated>\n',
}) as string;
post.writeln(repr);
}
if (pyodide.isPyProxy(value)) value.destroy();
} catch (error) {
if (!(error instanceof Error)) throw error;
const message = future.formatted_error || error.message;
post.error(message.trimEnd());
handleRangeErrorAndRestartPyodide(error);
} finally {
post.prompt();
future.destroy();
wrapped.destroy();
}
},
};
onmessage = async (event: MessageEvent<Message<typeof listeners>>) => {
listeners[event.data.type]?.(event.data.payload);
};
| src/workers/interpreter.worker.ts | NUSSOC-glide-3ab6925 | [
{
"filename": "src/pages/IDEPage.tsx",
"retrieved_chunk": " const interpreter = useInterpreter({\n write: (text: string) => consoleRef.current?.write(text),\n writeln: (text: string) => consoleRef.current?.append(text),\n error: (text: string) => consoleRef.current?.error(text),\n system: (text: string) => consoleRef.current?.system(text),\n exports: useFile.Exports,\n lock: () => setRunning(true),\n unlock: () => setRunning(false),\n });\n return (",
"score": 0.7017765045166016
},
{
"filename": "src/hooks/useInterpreter.ts",
"retrieved_chunk": " resetInterruptBuffer();\n workerRef.current?.postMessage({\n type: 'replInput',\n payload: { code, exports: callbacks.exports?.() },\n });\n },\n restart: () => {\n callbacks.system('\\nOkies! Restarting interpreter...\\n');\n restartInterpreter();\n },",
"score": 0.6902092695236206
},
{
"filename": "src/hooks/useInterpreter.ts",
"retrieved_chunk": "const useInterpreter = (callbacks: Callbacks): Interpreter => {\n const workerRef = useRef<Worker>();\n const interruptBufferRef = useRef<Uint8Array>();\n const setUpInterpreterWorker = () => {\n const worker = new Worker(\n new URL('../workers/interpreter.worker.ts', import.meta.url),\n );\n worker.onmessage = (event: MessageEvent<Message<Callbacks>>) => {\n callbacks[event.data.type]?.(event.data.payload);\n };",
"score": 0.672500491142273
},
{
"filename": "src/components/Terminal.tsx",
"retrieved_chunk": " }\n xterm.onKey(({ key }) => {\n if (!(isASCIIPrintable(key) || key >= '\\u00a0')) return;\n promptRef.current?.focusWith(key);\n });\n xterm.open(terminal);\n fitAddon.fit();\n xtermRef.current = xterm;\n fitAddonRef.current = fitAddon;\n return () => xterm.dispose();",
"score": 0.6598338484764099
},
{
"filename": "src/hooks/useInterpreter.ts",
"retrieved_chunk": " setUpInterpreterWorker();\n }, []);\n const resetInterruptBuffer = () => {\n if (!interruptBufferRef.current) return;\n interruptBufferRef.current[0] = 0;\n };\n const restartInterpreter = () => {\n workerRef.current?.terminate();\n setUpInterpreterWorker();\n };",
"score": 0.6589388847351074
}
] | typescript | runPython(consoleScript, { globals }); |
import Express from "express";
import { ErrorCodes } from "../const/errors";
import { sendErrorResponse, sendJSONResponse, isURL } from "../utils";
import dns from "node:dns";
import EmailCache from "../models/EmailCache";
import RateLimiter from "../models/RateLimiter";
const RATE_TIMEOUT = 5000;
const RATE_LIMITER = new RateLimiter(5, RATE_TIMEOUT); // Throttle the requests to prevent overload
function validateEmailSyntax(email: string): boolean {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const maxDomainLength = 255;
const maxLocalPartLength = 64;
const maxEmailLength = maxLocalPartLength + 1 + maxDomainLength;
if (email.length > maxEmailLength) {
return false;
}
const [localPart, domain] = email.split("@");
if (localPart?.length > maxLocalPartLength || domain?.length > maxDomainLength) {
return false;
}
return regex.test(email);
}
function validateEmailDomain(email: string): Promise<boolean> {
if (!validateEmailSyntax(email)) return Promise.resolve(false);
const [mail, tld] = email.split("@");
if (!tld || !isURL(tld)) return Promise.resolve(false);
return new Promise((resolve, reject) => {
dns.resolve(tld, "MX", (err, addresses) => {
if (err) resolve(false);
resolve(addresses?.length > 0)
})
})
}
export default async function (req: Express.Request, res: Express.Response) {
const queryEmail = req.query?.email;
if (RATE_LIMITER.checkIfTimedOut(req)) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.TOO_MANY_REQUESTS,
details: {
retry_after: `${RATE_TIMEOUT} ms`
},
message: "Too many requests. Please try again later",
},
status: 429
});
RATE_LIMITER.resetRequest(req);
return;
}
RATE_LIMITER.logRequest(req);
if (!queryEmail || queryEmail?.length === 0) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.BAD_INPUT,
message: "email is a required argument",
},
status: 400
});
return;
}
const | cachedEmailData = await EmailCache.getEmail(queryEmail as string); |
let emailChecks;
if (cachedEmailData?.length) {
emailChecks = cachedEmailData;
} else {
emailChecks = [
validateEmailSyntax(queryEmail as string),
await validateEmailDomain(queryEmail as string)
]
}
emailChecks = emailChecks as Array<boolean>;
const response = {
data: {
email: queryEmail as string,
valid: emailChecks.every(e => e),
format_valid: emailChecks[0],
domain_valid: emailChecks[1],
},
status: 200
}
if (!cachedEmailData?.length) {
await EmailCache.pushEmail(queryEmail as string, emailChecks as Array<boolean>);
}
sendJSONResponse(res, response)
}
| src/routes/EmailValidate.ts | Aadv1k-ZapMail-fd3be91 | [
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\t\t\tmessage: \"Bad input\",\n\t\t\t\t\t\t\t\tdetails: ajv.errors,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n\t\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\t\tconst receivedMailId = await sendMail(body);\n\t\t\t\tsendJSONResponse(res, {",
"score": 0.8107436895370483
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n\t\t\t\treturn;\n\t\t}\n\t\tconst isMailValid = ajv.validate(mailSchema, body);\n\t\tif (!isMailValid) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.BAD_INPUT,",
"score": 0.8065133094787598
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\tmessageId: receivedMailId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 200,\n\t\t\t\t}, 200)\n\t\t} catch (error) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.INTERNAL_ERROR,\n\t\t\t\t\t\t\t\tmessage: \"Internall error while sending mail\",",
"score": 0.8014912605285645
},
{
"filename": "src/routes/EmailSend.ts",
"retrieved_chunk": "\t\t\t\t\t\t\t\tdetails: {\n\t\t\t\t\t\t\t\t\t\tretry_after: `${RATE_TIMEOUT} ms`\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tmessage: \"Too many requests. Please try again later\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 429\n\t\t\t\t});\n\t\t\t\tRATE_LIMITER.resetRequest(req);\n\t\t\t\treturn;\n\t\t}",
"score": 0.7917400598526001
},
{
"filename": "src/const/errors.ts",
"retrieved_chunk": "\t\terror: {\n\t\t\t\tcode: ErrorCodes,\n\t\t\t\tmessage: string,\n\t\t\t\tdetails?: any,\n\t\t}\n\t\tstatus: number,\n}",
"score": 0.7839353680610657
}
] | typescript | cachedEmailData = await EmailCache.getEmail(queryEmail as string); |
import Express from "express";
import { ErrorCodes } from "../const/errors";
import { sendErrorResponse, sendJSONResponse, isURL } from "../utils";
import { MAIL_CONFIG } from "../const/vars";
import nodemailer from "nodemailer"
;
import mailSchema from "../const/mailSchema";
import { Mail } from "../const/email";
import RateLimiter from "../models/RateLimiter";
const RATE_TIMEOUT = 20_000;
const RATE_LIMITER = new RateLimiter(1, RATE_TIMEOUT); // Throttle the requests to prevent overload
import Ajv from "ajv";
const ajv = new Ajv({ allErrors: true });
ajv.addFormat('email', {
type: 'string',
validate: (value: string) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(value);
},
});
const transporter = nodemailer.createTransport({
maxConnections: 2,
pool: true,
service: "hotmail",
auth: {
user: MAIL_CONFIG.address,
pass: MAIL_CONFIG.password
}
});
function sendMail(blob: Mail): Promise<string> {
const toEmails = blob.to.map(e => e.email);
const fromEmail = blob.from;
const body = `Forwarded via Zap<https://github.com/aadv1k/zap> originally by ${fromEmail}\n` + blob.body.content;
return new Promise((resolve, reject) => {
transporter.sendMail({
from: MAIL_CONFIG.address,
to: toEmails,
subject: blob.subject,
html: body
}, (error: any, info: any) => {
if (error) reject(error);
resolve(info.messageId);
})
})
}
export default async function (req: Express.Request, res: Express.Response) {
if (RATE_LIMITER.checkIfTimedOut(req)) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.TOO_MANY_REQUESTS,
details: {
retry_after: `${RATE_TIMEOUT} ms`
},
message: "Too many requests. Please try again later",
},
status: 429
});
RATE_LIMITER.resetRequest(req);
return;
}
RATE_LIMITER.logRequest(req);
let body: Mail;
try {
body = req.body;
} catch (err) {
console.log("DEBUG LOG >>>>> ", err)
sendErrorResponse(res, {
error: {
code: ErrorCodes.BAD_INPUT,
message: "Invalid JSON data",
},
status: 400
})
return;
}
| const isMailValid = ajv.validate(mailSchema, body); |
if (!isMailValid) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.BAD_INPUT,
message: "Bad input",
details: ajv.errors,
},
status: 400
})
return;
}
try {
const receivedMailId = await sendMail(body);
sendJSONResponse(res, {
data: {
messageId: receivedMailId,
},
status: 200,
}, 200)
} catch (error) {
sendErrorResponse(res, {
error: {
code: ErrorCodes.INTERNAL_ERROR,
message: "Internall error while sending mail",
details: error,
},
status: 500
})
}
}
| src/routes/EmailSend.ts | Aadv1k-ZapMail-fd3be91 | [
{
"filename": "src/routes/EmailValidate.ts",
"retrieved_chunk": "\t\tif (!queryEmail || queryEmail?.length === 0) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.BAD_INPUT,\n\t\t\t\t\t\t\t\tmessage: \"email is a required argument\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t}",
"score": 0.8519343733787537
},
{
"filename": "src/server.ts",
"retrieved_chunk": "app.use((err: any, req: any, res: any, next: any) => {\n if (err instanceof SyntaxError) \n\t\t\t\tsendErrorResponse(res as express.Response, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.BAD_INPUT,\n\t\t\t\t\t\t\t\tmessage: \"Bad JSON input\"\n\t\t\t\t\t\t},\n\t\t\t\t\t\tstatus: 400\n\t\t\t\t})\n return;",
"score": 0.8301244974136353
},
{
"filename": "src/routes/EmailValidate.ts",
"retrieved_chunk": "\t\t\t\t})\n })\n}\nexport default async function (req: Express.Request, res: Express.Response) {\n\t\tconst queryEmail = req.query?.email;\n\t\tif (RATE_LIMITER.checkIfTimedOut(req)) {\n\t\t\t\tsendErrorResponse(res, {\n\t\t\t\t\t\terror: {\n\t\t\t\t\t\t\t\tcode: ErrorCodes.TOO_MANY_REQUESTS,\n\t\t\t\t\t\t\t\tdetails: {",
"score": 0.7749378681182861
},
{
"filename": "src/routes/EmailValidate.ts",
"retrieved_chunk": "\t\temailChecks = emailChecks as Array<boolean>;\n\t\tconst response = {\n\t\t\t\tdata: {\n\t\t\t\t\t\temail: queryEmail as string,\n\t\t\t\t\t\tvalid: emailChecks.every(e => e),\n\t\t\t\t\t\tformat_valid: emailChecks[0],\n\t\t\t\t\t\tdomain_valid: emailChecks[1],\n\t\t\t\t},\n\t\t\t\tstatus: 200\n\t\t}",
"score": 0.7694920301437378
},
{
"filename": "src/const/errors.ts",
"retrieved_chunk": "\t\terror: {\n\t\t\t\tcode: ErrorCodes,\n\t\t\t\tmessage: string,\n\t\t\t\tdetails?: any,\n\t\t}\n\t\tstatus: number,\n}",
"score": 0.7197259664535522
}
] | typescript | const isMailValid = ajv.validate(mailSchema, body); |
import { Request, response, Response } from "express"
import Product from "../models/product"
import { IProduct } from "../types"
type CreateProductRequestType = Pick<
IProduct,
"image" | "name" | "description" | "price"
>
export const createProduct = async (request: Request, response: Response) => {
try {
const { image, name, price, description }: CreateProductRequestType =
request.body
const product = await Product.create({
image,
name,
price,
description,
})
response.send(product)
} catch (error) {
console.log("error in createProduct", error)
response.send({
message: "Something went wrong while creating product",
})
throw error
}
}
export const getProducts = async (request: Request, response: Response) => {
try {
const products = await Product.find({})
response.send(products)
} catch (error) {
console.log("error in getProducts", error)
response.send({ message: "Something went wrong in get products" })
throw error
}
}
export const getProductById = async (request: Request, response: Response) => {
try {
const { id } = request.params
| const product = await Product.findById(id)
response.send(product)
} catch (error) { |
console.log("error in getProductById", error)
response.send({
message: "Something went wrong while fetching the product",
})
throw error
}
}
| src/controller/product.ts | omkhetwal-komorebi-backend-production-8f46fde | [
{
"filename": "src/controller/order.ts",
"retrieved_chunk": " * @param request\n * @param response\n *\n * 1. To make a request to stripe, it's gonna return paymentIntent,we've to pass currency and order amount\n * 2. Save paymentIntentId in order model\n * 3. Return paymentIntentId.client_secret\n *\n */\nexport const createOrder = async (request: Request, response: Response) => {\n try {",
"score": 0.8303183317184448
},
{
"filename": "src/controller/order.ts",
"retrieved_chunk": " console.log(\"error in createOrder\", error)\n response.send({\n message: \"Something went wrong in create order\",\n })\n throw error\n }\n}",
"score": 0.8040804862976074
},
{
"filename": "src/db.ts",
"retrieved_chunk": "import mongoose from \"mongoose\"\nconst connectToDatabase = async () => {\n try {\n const connection = await mongoose.connect(process.env.MONGO_URI)\n console.log(\"Connection established\")\n } catch (error) {\n console.log(\"error in connectToDatabase\", error)\n throw error\n }\n}",
"score": 0.8035180568695068
},
{
"filename": "src/webhook/index.ts",
"retrieved_chunk": " order.paymentStatus = \"failed\"\n order.paymentDetails = charge\n await order.save()\n }\n }\n response.send({ received: true })\n } catch (error) {\n console.log(\"error in webhookHandler\", error)\n throw error\n }",
"score": 0.800689160823822
},
{
"filename": "src/models/product.ts",
"retrieved_chunk": "import mongoose, { Schema } from \"mongoose\"\nimport { IProduct } from \"../types\"\nconst productSchema = new Schema<IProduct>(\n {\n name: {\n type: String,\n required: true,\n },\n image: {\n type: String,",
"score": 0.7975861430168152
}
] | typescript | const product = await Product.findById(id)
response.send(product)
} catch (error) { |
import EventEmitter from 'events'
import { ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
export type Data = {
model?: ModelID
provider?: WindowAiProvider
}
type EventMap = {
change: Data
disconnect: undefined
error: Error
}
type EventKey<T extends EventMap> = string & keyof T
type EventReceiver<T> = (params: T) => void
interface IEmitter<T extends EventMap> {
on<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void
off<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void
emit<K extends EventKey<T>>(
eventName: K,
...params: T[K] extends undefined ? [undefined?] : [T[K]]
): void
}
export abstract class Emitter implements IEmitter<EventMap> {
private emitter = new EventEmitter()
on<K extends EventKey<EventMap>>(
eventName: K,
fn: EventReceiver<EventMap[K]>,
): void {
this.emitter.on(eventName, fn)
}
off<K extends EventKey<EventMap>>(
eventName: K,
fn: EventReceiver<EventMap[K]>,
): void {
this.emitter.off(eventName, fn)
}
emit<K extends EventKey<EventMap>>(
eventName: K,
...params: EventMap[K] extends undefined ? [undefined?] : [EventMap[K]]
): void {
this.emitter.emit(eventName, ...params)
}
}
export abstract class Connector extends Emitter {
abstract name: string
abstract activate(): Promise<Data>
abstract deactivate(): void
abstract getModel(): Promise<ModelID>
| abstract getProvider(): Promise<WindowAiProvider>
} | src/connectors/types.ts | haardikk21-wanda-788b8e1 | [
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": "import { ErrorCode, EventType, ModelID } from '../types'\nimport { WindowAiProvider } from '../types/declarations'\nimport { Connector, Data } from './types'\nexport class InjectedConnector extends Connector {\n name = 'injected'\n constructor() {\n super()\n this.handleEvent = this.handleEvent.bind(this)\n }\n async activate(): Promise<Data> {",
"score": 0.837651252746582
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " throw Error('model not found')\n }\n }\n async getProvider(): Promise<WindowAiProvider> {\n if (!window.ai) throw Error(`window.ai not found`)\n return window.ai\n }\n private handleEvent(event: EventType, data: unknown) {\n if (event === EventType.ModelChanged) {\n this.emit('change', { model: (<{ model: ModelID }>data).model })",
"score": 0.7947651147842407
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 0.7886040210723877
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": "import { useCallback, useState } from 'react'\nimport { useContext } from './useContext'\nimport { Connector } from '../connectors'\ntype UseConnectState = {\n connecting: boolean\n error?: Error\n}\nexport const useConnect = () => {\n const [globalState, setGlobalState] = useContext()\n const [state, setState] = useState<UseConnectState>({ connecting: false })",
"score": 0.7882938981056213
},
{
"filename": "src/context.ts",
"retrieved_chunk": "import React from 'react'\nimport { Connector, Data, InjectedConnector } from './connectors'\ntype State = {\n connector?: Connector\n data?: Data\n error?: Error\n}\ntype ContextValue = [\n {\n connectors: Connector[]",
"score": 0.7863484025001526
}
] | typescript | abstract getProvider(): Promise<WindowAiProvider>
} |
|
import { persistor } from '../store';
import { filesActions } from '../store/filesSlice';
import { useAppDispatch } from '../store/hooks';
import { vaultActions } from '../store/vaultSlice';
interface UseFilesMutationsHook {
/**
* For performance reasons, the caller should ensure that the new
* name is not already in use in *both* the files and vault stores.
*/
rename: (from: string, to: string) => void;
save: (name: string, content: string) => void;
destroy: (name: string) => void;
draft: (autoSelect?: boolean) => void;
select: (name: string) => void;
update: (content: string) => void;
create: (name: string, content: string) => void;
}
const useFilesMutations = (): UseFilesMutationsHook => {
const dispatch = useAppDispatch();
return {
save: (name: string, content: string) => {
dispatch(filesActions.updateSelected(content));
dispatch(vaultActions.save({ name, content }));
persistor.flush();
},
rename: (from: string, to: string) => {
if (from === to) return;
dispatch(filesActions.rename({ from, to }));
dispatch(vaultActions.rename({ from, to }));
persistor.flush();
},
destroy: (name: string) => {
dispatch(filesActions.destroy(name));
dispatch(vaultActions.destroy(name));
persistor.flush();
},
draft: (autoSelect?: boolean) => {
dispatch(filesActions.draft(autoSelect));
},
select: (name: string) => {
dispatch(filesActions.select(name));
},
update: (content: string) => {
dispatch(filesActions.updateSelected(content));
},
create: (name: string, content: string) => {
| dispatch(filesActions.create({ name, content })); |
dispatch(vaultActions.save({ name, content }));
persistor.flush();
},
};
};
export default useFilesMutations;
| src/hooks/useFilesMutations.ts | NUSSOC-glide-3ab6925 | [
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": "});\nconst selectFiles = (state: RootState) => state.files;\nexport const getSelectedFileName = createSelector(\n selectFiles,\n (files) => files.selected,\n);\nexport const getSelectedFile = createSelector(selectFiles, (files) =>\n files.selected\n ? { name: files.selected, content: files.files[files.selected] }\n : { name: undefined, content: undefined },",
"score": 0.8499890565872192
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " state.selected = newName;\n },\n updateSelected: (state, action: PayloadAction<string>) => {\n if (state.selected === undefined) return;\n state.files[state.selected] = action.payload;\n },\n destroy: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n delete state.files[name];\n state.list = state.list.filter((file) => file !== name);",
"score": 0.8379067182540894
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " if (state.selected === name) state.selected = undefined;\n },\n select: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n if (state.files[name] === undefined) return;\n state.selected = name;\n },\n rename: (state, action: PayloadAction<{ from: string; to: string }>) => {\n const { from: oldName, to: newName } = action.payload;\n const isOldNameExist = state.files[oldName] !== undefined;",
"score": 0.8315649628639221
},
{
"filename": "src/store/filesSlice.ts",
"retrieved_chunk": " rehydrate: (\n state,\n action: PayloadAction<Pick<FilesState, 'files' | 'list'>>,\n ) => {\n state.files = action.payload.files;\n state.list = action.payload.list;\n },\n draft: (state, action: PayloadAction<boolean | undefined>) => {\n const name = findSuitableName(\n 'untitled.py',",
"score": 0.8216969966888428
},
{
"filename": "src/store/vaultSlice.ts",
"retrieved_chunk": " const { name, content } = action.payload;\n if (state.files[name] === undefined) state.list.push(name);\n state.files[name] = content;\n },\n destroy: (state, action: PayloadAction<string>) => {\n const name = action.payload;\n delete state.files[name];\n state.list = state.list.filter((file) => file !== name);\n },\n rename: (state, action: PayloadAction<{ from: string; to: string }>) => {",
"score": 0.8038755655288696
}
] | typescript | dispatch(filesActions.create({ name, content })); |
import { ErrorCode, EventType, ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
import { Connector, Data } from './types'
export class InjectedConnector extends Connector {
name = 'injected'
constructor() {
super()
this.handleEvent = this.handleEvent.bind(this)
}
async activate(): Promise<Data> {
if (!window.ai) throw Error(`window.ai not found`)
if (window.ai.addEventListener) {
window.ai.addEventListener(this.handleEvent)
}
try {
const model = await window.ai.getCurrentModel()
return { model, provider: window.ai }
} catch (error) {
throw Error(`activate failed`)
}
}
deactivate(): void {
// no-op
// Disconnect event listeners here once window.ai upstream has removeEventListener
}
async getModel(): Promise<ModelID> {
if (!window.ai) throw Error(`window.ai not found`)
try {
return await window.ai.getCurrentModel()
} catch {
throw Error('model not found')
}
}
async getProvider(): Promise<WindowAiProvider> {
if (!window.ai) throw Error(`window.ai not found`)
return window.ai
}
private handleEvent(event: EventType, data: unknown) {
if (event === EventType.ModelChanged) {
this.emit('change', { model: (<{ model: ModelID }>data).model })
} else if (event === EventType.Error) {
this. | emit('error', Error(data as ErrorCode))
} |
}
}
| src/connectors/injected.ts | haardikk21-wanda-788b8e1 | [
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " const connect = useCallback(\n async (connector: Connector) => {\n try {\n if (connector === globalState.connector) return\n setGlobalState((state) => ({ ...state, connector }))\n setState((state) => ({ ...state, connecting: true, error: undefined }))\n const data = await connector.activate()\n setGlobalState((state) => ({ ...state, data }))\n } catch (error) {\n console.error(error)",
"score": 0.7917876839637756
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " setState((state) => ({ ...state, error: error as Error }))\n } finally {\n setState((state) => ({ ...state, connecting: false }))\n }\n },\n [globalState.connector, setGlobalState],\n )\n return [\n {\n connecting: state.connecting,",
"score": 0.7803635597229004
},
{
"filename": "src/context.ts",
"retrieved_chunk": " children,\n connectors = [new InjectedConnector()],\n}) => {\n const [state, setState] = React.useState<State>({})\n React.useEffect(() => {\n if (!state.connector) return\n const handleChange = (data: Data) => {\n setState((state) => ({ ...state, data }))\n }\n state.connector.on('change', handleChange)",
"score": 0.772323727607727
},
{
"filename": "src/context.ts",
"retrieved_chunk": " return () => {\n if (!state.connector) return\n state.connector.off('change', handleChange)\n }\n }, [state.connector])\n // Close connectors when unmounting\n React.useEffect(() => {\n return () => {\n if (!state.connector) return\n state.connector.deactivate()",
"score": 0.7585107684135437
},
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": "import EventEmitter from 'events'\nimport { ModelID } from '../types'\nimport { WindowAiProvider } from '../types/declarations'\nexport type Data = {\n model?: ModelID\n provider?: WindowAiProvider\n}\ntype EventMap = {\n change: Data\n disconnect: undefined",
"score": 0.7440185546875
}
] | typescript | emit('error', Error(data as ErrorCode))
} |
import { ErrorCode, EventType, ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
import { Connector, Data } from './types'
export class InjectedConnector extends Connector {
name = 'injected'
constructor() {
super()
this.handleEvent = this.handleEvent.bind(this)
}
async activate(): Promise<Data> {
if (!window.ai) throw Error(`window.ai not found`)
if (window.ai.addEventListener) {
window.ai.addEventListener(this.handleEvent)
}
try {
const model = await window.ai.getCurrentModel()
return { model, provider: window.ai }
} catch (error) {
throw Error(`activate failed`)
}
}
deactivate(): void {
// no-op
// Disconnect event listeners here once window.ai upstream has removeEventListener
}
async getModel(): Promise<ModelID> {
if (!window.ai) throw Error(`window.ai not found`)
try {
return await window.ai.getCurrentModel()
} catch {
throw Error('model not found')
}
}
| async getProvider(): Promise<WindowAiProvider> { |
if (!window.ai) throw Error(`window.ai not found`)
return window.ai
}
private handleEvent(event: EventType, data: unknown) {
if (event === EventType.ModelChanged) {
this.emit('change', { model: (<{ model: ModelID }>data).model })
} else if (event === EventType.Error) {
this.emit('error', Error(data as ErrorCode))
}
}
}
| src/connectors/injected.ts | haardikk21-wanda-788b8e1 | [
{
"filename": "src/hooks/useCompletion.ts",
"retrieved_chunk": "import { useContext } from './useContext'\nimport { CompletionOptions, Input } from '../types'\nexport const useCompletion = () => {\n const [state] = useContext()\n const getCompletion = async <T extends Input>(\n input: T,\n options?: CompletionOptions<T>,\n ) => {\n const provider = await state.connector?.getProvider()\n if (!provider) {",
"score": 0.7772402167320251
},
{
"filename": "src/hooks/useContext.ts",
"retrieved_chunk": "import React from 'react'\nimport { Context } from '../context'\nexport const useContext = () => {\n const context = React.useContext(Context)\n if (!context) throw Error(`useContext must be used within a Provider`)\n return context\n}",
"score": 0.7714787721633911
},
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": " this.emitter.emit(eventName, ...params)\n }\n}\nexport abstract class Connector extends Emitter {\n abstract name: string\n abstract activate(): Promise<Data>\n abstract deactivate(): void\n abstract getModel(): Promise<ModelID>\n abstract getProvider(): Promise<WindowAiProvider>\n}",
"score": 0.7713301777839661
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " const connect = useCallback(\n async (connector: Connector) => {\n try {\n if (connector === globalState.connector) return\n setGlobalState((state) => ({ ...state, connector }))\n setState((state) => ({ ...state, connecting: true, error: undefined }))\n const data = await connector.activate()\n setGlobalState((state) => ({ ...state, data }))\n } catch (error) {\n console.error(error)",
"score": 0.7677624225616455
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " setState((state) => ({ ...state, error: error as Error }))\n } finally {\n setState((state) => ({ ...state, connecting: false }))\n }\n },\n [globalState.connector, setGlobalState],\n )\n return [\n {\n connecting: state.connecting,",
"score": 0.7555729746818542
}
] | typescript | async getProvider(): Promise<WindowAiProvider> { |
import EventEmitter from 'events'
import { ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
export type Data = {
model?: ModelID
provider?: WindowAiProvider
}
type EventMap = {
change: Data
disconnect: undefined
error: Error
}
type EventKey<T extends EventMap> = string & keyof T
type EventReceiver<T> = (params: T) => void
interface IEmitter<T extends EventMap> {
on<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void
off<K extends EventKey<T>>(eventName: K, fn: EventReceiver<T[K]>): void
emit<K extends EventKey<T>>(
eventName: K,
...params: T[K] extends undefined ? [undefined?] : [T[K]]
): void
}
export abstract class Emitter implements IEmitter<EventMap> {
private emitter = new EventEmitter()
on<K extends EventKey<EventMap>>(
eventName: K,
fn: EventReceiver<EventMap[K]>,
): void {
this.emitter.on(eventName, fn)
}
off<K extends EventKey<EventMap>>(
eventName: K,
fn: EventReceiver<EventMap[K]>,
): void {
this.emitter.off(eventName, fn)
}
emit<K extends EventKey<EventMap>>(
eventName: K,
...params: EventMap[K] extends undefined ? [undefined?] : [EventMap[K]]
): void {
this.emitter.emit(eventName, ...params)
}
}
export abstract class Connector extends Emitter {
abstract name: string
abstract activate(): Promise<Data>
abstract deactivate(): void
| abstract getModel(): Promise<ModelID>
abstract getProvider(): Promise<WindowAiProvider>
} | src/connectors/types.ts | haardikk21-wanda-788b8e1 | [
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": "import { ErrorCode, EventType, ModelID } from '../types'\nimport { WindowAiProvider } from '../types/declarations'\nimport { Connector, Data } from './types'\nexport class InjectedConnector extends Connector {\n name = 'injected'\n constructor() {\n super()\n this.handleEvent = this.handleEvent.bind(this)\n }\n async activate(): Promise<Data> {",
"score": 0.837651252746582
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " throw Error('model not found')\n }\n }\n async getProvider(): Promise<WindowAiProvider> {\n if (!window.ai) throw Error(`window.ai not found`)\n return window.ai\n }\n private handleEvent(event: EventType, data: unknown) {\n if (event === EventType.ModelChanged) {\n this.emit('change', { model: (<{ model: ModelID }>data).model })",
"score": 0.7947651147842407
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 0.7886040210723877
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": "import { useCallback, useState } from 'react'\nimport { useContext } from './useContext'\nimport { Connector } from '../connectors'\ntype UseConnectState = {\n connecting: boolean\n error?: Error\n}\nexport const useConnect = () => {\n const [globalState, setGlobalState] = useContext()\n const [state, setState] = useState<UseConnectState>({ connecting: false })",
"score": 0.7882938981056213
},
{
"filename": "src/context.ts",
"retrieved_chunk": "import React from 'react'\nimport { Connector, Data, InjectedConnector } from './connectors'\ntype State = {\n connector?: Connector\n data?: Data\n error?: Error\n}\ntype ContextValue = [\n {\n connectors: Connector[]",
"score": 0.7863484025001526
}
] | typescript | abstract getModel(): Promise<ModelID>
abstract getProvider(): Promise<WindowAiProvider>
} |
|
import { ErrorCode, EventType, ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
import { Connector, Data } from './types'
export class InjectedConnector extends Connector {
name = 'injected'
constructor() {
super()
this.handleEvent = this.handleEvent.bind(this)
}
async activate(): Promise<Data> {
if (!window.ai) throw Error(`window.ai not found`)
if (window.ai.addEventListener) {
window.ai.addEventListener(this.handleEvent)
}
try {
const model = await window.ai.getCurrentModel()
return { model, provider: window.ai }
} catch (error) {
throw Error(`activate failed`)
}
}
deactivate(): void {
// no-op
// Disconnect event listeners here once window.ai upstream has removeEventListener
}
async getModel(): Promise<ModelID> {
if (!window.ai) throw Error(`window.ai not found`)
try {
return await window.ai.getCurrentModel()
} catch {
throw Error('model not found')
}
}
async getProvider(): Promise<WindowAiProvider> {
if (!window.ai) throw Error(`window.ai not found`)
return window.ai
}
private handleEvent(event | : EventType, data: unknown) { |
if (event === EventType.ModelChanged) {
this.emit('change', { model: (<{ model: ModelID }>data).model })
} else if (event === EventType.Error) {
this.emit('error', Error(data as ErrorCode))
}
}
}
| src/connectors/injected.ts | haardikk21-wanda-788b8e1 | [
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": " this.emitter.emit(eventName, ...params)\n }\n}\nexport abstract class Connector extends Emitter {\n abstract name: string\n abstract activate(): Promise<Data>\n abstract deactivate(): void\n abstract getModel(): Promise<ModelID>\n abstract getProvider(): Promise<WindowAiProvider>\n}",
"score": 0.7949393391609192
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 0.7812406420707703
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " setState((state) => ({ ...state, error: error as Error }))\n } finally {\n setState((state) => ({ ...state, connecting: false }))\n }\n },\n [globalState.connector, setGlobalState],\n )\n return [\n {\n connecting: state.connecting,",
"score": 0.7788032293319702
},
{
"filename": "src/hooks/useCompletion.ts",
"retrieved_chunk": "import { useContext } from './useContext'\nimport { CompletionOptions, Input } from '../types'\nexport const useCompletion = () => {\n const [state] = useContext()\n const getCompletion = async <T extends Input>(\n input: T,\n options?: CompletionOptions<T>,\n ) => {\n const provider = await state.connector?.getProvider()\n if (!provider) {",
"score": 0.7739497423171997
},
{
"filename": "src/hooks/useCompletion.ts",
"retrieved_chunk": " throw Error('No provider found')\n }\n return provider.getCompletion(input, options)\n }\n return { getCompletion }\n}",
"score": 0.7691973447799683
}
] | typescript | : EventType, data: unknown) { |
import React from 'react'
import { Connector, Data, InjectedConnector } from './connectors'
type State = {
connector?: Connector
data?: Data
error?: Error
}
type ContextValue = [
{
connectors: Connector[]
connector?: State['connector']
data?: State['data']
},
React.Dispatch<React.SetStateAction<State>>,
]
export const Context = React.createContext<ContextValue | null>(null)
type Props = {
connectors: Connector[]
}
export const Provider: React.FC<React.PropsWithChildren<Props>> = ({
children,
connectors = [new InjectedConnector()],
}) => {
const [state, setState] = React.useState<State>({})
React.useEffect(() => {
if (!state.connector) return
const handleChange = (data: Data) => {
setState((state) => ({ ...state, data }))
}
state.connector.on('change', handleChange)
return () => {
if (!state.connector) return
| state.connector.off('change', handleChange)
} |
}, [state.connector])
// Close connectors when unmounting
React.useEffect(() => {
return () => {
if (!state.connector) return
state.connector.deactivate()
}
}, [state.connector])
const value = [
{
connectors,
connector: state.connector,
data: state.data,
},
setState,
] as ContextValue
return React.createElement(Context.Provider, { value }, children)
}
| src/context.ts | haardikk21-wanda-788b8e1 | [
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " const connect = useCallback(\n async (connector: Connector) => {\n try {\n if (connector === globalState.connector) return\n setGlobalState((state) => ({ ...state, connector }))\n setState((state) => ({ ...state, connecting: true, error: undefined }))\n const data = await connector.activate()\n setGlobalState((state) => ({ ...state, data }))\n } catch (error) {\n console.error(error)",
"score": 0.9026495218276978
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " setState((state) => ({ ...state, error: error as Error }))\n } finally {\n setState((state) => ({ ...state, connecting: false }))\n }\n },\n [globalState.connector, setGlobalState],\n )\n return [\n {\n connecting: state.connecting,",
"score": 0.8517094850540161
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " throw Error('model not found')\n }\n }\n async getProvider(): Promise<WindowAiProvider> {\n if (!window.ai) throw Error(`window.ai not found`)\n return window.ai\n }\n private handleEvent(event: EventType, data: unknown) {\n if (event === EventType.ModelChanged) {\n this.emit('change', { model: (<{ model: ModelID }>data).model })",
"score": 0.7956663966178894
},
{
"filename": "src/connectors/injected.ts",
"retrieved_chunk": " }\n deactivate(): void {\n // no-op\n // Disconnect event listeners here once window.ai upstream has removeEventListener\n }\n async getModel(): Promise<ModelID> {\n if (!window.ai) throw Error(`window.ai not found`)\n try {\n return await window.ai.getCurrentModel()\n } catch {",
"score": 0.7930996417999268
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": "import { useCallback, useState } from 'react'\nimport { useContext } from './useContext'\nimport { Connector } from '../connectors'\ntype UseConnectState = {\n connecting: boolean\n error?: Error\n}\nexport const useConnect = () => {\n const [globalState, setGlobalState] = useContext()\n const [state, setState] = useState<UseConnectState>({ connecting: false })",
"score": 0.7761536240577698
}
] | typescript | state.connector.off('change', handleChange)
} |
import { ErrorCode, EventType, ModelID } from '../types'
import { WindowAiProvider } from '../types/declarations'
import { Connector, Data } from './types'
export class InjectedConnector extends Connector {
name = 'injected'
constructor() {
super()
this.handleEvent = this.handleEvent.bind(this)
}
async activate(): Promise<Data> {
if (!window.ai) throw Error(`window.ai not found`)
if (window.ai.addEventListener) {
window.ai.addEventListener(this.handleEvent)
}
try {
const model = await window.ai.getCurrentModel()
return { model, provider: window.ai }
} catch (error) {
throw Error(`activate failed`)
}
}
deactivate(): void {
// no-op
// Disconnect event listeners here once window.ai upstream has removeEventListener
}
async getModel(): Promise<ModelID> {
if (!window.ai) throw Error(`window.ai not found`)
try {
return await window.ai.getCurrentModel()
} catch {
throw Error('model not found')
}
}
async getProvider(): Promise<WindowAiProvider> {
if (!window.ai) throw Error(`window.ai not found`)
return window.ai
}
private handleEvent(event: EventType, data: unknown) {
if | (event === EventType.ModelChanged) { |
this.emit('change', { model: (<{ model: ModelID }>data).model })
} else if (event === EventType.Error) {
this.emit('error', Error(data as ErrorCode))
}
}
}
| src/connectors/injected.ts | haardikk21-wanda-788b8e1 | [
{
"filename": "src/hooks/useCompletion.ts",
"retrieved_chunk": "import { useContext } from './useContext'\nimport { CompletionOptions, Input } from '../types'\nexport const useCompletion = () => {\n const [state] = useContext()\n const getCompletion = async <T extends Input>(\n input: T,\n options?: CompletionOptions<T>,\n ) => {\n const provider = await state.connector?.getProvider()\n if (!provider) {",
"score": 0.8038005828857422
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " setState((state) => ({ ...state, error: error as Error }))\n } finally {\n setState((state) => ({ ...state, connecting: false }))\n }\n },\n [globalState.connector, setGlobalState],\n )\n return [\n {\n connecting: state.connecting,",
"score": 0.7939853072166443
},
{
"filename": "src/connectors/types.ts",
"retrieved_chunk": " this.emitter.emit(eventName, ...params)\n }\n}\nexport abstract class Connector extends Emitter {\n abstract name: string\n abstract activate(): Promise<Data>\n abstract deactivate(): void\n abstract getModel(): Promise<ModelID>\n abstract getProvider(): Promise<WindowAiProvider>\n}",
"score": 0.7922657132148743
},
{
"filename": "src/types/declarations.d.ts",
"retrieved_chunk": "declare global {\n interface Window {\n ai?: WindowAiProvider\n }\n}",
"score": 0.7866091132164001
},
{
"filename": "src/hooks/useConnect.ts",
"retrieved_chunk": " const connect = useCallback(\n async (connector: Connector) => {\n try {\n if (connector === globalState.connector) return\n setGlobalState((state) => ({ ...state, connector }))\n setState((state) => ({ ...state, connecting: true, error: undefined }))\n const data = await connector.activate()\n setGlobalState((state) => ({ ...state, data }))\n } catch (error) {\n console.error(error)",
"score": 0.7835592031478882
}
] | typescript | (event === EventType.ModelChanged) { |
import { createCollectionRef } from './createCollectionRef'
import { firestore } from 'firebase-admin'
import { serverTimestamp } from './serverTimestamp'
/**
* Adds multiple documents to the specified collection in Firestore.
* This function supports batched writes, and if the number of items exceeds the maximum batch size (500),
* it will split the items into multiple batches and write them sequentially.
*
* @param db - The instance of the Firestore database to use.
* @param collectionPath - The path of the collection to which the documents will be added.
* @param items - An array of document data to be added.
*
* @returns An array of WriteResult arrays corresponding to each batch.
*
* @throws Throws an exception with an error message if an error occurs.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { adds } from '@skeet-framework/firestore'
*
* const db = firestore();
* const users: User[] = [
* { name: "John Doe", age: 30 },
* { name: "Jane Smith", age: 25 },
* // ... more users ...
* ];
*
* async function run() {
* try {
* const path = 'Users'
* const results = await adds<User>(db, path, users);
* console.log(`Added ${users.length} users in ${results.length} batches.`);
* } catch (error) {
* console.error(`Error adding documents: ${error}`);
* }
* }
*
* run();
* ```
*/
export const addMultipleCollectionItems = async <
T extends firestore.DocumentData
>(
db: firestore.Firestore,
collectionPath: string,
items: T[]
): Promise<firestore.WriteResult[][]> => {
const MAX_BATCH_SIZE = 500
const chunkedItems =
items.length > 500 ? chunkArray(items, MAX_BATCH_SIZE) : [items]
const batchResults: firestore.WriteResult[][] = []
for (const chunk of chunkedItems) {
try {
const batch = db.batch()
const collectionRef | = createCollectionRef<T>(db, collectionPath)
chunk.forEach((item) => { |
const docRef = collectionRef.doc()
batch.set(docRef, {
...item,
createdAt: serverTimestamp(),
updatedAt: serverTimestamp(),
})
})
const writeResults = await batch.commit()
batchResults.push(writeResults)
} catch (error) {
throw new Error(`Error adding a batch of documents: ${error}`)
}
}
return batchResults
}
/**
* Helper function to divide an array into chunks of a specified size.
*
* @param array - The array to be divided.
* @param size - The size of each chunk.
*
* @returns An array of chunked arrays.
*/
function chunkArray<T>(array: T[], size: number): T[][] {
const chunked = []
let index = 0
while (index < array.length) {
chunked.push(array.slice(index, size + index))
index += size
}
return chunked
}
| src/lib/addMultipleCollectionItems.ts | elsoul-skeet-firestore-8c637de | [
{
"filename": "src/lib/queryCollectionItems.ts",
"retrieved_chunk": " */\nexport const queryCollectionItems = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n conditions: QueryCondition[]\n): Promise<T[]> => {\n try {\n let query: firestore.Query = db\n .collection(collectionPath)\n .withConverter(createFirestoreDataConverter<T>())",
"score": 0.8070001602172852
},
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": ") => {\n try {\n const collectionRef = createCollectionRef<T>(db, collectionPath)\n if (id) {\n const docRef = collectionRef.doc(id)\n await docRef.set({\n ...params,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n })",
"score": 0.8006621599197388
},
{
"filename": "src/lib/updateCollectionItem.ts",
"retrieved_chunk": " */\nexport const updateCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string,\n params: firestore.UpdateData<T>\n): Promise<boolean> => {\n try {\n const docRef = db\n .collection(collectionPath)",
"score": 0.7859451770782471
},
{
"filename": "src/lib/deleteCollectionItem.ts",
"retrieved_chunk": "): Promise<boolean> => {\n try {\n const docRef = db.collection(collectionPath).doc(docId)\n await docRef.delete()\n return true\n } catch (error) {\n throw new Error(`Error deleting document with ID ${docId}: ${error}`)\n }\n}",
"score": 0.7714734077453613
},
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": " return docRef\n } else {\n const data = await collectionRef.add({\n ...params,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n })\n if (!data) {\n throw new Error('no data')\n }",
"score": 0.769683301448822
}
] | typescript | = createCollectionRef<T>(db, collectionPath)
chunk.forEach((item) => { |
import { firestore } from 'firebase-admin'
import { createFirestoreDataConverter } from './createFirestoreDataConverter'
/**
* Represents a condition for querying Firestore collections.
*/
type QueryCondition = {
field?: string
operator?: firestore.WhereFilterOp
value?: any
orderDirection?: firestore.OrderByDirection // "asc" or "desc"
limit?: number
}
/**
* Queries the specified collection in Firestore based on the provided conditions
* and returns an array of documents that match the conditions.
*
* @param db - The instance of the Firestore database to use.
* @param collectionPath - The path of the collection to be queried.
* @param conditions - An array of conditions to apply to the query.
*
* @returns An array of documents from the collection that match the conditions.
*
* @throws Throws an exception with an error message if an error occurs.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { query } from '@skeet-framework/firestore'
* const db = firestore();
*
* // Simple query to get users over 25 years old
* const simpleConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 }
* ];
*
* // Advanced query to get users over 25 years old, ordered by their names
* const advancedConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 },
* { field: "name", orderDirection: "asc" }
* ];
*
* // Query to get users over 25 years old and limit the results to 5
* const limitedConditions: QueryCondition[] = [
* { field: "age", operator: ">", value: 25 },
* { limit: 5 }
* ];
*
* async function run() {
* try {
* const path = 'Users';
*
* // Using the simple conditions
* const usersByAge = await query<User>(db, path, simpleConditions);
* console.log(`Found ${usersByAge.length} users over 25 years old.`);
*
* // Using the advanced conditions
* const orderedUsers = await query<User>(db, path, advancedConditions);
* console.log(`Found ${orderedUsers.length} users over 25 years old, ordered by name.`);
*
* // Using the limited conditions
* const limitedUsers = await query<User>(db, path, limitedConditions);
* console.log(`Found ${limitedUsers.length} users over 25 years old, limited to 5.`);
*
* } catch (error) {
* console.error(`Error querying collection: ${error}`);
* }
* }
*
* run();
* ```
*/
export const queryCollectionItems = async <T extends firestore.DocumentData>(
db: firestore.Firestore,
collectionPath: string,
conditions: QueryCondition[]
): Promise<T[]> => {
try {
let query: firestore.Query = db
.collection(collectionPath)
.withConverter | (createFirestoreDataConverter<T>())
for (const condition of conditions) { |
if (
condition.field &&
condition.operator &&
condition.value !== undefined
) {
query = query.where(
condition.field,
condition.operator,
condition.value
)
}
if (condition.field && condition.orderDirection) {
query = query.orderBy(condition.field, condition.orderDirection)
}
if (condition.limit !== undefined) {
query = query.limit(condition.limit)
}
}
const snapshot = await query.get()
return snapshot.docs.map((doc) => ({
id: doc.id,
...(doc.data() as T),
}))
} catch (error) {
throw new Error(`Error querying collection: ${error}`)
}
}
| src/lib/queryCollectionItems.ts | elsoul-skeet-firestore-8c637de | [
{
"filename": "src/lib/updateCollectionItem.ts",
"retrieved_chunk": " */\nexport const updateCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string,\n params: firestore.UpdateData<T>\n): Promise<boolean> => {\n try {\n const docRef = db\n .collection(collectionPath)",
"score": 0.8942421674728394
},
{
"filename": "src/lib/getCollectionItem.ts",
"retrieved_chunk": " * run();\n * ```\n */\nexport const getCollectionItem = async <T>(\n db: firestore.Firestore,\n collectionPath: string,\n docId: string\n): Promise<T> => {\n const dataRef = db\n .collection(collectionPath)",
"score": 0.8656390905380249
},
{
"filename": "src/lib/addMultipleCollectionItems.ts",
"retrieved_chunk": " */\nexport const addMultipleCollectionItems = async <\n T extends firestore.DocumentData\n>(\n db: firestore.Firestore,\n collectionPath: string,\n items: T[]\n): Promise<firestore.WriteResult[][]> => {\n const MAX_BATCH_SIZE = 500\n const chunkedItems =",
"score": 0.8585634231567383
},
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": " * }\n *\n * run();\n * ```\n */\nexport const addCollectionItem = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n params: T,\n id?: string",
"score": 0.8472942113876343
},
{
"filename": "src/lib/addMultipleCollectionItems.ts",
"retrieved_chunk": " items.length > 500 ? chunkArray(items, MAX_BATCH_SIZE) : [items]\n const batchResults: firestore.WriteResult[][] = []\n for (const chunk of chunkedItems) {\n try {\n const batch = db.batch()\n const collectionRef = createCollectionRef<T>(db, collectionPath)\n chunk.forEach((item) => {\n const docRef = collectionRef.doc()\n batch.set(docRef, {\n ...item,",
"score": 0.8322206735610962
}
] | typescript | (createFirestoreDataConverter<T>())
for (const condition of conditions) { |
import { firestore } from 'firebase-admin'
import { createFirestoreDataConverter } from './createFirestoreDataConverter'
import { serverTimestamp } from './serverTimestamp'
/**
* Updates the specified document in the provided Firestore collection with the given data.
*
* @param db - The instance of the Firestore database to use.
* @param collectionPath - The path of the collection containing the document to be updated.
* @param docId - The ID of the document to be updated.
* @param params - The data to update the document with.
*
* @returns A boolean indicating the success of the update operation.
*
* @throws Throws an exception with an error message if an error occurs.
*
* @example
* ```typescript
* import { firestore } from 'firebase-admin'
* import { update } from '@skeet-framework/firestore'
*
* const db = firestore();
* const updatedData: firestore.UpdateData<User> = {
* age: 31
* };
*
* async function run() {
* try {
* const path = 'Users'
* const docId = '123456'; // Assuming this ID exists in the Users collection.
* const success = await update<User>(db, path, docId, updatedData);
* if (success) {
* console.log(`Document with ID ${docId} updated successfully.`);
* }
* } catch (error) {
* console.error(`Error updating document: ${error}`);
* }
* }
*
* run();
* ```
*/
export const updateCollectionItem = async <T extends firestore.DocumentData>(
db: firestore.Firestore,
collectionPath: string,
docId: string,
params: firestore.UpdateData<T>
): Promise<boolean> => {
try {
const docRef = db
.collection(collectionPath)
.doc(docId)
.withConverter(createFirestoreDataConverter<T>())
| await docRef.update({ ...params, updatedAt: serverTimestamp() })
return true
} catch (error) { |
throw new Error(`Error updating document with ID ${docId}: ${error}`)
}
}
| src/lib/updateCollectionItem.ts | elsoul-skeet-firestore-8c637de | [
{
"filename": "src/lib/addCollectionItem.ts",
"retrieved_chunk": ") => {\n try {\n const collectionRef = createCollectionRef<T>(db, collectionPath)\n if (id) {\n const docRef = collectionRef.doc(id)\n await docRef.set({\n ...params,\n createdAt: serverTimestamp(),\n updatedAt: serverTimestamp(),\n })",
"score": 0.9010629057884216
},
{
"filename": "src/lib/deleteCollectionItem.ts",
"retrieved_chunk": "): Promise<boolean> => {\n try {\n const docRef = db.collection(collectionPath).doc(docId)\n await docRef.delete()\n return true\n } catch (error) {\n throw new Error(`Error deleting document with ID ${docId}: ${error}`)\n }\n}",
"score": 0.8963221907615662
},
{
"filename": "src/lib/queryCollectionItems.ts",
"retrieved_chunk": " */\nexport const queryCollectionItems = async <T extends firestore.DocumentData>(\n db: firestore.Firestore,\n collectionPath: string,\n conditions: QueryCondition[]\n): Promise<T[]> => {\n try {\n let query: firestore.Query = db\n .collection(collectionPath)\n .withConverter(createFirestoreDataConverter<T>())",
"score": 0.8587945699691772
},
{
"filename": "src/lib/addMultipleCollectionItems.ts",
"retrieved_chunk": " items.length > 500 ? chunkArray(items, MAX_BATCH_SIZE) : [items]\n const batchResults: firestore.WriteResult[][] = []\n for (const chunk of chunkedItems) {\n try {\n const batch = db.batch()\n const collectionRef = createCollectionRef<T>(db, collectionPath)\n chunk.forEach((item) => {\n const docRef = collectionRef.doc()\n batch.set(docRef, {\n ...item,",
"score": 0.8420394659042358
},
{
"filename": "src/lib/getCollectionItem.ts",
"retrieved_chunk": " .doc(docId) as FirebaseFirestore.DocumentReference<T>\n const doc = await dataRef.get()\n if (!doc.exists) {\n throw new Error('Document not found at path: ' + dataRef.path)\n }\n const data = doc.data()\n if (!data) throw new Error('Document data not found at path: ' + dataRef.path)\n return data\n}",
"score": 0.83909672498703
}
] | typescript | await docRef.update({ ...params, updatedAt: serverTimestamp() })
return true
} catch (error) { |
import { BasicRequest } from './request'
import { RequestMethod, Route, RouteHandler } from './types'
export class Router<Env> {
routes: Route<Env>[] = []
/**
* Handles a request by matching it against the registered routes.
* @param request Request
* @param env Environment
* @param ctx Context (for Workers)
* @returns Response
**/
handle(rawRequest: Request, env: Env, ctx: ExecutionContext) {
const request = new BasicRequest(rawRequest)
for (const route of this.routes) {
const match = route[0](request)
if (match) {
return route[1]({ request, env, ctx, params: match.params })
}
}
const match = this.routes.find(([matcher]) => matcher(request))
if (match) {
return match[1]({ request, env, ctx })
}
}
/**
* Registers a new route.
* @param handler RouteHandler
* @param path Path to match
* @param method HTTP method to match
*
* @example
* const router = new Router<Env>()
*
* router.register(async ({ request }) => {
* return new Response('ok')
* }, '/test')
*/
register(handler: RouteHandler<Env>, path: | string, method?: RequestMethod) { |
const urlPattern = new URLPattern({ pathname: path })
this.routes.push([
(request) => {
if (!method || request.method === method) {
const match = urlPattern.exec({
pathname: request.url.pathname,
})
if (match) {
return { params: match.pathname.groups }
}
}
},
handler,
])
}
options(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'options')
}
head(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'head')
}
/**
* Register a new GET route.
* @param path
* @param handler
*
* @example
* const router = new Router<Env>()
*
* router.get('/test', async ({ request }) => {
* return new Response('ok')
* })
*/
get(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'get')
}
post(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'post')
}
put(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'put')
}
patch(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'patch')
}
delete(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'delete')
}
/**
* Registers a new route for all HTTP methods.
* @param path
* @param handler
*/
all(path: string, handler: RouteHandler<Env>) {
this.register(handler, path)
}
}
| src/router.ts | team-openpm-cloudflare-basics-5bf8ecd | [
{
"filename": "src/router.test.ts",
"retrieved_chunk": "import { describe, it, expect } from 'vitest'\nimport { Router } from './router'\nimport 'urlpattern-polyfill'\ndescribe('router', () => {\n type Env = {\n foo: string\n }\n it('handles routes', async () => {\n const router = new Router<Env>()\n router.register(async ({ request }) => {",
"score": 0.8813448548316956
},
{
"filename": "src/middleware/zod-validation.ts",
"retrieved_chunk": " * @return {ZodRouteHandler}\n *\n * @example\n * const schema = z.object({\n * name: z.string(),\n * })\n *\n * type schemaType = z.infer<typeof schema>\n *\n * withZod<Env, schemaType>(schema, async (options) => {",
"score": 0.8598889708518982
},
{
"filename": "src/response.ts",
"retrieved_chunk": "export function error(\n message: string,\n { type = 'invalid_request', status = 400 } = {}\n) {\n return json({ error: { message, type } }, status)\n}\n/**\n * A shortcut for creating a JSON response.\n *\n * @param data An object to be JSON stringified.",
"score": 0.8325446844100952
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " it('handles post routes', async () => {\n const router = new Router<Env>()\n router.post('/test', async ({ request }) => {\n expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n })\n const response = await router.handle(\n new Request('https://example.com/test', { method: 'POST' }),\n { foo: 'bar' },\n {} as any",
"score": 0.8314313888549805
},
{
"filename": "src/middleware/zod-validation.ts",
"retrieved_chunk": " * console.log(options.data) //=> { name: 'test' }\n * return new Response('ok')\n * })\n *\n */\nexport function withZod<Env, Schema>(\n schema: z.Schema,\n callback: ZodRouteHandler<Env, Schema>\n) {\n return async (options: RouteOptions<Env>) => {",
"score": 0.8264728784561157
}
] | typescript | string, method?: RequestMethod) { |
import z from 'zod'
import { RouteOptions, ZodRouteHandler } from '../types'
import { error } from '../response'
/**
* Creates a route handler that validates the request data and parameters using the Zod schema.
* If validation fails, it returns a 400 json error with a detailed message.
*
* @param {z.Schema} schema - A Zod schema used to validate the incoming request data and parameters.
* @param {ZodRouteHandler<Env, Schema>} callback - The main callback that will be executed after validation is successful.
*
* @return {ZodRouteHandler}
*
* @example
* const schema = z.object({
* name: z.string(),
* })
*
* type schemaType = z.infer<typeof schema>
*
* withZod<Env, schemaType>(schema, async (options) => {
* console.log(options.data) //=> { name: 'test' }
* return new Response('ok')
* })
*
*/
export function withZod<Env, Schema>(
schema: z.Schema,
callback: ZodRouteHandler<Env, Schema>
) {
return async (options: RouteOptions<Env>) => {
const { request } = options
const queryParams = request.query
const bodyParams = (await request.body()) ?? {}
const existingParams = options.params ?? {}
const params = {
...queryParams,
...bodyParams,
...existingParams,
}
const result = schema.safeParse(params)
if (!result.success) {
const firstError = result.error?.errors?.[0]
if (firstError) {
| return error(`${firstError.path} ${firstError.message}`.toLowerCase(), { |
type: firstError.code,
status: 400,
})
} else {
return error('invalid_request')
}
}
return callback({
...options,
data: result.data,
})
}
}
| src/middleware/zod-validation.ts | team-openpm-cloudflare-basics-5bf8ecd | [
{
"filename": "src/router.ts",
"retrieved_chunk": " (request) => {\n if (!method || request.method === method) {\n const match = urlPattern.exec({\n pathname: request.url.pathname,\n })\n if (match) {\n return { params: match.pathname.groups }\n }\n }\n },",
"score": 0.758223295211792
},
{
"filename": "src/router.ts",
"retrieved_chunk": " **/\n handle(rawRequest: Request, env: Env, ctx: ExecutionContext) {\n const request = new BasicRequest(rawRequest)\n for (const route of this.routes) {\n const match = route[0](request)\n if (match) {\n return route[1]({ request, env, ctx, params: match.params })\n }\n }\n const match = this.routes.find(([matcher]) => matcher(request))",
"score": 0.7428023815155029
},
{
"filename": "src/response.ts",
"retrieved_chunk": "export function error(\n message: string,\n { type = 'invalid_request', status = 400 } = {}\n) {\n return json({ error: { message, type } }, status)\n}\n/**\n * A shortcut for creating a JSON response.\n *\n * @param data An object to be JSON stringified.",
"score": 0.7300772666931152
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " body: 'name=test',\n })\n )\n expect(response.status).toBe(200)\n })\n it('should should a validation error', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ bar: 'test' })\n return new Response('ok')\n })",
"score": 0.7243086099624634
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " it('should pass through form parms', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ name: 'test' })\n return new Response('ok')\n })\n const response = await execRoute(\n route,\n buildRequest('https://example.com?name=test', {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },",
"score": 0.720321536064148
}
] | typescript | return error(`${firstError.path} ${firstError.message}`.toLowerCase(), { |
import { BasicRequest } from './request'
import { RequestMethod, Route, RouteHandler } from './types'
export class Router<Env> {
routes: Route<Env>[] = []
/**
* Handles a request by matching it against the registered routes.
* @param request Request
* @param env Environment
* @param ctx Context (for Workers)
* @returns Response
**/
handle(rawRequest: Request, env: Env, ctx: ExecutionContext) {
const request = new BasicRequest(rawRequest)
for (const route of this.routes) {
const match = route[0](request)
if (match) {
return route[1]({ request, env, ctx, params: match.params })
}
}
const match = this.routes.find(([matcher]) => matcher(request))
if (match) {
return match[1]({ request, env, ctx })
}
}
/**
* Registers a new route.
* @param handler RouteHandler
* @param path Path to match
* @param method HTTP method to match
*
* @example
* const router = new Router<Env>()
*
* router.register(async ({ request }) => {
* return new Response('ok')
* }, '/test')
*/
register(handler: | RouteHandler<Env>, path: string, method?: RequestMethod) { |
const urlPattern = new URLPattern({ pathname: path })
this.routes.push([
(request) => {
if (!method || request.method === method) {
const match = urlPattern.exec({
pathname: request.url.pathname,
})
if (match) {
return { params: match.pathname.groups }
}
}
},
handler,
])
}
options(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'options')
}
head(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'head')
}
/**
* Register a new GET route.
* @param path
* @param handler
*
* @example
* const router = new Router<Env>()
*
* router.get('/test', async ({ request }) => {
* return new Response('ok')
* })
*/
get(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'get')
}
post(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'post')
}
put(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'put')
}
patch(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'patch')
}
delete(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'delete')
}
/**
* Registers a new route for all HTTP methods.
* @param path
* @param handler
*/
all(path: string, handler: RouteHandler<Env>) {
this.register(handler, path)
}
}
| src/router.ts | team-openpm-cloudflare-basics-5bf8ecd | [
{
"filename": "src/router.test.ts",
"retrieved_chunk": "import { describe, it, expect } from 'vitest'\nimport { Router } from './router'\nimport 'urlpattern-polyfill'\ndescribe('router', () => {\n type Env = {\n foo: string\n }\n it('handles routes', async () => {\n const router = new Router<Env>()\n router.register(async ({ request }) => {",
"score": 0.8830323219299316
},
{
"filename": "src/middleware/zod-validation.ts",
"retrieved_chunk": " * @return {ZodRouteHandler}\n *\n * @example\n * const schema = z.object({\n * name: z.string(),\n * })\n *\n * type schemaType = z.infer<typeof schema>\n *\n * withZod<Env, schemaType>(schema, async (options) => {",
"score": 0.8606477975845337
},
{
"filename": "src/response.ts",
"retrieved_chunk": "export function error(\n message: string,\n { type = 'invalid_request', status = 400 } = {}\n) {\n return json({ error: { message, type } }, status)\n}\n/**\n * A shortcut for creating a JSON response.\n *\n * @param data An object to be JSON stringified.",
"score": 0.8344935178756714
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " it('handles post routes', async () => {\n const router = new Router<Env>()\n router.post('/test', async ({ request }) => {\n expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n })\n const response = await router.handle(\n new Request('https://example.com/test', { method: 'POST' }),\n { foo: 'bar' },\n {} as any",
"score": 0.8337774276733398
},
{
"filename": "src/middleware/zod-validation.ts",
"retrieved_chunk": " * console.log(options.data) //=> { name: 'test' }\n * return new Response('ok')\n * })\n *\n */\nexport function withZod<Env, Schema>(\n schema: z.Schema,\n callback: ZodRouteHandler<Env, Schema>\n) {\n return async (options: RouteOptions<Env>) => {",
"score": 0.8289549946784973
}
] | typescript | RouteHandler<Env>, path: string, method?: RequestMethod) { |
import { BasicRequest } from './request'
import { RequestMethod, Route, RouteHandler } from './types'
export class Router<Env> {
routes: Route<Env>[] = []
/**
* Handles a request by matching it against the registered routes.
* @param request Request
* @param env Environment
* @param ctx Context (for Workers)
* @returns Response
**/
handle(rawRequest: Request, env: Env, ctx: ExecutionContext) {
const request = new BasicRequest(rawRequest)
for (const route of this.routes) {
const match = route[0](request)
if (match) {
return route[1]({ request, env, ctx, params: match.params })
}
}
const match = this.routes.find(([matcher]) => matcher(request))
if (match) {
return match[1]({ request, env, ctx })
}
}
/**
* Registers a new route.
* @param handler RouteHandler
* @param path Path to match
* @param method HTTP method to match
*
* @example
* const router = new Router<Env>()
*
* router.register(async ({ request }) => {
* return new Response('ok')
* }, '/test')
*/
register(handler: RouteHandler<Env>, path: string, method?: RequestMethod) {
const urlPattern = new URLPattern({ pathname: path })
this.routes.push([
| (request) => { |
if (!method || request.method === method) {
const match = urlPattern.exec({
pathname: request.url.pathname,
})
if (match) {
return { params: match.pathname.groups }
}
}
},
handler,
])
}
options(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'options')
}
head(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'head')
}
/**
* Register a new GET route.
* @param path
* @param handler
*
* @example
* const router = new Router<Env>()
*
* router.get('/test', async ({ request }) => {
* return new Response('ok')
* })
*/
get(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'get')
}
post(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'post')
}
put(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'put')
}
patch(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'patch')
}
delete(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'delete')
}
/**
* Registers a new route for all HTTP methods.
* @param path
* @param handler
*/
all(path: string, handler: RouteHandler<Env>) {
this.register(handler, path)
}
}
| src/router.ts | team-openpm-cloudflare-basics-5bf8ecd | [
{
"filename": "src/router.test.ts",
"retrieved_chunk": "import { describe, it, expect } from 'vitest'\nimport { Router } from './router'\nimport 'urlpattern-polyfill'\ndescribe('router', () => {\n type Env = {\n foo: string\n }\n it('handles routes', async () => {\n const router = new Router<Env>()\n router.register(async ({ request }) => {",
"score": 0.8856558799743652
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " it('handles post routes', async () => {\n const router = new Router<Env>()\n router.post('/test', async ({ request }) => {\n expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n })\n const response = await router.handle(\n new Request('https://example.com/test', { method: 'POST' }),\n { foo: 'bar' },\n {} as any",
"score": 0.8760712742805481
},
{
"filename": "src/middleware/zod-validation.ts",
"retrieved_chunk": " * console.log(options.data) //=> { name: 'test' }\n * return new Response('ok')\n * })\n *\n */\nexport function withZod<Env, Schema>(\n schema: z.Schema,\n callback: ZodRouteHandler<Env, Schema>\n) {\n return async (options: RouteOptions<Env>) => {",
"score": 0.8539044260978699
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BasicRequest } from './request'\nexport type RouteMatcher = (\n request: BasicRequest\n) => { params: Record<string, string> } | undefined\nexport type RouteOptions<Env> = {\n request: BasicRequest\n env: Env\n ctx: ExecutionContext\n params?: Record<string, string>\n}",
"score": 0.8426815271377563
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " body: 'name=test',\n })\n )\n expect(response.status).toBe(200)\n })\n it('should should a validation error', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ bar: 'test' })\n return new Response('ok')\n })",
"score": 0.8342093825340271
}
] | typescript | (request) => { |
import { BasicRequest } from './request'
import { RequestMethod, Route, RouteHandler } from './types'
export class Router<Env> {
routes: Route<Env>[] = []
/**
* Handles a request by matching it against the registered routes.
* @param request Request
* @param env Environment
* @param ctx Context (for Workers)
* @returns Response
**/
handle(rawRequest: Request, env: Env, ctx: ExecutionContext) {
const request = new BasicRequest(rawRequest)
for (const route of this.routes) {
const match = route[0](request)
if (match) {
return route[1]({ request, env, ctx, params: match.params })
}
}
const match = this.routes.find(([matcher]) => matcher(request))
if (match) {
return match[1]({ request, env, ctx })
}
}
/**
* Registers a new route.
* @param handler RouteHandler
* @param path Path to match
* @param method HTTP method to match
*
* @example
* const router = new Router<Env>()
*
* router.register(async ({ request }) => {
* return new Response('ok')
* }, '/test')
*/
register(handler: RouteHandler<Env>, path: string, method?: RequestMethod) {
const urlPattern = new URLPattern({ pathname: path })
this.routes.push([
( | request) => { |
if (!method || request.method === method) {
const match = urlPattern.exec({
pathname: request.url.pathname,
})
if (match) {
return { params: match.pathname.groups }
}
}
},
handler,
])
}
options(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'options')
}
head(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'head')
}
/**
* Register a new GET route.
* @param path
* @param handler
*
* @example
* const router = new Router<Env>()
*
* router.get('/test', async ({ request }) => {
* return new Response('ok')
* })
*/
get(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'get')
}
post(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'post')
}
put(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'put')
}
patch(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'patch')
}
delete(path: string, handler: RouteHandler<Env>) {
this.register(handler, path, 'delete')
}
/**
* Registers a new route for all HTTP methods.
* @param path
* @param handler
*/
all(path: string, handler: RouteHandler<Env>) {
this.register(handler, path)
}
}
| src/router.ts | team-openpm-cloudflare-basics-5bf8ecd | [
{
"filename": "src/router.test.ts",
"retrieved_chunk": " it('handles post routes', async () => {\n const router = new Router<Env>()\n router.post('/test', async ({ request }) => {\n expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n })\n const response = await router.handle(\n new Request('https://example.com/test', { method: 'POST' }),\n { foo: 'bar' },\n {} as any",
"score": 0.8728222846984863
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": "import { describe, it, expect } from 'vitest'\nimport { Router } from './router'\nimport 'urlpattern-polyfill'\ndescribe('router', () => {\n type Env = {\n foo: string\n }\n it('handles routes', async () => {\n const router = new Router<Env>()\n router.register(async ({ request }) => {",
"score": 0.8721256256103516
},
{
"filename": "src/middleware/zod-validation.ts",
"retrieved_chunk": " * console.log(options.data) //=> { name: 'test' }\n * return new Response('ok')\n * })\n *\n */\nexport function withZod<Env, Schema>(\n schema: z.Schema,\n callback: ZodRouteHandler<Env, Schema>\n) {\n return async (options: RouteOptions<Env>) => {",
"score": 0.8510342836380005
},
{
"filename": "src/types.ts",
"retrieved_chunk": "import { BasicRequest } from './request'\nexport type RouteMatcher = (\n request: BasicRequest\n) => { params: Record<string, string> } | undefined\nexport type RouteOptions<Env> = {\n request: BasicRequest\n env: Env\n ctx: ExecutionContext\n params?: Record<string, string>\n}",
"score": 0.8315684795379639
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " })\n type schemaType = z.infer<typeof schema>\n it('should pass through json', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ name: 'test' })\n return new Response('ok')\n })\n const response = await execRoute(\n route,\n buildRequest('https://example.com', {",
"score": 0.8292257785797119
}
] | typescript | request) => { |
import { describe, it, expect } from 'vitest'
import { BasicRequest } from './request'
describe('request', () => {
it('parses query params', () => {
const request = new BasicRequest(
new Request('https://example.com/test?foo=bar')
)
expect(request.query).toEqual({ foo: 'bar' })
})
it('parses cookies', () => {
const request = new BasicRequest(
new Request('https://example.com/test', {
headers: {
cookie: 'foo=bar',
},
})
)
expect(request.cookies).toEqual({ foo: 'bar' })
})
it('parses headers', () => {
const request = new BasicRequest(
new Request('https://example.com/test', {
headers: {
'content-type': 'application/json',
},
})
)
expect(request.headers.get('content-type')).toBe('application/json')
})
it('parses origin', () => {
const request = new BasicRequest(
new Request('https://example.com/test', {
headers: {
'content-type': 'application/json',
},
})
)
| expect(request.origin).toBe('https://example.com')
})
it('parses json', async () => { |
const request = new BasicRequest(
new Request('https://example.com/test', {
method: 'POST',
headers: {
'content-type': 'application/json',
},
body: JSON.stringify({ foo: 'bar' }),
})
)
expect(await request.body()).toEqual({ foo: 'bar' })
})
it('parses forms', async () => {
const request = new BasicRequest(
new Request('https://example.com/test', {
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
body: 'foo=bar',
})
)
expect(await request.body()).toEqual({ foo: 'bar' })
})
})
| src/request.test.ts | team-openpm-cloudflare-basics-5bf8ecd | [
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " const response = await execRoute(\n route,\n buildRequest('https://example.com', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ bar: 'test' }),\n })\n )\n expect(response.status).toBe(400)\n expect(await response.json()).toMatchInlineSnapshot(`",
"score": 0.8988957405090332
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " return new Response('ok')\n })\n const response = await execRoute(\n route,\n buildRequest('https://example.com?name=test', {\n method: 'GET',\n })\n )\n expect(response.status).toBe(200)\n })",
"score": 0.8887298107147217
},
{
"filename": "src/middleware/zod-validation.test.ts",
"retrieved_chunk": " method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ name: 'test' }),\n })\n )\n expect(response.status).toBe(200)\n })\n it('should pass through query', async () => {\n const route = withZod<Env, schemaType>(schema, async (options) => {\n expect(options.data).toEqual({ name: 'test' })",
"score": 0.8823928833007812
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n }, '/test')\n const response = await router.handle(\n new Request('https://example.com/test'),\n { foo: 'bar' },\n {} as any\n )\n expect(response?.status).toBe(200)\n })",
"score": 0.8710082769393921
},
{
"filename": "src/router.test.ts",
"retrieved_chunk": " it('handles post routes', async () => {\n const router = new Router<Env>()\n router.post('/test', async ({ request }) => {\n expect(request.url.href).toBe('https://example.com/test')\n return new Response('ok')\n })\n const response = await router.handle(\n new Request('https://example.com/test', { method: 'POST' }),\n { foo: 'bar' },\n {} as any",
"score": 0.8694776296615601
}
] | typescript | expect(request.origin).toBe('https://example.com')
})
it('parses json', async () => { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
| export class TestBase extends Base { |
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": "// ok, so, export the root PluginBase, PluginHost, and the Base\n// Both have the stream stuff, and basic TAP parser stuff\n// PluginHost has all the default assertions, so a Plugin can\n// do stuff like `return t.ok()`\n// Base is a parent of PluginBase, and used for stuff like Spawn,\n// Stdin, and Worker subclasses\n//\n// tap.Test is extended from the generated source, so it has all plugins\n/*\n## Class heirarchy",
"score": 0.9017033576965332
},
{
"filename": "src/base.ts",
"retrieved_chunk": "Base - streaming, parsing, test status, config loading\n+-- Spawn - run a child proc, consume output as tap stream\n+-- Stdin - consume stdin as tap stream\n+-- Worker - run a worker thread, consume output as tap stream\n+-- TestBase - generate tap stream, built-in set of assertions\n +-- (builtin plugins...) - add functions for spawn, assertions, snapshot, mock, etc\n +-- (user plugins...) - whatever the config says to load\n +-- Test - the test class exposed to user\n +-- TAP - the root test runner\n*/",
"score": 0.8691149950027466
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " return true\n },\n get(_, p) {\n // cache get results so t.blah === t.blah\n // we only cache functions, so that getters aren't memoized\n // Of course, a getter that returns a function will be broken,\n // at least when accessed from outside the plugin, but that's\n // a pretty narrow caveat, and easily documented.\n if (getCache.has(p)) return getCache.get(p)\n for (const plug of ext) {",
"score": 0.8351550102233887
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " }\n }\n }\n // show a line by line string diff\n // diff the yaml, to make it more humane, especially\n // when strings or buffers are very large or multi-line\n // the shipped compare methods will generally supply\n // their own diff, which is much nicer.\n if (\n res.found &&",
"score": 0.8304734230041504
},
{
"filename": "src/base.ts",
"retrieved_chunk": " stream: Minipass<string> = new Minipass<string>({\n encoding: 'utf8',\n })\n readyToProcess: boolean = false\n options: BaseOpts\n indent: string\n hook: TapWrap\n // this actually is deterministically set in the ctor, but\n // in the hook, so tsc doesn't see it.\n hookDomain!: Domain",
"score": 0.8252565860748291
}
] | typescript | export class TestBase extends Base { |
import stack from './stack'
import type {BaseOpts} from './base'
export default (er:any, extra?:{[k: string]:any}, options?:BaseOpts) => {
// the yaml module puts big stuff here, pluck it off
if (er.source && typeof er.source === 'object' && er.source.context)
er.source = { ...er.source, context: null }
// pull out all fields from options, other than anything starting
// with tapChild, or anything already set in the extra object.
extra = Object.fromEntries(Object.entries(options || {}).filter(([k]) =>
!/^tapChild/.test(k) && !(k in (extra || {}))))
if (!er || typeof er !== 'object') {
extra.error = er
return extra
}
// pull out error details
const message = er.message ? er.message
: er.stack ? er.stack.split('\n')[0]
: ''
if (er.message) {
try {
Object.defineProperty(er, 'message', {
value: '',
configurable: true
})
} catch {}
}
const st = er.stack && er.stack.substr(
er._babel ? (message + er.codeFrame).length : 0)
if (st) {
const splitst = st.split('\n')
if (er._babel && er.loc) {
const msplit = message.split(': ')
const f = msplit[0].trim()
extra.message = msplit.slice(1).join(': ')
.replace(/ \([0-9]+:[0-9]+\)$/, '').trim()
const file = f.indexOf(process.cwd()) === 0
? f.substr(process.cwd().length + 1) : f
if (file !== 'unknown')
delete er.codeFrame
extra.at = {
file,
line: er.loc.line,
column: er.loc.column + 1,
}
} else {
// parse out the 'at' bit from the first line.
extra | .at = stack.parseLine(splitst[1])
} |
extra.stack = stack.clean(splitst)
}
if (message) {
try {
Object.defineProperty(er, 'message', {
value: message,
configurable: true
})
} catch {}
}
if (er.name && er.name !== 'Error') {
extra.type = er.name
}
Object.assign(extra, Object.fromEntries(Object.entries(er).filter(([k]) =>
k !== 'message')))
return extra
}
| src/extra-from-error.ts | tapjs-core-edd7403 | [
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " // don't print locations in tap itself, that's almost never useful\n delete res.at\n }\n if (\n file &&\n res.at &&\n res.at.file &&\n res.at.line &&\n !res.source\n ) {",
"score": 0.8071386814117432
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " extra.at = stack.parseLine(extra.stack.split('\\n')[0])\n }\n if (\n !ok &&\n !extra.skip &&\n !extra.at &&\n typeof fn === 'function'\n ) {\n extra.at = stack.at(fn)\n if (!extra.todo) {",
"score": 0.8017812967300415
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const content = tryReadFile(file)\n if (content) {\n const lines = content.split('\\n')\n if (res.at.line <= lines.length) {\n const startLine = Math.max(res.at.line - 2, 0)\n const endLine = Math.min(\n res.at.line + 2,\n lines.length\n )\n const caret =",
"score": 0.7860355377197266
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.7731797695159912
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.7641144394874573
}
] | typescript | .at = stack.parseLine(splitst[1])
} |
// ok, so, export the root PluginBase, PluginHost, and the Base
// Both have the stream stuff, and basic TAP parser stuff
// PluginHost has all the default assertions, so a Plugin can
// do stuff like `return t.ok()`
// Base is a parent of PluginBase, and used for stuff like Spawn,
// Stdin, and Worker subclasses
//
// tap.Test is extended from the generated source, so it has all plugins
/*
## Class heirarchy
Base - streaming, parsing, test status, config loading
+-- Spawn - run a child proc, consume output as tap stream
+-- Stdin - consume stdin as tap stream
+-- Worker - run a worker thread, consume output as tap stream
+-- TestBase - generate tap stream, built-in set of assertions
+-- (builtin plugins...) - add functions for spawn, assertions, snapshot, mock, etc
+-- (user plugins...) - whatever the config says to load
+-- Test - the test class exposed to user
+-- TAP - the root test runner
*/
import Domain from 'async-hook-domain'
import { AsyncResource } from 'async_hooks'
import Minipass, {
ContiguousData,
Encoding,
} from 'minipass'
import { hrtime } from 'node:process'
import { format } from 'node:util'
import {
FinalResults,
Parser,
Result,
TapError,
} from 'tap-parser'
import Deferred from 'trivial-deferred'
import extraFromError from './extra-from-error'
export class TapWrap extends AsyncResource {
test: Base
constructor(test: Base) {
super(`tap.${test.constructor.name}`)
this.test = test
}
}
export class Counts {
total: number = 0
pass: number = 0
fail: number = 0
skip: number = 0
todo: number = 0
}
export class Lists {
fail: Result[] = []
todo: Result[] = []
skip: Result[] = []
pass: Result[] = []
}
const debug =
(name: string) =>
(...args: any[]) => {
const prefix = `TAP ${process.pid} ${name}: `
const msg = format(...args).trim()
console.error(
prefix + msg.split('\n').join(`\n${prefix}`)
)
}
export interface BaseOpts {
// parser-related options
bail?: boolean
strict?: boolean
omitVersion?: boolean
preserveWhitespace?: boolean
skip?: boolean | string
todo?: boolean | string
timeout?: number
time?: number
tapChildBuffer?: string
stack?: string
// basically only set when running in this project
stackIncludesTap?: boolean
parent?: Base
name?: string
childId?: number
context?: any
indent?: string
debug?: boolean
parser?: Parser
buffered?: boolean
silent?: boolean
}
export class Base {
stream: Minipass<string> = new Minipass<string>({
encoding: 'utf8',
})
readyToProcess: boolean = false
options: BaseOpts
indent: string
hook: TapWrap
// this actually is deterministically set in the ctor, but
// in the hook, so tsc doesn't see it.
hookDomain!: Domain
timer?: NodeJS.Timeout
parser: Parser
debug: (...args: any[]) => void
counts: Counts
lists: Lists
name: string
results?: FinalResults
parent?: Base
bail: boolean
strict: boolean
omitVersion: boolean
preserveWhitespace: boolean
errors: TapError[]
childId: number
context: any
output: string
buffered: boolean
bailedOut: string | boolean
start: bigint
time: number
hrtime: bigint
silent: boolean
deferred?: Deferred<FinalResults>
constructor(options: BaseOpts = {}) {
// all tap streams are sync string minipasses
this.hook = new TapWrap(this)
this.options = options
this.counts = new Counts()
this.lists = new Lists()
this.silent = !!options.silent
// if it's null or an object, inherit from it. otherwise, copy it.
const ctx = options.context
if (ctx !== undefined) {
this.context =
typeof ctx === 'object' ? Object.create(ctx) : ctx
} else {
this.context = null
}
this.bail = !!options.bail
this.strict = !!options.strict
this.omitVersion = !!options.omitVersion
this.preserveWhitespace = !!options.preserveWhitespace
this.buffered = !!options.buffered
this.bailedOut = false
this.errors = []
this.parent = options.parent
this.time = 0
this.hrtime = 0n
this.start = 0n
this.childId = options.childId || 0
// do we need this? couldn't we just call the Minipass
this.output = ''
this.indent = options.indent || ''
this.name = options.name || '(unnamed test)'
this.hook.runInAsyncScope(
() =>
(this.hookDomain = new Domain((er, type) => {
if (!er || typeof er !== 'object')
er = { error: er }
er.tapCaught = type
this.threw(er)
}))
)
this.debug = !!options.debug
? debug(this.name)
: () => {}
this.parser =
options.parser ||
new Parser({
bail: this.bail,
strict: this.strict,
omitVersion: this.omitVersion,
preserveWhitespace: this.preserveWhitespace,
name: this.name,
})
this.setupParser()
// ensure that a skip or todo on a child class reverts
// back to Base's no-op main.
if (options.skip || options.todo) {
this.main = Base.prototype.main
}
}
setupParser() {
this.parser.on('line', l => this.online(l))
this.parser.once('bailout', reason =>
this.onbail(reason)
)
this.parser.on('complete', result =>
this.oncomplete(result)
)
this.parser.on('result', () => this.counts.total++)
this.parser.on('pass', () => this.counts.pass++)
this.parser.on('todo', res => {
this.counts.todo++
this.lists.todo.push(res)
})
this.parser.on('skip', res => {
// it is uselessly noisy to print out lists of tests skipped
// because of a --grep or --only argument.
if (/^filter: (only|\/.*\/)$/.test(res.skip)) return
this.counts.skip++
this.lists.skip.push(res)
})
this.parser.on('fail', res => {
this.counts.fail++
this.lists.fail.push(res)
})
}
setTimeout(n: number) {
if (n <= 0) {
if (this.timer) {
clearTimeout(this.timer)
}
this.timer = undefined
} else {
this.timer = setTimeout(() => this.timeout(), n)
this.timer.unref()
}
}
timeout(options?: { [k: string]: any }) {
this.setTimeout(0)
options = options || {}
options.expired = options.expired || this.name
const threw = this.threw(new Error('timeout!'), options)
if (threw) {
this.emit('timeout', threw)
}
}
runMain(cb: () => void) {
this.debug('BASE runMain')
this.start = hrtime.bigint()
this.hook.runInAsyncScope(this.main, this, cb)
}
main(cb: () => void) {
cb()
}
onbail(reason?: string) {
this.bailedOut = reason || true
this.emit('bailout', reason)
}
online(line: string) {
this.debug('LINE %j', line, [this.name, this.indent])
return this.write(this.indent + line)
}
write(
c: ContiguousData,
e?: Encoding | (() => any),
cb?: () => any
) {
if (this.buffered) {
this.output += c
return true
}
if (typeof e === 'function') {
cb = e
e = undefined
}
return this.stream.write(
c,
e as Encoding | undefined,
cb
)
}
oncomplete(results: FinalResults) {
if (this.start) {
this.hrtime = hrtime.bigint() - this.start
this.time =
results.time || Number(this.hrtime / 1000n)
}
this.debug('ONCOMPLETE %j %j', this.name, results)
if (this.results) {
Object.assign(results, this.results)
}
this.results = results
this.emit('complete', results)
const errors = results.failures
.filter(f => f.tapError)
.map(f => {
delete f.diag
delete f.ok
return f
})
if (errors.length) {
this.errors = errors
}
this.onbeforeend()
// XXX old tap had a check here to ensure that buffer and pipes
// are cleared. But Minipass "should" do this now for us, so
// this ought to be fine, but revisit if it causes problems.
this.stream.end()
}
// extension points for Test, Spawn, etc.
onbeforeend() {}
ondone() {}
once(ev: string, handler: (...a: any[]) => any) {
return this.stream.once(ev, handler)
}
on(ev: string, handler: (...a: any[]) => any) {
return this.stream.on(ev, handler)
}
emit(ev: string, ...data: any[]) {
const ret = this.stream.emit(ev, ...data)
if (ev === 'end') {
this.ondone()
this.hook.emitDestroy()
this.hookDomain.destroy()
}
return ret
}
end() {
this.stream.end()
return this
}
threw(er: any, extra?: any, proxy?: boolean) {
this.hook.emitDestroy()
this.hookDomain.destroy()
if (typeof er === 'string') {
er = { message: er }
} else if (!er || typeof er !== 'object') {
er = { error: er }
}
if (this.name && !proxy) {
er.test = this.name
}
const message = er.message
if (!extra) {
extra | = extraFromError(er, extra, this.options)
} |
// if we ended, we have to report it SOMEWHERE, unless we're
// already in the process of bailing out, in which case it's
// a bit excessive.
if (this.results) {
const alreadyBailing = !this.results.ok && this.bail
this.results.ok = false
if (this.parent) {
this.parent.threw(er, extra, true)
} else if (alreadyBailing) {
// we are already bailing out, and this is the top level,
// just make our way hastily to the nearest exit.
return
} else if (!er.stack) {
console.error(er)
} else {
if (message) {
er.message = message
}
delete extra.stack
delete extra.at
console.error('%s: %s', er.name || 'Error', message)
console.error(
er.stack.split(/\n/).slice(1).join('\n')
)
console.error(extra)
}
} else {
this.parser.ok = false
}
return extra
}
passing() {
return this.parser.ok
}
}
| src/base.ts | tapjs-core-edd7403 | [
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (!er || typeof er !== 'object') {\n extra.error = er\n return extra\n }\n // pull out error details\n const message = er.message ? er.message\n : er.stack ? er.stack.split('\\n')[0]\n : ''\n if (er.message) {\n try {",
"score": 0.8789377808570862
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (message) {\n try {\n Object.defineProperty(er, 'message', {\n value: message,\n configurable: true\n })\n } catch {}\n }\n if (er.name && er.name !== 'Error') {\n extra.type = er.name",
"score": 0.8623114228248596
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " plan: this.#planEnd,\n },\n })\n Error.captureStackTrace(er, fn || undefined)\n this.threw(er)\n return\n }\n extra = extra || {}\n if (extra.expectFail) {\n ok = !ok",
"score": 0.8524556159973145
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " } else {\n extra.buffered = false\n }\n }\n extra.bail =\n extra.bail !== undefined ? extra.bail : this.bail\n extra.parent = this\n extra.stack = stack.captureString(80, caller)\n extra.context = this.context\n const t = new Class(extra)",
"score": 0.8444390296936035
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " try {\n return this.cb(this)\n } catch (er: any) {\n if (!er || typeof er !== 'object') {\n er = { error: er }\n }\n er.tapCaught = 'testFunctionThrow'\n this.threw(er)\n }\n })()",
"score": 0.8433740139007568
}
] | typescript | = extraFromError(er, extra, this.options)
} |
import { StdioOptions } from 'child_process'
import { FinalResults } from 'tap-parser'
import { BaseOpts } from '../base.js'
import { Spawn } from '../spawn.js'
import { TapPlugin, TestBase } from '../test-base.js'
export interface SpawnOpts extends BaseOpts {
cwd?: string
command?: string
args?: string[]
stdio?: StdioOptions
env?: { [k: string]: string } | typeof process.env
exitCode?: number | null
signal?: string | null
}
class SpawnPlugin {
#t: TestBase
constructor(t: TestBase) {
this.#t = t
}
spawn(cmd: string): Promise<FinalResults | null>
spawn(
cmd: string,
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args?: string | string[] | SpawnOpts,
options?: SpawnOpts | string,
name?: string
): Promise<FinalResults | null> {
if (typeof args === 'string') {
args = [args]
}
if (typeof options === 'string') {
name = options
options = {}
}
if (typeof args === 'object' && !Array.isArray(args)) {
options = args
args = []
}
options = options || {}
if (options.name === undefined) {
options.name = name
}
options.command = cmd
options.args = args
| return this.#t.sub(Spawn, options, this.spawn)
} |
}
const plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
| src/plugin/spawn.ts | tapjs-core-edd7403 | [
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n options = options || {}\n const cwd =\n typeof options.cwd === 'string'\n ? options.cwd\n : process.cwd()\n const args = options.args || []\n options.name =\n options.name || Spawn.procName(cwd, command, args)\n super(options)",
"score": 0.885009229183197
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " public args: string[]\n public stdio: StdioOptions\n public env: { [k: string]: string } | typeof process.env\n public proc: null | ChildProcess\n public cb: null | (() => void)\n constructor(options: SpawnOpts) {\n // figure out the name before calling super()\n const command = options.command\n if (!command) {\n throw new TypeError('no command provided')",
"score": 0.8424555063247681
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.cwd = cwd\n this.command = command\n this.args = args\n if (options.stdio) {\n if (typeof options.stdio === 'string')\n this.stdio = [options.stdio, 'pipe', options.stdio]\n else {\n this.stdio = options.stdio.slice(0) as StdioOptions\n }\n } else {",
"score": 0.8319573402404785
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.threw(er)\n }))\n )\n this.debug = !!options.debug\n ? debug(this.name)\n : () => {}\n this.parser =\n options.parser ||\n new Parser({\n bail: this.bail,",
"score": 0.8246946334838867
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // do we need this? couldn't we just call the Minipass\n this.output = ''\n this.indent = options.indent || ''\n this.name = options.name || '(unnamed test)'\n this.hook.runInAsyncScope(\n () =>\n (this.hookDomain = new Domain((er, type) => {\n if (!er || typeof er !== 'object')\n er = { error: er }\n er.tapCaught = type",
"score": 0.8166118264198303
}
] | typescript | return this.#t.sub(Spawn, options, this.spawn)
} |
import { StdioOptions } from 'child_process'
import { FinalResults } from 'tap-parser'
import { BaseOpts } from '../base.js'
import { Spawn } from '../spawn.js'
import { TapPlugin, TestBase } from '../test-base.js'
export interface SpawnOpts extends BaseOpts {
cwd?: string
command?: string
args?: string[]
stdio?: StdioOptions
env?: { [k: string]: string } | typeof process.env
exitCode?: number | null
signal?: string | null
}
class SpawnPlugin {
#t: TestBase
constructor(t: TestBase) {
this.#t = t
}
spawn(cmd: string): Promise<FinalResults | null>
spawn(
cmd: string,
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args?: string | string[] | SpawnOpts,
options?: SpawnOpts | string,
name?: string
): Promise<FinalResults | null> {
if (typeof args === 'string') {
args = [args]
}
if (typeof options === 'string') {
name = options
options = {}
}
if (typeof args === 'object' && !Array.isArray(args)) {
options = args
args = []
}
options = options || {}
if (options.name === undefined) {
options.name = name
}
options.command = cmd
options.args = args
return this.#t.sub(Spawn, options, this.spawn)
}
}
| const plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
| src/plugin/spawn.ts | tapjs-core-edd7403 | [
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": "}\nconst plugin: TapPlugin<StdinPlugin> = (t: TestBase) =>\n new StdinPlugin(t)\nexport default plugin",
"score": 0.8298289179801941
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " }\n }\n }\n },\n })\n Object.assign(base, { t })\n ext.unshift({ t })\n return t\n}\nexport class Test extends TestBase {",
"score": 0.803451418876648
},
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": "import { FinalResults } from 'tap-parser'\nimport parseTestArgs from '../parse-test-args.js'\nimport { Stdin, StdinOpts } from '../stdin.js'\nimport { TapPlugin, TestBase } from '../test-base.js'\nclass StdinPlugin {\n #t: TestBase\n constructor(t: TestBase) {\n this.#t = t\n }\n stdin(",
"score": 0.8015609979629517
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " return t\n}\nexport class Test extends TestBase {\n constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },",
"score": 0.7974721789360046
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ...args: TestArgs<Test>\n ): Promise<FinalResults | null>\n}\nconst applyPlugins = (base: Test): Test => {\n const ext: Plug[] = [\n ...plugins.map(p => p(base, base.options)),\n base,\n ]\n const getCache = new Map<any, any>()\n const t = new Proxy(base, {",
"score": 0.7899627685546875
}
] | typescript | const plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
|
|
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this. | hook.runInAsyncScope(cb, this, ...args)
} |
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/plugin/before-each.ts",
"retrieved_chunk": " const runMain = t.runMain\n t.runMain = (cb: () => void) => {\n this.#runBeforeEach(this.#t, () =>\n runMain.call(t, cb)\n )\n }\n }\n #onBeforeEach: ((t: Test) => void)[] = []\n beforeEach(fn: (t: Test) => void | Promise<void>) {\n this.#onBeforeEach.push(fn)",
"score": 0.8924282789230347
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " t.runMain = (cb: () => void) => {\n runMain.call(t, () => this.#runAfterEach(this.#t, cb))\n }\n }\n #onAfterEach: ((t: Test) => void)[] = []\n afterEach(fn: (t: Test) => void | Promise<void>) {\n this.#onAfterEach.push(fn)\n }\n #runAfterEach(who: TestBase, cb: () => void) {\n // run all the afterEach methods from the parent",
"score": 0.8871197700500488
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " ): Promise<FinalResults | null>\n todo(cb?: (t: Test) => any): Promise<FinalResults | null>\n todo(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.todo)\n }\n skip(",
"score": 0.8295815587043762
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.8257941603660583
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(",
"score": 0.8253942728042603
}
] | typescript | hook.runInAsyncScope(cb, this, ...args)
} |
import Event from '../../events/event';
import DebugEvent from '../../events/debug';
import Listener from './listener';
import type Klient from '../../klient';
export type Callback<T extends Event> = (e: T) => Promise<void> | void;
export type Listeners = { [event: string]: Listener<never>[] };
export default class Dispatcher {
readonly listeners: Listeners = {};
constructor(protected readonly klient: Klient) {}
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
// Avoid duplication
if (this.findListenerIndex(event, callback) !== undefined) {
return this;
}
// Initialize listeners collection if not exists
this.listeners[event] = this.listeners[event] || [];
// Get reference to array containing listeners
const listeners = this.listeners[event];
// Build listener id (incremental)
const id = listeners.length ? Math.max(...listeners.map((l) => l.id)) + 1 : 0;
// Register the listener
listeners.push(new Listener(callback, priority, once, id));
// Listener are sorted in order they are defined
listeners.sort((a, b) => b.id - a.id);
// Sort by priority listeners binded to same event
// Lower priorities are first because we loop on collection from the end (see dispatch method)
listeners.sort((a, b) => a.priority - b.priority);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
return this.on(event, callback, priority, true);
}
off<T extends Event>(event: string, callback: Callback<T>): this {
const index = this.findListenerIndex(event, callback);
if (index !== undefined) {
this.listeners[event].splice(index, 1);
}
return this;
}
/**
* Invoke all listeners attached to given event.
*
* @param abortOnFailure - Specify if listener failures must abort dispatch process.
*/
async dispatch(e: Event, abortOnFailure = true): Promise<void> {
const event = (e.constructor as typeof Event).NAME;
const listeners = this.listeners[event] || [];
this.debug('start', e, listeners);
// Use inverse loop because we need to remove listeners callable once
for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {
listener = listeners[i];
if (Dispatcher.handleListenerSkipping(e, listener)) {
this.debug('skipped', e, listener);
continue;
}
if (listener.once) {
this.listeners[event].splice(i, 1);
}
try {
this.debug('invoking', e, listener);
// Wait for listener whose return a promise
await listener.invoke(e as never); // eslint-disable-line no-await-in-loop
this.debug('invoked', e, listener);
} catch (err) {
this.debug('failed', e, listener, err as Error);
if (abortOnFailure) {
// Reject promise on "abort on listener failure" strategy
return Promise.reject(err);
}
}
if (!e.dispatch.propagation) {
this.debug('stopped', e, listener);
// Stop listeners invokation
break;
}
}
this.debug('end', e, listeners);
return Promise.resolve();
}
protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {
const listeners = this.listeners[event] || [];
for (let i = 0, len = listeners.length; i < len; i += 1) {
if (listeners[i].callback === callback) {
return i;
}
}
return undefined;
}
protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void {
const { skipNextListeners, skipUntilListener } = event.dispatch;
if (skipNextListeners > 0) {
event.dispatch.skipNextListeners -= 1;
return true;
}
if (skipUntilListener) {
if (listener.id === skipUntilListener) {
event.dispatch.skipUntilListener = undefined;
return;
}
return true;
}
}
protected debug(
action: string,
relatedEvent: Event,
| handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void { |
if (relatedEvent instanceof DebugEvent || !this.klient.debug) {
return;
}
this.dispatch(new DebugEvent(action, relatedEvent, handler, error), false);
}
}
| src/services/dispatcher/dispatcher.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": " protected debug(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error?: Error | null): void;\n}\nexport {};",
"score": 0.8787024021148682
},
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "export default class Dispatcher {\n protected readonly klient: Klient;\n readonly listeners: Listeners;\n constructor(klient: Klient);\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;\n dispatch(e: Event, abortOnFailure?: boolean): Promise<void>;\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined;\n protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void;",
"score": 0.8609564304351807
},
{
"filename": "src/events/debug.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n static NAME = 'debug';\n constructor(\n public action: string,\n public relatedEvent: Event,\n public handler: Listener<never> | Listener<never>[],\n public error: Error | null\n ) {",
"score": 0.8445733189582825
},
{
"filename": "src/events/debug.d.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n action: string;\n relatedEvent: Event;\n handler: Listener<never> | Listener<never>[];\n error: Error | null;\n static NAME: string;\n constructor(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error: Error | null);\n}",
"score": 0.8356935977935791
},
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " constructor(urlOrParams?: P | string);\n get url(): string | undefined;\n get debug(): boolean;\n get factory(): RequestFactory;\n get dispatcher(): Dispatcher;\n extends(property: string, value: unknown, writable?: boolean): this;\n load(names?: string[]): this;\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;",
"score": 0.828795313835144
}
] | typescript | handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void { |
import Bag from './services/bag/bag';
import Dispatcher from './services/dispatcher/dispatcher';
import RequestFactory from './services/request/factory';
import Extensions from './extensions';
import { defaultParameters } from './parameters';
import type Event from './events/event';
import type Request from './services/request/request';
import type { KlientRequestConfig } from './services/request/request';
import type { Callback } from './services/dispatcher/dispatcher';
import type { Parameters } from './parameters';
export default class Klient<P extends Parameters = Parameters> {
readonly extensions: string[] = [];
readonly parameters = new Bag(defaultParameters);
readonly services = new Bag();
constructor(urlOrParams?: P | string) {
let parameters: Parameters = {};
if (typeof urlOrParams === 'string') {
parameters.url = urlOrParams;
} else if (urlOrParams && typeof urlOrParams === 'object') {
parameters = urlOrParams;
}
this.parameters.merge(parameters);
// prettier-ignore
this.services
.set('klient', this)
.set('dispatcher', new Dispatcher(this))
.set('factory', new RequestFactory(this));
this.load(this.parameters.get('extensions') as string[] | undefined);
}
/** === Common parameters === */
get url(): string | undefined {
return this.parameters.get('url');
}
get debug(): boolean {
return Boolean(this.parameters.get('debug'));
}
/** === Common services === */
get factory(): RequestFactory {
return this.services.get('factory') as RequestFactory;
}
get dispatcher(): Dispatcher {
return this.services.get('dispatcher') as Dispatcher;
}
/** === Extensions === */
extends(property: string, value: unknown, writable = false): this {
return Object.defineProperty(this, property, { writable, value });
}
load(names?: string[]): this {
Extensions.load(this, names);
return this;
}
/** === Dispatcher/Events === */
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
this.dispatcher.on(event, callback, priority, once);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
this.dispatcher.once(event, callback, priority);
return this;
}
off<T extends Event>(event: string, callback: Callback<T>): this {
this.dispatcher.off(event, callback);
return this;
}
/** === Request === */
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.factory.request(urlOrConfig);
}
| get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> { |
return this.request<T>({ ...config, method: 'GET', url });
}
post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'POST', url, data });
}
put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PUT', url, data });
}
patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PATCH', url, data });
}
delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'DELETE', url });
}
head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'HEAD', url });
}
options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'OPTIONS', url });
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
return this.factory.file(urlOrConfig);
}
cancelPendingRequests(): this {
this.factory.cancelPendingRequests();
return this;
}
isCancel(e: Error) {
return this.factory.isCancel(e);
}
}
| src/klient.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.createRequest<T>(urlOrConfig).execute();\n }\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {\n const config = deepmerge(\n { responseType: 'blob', context: { action: 'file' } },\n typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig\n );\n return this.request<Blob>(config).then(({ data }) => data);\n }",
"score": 0.8748428821563721
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " protected constructor(callback: RequestCallback) {\n super(callback);\n }\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {\n const callbacks = {} as PromiseCallbacks;\n const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {\n callbacks.resolve = resolve;\n callbacks.reject = reject;\n });\n request.klient = klient;",
"score": 0.8712481260299683
},
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "export default class Dispatcher {\n protected readonly klient: Klient;\n readonly listeners: Listeners;\n constructor(klient: Klient);\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;\n dispatch(e: Event, abortOnFailure?: boolean): Promise<void>;\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined;\n protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void;",
"score": 0.8674778342247009
},
{
"filename": "src/services/request/factory.d.ts",
"retrieved_chunk": " constructor(klient: Klient);\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n isCancel(e: Error): any;\n protected prepare(config: KlientRequestConfig): KlientRequestConfig;\n protected removePendingRequest(request: Request): void;\n}\nexport {};",
"score": 0.852407693862915
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " cancelPendingRequests(): this {\n for (let i = 0, len = this.requests.length; i < len; i += 1) {\n this.requests[i].cancel();\n }\n return this;\n }\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;\n const request = this.model.new<T>(this.prepare(config), this.klient);\n // Store request during pending state only",
"score": 0.8510082960128784
}
] | typescript | get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> { |
import axios from 'axios';
import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';
import RequestEvent from '../../events/request/request';
import RequestSuccessEvent from '../../events/request/success';
import RequestErrorEvent from '../../events/request/error';
import RequestDoneEvent from '../../events/request/done';
import RequestCancelEvent from '../../events/request/cancel';
import type Klient from '../..';
export type ResolveRequest = (response: AxiosResponse) => void;
export type RejectRequest = (error: AxiosError) => void;
export type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;
type PromiseCallbacks = { resolve: ResolveRequest; reject: RejectRequest };
type RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;
type RequestContext = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface KlientRequestConfig extends AxiosRequestConfig {
context?: RequestContext;
}
/**
* Request is a Promise object able to dispatch events before/after axios execution.
* Theses events allow to access and make action on request config/result at any step of execution.
* The Request will be resolved/rejected only after all events be dispatched.
*
* The events workflow is describe below :
*
* 1) RequestEvent (dispatched with abortOnFailure strategy)
* 2) Axios execution
* 2.1) Optional : RequestCancelEvent - only if request is cancelled (will reject promise and skip next events)
* 3) RequestSuccessEvent OR RequestErrorEvent
* 4) RequestDoneEvent
*/
export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {
context: RequestContext = { action: 'request' };
config: KlientRequestConfig = {};
result?: AxiosError | AxiosResponse;
// Allow override axios execution
handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;
protected klient!: Klient;
protected callbacks!: PromiseCallbacks;
protected readonly primaryEvent | = new RequestEvent<T>(this); |
protected readonly abortController = new AbortController();
protected constructor(callback: RequestCallback) {
super(callback);
}
static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {
const callbacks = {} as PromiseCallbacks;
const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {
callbacks.resolve = resolve;
callbacks.reject = reject;
});
request.klient = klient;
request.config = axiosConfig;
request.callbacks = callbacks;
request.config.signal = request.abortController.signal;
request.context = { ...request.context, ...context };
return request;
}
static isCancel(e: Error) {
return axios.isCancel(e);
}
cancel(): this {
this.abortController.abort();
return this;
}
execute(): this {
this.dispatcher
.dispatch(this.primaryEvent)
.then(() => {
this.doRequest();
})
.catch((e) => {
this.reject(e);
});
return this;
}
protected doRequest(): this {
if (!this.result) {
this.handler(this.config)
.then((r) => {
this.resolve(r);
})
.catch((e) => {
this.reject(e);
});
}
return this;
}
protected resolve(response: AxiosResponse<T>): Promise<void> {
this.result = response;
return this.dispatchResultEvent(RequestSuccessEvent).then(() => {
this.callbacks.resolve(this.result as AxiosResponse<T>);
});
}
protected reject(error: AxiosError): Promise<void> {
this.result = error;
return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {
this.callbacks.reject(this.result as AxiosError);
});
}
protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {
const event = new EventClass(this.primaryEvent);
return new Promise((resolve) => {
this.dispatcher.dispatch(event, false).then(() => {
if (event instanceof RequestCancelEvent) {
return resolve();
}
this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);
});
});
}
protected get dispatcher() {
return this.klient.dispatcher;
}
}
| src/services/request/request.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "export interface KlientRequestConfig extends AxiosRequestConfig {\n context?: RequestContext;\n}\nexport default class Request<T = unknown> extends Promise<AxiosResponse<T>> {\n context: RequestContext;\n config: KlientRequestConfig;\n result?: AxiosError | AxiosResponse;\n handler: (config: AxiosRequestConfig) => AxiosPromise<T>;\n protected klient: Klient;\n protected callbacks: PromiseCallbacks;",
"score": 0.9605117440223694
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.9277575016021729
},
{
"filename": "src/events/request/success.d.ts",
"retrieved_chunk": "import type { AxiosResponse } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestSuccessEvent<T = unknown> extends RequestEvent {\n relatedEvent: RequestEvent<T>;\n static NAME: string;\n constructor(relatedEvent: RequestEvent<T>);\n get response(): AxiosResponse<T>;\n get data(): T;\n}",
"score": 0.8697444796562195
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "}\nexport type ResolveRequest = (response: AxiosResponse) => void;\nexport type RejectRequest = (error: AxiosError) => void;\nexport type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;\ntype PromiseCallbacks = {\n resolve: ResolveRequest;\n reject: RejectRequest;\n};\ntype RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;\ntype RequestContext = Record<string, any>;",
"score": 0.8634941577911377
},
{
"filename": "src/events/request/error.d.ts",
"retrieved_chunk": "import type { AxiosError } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestErrorEvent<T = unknown> extends RequestEvent<T> {\n relatedEvent: RequestEvent<T>;\n static NAME: string;\n constructor(relatedEvent: RequestEvent<T>);\n get error(): AxiosError;\n get response(): import(\"axios\").AxiosResponse<unknown, any> | undefined;\n get data(): unknown;\n}",
"score": 0.8633307814598083
}
] | typescript | = new RequestEvent<T>(this); |
import { StdioOptions } from 'child_process'
import { FinalResults } from 'tap-parser'
import { BaseOpts } from '../base.js'
import { Spawn } from '../spawn.js'
import { TapPlugin, TestBase } from '../test-base.js'
export interface SpawnOpts extends BaseOpts {
cwd?: string
command?: string
args?: string[]
stdio?: StdioOptions
env?: { [k: string]: string } | typeof process.env
exitCode?: number | null
signal?: string | null
}
class SpawnPlugin {
#t: TestBase
constructor(t: TestBase) {
this.#t = t
}
spawn(cmd: string): Promise<FinalResults | null>
spawn(
cmd: string,
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args?: string | string[] | SpawnOpts,
options?: SpawnOpts | string,
name?: string
): Promise<FinalResults | null> {
if (typeof args === 'string') {
args = [args]
}
if (typeof options === 'string') {
name = options
options = {}
}
if (typeof args === 'object' && !Array.isArray(args)) {
options = args
args = []
}
options = options || {}
if (options.name === undefined) {
options.name = name
}
options.command = cmd
options.args = args
return this.#t.sub(Spawn, options, this.spawn)
}
}
const plugin: | TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
| src/plugin/spawn.ts | tapjs-core-edd7403 | [
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": "}\nconst plugin: TapPlugin<StdinPlugin> = (t: TestBase) =>\n new StdinPlugin(t)\nexport default plugin",
"score": 0.8420222997665405
},
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": "import { FinalResults } from 'tap-parser'\nimport parseTestArgs from '../parse-test-args.js'\nimport { Stdin, StdinOpts } from '../stdin.js'\nimport { TapPlugin, TestBase } from '../test-base.js'\nclass StdinPlugin {\n #t: TestBase\n constructor(t: TestBase) {\n this.#t = t\n }\n stdin(",
"score": 0.8048909902572632
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": "const plugin: TapPlugin<AfterEach> = (t: TestBase) => new AfterEach(t)\nexport default plugin",
"score": 0.7942471504211426
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ...args: TestArgs<Test>\n ): Promise<FinalResults | null>\n}\nconst applyPlugins = (base: Test): Test => {\n const ext: Plug[] = [\n ...plugins.map(p => p(base, base.options)),\n base,\n ]\n const getCache = new Map<any, any>()\n const t = new Proxy(base, {",
"score": 0.7940797805786133
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " return t\n}\nexport class Test extends TestBase {\n constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },",
"score": 0.7904829382896423
}
] | typescript | TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
|
|
import * as deepmerge from 'deepmerge';
import type { AxiosRequestConfig } from 'axios';
import type Klient from '../../klient';
import Request from './request';
import type { KlientRequestConfig } from './request';
export default class RequestFactory {
model = Request;
// Requests are stocked during their execution only.
readonly requests: Request[] = [];
constructor(protected readonly klient: Klient) {}
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.createRequest<T>(urlOrConfig).execute();
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
const config = deepmerge(
{ responseType: 'blob', context: { action: 'file' } },
typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig
);
return this.request<Blob>(config).then(({ data }) => data);
}
cancelPendingRequests(): this {
for (let i = 0, len = this.requests.length; i < len; i += 1) {
this.requests[i].cancel();
}
return this;
}
createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;
const request = this.model.new<T>(this.prepare(config), this.klient);
// Store request during pending state only
this.requests.push(request);
// Remove request when promise has been fulfilled
request
.then((r) => {
this.removePendingRequest(request);
return r;
})
.catch((e) => {
this.removePendingRequest(request);
return e;
});
return request;
}
isCancel(e: Error) {
return this.model.isCancel(e);
}
protected | prepare(config: KlientRequestConfig): KlientRequestConfig { |
return deepmerge.all([
{ baseURL: this.klient.url },
(this.klient.parameters.get('request') as AxiosRequestConfig) || {},
config
]);
}
protected removePendingRequest(request: Request) {
const i = this.requests.indexOf(request);
if (this.requests[i] instanceof Request) {
this.requests.splice(i, 1);
}
}
}
| src/services/request/factory.ts | klientjs-core-9a67a61 | [
{
"filename": "src/klient.ts",
"retrieved_chunk": " return this.factory.file(urlOrConfig);\n }\n cancelPendingRequests(): this {\n this.factory.cancelPendingRequests();\n return this;\n }\n isCancel(e: Error) {\n return this.factory.isCancel(e);\n }\n}",
"score": 0.890006959438324
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " request.config = axiosConfig;\n request.callbacks = callbacks;\n request.config.signal = request.abortController.signal;\n request.context = { ...request.context, ...context };\n return request;\n }\n static isCancel(e: Error) {\n return axios.isCancel(e);\n }\n cancel(): this {",
"score": 0.8617167472839355
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " protected constructor(callback: RequestCallback) {\n super(callback);\n }\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {\n const callbacks = {} as PromiseCallbacks;\n const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {\n callbacks.resolve = resolve;\n callbacks.reject = reject;\n });\n request.klient = klient;",
"score": 0.8534564971923828
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.8426937460899353
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " off<T extends Event>(event: string, callback: Callback<T>): this {\n this.dispatcher.off(event, callback);\n return this;\n }\n /** === Request === */\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.factory.request(urlOrConfig);\n }\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'GET', url });",
"score": 0.8424853086471558
}
] | typescript | prepare(config: KlientRequestConfig): KlientRequestConfig { |
import Event from '../../events/event';
import DebugEvent from '../../events/debug';
import Listener from './listener';
import type Klient from '../../klient';
export type Callback<T extends Event> = (e: T) => Promise<void> | void;
export type Listeners = { [event: string]: Listener<never>[] };
export default class Dispatcher {
readonly listeners: Listeners = {};
constructor(protected readonly klient: Klient) {}
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
// Avoid duplication
if (this.findListenerIndex(event, callback) !== undefined) {
return this;
}
// Initialize listeners collection if not exists
this.listeners[event] = this.listeners[event] || [];
// Get reference to array containing listeners
const listeners = this.listeners[event];
// Build listener id (incremental)
const id = listeners.length ? Math.max(...listeners.map((l) => l.id)) + 1 : 0;
// Register the listener
listeners.push(new Listener(callback, priority, once, id));
// Listener are sorted in order they are defined
listeners.sort((a, b) => b.id - a.id);
// Sort by priority listeners binded to same event
// Lower priorities are first because we loop on collection from the end (see dispatch method)
listeners.sort((a, b) => a.priority - b.priority);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
return this.on(event, callback, priority, true);
}
off<T extends Event>(event: string, callback: Callback<T>): this {
const index = this.findListenerIndex(event, callback);
if (index !== undefined) {
this.listeners[event].splice(index, 1);
}
return this;
}
/**
* Invoke all listeners attached to given event.
*
* @param abortOnFailure - Specify if listener failures must abort dispatch process.
*/
async dispatch(e: Event, abortOnFailure = true): Promise<void> {
const event = (e.constructor as typeof Event).NAME;
const listeners = this.listeners[event] || [];
this.debug('start', e, listeners);
// Use inverse loop because we need to remove listeners callable once
for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {
listener = listeners[i];
if (Dispatcher.handleListenerSkipping(e, listener)) {
this.debug('skipped', e, listener);
continue;
}
if (listener.once) {
this.listeners[event].splice(i, 1);
}
try {
this.debug('invoking', e, listener);
// Wait for listener whose return a promise
await listener.invoke(e as never); // eslint-disable-line no-await-in-loop
this.debug('invoked', e, listener);
} catch (err) {
this.debug('failed', e, listener, err as Error);
if (abortOnFailure) {
// Reject promise on "abort on listener failure" strategy
return Promise.reject(err);
}
}
if (!e.dispatch.propagation) {
this.debug('stopped', e, listener);
// Stop listeners invokation
break;
}
}
this.debug('end', e, listeners);
return Promise.resolve();
}
protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {
const listeners = this.listeners[event] || [];
for (let i = 0, len = listeners.length; i < len; i += 1) {
if (listeners[i].callback === callback) {
return i;
}
}
return undefined;
}
| protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void { |
const { skipNextListeners, skipUntilListener } = event.dispatch;
if (skipNextListeners > 0) {
event.dispatch.skipNextListeners -= 1;
return true;
}
if (skipUntilListener) {
if (listener.id === skipUntilListener) {
event.dispatch.skipUntilListener = undefined;
return;
}
return true;
}
}
protected debug(
action: string,
relatedEvent: Event,
handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void {
if (relatedEvent instanceof DebugEvent || !this.klient.debug) {
return;
}
this.dispatch(new DebugEvent(action, relatedEvent, handler, error), false);
}
}
| src/services/dispatcher/dispatcher.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n let index: number | null = null;\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n index = i;\n break;\n }\n }\n if (index === null) {",
"score": 0.8921355605125427
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": "const watchers: Record<string, Record<string, WatcherItem[]>> = {};\n/**\n * Determine the instance ID for given watchable object.\n */\nfunction getInstanceId(watchable: Watchable) {\n const ids = Object.keys(instances);\n let id = null;\n for (let i = 0, len = ids.length; i < len; i += 1) {\n if (instances[ids[i]] === watchable) {\n id = ids[i];",
"score": 0.867789626121521
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " * Register callback to listen changes made on specific path of given watchable object\n */\nexport function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T {\n const id = getInstanceId(watchable);\n watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n return watchable;\n }",
"score": 0.8550965785980225
},
{
"filename": "src/extensions.ts",
"retrieved_chunk": "import type Klient from '.';\nexport type Extension = {\n name: string;\n initialize: (klient: Klient) => void;\n};\nclass Extensions extends Array<Extension> {\n load(klient: Klient, extensions?: string[]): void {\n for (let i = 0, len = this.length; i < len; i += 1) {\n const { name, initialize } = this[i];\n if (!klient.extensions.includes(name) && (!extensions || extensions.includes(name))) {",
"score": 0.8309459686279297
},
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "export default class Dispatcher {\n protected readonly klient: Klient;\n readonly listeners: Listeners;\n constructor(klient: Klient);\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;\n dispatch(e: Event, abortOnFailure?: boolean): Promise<void>;\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined;\n protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void;",
"score": 0.8203803300857544
}
] | typescript | protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void { |
import Event from '../../events/event';
import DebugEvent from '../../events/debug';
import Listener from './listener';
import type Klient from '../../klient';
export type Callback<T extends Event> = (e: T) => Promise<void> | void;
export type Listeners = { [event: string]: Listener<never>[] };
export default class Dispatcher {
readonly listeners: Listeners = {};
constructor(protected readonly klient: Klient) {}
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
// Avoid duplication
if (this.findListenerIndex(event, callback) !== undefined) {
return this;
}
// Initialize listeners collection if not exists
this.listeners[event] = this.listeners[event] || [];
// Get reference to array containing listeners
const listeners = this.listeners[event];
// Build listener id (incremental)
const id = listeners.length ? Math.max(...listeners.map((l) => l.id)) + 1 : 0;
// Register the listener
listeners.push(new Listener(callback, priority, once, id));
// Listener are sorted in order they are defined
listeners.sort((a, b) => b.id - a.id);
// Sort by priority listeners binded to same event
// Lower priorities are first because we loop on collection from the end (see dispatch method)
listeners.sort((a, b) => a.priority - b.priority);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
return this.on(event, callback, priority, true);
}
off<T extends Event>(event: string, callback: Callback<T>): this {
const index = this.findListenerIndex(event, callback);
if (index !== undefined) {
this.listeners[event].splice(index, 1);
}
return this;
}
/**
* Invoke all listeners attached to given event.
*
* @param abortOnFailure - Specify if listener failures must abort dispatch process.
*/
async dispatch(e: Event, abortOnFailure = true): Promise<void> {
const event = (e.constructor as typeof Event).NAME;
const listeners = this.listeners[event] || [];
this.debug('start', e, listeners);
// Use inverse loop because we need to remove listeners callable once
for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {
listener = listeners[i];
if (Dispatcher.handleListenerSkipping(e, listener)) {
this.debug('skipped', e, listener);
continue;
}
if (listener.once) {
this.listeners[event].splice(i, 1);
}
try {
this.debug('invoking', e, listener);
// Wait for listener whose return a promise
await listener.invoke(e as never); // eslint-disable-line no-await-in-loop
this.debug('invoked', e, listener);
} catch (err) {
this.debug('failed', e, listener, err as Error);
if (abortOnFailure) {
// Reject promise on "abort on listener failure" strategy
return Promise.reject(err);
}
}
if (!e.dispatch.propagation) {
this.debug('stopped', e, listener);
// Stop listeners invokation
break;
}
}
this.debug('end', e, listeners);
return Promise.resolve();
}
protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {
const listeners = this.listeners[event] || [];
for (let i = 0, len = listeners.length; i < len; i += 1) {
if (listeners[i].callback === callback) {
return i;
}
}
return undefined;
}
protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void {
const { skipNextListeners, skipUntilListener } = event.dispatch;
if (skipNextListeners > 0) {
event.dispatch.skipNextListeners -= 1;
return true;
}
if (skipUntilListener) {
if (listener.id === skipUntilListener) {
event.dispatch.skipUntilListener = undefined;
return;
}
return true;
}
}
protected debug(
action: string,
relatedEvent: Event,
handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void {
if (relatedEvent | instanceof DebugEvent || !this.klient.debug) { |
return;
}
this.dispatch(new DebugEvent(action, relatedEvent, handler, error), false);
}
}
| src/services/dispatcher/dispatcher.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "export default class Dispatcher {\n protected readonly klient: Klient;\n readonly listeners: Listeners;\n constructor(klient: Klient);\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;\n dispatch(e: Event, abortOnFailure?: boolean): Promise<void>;\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined;\n protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void;",
"score": 0.8620907068252563
},
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": " protected debug(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error?: Error | null): void;\n}\nexport {};",
"score": 0.8555719256401062
},
{
"filename": "src/events/debug.d.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n action: string;\n relatedEvent: Event;\n handler: Listener<never> | Listener<never>[];\n error: Error | null;\n static NAME: string;\n constructor(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error: Error | null);\n}",
"score": 0.8412939310073853
},
{
"filename": "src/events/debug.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n static NAME = 'debug';\n constructor(\n public action: string,\n public relatedEvent: Event,\n public handler: Listener<never> | Listener<never>[],\n public error: Error | null\n ) {",
"score": 0.8389084935188293
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " off<T extends Event>(event: string, callback: Callback<T>): this {\n this.dispatcher.off(event, callback);\n return this;\n }\n /** === Request === */\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.factory.request(urlOrConfig);\n }\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'GET', url });",
"score": 0.8198673725128174
}
] | typescript | instanceof DebugEvent || !this.klient.debug) { |
import * as deepmerge from 'deepmerge';
import * as objectPath from 'object-path';
import { isPlainObject, isPlainArray, softClone } from '../../toolbox/object';
import { watch, unwatch, invokeWatchers, getWatchers, Watchable, WatchCallback } from './watch';
type BagItems = Record<string, unknown>;
export default class Bag implements BagItems, Watchable {
[x: string]: unknown;
constructor(items: BagItems = {}) {
Object.keys(items).forEach((key) => {
this[key] = items[key];
});
}
get watchers() {
return getWatchers(this);
}
has(path: string) {
return objectPath.get(this, path) !== undefined;
}
get(path: string) {
return objectPath.get(this.all(), path);
}
all() {
return softClone(this);
}
set(path: string, value: unknown): this {
const prevState = this.all();
objectPath.set(this, path, value);
return invokeWatchers(this, this.all(), prevState);
}
merge(...items: BagItems[]): this {
const prevState = this.all();
const nextState = deepmerge.all<BagItems>([this.all(), ...items], {
arrayMerge: (_destinationArray: unknown[], sourceArray: unknown[]) => sourceArray,
isMergeableObject: (o: object) => isPlainArray(o) || isPlainObject(o)
});
Object.keys(nextState).forEach((key) => {
this[key] = nextState[key];
});
return invokeWatchers(this, nextState, prevState);
}
watch(path: | string, onChange: WatchCallback, deep = false): this { |
return watch(this, path, onChange, deep);
}
unwatch(path: string, onChange: WatchCallback): this {
return unwatch(this, path, onChange);
}
}
| src/services/bag/bag.ts | klientjs-core-9a67a61 | [
{
"filename": "src/toolbox/object.ts",
"retrieved_chunk": "export function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.constructor.name === 'Array';\n}\n/**\n * Deep clone object properties (traverse only native plain objects)\n */\nexport function softClone(obj: AnyObject) {\n const values: AnyObject = {};\n Object.keys(obj).forEach((prop) => {\n const value = obj[prop];",
"score": 0.8361132144927979
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " }\n collection.push({ callback: onChange, deep });\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Unregister watcher callback for given path\n */\nexport function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T {\n const id = getInstanceId(watchable);",
"score": 0.8352929353713989
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " * Register callback to listen changes made on specific path of given watchable object\n */\nexport function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T {\n const id = getInstanceId(watchable);\n watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n return watchable;\n }",
"score": 0.8301877975463867
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " const watched = getWatchers(watchable);\n const watchedPaths = Object.keys(watched);\n if (watchedPaths.length === 0) {\n return watchable;\n }\n const changedPaths = deepDiff(prev, next)?.map((diff) => (diff.path as string[]).join('.'));\n const invoked: WatcherItem[] = [];\n changedPaths?.forEach((path) => {\n watchedPaths.forEach((targetPath) => {\n if (!path.startsWith(targetPath)) return;",
"score": 0.8283509016036987
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " return watchable;\n }\n collection.splice(index, 1);\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Invoke all watchers attached to given watchable object with prev and next state\n */\nexport function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T {",
"score": 0.8274809122085571
}
] | typescript | string, onChange: WatchCallback, deep = false): this { |
import { StdioOptions } from 'child_process'
import { FinalResults } from 'tap-parser'
import { BaseOpts } from '../base.js'
import { Spawn } from '../spawn.js'
import { TapPlugin, TestBase } from '../test-base.js'
export interface SpawnOpts extends BaseOpts {
cwd?: string
command?: string
args?: string[]
stdio?: StdioOptions
env?: { [k: string]: string } | typeof process.env
exitCode?: number | null
signal?: string | null
}
class SpawnPlugin {
#t: TestBase
constructor(t: TestBase) {
this.#t = t
}
spawn(cmd: string): Promise<FinalResults | null>
spawn(
cmd: string,
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args: string | string[],
options: SpawnOpts,
name?: string
): Promise<FinalResults | null>
spawn(
cmd: string,
args?: string | string[] | SpawnOpts,
options?: SpawnOpts | string,
name?: string
): Promise<FinalResults | null> {
if (typeof args === 'string') {
args = [args]
}
if (typeof options === 'string') {
name = options
options = {}
}
if (typeof args === 'object' && !Array.isArray(args)) {
options = args
args = []
}
options = options || {}
| if (options.name === undefined) { |
options.name = name
}
options.command = cmd
options.args = args
return this.#t.sub(Spawn, options, this.spawn)
}
}
const plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>
new SpawnPlugin(t)
export default plugin
| src/plugin/spawn.ts | tapjs-core-edd7403 | [
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " (typeof arg === 'string' || typeof arg === 'number')\n )\n name = '' + arg\n else if (arg && typeof arg === 'object') {\n extra = arg\n if (name === undefined) name = null\n } else if (typeof arg === 'function') {\n if (extra === undefined) extra = {}\n if (name === undefined) name = null\n cb = arg",
"score": 0.9045265913009644
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " }\n options = options || {}\n const cwd =\n typeof options.cwd === 'string'\n ? options.cwd\n : process.cwd()\n const args = options.args || []\n options.name =\n options.name || Spawn.procName(cwd, command, args)\n super(options)",
"score": 0.8617709875106812
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // if it's null or an object, inherit from it. otherwise, copy it.\n const ctx = options.context\n if (ctx !== undefined) {\n this.context =\n typeof ctx === 'object' ? Object.create(ctx) : ctx\n } else {\n this.context = null\n }\n this.bail = !!options.bail\n this.strict = !!options.strict",
"score": 0.8493785858154297
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " let extra: { [k: string]: any } | null | undefined =\n undefined\n let cb: ((t: T) => any) | null | undefined = undefined\n // this only works if it's literally the 4th argument.\n // used internally.\n const defaultName = args[3] || ''\n for (let i = 0; i < 3 && i < args.length; i++) {\n const arg = args[i]\n if (\n name === undefined &&",
"score": 0.8445558547973633
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " } else if (arg === false) {\n // it's handy while developing to put a ! in front of a\n // function to temporarily make a test todo\n continue\n } else if (typeof arg !== 'undefined')\n throw new TypeError(\n 'unknown argument passed to parseTestArgs: ' +\n typeof arg\n )\n }",
"score": 0.8398248553276062
}
] | typescript | if (options.name === undefined) { |
import * as deepmerge from 'deepmerge';
import * as objectPath from 'object-path';
import { isPlainObject, isPlainArray, softClone } from '../../toolbox/object';
import { watch, unwatch, invokeWatchers, getWatchers, Watchable, WatchCallback } from './watch';
type BagItems = Record<string, unknown>;
export default class Bag implements BagItems, Watchable {
[x: string]: unknown;
constructor(items: BagItems = {}) {
Object.keys(items).forEach((key) => {
this[key] = items[key];
});
}
get watchers() {
return getWatchers(this);
}
has(path: string) {
return objectPath.get(this, path) !== undefined;
}
get(path: string) {
return objectPath.get(this.all(), path);
}
all() {
return softClone(this);
}
set(path: string, value: unknown): this {
const prevState = this.all();
objectPath.set(this, path, value);
return invokeWatchers(this, this.all(), prevState);
}
merge(...items: BagItems[]): this {
const prevState = this.all();
const nextState = deepmerge.all<BagItems>([this.all(), ...items], {
arrayMerge: (_destinationArray: unknown[], sourceArray: unknown[]) => sourceArray,
isMergeableObject: (o: object) => isPlainArray(o) || isPlainObject(o)
});
Object.keys(nextState).forEach((key) => {
this[key] = nextState[key];
});
return invokeWatchers(this, nextState, prevState);
}
watch(path: string, onChange: WatchCallback, deep = false): this {
| return watch(this, path, onChange, deep); |
}
unwatch(path: string, onChange: WatchCallback): this {
return unwatch(this, path, onChange);
}
}
| src/services/bag/bag.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " * Register callback to listen changes made on specific path of given watchable object\n */\nexport function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T {\n const id = getInstanceId(watchable);\n watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n return watchable;\n }",
"score": 0.8485429286956787
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " }\n collection.push({ callback: onChange, deep });\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Unregister watcher callback for given path\n */\nexport function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T {\n const id = getInstanceId(watchable);",
"score": 0.8413543105125427
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " return watchable;\n }\n collection.splice(index, 1);\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Invoke all watchers attached to given watchable object with prev and next state\n */\nexport function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T {",
"score": 0.8316367864608765
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " const watched = getWatchers(watchable);\n const watchedPaths = Object.keys(watched);\n if (watchedPaths.length === 0) {\n return watchable;\n }\n const changedPaths = deepDiff(prev, next)?.map((diff) => (diff.path as string[]).join('.'));\n const invoked: WatcherItem[] = [];\n changedPaths?.forEach((path) => {\n watchedPaths.forEach((targetPath) => {\n if (!path.startsWith(targetPath)) return;",
"score": 0.8300982117652893
},
{
"filename": "src/toolbox/object.ts",
"retrieved_chunk": "export function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.constructor.name === 'Array';\n}\n/**\n * Deep clone object properties (traverse only native plain objects)\n */\nexport function softClone(obj: AnyObject) {\n const values: AnyObject = {};\n Object.keys(obj).forEach((prop) => {\n const value = obj[prop];",
"score": 0.8252516984939575
}
] | typescript | return watch(this, path, onChange, deep); |
import * as deepmerge from 'deepmerge';
import * as objectPath from 'object-path';
import { isPlainObject, isPlainArray, softClone } from '../../toolbox/object';
import { watch, unwatch, invokeWatchers, getWatchers, Watchable, WatchCallback } from './watch';
type BagItems = Record<string, unknown>;
export default class Bag implements BagItems, Watchable {
[x: string]: unknown;
constructor(items: BagItems = {}) {
Object.keys(items).forEach((key) => {
this[key] = items[key];
});
}
get watchers() {
return getWatchers(this);
}
has(path: string) {
return objectPath.get(this, path) !== undefined;
}
get(path: string) {
return objectPath.get(this.all(), path);
}
all() {
return softClone(this);
}
set(path: string, value: unknown): this {
const prevState = this.all();
objectPath.set(this, path, value);
return invokeWatchers(this, this.all(), prevState);
}
merge(...items: BagItems[]): this {
const prevState = this.all();
const nextState = deepmerge.all<BagItems>([this.all(), ...items], {
arrayMerge: (_destinationArray: unknown[], sourceArray: unknown[]) => sourceArray,
isMergeableObject: (o: object) => isPlainArray(o) || isPlainObject(o)
});
Object.keys(nextState).forEach((key) => {
this[key] = nextState[key];
});
return invokeWatchers(this, nextState, prevState);
}
watch(path: string, onChange | : WatchCallback, deep = false): this { |
return watch(this, path, onChange, deep);
}
unwatch(path: string, onChange: WatchCallback): this {
return unwatch(this, path, onChange);
}
}
| src/services/bag/bag.ts | klientjs-core-9a67a61 | [
{
"filename": "src/toolbox/object.ts",
"retrieved_chunk": "export function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.constructor.name === 'Array';\n}\n/**\n * Deep clone object properties (traverse only native plain objects)\n */\nexport function softClone(obj: AnyObject) {\n const values: AnyObject = {};\n Object.keys(obj).forEach((prop) => {\n const value = obj[prop];",
"score": 0.83724045753479
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " }\n collection.push({ callback: onChange, deep });\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Unregister watcher callback for given path\n */\nexport function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T {\n const id = getInstanceId(watchable);",
"score": 0.8347396850585938
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " * Register callback to listen changes made on specific path of given watchable object\n */\nexport function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T {\n const id = getInstanceId(watchable);\n watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n return watchable;\n }",
"score": 0.8291579484939575
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " const watched = getWatchers(watchable);\n const watchedPaths = Object.keys(watched);\n if (watchedPaths.length === 0) {\n return watchable;\n }\n const changedPaths = deepDiff(prev, next)?.map((diff) => (diff.path as string[]).join('.'));\n const invoked: WatcherItem[] = [];\n changedPaths?.forEach((path) => {\n watchedPaths.forEach((targetPath) => {\n if (!path.startsWith(targetPath)) return;",
"score": 0.826576828956604
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " return watchable;\n }\n collection.splice(index, 1);\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Invoke all watchers attached to given watchable object with prev and next state\n */\nexport function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T {",
"score": 0.8263571262359619
}
] | typescript | : WatchCallback, deep = false): this { |
import Bag from './services/bag/bag';
import Dispatcher from './services/dispatcher/dispatcher';
import RequestFactory from './services/request/factory';
import Extensions from './extensions';
import { defaultParameters } from './parameters';
import type Event from './events/event';
import type Request from './services/request/request';
import type { KlientRequestConfig } from './services/request/request';
import type { Callback } from './services/dispatcher/dispatcher';
import type { Parameters } from './parameters';
export default class Klient<P extends Parameters = Parameters> {
readonly extensions: string[] = [];
readonly parameters = new Bag(defaultParameters);
readonly services = new Bag();
constructor(urlOrParams?: P | string) {
let parameters: Parameters = {};
if (typeof urlOrParams === 'string') {
parameters.url = urlOrParams;
} else if (urlOrParams && typeof urlOrParams === 'object') {
parameters = urlOrParams;
}
this.parameters.merge(parameters);
// prettier-ignore
this.services
.set('klient', this)
.set('dispatcher', new Dispatcher(this))
.set('factory', new RequestFactory(this));
this.load(this.parameters.get('extensions') as string[] | undefined);
}
/** === Common parameters === */
get url(): string | undefined {
return this.parameters.get('url');
}
get debug(): boolean {
return Boolean(this.parameters.get('debug'));
}
/** === Common services === */
get factory(): RequestFactory {
return this.services.get('factory') as RequestFactory;
}
| get dispatcher(): Dispatcher { |
return this.services.get('dispatcher') as Dispatcher;
}
/** === Extensions === */
extends(property: string, value: unknown, writable = false): this {
return Object.defineProperty(this, property, { writable, value });
}
load(names?: string[]): this {
Extensions.load(this, names);
return this;
}
/** === Dispatcher/Events === */
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
this.dispatcher.on(event, callback, priority, once);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
this.dispatcher.once(event, callback, priority);
return this;
}
off<T extends Event>(event: string, callback: Callback<T>): this {
this.dispatcher.off(event, callback);
return this;
}
/** === Request === */
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.factory.request(urlOrConfig);
}
get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'GET', url });
}
post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'POST', url, data });
}
put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PUT', url, data });
}
patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PATCH', url, data });
}
delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'DELETE', url });
}
head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'HEAD', url });
}
options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'OPTIONS', url });
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
return this.factory.file(urlOrConfig);
}
cancelPendingRequests(): this {
this.factory.cancelPendingRequests();
return this;
}
isCancel(e: Error) {
return this.factory.isCancel(e);
}
}
| src/klient.ts | klientjs-core-9a67a61 | [
{
"filename": "src/events/request/done.ts",
"retrieved_chunk": " }\n get result() {\n return this.request.result;\n }\n get data() {\n return this.relatedEvent.data;\n }\n}",
"score": 0.8106725215911865
},
{
"filename": "src/services/dispatcher/dispatcher.ts",
"retrieved_chunk": " if (!e.dispatch.propagation) {\n this.debug('stopped', e, listener);\n // Stop listeners invokation\n break;\n }\n }\n this.debug('end', e, listeners);\n return Promise.resolve();\n }\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {",
"score": 0.7922857999801636
},
{
"filename": "src/events/request/request.ts",
"retrieved_chunk": " }\n get context() {\n return this.request.context;\n }\n}",
"score": 0.7847484350204468
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " cancelPendingRequests(): this {\n for (let i = 0, len = this.requests.length; i < len; i += 1) {\n this.requests[i].cancel();\n }\n return this;\n }\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;\n const request = this.model.new<T>(this.prepare(config), this.klient);\n // Store request during pending state only",
"score": 0.7833847999572754
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " this.reject(e);\n });\n return this;\n }\n protected doRequest(): this {\n if (!this.result) {\n this.handler(this.config)\n .then((r) => {\n this.resolve(r);\n })",
"score": 0.7776473164558411
}
] | typescript | get dispatcher(): Dispatcher { |
import * as deepmerge from 'deepmerge';
import type { AxiosRequestConfig } from 'axios';
import type Klient from '../../klient';
import Request from './request';
import type { KlientRequestConfig } from './request';
export default class RequestFactory {
model = Request;
// Requests are stocked during their execution only.
readonly requests: Request[] = [];
constructor(protected readonly klient: Klient) {}
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.createRequest<T>(urlOrConfig).execute();
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
const config = deepmerge(
{ responseType: 'blob', context: { action: 'file' } },
typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig
);
return this.request<Blob>(config).then(({ data }) => data);
}
cancelPendingRequests(): this {
for (let i = 0, len = this.requests.length; i < len; i += 1) {
this.requests[i].cancel();
}
return this;
}
createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;
const request = this.model.new<T>(this.prepare(config), this.klient);
// Store request during pending state only
this.requests.push(request);
// Remove request when promise has been fulfilled
request
.then((r) => {
this.removePendingRequest(request);
return r;
})
.catch((e) => {
this.removePendingRequest(request);
return e;
});
return request;
}
isCancel(e: Error) {
return this.model.isCancel(e);
}
protected prepare | (config: KlientRequestConfig): KlientRequestConfig { |
return deepmerge.all([
{ baseURL: this.klient.url },
(this.klient.parameters.get('request') as AxiosRequestConfig) || {},
config
]);
}
protected removePendingRequest(request: Request) {
const i = this.requests.indexOf(request);
if (this.requests[i] instanceof Request) {
this.requests.splice(i, 1);
}
}
}
| src/services/request/factory.ts | klientjs-core-9a67a61 | [
{
"filename": "src/klient.ts",
"retrieved_chunk": " return this.factory.file(urlOrConfig);\n }\n cancelPendingRequests(): this {\n this.factory.cancelPendingRequests();\n return this;\n }\n isCancel(e: Error) {\n return this.factory.isCancel(e);\n }\n}",
"score": 0.8949437141418457
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " request.config = axiosConfig;\n request.callbacks = callbacks;\n request.config.signal = request.abortController.signal;\n request.context = { ...request.context, ...context };\n return request;\n }\n static isCancel(e: Error) {\n return axios.isCancel(e);\n }\n cancel(): this {",
"score": 0.8580551147460938
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " protected constructor(callback: RequestCallback) {\n super(callback);\n }\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {\n const callbacks = {} as PromiseCallbacks;\n const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {\n callbacks.resolve = resolve;\n callbacks.reject = reject;\n });\n request.klient = klient;",
"score": 0.8434045314788818
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " });\n }\n protected reject(error: AxiosError): Promise<void> {\n this.result = error;\n return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {\n this.callbacks.reject(this.result as AxiosError);\n });\n }\n protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {\n const event = new EventClass(this.primaryEvent);",
"score": 0.8415833711624146
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.839574933052063
}
] | typescript | (config: KlientRequestConfig): KlientRequestConfig { |
import * as deepmerge from 'deepmerge';
import * as objectPath from 'object-path';
import { isPlainObject, isPlainArray, softClone } from '../../toolbox/object';
import { watch, unwatch, invokeWatchers, getWatchers, Watchable, WatchCallback } from './watch';
type BagItems = Record<string, unknown>;
export default class Bag implements BagItems, Watchable {
[x: string]: unknown;
constructor(items: BagItems = {}) {
Object.keys(items).forEach((key) => {
this[key] = items[key];
});
}
get watchers() {
return getWatchers(this);
}
has(path: string) {
return objectPath.get(this, path) !== undefined;
}
get(path: string) {
return objectPath.get(this.all(), path);
}
all() {
return softClone(this);
}
set(path: string, value: unknown): this {
const prevState = this.all();
objectPath.set(this, path, value);
return invokeWatchers(this, this.all(), prevState);
}
merge(...items: BagItems[]): this {
const prevState = this.all();
const nextState = deepmerge.all<BagItems>([this.all(), ...items], {
arrayMerge: (_destinationArray: unknown[], sourceArray: unknown[]) => sourceArray,
isMergeableObject: (o: object) => isPlainArray(o) || isPlainObject(o)
});
Object.keys(nextState).forEach((key) => {
this[key] = nextState[key];
});
return invokeWatchers(this, nextState, prevState);
}
watch(path: string, | onChange: WatchCallback, deep = false): this { |
return watch(this, path, onChange, deep);
}
unwatch(path: string, onChange: WatchCallback): this {
return unwatch(this, path, onChange);
}
}
| src/services/bag/bag.ts | klientjs-core-9a67a61 | [
{
"filename": "src/toolbox/object.ts",
"retrieved_chunk": "export function isPlainArray(value: unknown) {\n return Array.isArray(value) && value.constructor.name === 'Array';\n}\n/**\n * Deep clone object properties (traverse only native plain objects)\n */\nexport function softClone(obj: AnyObject) {\n const values: AnyObject = {};\n Object.keys(obj).forEach((prop) => {\n const value = obj[prop];",
"score": 0.8363427519798279
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " }\n collection.push({ callback: onChange, deep });\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Unregister watcher callback for given path\n */\nexport function unwatch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback): T {\n const id = getInstanceId(watchable);",
"score": 0.8331025242805481
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " * Register callback to listen changes made on specific path of given watchable object\n */\nexport function watch<T extends Watchable>(watchable: T, path: string, onChange: WatchCallback, deep: boolean): T {\n const id = getInstanceId(watchable);\n watchers[id] = getWatchers(watchable);\n const collection = watchers[id][path] || [];\n for (let i = 0, len = collection.length; i < len; i += 1) {\n if (collection[i].callback === onChange) {\n return watchable;\n }",
"score": 0.8323320150375366
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " const watched = getWatchers(watchable);\n const watchedPaths = Object.keys(watched);\n if (watchedPaths.length === 0) {\n return watchable;\n }\n const changedPaths = deepDiff(prev, next)?.map((diff) => (diff.path as string[]).join('.'));\n const invoked: WatcherItem[] = [];\n changedPaths?.forEach((path) => {\n watchedPaths.forEach((targetPath) => {\n if (!path.startsWith(targetPath)) return;",
"score": 0.8295555710792542
},
{
"filename": "src/services/bag/watch.ts",
"retrieved_chunk": " return watchable;\n }\n collection.splice(index, 1);\n watchers[id][path] = collection;\n return watchable;\n}\n/**\n * Invoke all watchers attached to given watchable object with prev and next state\n */\nexport function invokeWatchers<T extends Watchable>(watchable: T, next: object, prev: object): T {",
"score": 0.82573002576828
}
] | typescript | onChange: WatchCallback, deep = false): this { |
import Bag from './services/bag/bag';
import Dispatcher from './services/dispatcher/dispatcher';
import RequestFactory from './services/request/factory';
import Extensions from './extensions';
import { defaultParameters } from './parameters';
import type Event from './events/event';
import type Request from './services/request/request';
import type { KlientRequestConfig } from './services/request/request';
import type { Callback } from './services/dispatcher/dispatcher';
import type { Parameters } from './parameters';
export default class Klient<P extends Parameters = Parameters> {
readonly extensions: string[] = [];
readonly parameters = new Bag(defaultParameters);
readonly services = new Bag();
constructor(urlOrParams?: P | string) {
let parameters: Parameters = {};
if (typeof urlOrParams === 'string') {
parameters.url = urlOrParams;
} else if (urlOrParams && typeof urlOrParams === 'object') {
parameters = urlOrParams;
}
this.parameters.merge(parameters);
// prettier-ignore
this.services
.set('klient', this)
.set('dispatcher', new Dispatcher(this))
.set('factory', new RequestFactory(this));
this.load(this.parameters.get('extensions') as string[] | undefined);
}
/** === Common parameters === */
get url(): string | undefined {
return this.parameters.get('url');
}
get debug(): boolean {
return Boolean(this.parameters.get('debug'));
}
/** === Common services === */
get factory(): RequestFactory {
return this.services.get('factory') as RequestFactory;
}
get dispatcher(): Dispatcher {
return this.services.get('dispatcher') as Dispatcher;
}
/** === Extensions === */
extends(property: string, value: unknown, writable = false): this {
return Object.defineProperty(this, property, { writable, value });
}
load(names?: string[]): this {
Extensions.load(this, names);
return this;
}
/** === Dispatcher/Events === */
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
this.dispatcher.on(event, callback, priority, once);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
this.dispatcher.once(event, callback, priority);
return this;
}
off<T extends Event>(event: string, callback: Callback<T>): this {
this.dispatcher.off(event, callback);
return this;
}
/** === Request === */
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.factory. | request(urlOrConfig); |
}
get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'GET', url });
}
post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'POST', url, data });
}
put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PUT', url, data });
}
patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PATCH', url, data });
}
delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'DELETE', url });
}
head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'HEAD', url });
}
options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'OPTIONS', url });
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
return this.factory.file(urlOrConfig);
}
cancelPendingRequests(): this {
this.factory.cancelPendingRequests();
return this;
}
isCancel(e: Error) {
return this.factory.isCancel(e);
}
}
| src/klient.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " protected constructor(callback: RequestCallback) {\n super(callback);\n }\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {\n const callbacks = {} as PromiseCallbacks;\n const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {\n callbacks.resolve = resolve;\n callbacks.reject = reject;\n });\n request.klient = klient;",
"score": 0.8707063794136047
},
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "export default class Dispatcher {\n protected readonly klient: Klient;\n readonly listeners: Listeners;\n constructor(klient: Klient);\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;\n dispatch(e: Event, abortOnFailure?: boolean): Promise<void>;\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined;\n protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void;",
"score": 0.8578356504440308
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.createRequest<T>(urlOrConfig).execute();\n }\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {\n const config = deepmerge(\n { responseType: 'blob', context: { action: 'file' } },\n typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig\n );\n return this.request<Blob>(config).then(({ data }) => data);\n }",
"score": 0.8576709032058716
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.8468166589736938
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " cancelPendingRequests(): this {\n for (let i = 0, len = this.requests.length; i < len; i += 1) {\n this.requests[i].cancel();\n }\n return this;\n }\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;\n const request = this.model.new<T>(this.prepare(config), this.klient);\n // Store request during pending state only",
"score": 0.8463121652603149
}
] | typescript | request(urlOrConfig); |
import Bag from './services/bag/bag';
import Dispatcher from './services/dispatcher/dispatcher';
import RequestFactory from './services/request/factory';
import Extensions from './extensions';
import { defaultParameters } from './parameters';
import type Event from './events/event';
import type Request from './services/request/request';
import type { KlientRequestConfig } from './services/request/request';
import type { Callback } from './services/dispatcher/dispatcher';
import type { Parameters } from './parameters';
export default class Klient<P extends Parameters = Parameters> {
readonly extensions: string[] = [];
readonly parameters = new Bag(defaultParameters);
readonly services = new Bag();
constructor(urlOrParams?: P | string) {
let parameters: Parameters = {};
if (typeof urlOrParams === 'string') {
parameters.url = urlOrParams;
} else if (urlOrParams && typeof urlOrParams === 'object') {
parameters = urlOrParams;
}
this.parameters.merge(parameters);
// prettier-ignore
this.services
.set('klient', this)
.set('dispatcher', new Dispatcher(this))
.set('factory', new RequestFactory(this));
this.load(this.parameters.get('extensions') as string[] | undefined);
}
/** === Common parameters === */
get url(): string | undefined {
return this.parameters.get('url');
}
get debug(): boolean {
return Boolean(this.parameters.get('debug'));
}
/** === Common services === */
get factory(): RequestFactory {
return this.services.get('factory') as RequestFactory;
}
get dispatcher(): Dispatcher {
return this.services.get('dispatcher') as Dispatcher;
}
/** === Extensions === */
extends(property: string, value: unknown, writable = false): this {
return Object.defineProperty(this, property, { writable, value });
}
load(names?: string[]): this {
| Extensions.load(this, names); |
return this;
}
/** === Dispatcher/Events === */
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
this.dispatcher.on(event, callback, priority, once);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
this.dispatcher.once(event, callback, priority);
return this;
}
off<T extends Event>(event: string, callback: Callback<T>): this {
this.dispatcher.off(event, callback);
return this;
}
/** === Request === */
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.factory.request(urlOrConfig);
}
get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'GET', url });
}
post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'POST', url, data });
}
put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PUT', url, data });
}
patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PATCH', url, data });
}
delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'DELETE', url });
}
head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'HEAD', url });
}
options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'OPTIONS', url });
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
return this.factory.file(urlOrConfig);
}
cancelPendingRequests(): this {
this.factory.cancelPendingRequests();
return this;
}
isCancel(e: Error) {
return this.factory.isCancel(e);
}
}
| src/klient.ts | klientjs-core-9a67a61 | [
{
"filename": "src/extensions.ts",
"retrieved_chunk": "import type Klient from '.';\nexport type Extension = {\n name: string;\n initialize: (klient: Klient) => void;\n};\nclass Extensions extends Array<Extension> {\n load(klient: Klient, extensions?: string[]): void {\n for (let i = 0, len = this.length; i < len; i += 1) {\n const { name, initialize } = this[i];\n if (!klient.extensions.includes(name) && (!extensions || extensions.includes(name))) {",
"score": 0.8537052273750305
},
{
"filename": "src/services/dispatcher/listener.ts",
"retrieved_chunk": "import type Event from '../../events/event';\nimport type { Callback } from './dispatcher';\nexport default class Listener<T extends Event> {\n constructor(readonly callback: Callback<T>, readonly priority: number, readonly once: boolean, readonly id: number) {}\n invoke(event: T): Promise<void> {\n let result;\n try {\n result = this.callback(event);\n if (!(result instanceof Promise)) {\n result = Promise.resolve();",
"score": 0.8309093117713928
},
{
"filename": "src/services/bag/bag.ts",
"retrieved_chunk": " }\n all() {\n return softClone(this);\n }\n set(path: string, value: unknown): this {\n const prevState = this.all();\n objectPath.set(this, path, value);\n return invokeWatchers(this, this.all(), prevState);\n }\n merge(...items: BagItems[]): this {",
"score": 0.82676762342453
},
{
"filename": "src/services/dispatcher/dispatcher.ts",
"retrieved_chunk": " * Invoke all listeners attached to given event.\n *\n * @param abortOnFailure - Specify if listener failures must abort dispatch process.\n */\n async dispatch(e: Event, abortOnFailure = true): Promise<void> {\n const event = (e.constructor as typeof Event).NAME;\n const listeners = this.listeners[event] || [];\n this.debug('start', e, listeners);\n // Use inverse loop because we need to remove listeners callable once\n for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {",
"score": 0.8136763572692871
},
{
"filename": "src/services/bag/bag.ts",
"retrieved_chunk": " });\n }\n get watchers() {\n return getWatchers(this);\n }\n has(path: string) {\n return objectPath.get(this, path) !== undefined;\n }\n get(path: string) {\n return objectPath.get(this.all(), path);",
"score": 0.8036314249038696
}
] | typescript | Extensions.load(this, names); |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this | .parser.write('Bail out!' + message + '\n')
} |
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/test-point.ts",
"retrieved_chunk": " extra = extra || {}\n message = message\n .trim()\n .replace(/[\\n\\r]/g, ' ')\n .replace(/\\t/g, ' ')\n this.res = { ok, message, extra }\n this.extra = extra\n this.name = message\n this.message = tpMessage(esc(this.name), extra)\n }",
"score": 0.8633533716201782
},
{
"filename": "src/base.ts",
"retrieved_chunk": " const msg = format(...args).trim()\n console.error(\n prefix + msg.split('\\n').join(`\\n${prefix}`)\n )\n }\nexport interface BaseOpts {\n // parser-related options\n bail?: boolean\n strict?: boolean\n omitVersion?: boolean",
"score": 0.8021641373634338
},
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8001124858856201
},
{
"filename": "src/diags.ts",
"retrieved_chunk": " .map(l => (l.trim() ? ' ' + l : l.trim()))\n .join('\\n') +\n ' ...\\n'\n )\n}",
"score": 0.7955576181411743
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": " message += ' ' + esc(extra.skip)\n }\n } else if (extra.todo) {\n message += ' # TODO'\n if (typeof extra.todo === 'string') {\n message += ' ' + esc(extra.todo)\n }\n } else if (extra.time) {\n message += ' # time=' + extra.time + 'ms'\n }",
"score": 0.7899621725082397
}
] | typescript | .parser.write('Bail out!' + message + '\n')
} |
import axios from 'axios';
import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';
import RequestEvent from '../../events/request/request';
import RequestSuccessEvent from '../../events/request/success';
import RequestErrorEvent from '../../events/request/error';
import RequestDoneEvent from '../../events/request/done';
import RequestCancelEvent from '../../events/request/cancel';
import type Klient from '../..';
export type ResolveRequest = (response: AxiosResponse) => void;
export type RejectRequest = (error: AxiosError) => void;
export type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;
type PromiseCallbacks = { resolve: ResolveRequest; reject: RejectRequest };
type RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;
type RequestContext = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface KlientRequestConfig extends AxiosRequestConfig {
context?: RequestContext;
}
/**
* Request is a Promise object able to dispatch events before/after axios execution.
* Theses events allow to access and make action on request config/result at any step of execution.
* The Request will be resolved/rejected only after all events be dispatched.
*
* The events workflow is describe below :
*
* 1) RequestEvent (dispatched with abortOnFailure strategy)
* 2) Axios execution
* 2.1) Optional : RequestCancelEvent - only if request is cancelled (will reject promise and skip next events)
* 3) RequestSuccessEvent OR RequestErrorEvent
* 4) RequestDoneEvent
*/
export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {
context: RequestContext = { action: 'request' };
config: KlientRequestConfig = {};
result?: AxiosError | AxiosResponse;
// Allow override axios execution
handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;
protected klient!: Klient;
protected callbacks!: PromiseCallbacks;
protected readonly primaryEvent = new RequestEvent<T>(this);
protected readonly abortController = new AbortController();
protected constructor(callback: RequestCallback) {
super(callback);
}
static new<T>({ context, ...axiosConfig } | : KlientRequestConfig, klient: Klient): Request<T> { |
const callbacks = {} as PromiseCallbacks;
const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {
callbacks.resolve = resolve;
callbacks.reject = reject;
});
request.klient = klient;
request.config = axiosConfig;
request.callbacks = callbacks;
request.config.signal = request.abortController.signal;
request.context = { ...request.context, ...context };
return request;
}
static isCancel(e: Error) {
return axios.isCancel(e);
}
cancel(): this {
this.abortController.abort();
return this;
}
execute(): this {
this.dispatcher
.dispatch(this.primaryEvent)
.then(() => {
this.doRequest();
})
.catch((e) => {
this.reject(e);
});
return this;
}
protected doRequest(): this {
if (!this.result) {
this.handler(this.config)
.then((r) => {
this.resolve(r);
})
.catch((e) => {
this.reject(e);
});
}
return this;
}
protected resolve(response: AxiosResponse<T>): Promise<void> {
this.result = response;
return this.dispatchResultEvent(RequestSuccessEvent).then(() => {
this.callbacks.resolve(this.result as AxiosResponse<T>);
});
}
protected reject(error: AxiosError): Promise<void> {
this.result = error;
return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {
this.callbacks.reject(this.result as AxiosError);
});
}
protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {
const event = new EventClass(this.primaryEvent);
return new Promise((resolve) => {
this.dispatcher.dispatch(event, false).then(() => {
if (event instanceof RequestCancelEvent) {
return resolve();
}
this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);
});
});
}
protected get dispatcher() {
return this.klient.dispatcher;
}
}
| src/services/request/request.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.9402898550033569
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "export interface KlientRequestConfig extends AxiosRequestConfig {\n context?: RequestContext;\n}\nexport default class Request<T = unknown> extends Promise<AxiosResponse<T>> {\n context: RequestContext;\n config: KlientRequestConfig;\n result?: AxiosError | AxiosResponse;\n handler: (config: AxiosRequestConfig) => AxiosPromise<T>;\n protected klient: Klient;\n protected callbacks: PromiseCallbacks;",
"score": 0.9201441407203674
},
{
"filename": "src/events/request/success.d.ts",
"retrieved_chunk": "import type { AxiosResponse } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestSuccessEvent<T = unknown> extends RequestEvent {\n relatedEvent: RequestEvent<T>;\n static NAME: string;\n constructor(relatedEvent: RequestEvent<T>);\n get response(): AxiosResponse<T>;\n get data(): T;\n}",
"score": 0.8601545095443726
},
{
"filename": "src/events/request/error.d.ts",
"retrieved_chunk": "import type { AxiosError } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestErrorEvent<T = unknown> extends RequestEvent<T> {\n relatedEvent: RequestEvent<T>;\n static NAME: string;\n constructor(relatedEvent: RequestEvent<T>);\n get error(): AxiosError;\n get response(): import(\"axios\").AxiosResponse<unknown, any> | undefined;\n get data(): unknown;\n}",
"score": 0.8557024002075195
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " off<T extends Event>(event: string, callback: Callback<T>): this {\n this.dispatcher.off(event, callback);\n return this;\n }\n /** === Request === */\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.factory.request(urlOrConfig);\n }\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'GET', url });",
"score": 0.8537547588348389
}
] | typescript | : KlientRequestConfig, klient: Klient): Request<T> { |
import Bag from './services/bag/bag';
import Dispatcher from './services/dispatcher/dispatcher';
import RequestFactory from './services/request/factory';
import Extensions from './extensions';
import { defaultParameters } from './parameters';
import type Event from './events/event';
import type Request from './services/request/request';
import type { KlientRequestConfig } from './services/request/request';
import type { Callback } from './services/dispatcher/dispatcher';
import type { Parameters } from './parameters';
export default class Klient<P extends Parameters = Parameters> {
readonly extensions: string[] = [];
readonly parameters = new Bag(defaultParameters);
readonly services = new Bag();
constructor(urlOrParams?: P | string) {
let parameters: Parameters = {};
if (typeof urlOrParams === 'string') {
parameters.url = urlOrParams;
} else if (urlOrParams && typeof urlOrParams === 'object') {
parameters = urlOrParams;
}
this.parameters.merge(parameters);
// prettier-ignore
this.services
.set('klient', this)
.set('dispatcher', new Dispatcher(this))
.set('factory', new RequestFactory(this));
this.load(this.parameters.get('extensions') as string[] | undefined);
}
/** === Common parameters === */
get url(): string | undefined {
return this.parameters.get('url');
}
get debug(): boolean {
return Boolean(this.parameters.get('debug'));
}
/** === Common services === */
get factory(): RequestFactory {
return this.services.get('factory') as RequestFactory;
}
get dispatcher(): Dispatcher {
return this.services.get('dispatcher') as Dispatcher;
}
/** === Extensions === */
extends(property: string, value: unknown, writable = false): this {
return Object.defineProperty(this, property, { writable, value });
}
load(names?: string[]): this {
Extensions.load(this, names);
return this;
}
/** === Dispatcher/Events === */
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
this.dispatcher.on(event, callback, priority, once);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
this.dispatcher.once(event, callback, priority);
return this;
}
off<T extends Event>(event: string, callback: Callback<T>): this {
this.dispatcher.off(event, callback);
return this;
}
/** === Request === */
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.factory.request(urlOrConfig);
}
get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'GET', url });
}
post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'POST', url, data });
}
put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PUT', url, data });
}
patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'PATCH', url, data });
}
delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'DELETE', url });
}
head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'HEAD', url });
}
options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {
return this.request<T>({ ...config, method: 'OPTIONS', url });
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
return this. | factory.file(urlOrConfig); |
}
cancelPendingRequests(): this {
this.factory.cancelPendingRequests();
return this;
}
isCancel(e: Error) {
return this.factory.isCancel(e);
}
}
| src/klient.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.createRequest<T>(urlOrConfig).execute();\n }\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {\n const config = deepmerge(\n { responseType: 'blob', context: { action: 'file' } },\n typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig\n );\n return this.request<Blob>(config).then(({ data }) => data);\n }",
"score": 0.9134557247161865
},
{
"filename": "src/services/request/factory.d.ts",
"retrieved_chunk": " constructor(klient: Klient);\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n isCancel(e: Error): any;\n protected prepare(config: KlientRequestConfig): KlientRequestConfig;\n protected removePendingRequest(request: Request): void;\n}\nexport {};",
"score": 0.8581933975219727
},
{
"filename": "src/klient.d.ts",
"retrieved_chunk": " request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T>;\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n post<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n put<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n patch<T = unknown>(url: string, data: unknown, config?: KlientRequestConfig): Request<T>;\n delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T>;\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob>;\n cancelPendingRequests(): this;",
"score": 0.8425579071044922
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " protected constructor(callback: RequestCallback) {\n super(callback);\n }\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {\n const callbacks = {} as PromiseCallbacks;\n const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {\n callbacks.resolve = resolve;\n callbacks.reject = reject;\n });\n request.klient = klient;",
"score": 0.8317655920982361
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " cancelPendingRequests(): this {\n for (let i = 0, len = this.requests.length; i < len; i += 1) {\n this.requests[i].cancel();\n }\n return this;\n }\n createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;\n const request = this.model.new<T>(this.prepare(config), this.klient);\n // Store request during pending state only",
"score": 0.825543999671936
}
] | typescript | factory.file(urlOrConfig); |
import axios from 'axios';
import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';
import RequestEvent from '../../events/request/request';
import RequestSuccessEvent from '../../events/request/success';
import RequestErrorEvent from '../../events/request/error';
import RequestDoneEvent from '../../events/request/done';
import RequestCancelEvent from '../../events/request/cancel';
import type Klient from '../..';
export type ResolveRequest = (response: AxiosResponse) => void;
export type RejectRequest = (error: AxiosError) => void;
export type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;
type PromiseCallbacks = { resolve: ResolveRequest; reject: RejectRequest };
type RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;
type RequestContext = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface KlientRequestConfig extends AxiosRequestConfig {
context?: RequestContext;
}
/**
* Request is a Promise object able to dispatch events before/after axios execution.
* Theses events allow to access and make action on request config/result at any step of execution.
* The Request will be resolved/rejected only after all events be dispatched.
*
* The events workflow is describe below :
*
* 1) RequestEvent (dispatched with abortOnFailure strategy)
* 2) Axios execution
* 2.1) Optional : RequestCancelEvent - only if request is cancelled (will reject promise and skip next events)
* 3) RequestSuccessEvent OR RequestErrorEvent
* 4) RequestDoneEvent
*/
export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {
context: RequestContext = { action: 'request' };
config: KlientRequestConfig = {};
result?: AxiosError | AxiosResponse;
// Allow override axios execution
handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;
protected klient!: Klient;
protected callbacks!: PromiseCallbacks;
protected readonly primaryEvent = new RequestEvent<T>(this);
protected readonly abortController = new AbortController();
protected constructor(callback: RequestCallback) {
super(callback);
}
static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {
const callbacks = {} as PromiseCallbacks;
const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {
callbacks.resolve = resolve;
callbacks.reject = reject;
});
request.klient = klient;
request.config = axiosConfig;
request.callbacks = callbacks;
request.config.signal = request.abortController.signal;
request.context = { ...request.context, ...context };
return request;
}
static isCancel(e: Error) {
return axios.isCancel(e);
}
cancel(): this {
this.abortController.abort();
return this;
}
execute(): this {
this.dispatcher
.dispatch(this.primaryEvent)
.then(() => {
this.doRequest();
})
.catch((e) => {
this.reject(e);
});
return this;
}
protected doRequest(): this {
if (!this.result) {
this.handler(this.config)
.then((r) => {
this.resolve(r);
})
.catch((e) => {
this.reject(e);
});
}
return this;
}
protected resolve(response: AxiosResponse<T>): Promise<void> {
this.result = response;
return this.dispatchResultEvent(RequestSuccessEvent).then(() => {
this.callbacks.resolve(this.result as AxiosResponse<T>);
});
}
protected reject(error: AxiosError): Promise<void> {
this.result = error;
return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {
this.callbacks.reject(this.result as AxiosError);
});
}
protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {
const event = new EventClass(this.primaryEvent);
return new Promise((resolve) => {
this.dispatcher.dispatch(event, false).then(() => {
if (event instanceof RequestCancelEvent) {
return resolve();
}
| this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve); |
});
});
}
protected get dispatcher() {
return this.klient.dispatcher;
}
}
| src/services/request/request.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " this.requests.push(request);\n // Remove request when promise has been fulfilled\n request\n .then((r) => {\n this.removePendingRequest(request);\n return r;\n })\n .catch((e) => {\n this.removePendingRequest(request);\n return e;",
"score": 0.8371496200561523
},
{
"filename": "src/services/dispatcher/listener.ts",
"retrieved_chunk": "import type Event from '../../events/event';\nimport type { Callback } from './dispatcher';\nexport default class Listener<T extends Event> {\n constructor(readonly callback: Callback<T>, readonly priority: number, readonly once: boolean, readonly id: number) {}\n invoke(event: T): Promise<void> {\n let result;\n try {\n result = this.callback(event);\n if (!(result instanceof Promise)) {\n result = Promise.resolve();",
"score": 0.8117690086364746
},
{
"filename": "src/services/dispatcher/dispatcher.ts",
"retrieved_chunk": " if (!e.dispatch.propagation) {\n this.debug('stopped', e, listener);\n // Stop listeners invokation\n break;\n }\n }\n this.debug('end', e, listeners);\n return Promise.resolve();\n }\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {",
"score": 0.8065279126167297
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "}\nexport type ResolveRequest = (response: AxiosResponse) => void;\nexport type RejectRequest = (error: AxiosError) => void;\nexport type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;\ntype PromiseCallbacks = {\n resolve: ResolveRequest;\n reject: RejectRequest;\n};\ntype RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;\ntype RequestContext = Record<string, any>;",
"score": 0.8039165139198303
},
{
"filename": "src/__tests__/request.test.ts",
"retrieved_chunk": "test('request:handler', async () => {\n const klient = new Klient();\n const spyRequestSuccessEvent = jest.fn();\n const spyRequestErrorEvent = jest.fn();\n const spyRequestHandler = jest.fn();\n klient.once('request', (e: RequestEvent) => {\n e.request.handler = () => {\n spyRequestHandler();\n return Promise.resolve({ status: 200, statusText: 'OK', data: [], headers: {}, config: {} });\n };",
"score": 0.8011974096298218
}
] | typescript | this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve); |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this. | write(message)
} else { |
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " const msg = format(...args).trim()\n console.error(\n prefix + msg.split('\\n').join(`\\n${prefix}`)\n )\n }\nexport interface BaseOpts {\n // parser-related options\n bail?: boolean\n strict?: boolean\n omitVersion?: boolean",
"score": 0.8363984823226929
},
{
"filename": "src/diags.ts",
"retrieved_chunk": " typeof clean !== 'object' ||\n !Object.keys(clean).length\n ) {\n return ''\n }\n return (\n ' ---\\n' +\n yaml\n .stringify(clean)\n .split('\\n')",
"score": 0.8115565776824951
},
{
"filename": "src/base.ts",
"retrieved_chunk": " online(line: string) {\n this.debug('LINE %j', line, [this.name, this.indent])\n return this.write(this.indent + line)\n }\n write(\n c: ContiguousData,\n e?: Encoding | (() => any),\n cb?: () => any\n ) {\n if (this.buffered) {",
"score": 0.8030837774276733
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " Object.defineProperty(er, 'message', {\n value: '',\n configurable: true\n })\n } catch {}\n }\n const st = er.stack && er.stack.substr(\n er._babel ? (message + er.codeFrame).length : 0)\n if (st) {\n const splitst = st.split('\\n')",
"score": 0.797083854675293
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (!er || typeof er !== 'object') {\n extra.error = er\n return extra\n }\n // pull out error details\n const message = er.message ? er.message\n : er.stack ? er.stack.split('\\n')[0]\n : ''\n if (er.message) {\n try {",
"score": 0.7735795974731445
}
] | typescript | write(message)
} else { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options | .expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) { |
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " this.setTimeout(0)\n options = options || {}\n options.expired = options.expired || this.name\n const threw = this.threw(new Error('timeout!'), options)\n if (threw) {\n this.emit('timeout', threw)\n }\n }\n runMain(cb: () => void) {\n this.debug('BASE runMain')",
"score": 0.8409918546676636
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.830449104309082
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " public args: string[]\n public stdio: StdioOptions\n public env: { [k: string]: string } | typeof process.env\n public proc: null | ChildProcess\n public cb: null | (() => void)\n constructor(options: SpawnOpts) {\n // figure out the name before calling super()\n const command = options.command\n if (!command) {\n throw new TypeError('no command provided')",
"score": 0.8191064596176147
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "}\nconst tpMessage = (\n description: string,\n extra: { [k: string]: any },\n options: TestBaseOpts = {}\n): string => {\n let message = description ? ` - ${description}` : ''\n if (extra.skip) {\n message += ' # SKIP'\n if (typeof extra.skip === 'string') {",
"score": 0.8098114728927612
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": " this.done = true\n this.value = er\n // make it clear that this is a problem by doing\n // the opposite of what was requested.\n this.rejected = !this.expectReject\n return this.finish()\n }\n finish () {\n if (this.ready && this.done && !this.finishing) {\n this.finishing = true",
"score": 0.8066185712814331
}
] | typescript | .expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) { |
/* eslint-disable @typescript-eslint/no-explicit-any */
import * as express from 'express';
import 'express-async-errors';
import { Application } from 'express';
import * as swaggerUi from 'swagger-ui-express';
import { swaggerSpec } from './util/swagger.util';
import Logger from './util/logger.util'
class App {
public app: Application;
public port: number;
constructor(
appInit: { port: number; earlyMiddlewares: any; lateMiddlewares: any; routes: any; },
) {
this.app = express();
this.port = appInit.port;
this.middlewares(appInit.earlyMiddlewares);
this.routes(appInit.routes);
this.middlewares(appInit.lateMiddlewares);
this.assets();
this.template();
}
private middlewares(middlewares: { forEach: (arg0: (middleware: any) => void) => void; }) {
middlewares.forEach((middleware) => {
this.app.use(middleware);
});
}
private routes(routes: { forEach: (arg0: (route: any) => void) => void; }) {
routes.forEach((route) => {
this.app.use('/', route.router);
});
this.app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
private assets() {
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
private template() {
}
public listen() {
this.app.listen(this.port, () => {
| Logger.info(`App listening on the http://localhost:${this.port}`); |
});
}
}
export default App;
| src/app.ts | erdemkosk-typescript-express-boilerplate-5b4e494 | [
{
"filename": "src/interfaces/IRouteBase.interface.ts",
"retrieved_chunk": "interface IRouteBase {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n initializeRoutes(): any\n}\nexport default IRouteBase;",
"score": 0.7770665884017944
},
{
"filename": "src/logic/container.logic.ts",
"retrieved_chunk": "import 'reflect-metadata';\nimport { container } from 'tsyringe';\nimport * as glob from 'glob';\nimport * as path from 'path';\nexport class ContainerLogic {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n public static getRouteClasses(): any[] {\n const moduleFolder = path.join(__dirname, '../modules');\n const routeFiles = glob.sync(`${moduleFolder}/**/*.route.{ts,js}`);\n return routeFiles.map((routeFile) => container.resolve(require(routeFile).default));",
"score": 0.7579810619354248
},
{
"filename": "src/config/enviroments/tests.ts",
"retrieved_chunk": "import BaseConfig from './base';\nclass TestConfig extends BaseConfig {\n // eslint-disable-next-line no-useless-constructor\n constructor() {\n super();\n }\n}\nexport default TestConfig;",
"score": 0.7285130023956299
},
{
"filename": "src/config/enviroments/dev.ts",
"retrieved_chunk": "import BaseConfig from './base';\nclass DevConfig extends BaseConfig {\n // eslint-disable-next-line no-useless-constructor\n constructor() {\n super();\n }\n}\nexport default DevConfig;",
"score": 0.717861533164978
},
{
"filename": "src/util/swagger.util.ts",
"retrieved_chunk": "import * as swaggerJSDoc from 'swagger-jsdoc';\nimport { Options } from 'swagger-jsdoc';\nimport * as glob from 'glob';\nimport * as path from 'path';\nconst moduleFolder = path.join(__dirname, '../modules');\nconst routeFiles = glob.sync(`${moduleFolder}/**/*.route.{ts,js}`);\nconst swaggerOptions: Options = {\n definition: {\n openapi: '3.0.0',\n info: {",
"score": 0.665989875793457
}
] | typescript | Logger.info(`App listening on the http://localhost:${this.port}`); |
import * as express from 'express';
import { autoInjectable } from 'tsyringe';
import { celebrate } from 'celebrate';
import IRouteBase from '../../interfaces/IRouteBase.interface';
import ExampleController from './example.controller';
import schemas from './example.schema'
@autoInjectable()
export default class FooRoute implements IRouteBase {
private exampleController: ExampleController;
constructor(exampleController: ExampleController) {
this.exampleController = exampleController;
this.initializeRoutes();
}
public router = express.Router();
initializeRoutes() {
/**
* @swagger
*
* /example:
* get:
* summary: Get a Example
* description: Retrieve a Example
* tags:
* - example
* produces:
* - application/json
* parameters:
* - name: id
* in: query
* required: true
* description: Example ID.
* schema:
* type: integer
* responses:
* 200:
* description: Example value.
* schema:
* type: object
* properties:
* value:
* type: string
*/
| this.router.get('/example', celebrate(schemas.getFoo), this.exampleController.getExampleValue); |
}
}
| src/modules/example/example.route.ts | erdemkosk-typescript-express-boilerplate-5b4e494 | [
{
"filename": "src/util/swagger.util.ts",
"retrieved_chunk": " title: 'My API',\n version: '1.0.0',\n description: 'A simple API for demonstrating Swagger',\n },\n servers: [\n {\n url: '/',\n },\n ],\n components: {",
"score": 0.8064846396446228
},
{
"filename": "src/modules/example/example.repository.ts",
"retrieved_chunk": "export default class ExampleRepository {\n public async getExampleValue(id: number) {\n const examples = [{\n id: 1,\n name: 'erdem',\n },\n {\n id: 1,\n name: 'kosk',\n }];",
"score": 0.7829898595809937
},
{
"filename": "src/util/swagger.util.ts",
"retrieved_chunk": " securitySchemes: {\n JWT: {\n type: 'apiKey',\n in: 'header',\n name: 'Authorization',\n description: '',\n },\n },\n securityDefinitions: {\n JWT: {",
"score": 0.7781969904899597
},
{
"filename": "src/interfaces/ICustomErrors.interface.ts",
"retrieved_chunk": "export default interface CustomErrors {\n [key: string]: {\n parentError: ErrorConstructor;\n message: string;\n code: number;\n httpCode?: number;\n };\n }",
"score": 0.7753788232803345
},
{
"filename": "src/util/base-errors.ts",
"retrieved_chunk": " type CustomErrors = {\n [key: string]: {\n parentError: typeof CustomError;\n message: string;\n code: number;\n httpCode: number;\n };\n };\nclass CustomError extends Error {\n constructor(",
"score": 0.762761652469635
}
] | typescript | this.router.get('/example', celebrate(schemas.getFoo), this.exampleController.getExampleValue); |
import Event from '../../events/event';
import DebugEvent from '../../events/debug';
import Listener from './listener';
import type Klient from '../../klient';
export type Callback<T extends Event> = (e: T) => Promise<void> | void;
export type Listeners = { [event: string]: Listener<never>[] };
export default class Dispatcher {
readonly listeners: Listeners = {};
constructor(protected readonly klient: Klient) {}
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
// Avoid duplication
if (this.findListenerIndex(event, callback) !== undefined) {
return this;
}
// Initialize listeners collection if not exists
this.listeners[event] = this.listeners[event] || [];
// Get reference to array containing listeners
const listeners = this.listeners[event];
// Build listener id (incremental)
const id = listeners.length ? Math.max(...listeners.map((l) => l.id)) + 1 : 0;
// Register the listener
listeners.push(new Listener(callback, priority, once, id));
// Listener are sorted in order they are defined
listeners.sort((a, b) => b.id - a.id);
// Sort by priority listeners binded to same event
// Lower priorities are first because we loop on collection from the end (see dispatch method)
listeners.sort((a, b) => a.priority - b.priority);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
return this.on(event, callback, priority, true);
}
off<T extends Event>(event: string, callback: Callback<T>): this {
const index = this.findListenerIndex(event, callback);
if (index !== undefined) {
this.listeners[event].splice(index, 1);
}
return this;
}
/**
* Invoke all listeners attached to given event.
*
* @param abortOnFailure - Specify if listener failures must abort dispatch process.
*/
async dispatch(e: Event, abortOnFailure = true): Promise<void> {
const event = (e.constructor as typeof Event).NAME;
const listeners = this.listeners[event] || [];
this.debug('start', e, listeners);
// Use inverse loop because we need to remove listeners callable once
for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {
listener = listeners[i];
if (Dispatcher.handleListenerSkipping(e, listener)) {
this.debug('skipped', e, listener);
continue;
}
if (listener.once) {
this.listeners[event].splice(i, 1);
}
try {
this.debug('invoking', e, listener);
// Wait for listener whose return a promise
await listener.invoke(e as never); // eslint-disable-line no-await-in-loop
this.debug('invoked', e, listener);
} catch (err) {
this.debug('failed', e, listener, err as Error);
if (abortOnFailure) {
// Reject promise on "abort on listener failure" strategy
return Promise.reject(err);
}
}
if (!e.dispatch.propagation) {
this.debug('stopped', e, listener);
// Stop listeners invokation
break;
}
}
this.debug('end', e, listeners);
return Promise.resolve();
}
protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {
const listeners = this.listeners[event] || [];
for (let i = 0, len = listeners.length; i < len; i += 1) {
if (listeners[i].callback === callback) {
return i;
}
}
return undefined;
}
protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void {
const { skipNextListeners, skipUntilListener } = event.dispatch;
if (skipNextListeners > 0) {
event.dispatch.skipNextListeners -= 1;
return true;
}
if (skipUntilListener) {
if (listener.id === skipUntilListener) {
event.dispatch.skipUntilListener = undefined;
return;
}
return true;
}
}
protected debug(
action: string,
relatedEvent: Event,
handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void {
| if (relatedEvent instanceof DebugEvent || !this.klient.debug) { |
return;
}
this.dispatch(new DebugEvent(action, relatedEvent, handler, error), false);
}
}
| src/services/dispatcher/dispatcher.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": "export default class Dispatcher {\n protected readonly klient: Klient;\n readonly listeners: Listeners;\n constructor(klient: Klient);\n on<T extends Event>(event: string, callback: Callback<T>, priority?: number, once?: boolean): this;\n once<T extends Event>(event: string, callback: Callback<T>, priority?: number): this;\n off<T extends Event>(event: string, callback: Callback<T>): this;\n dispatch(e: Event, abortOnFailure?: boolean): Promise<void>;\n protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined;\n protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void;",
"score": 0.8613561987876892
},
{
"filename": "src/services/dispatcher/dispatcher.d.ts",
"retrieved_chunk": " protected debug(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error?: Error | null): void;\n}\nexport {};",
"score": 0.860253095626831
},
{
"filename": "src/events/debug.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n static NAME = 'debug';\n constructor(\n public action: string,\n public relatedEvent: Event,\n public handler: Listener<never> | Listener<never>[],\n public error: Error | null\n ) {",
"score": 0.8408594727516174
},
{
"filename": "src/events/debug.d.ts",
"retrieved_chunk": "import Event from './event';\nimport type Listener from '../services/dispatcher/listener';\nexport default class DebugEvent extends Event {\n action: string;\n relatedEvent: Event;\n handler: Listener<never> | Listener<never>[];\n error: Error | null;\n static NAME: string;\n constructor(action: string, relatedEvent: Event, handler: Listener<never> | Listener<never>[], error: Error | null);\n}",
"score": 0.8389652967453003
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " off<T extends Event>(event: string, callback: Callback<T>): this {\n this.dispatcher.off(event, callback);\n return this;\n }\n /** === Request === */\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.factory.request(urlOrConfig);\n }\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'GET', url });",
"score": 0.821799099445343
}
] | typescript | if (relatedEvent instanceof DebugEvent || !this.klient.debug) { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
| if (n === 0 && comment && !this.options.skip) { |
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " } else if (arg === false) {\n // it's handy while developing to put a ! in front of a\n // function to temporarily make a test todo\n continue\n } else if (typeof arg !== 'undefined')\n throw new TypeError(\n 'unknown argument passed to parseTestArgs: ' +\n typeof arg\n )\n }",
"score": 0.850959300994873
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.8269177675247192
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " let extra: { [k: string]: any } | null | undefined =\n undefined\n let cb: ((t: T) => any) | null | undefined = undefined\n // this only works if it's literally the 4th argument.\n // used internally.\n const defaultName = args[3] || ''\n for (let i = 0; i < 3 && i < args.length; i++) {\n const arg = args[i]\n if (\n name === undefined &&",
"score": 0.8185404539108276
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": " this.done = true\n this.value = er\n // make it clear that this is a problem by doing\n // the opposite of what was requested.\n this.rejected = !this.expectReject\n return this.finish()\n }\n finish () {\n if (this.ready && this.done && !this.finishing) {\n this.finishing = true",
"score": 0.8072165846824646
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " (typeof arg === 'string' || typeof arg === 'number')\n )\n name = '' + arg\n else if (arg && typeof arg === 'object') {\n extra = arg\n if (name === undefined) name = null\n } else if (typeof arg === 'function') {\n if (extra === undefined) extra = {}\n if (name === undefined) name = null\n cb = arg",
"score": 0.8042053580284119
}
] | typescript | if (n === 0 && comment && !this.options.skip) { |
import axios from 'axios';
import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';
import RequestEvent from '../../events/request/request';
import RequestSuccessEvent from '../../events/request/success';
import RequestErrorEvent from '../../events/request/error';
import RequestDoneEvent from '../../events/request/done';
import RequestCancelEvent from '../../events/request/cancel';
import type Klient from '../..';
export type ResolveRequest = (response: AxiosResponse) => void;
export type RejectRequest = (error: AxiosError) => void;
export type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;
type PromiseCallbacks = { resolve: ResolveRequest; reject: RejectRequest };
type RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;
type RequestContext = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface KlientRequestConfig extends AxiosRequestConfig {
context?: RequestContext;
}
/**
* Request is a Promise object able to dispatch events before/after axios execution.
* Theses events allow to access and make action on request config/result at any step of execution.
* The Request will be resolved/rejected only after all events be dispatched.
*
* The events workflow is describe below :
*
* 1) RequestEvent (dispatched with abortOnFailure strategy)
* 2) Axios execution
* 2.1) Optional : RequestCancelEvent - only if request is cancelled (will reject promise and skip next events)
* 3) RequestSuccessEvent OR RequestErrorEvent
* 4) RequestDoneEvent
*/
export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {
context: RequestContext = { action: 'request' };
config: KlientRequestConfig = {};
result?: AxiosError | AxiosResponse;
// Allow override axios execution
handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;
protected klient!: Klient;
protected callbacks!: PromiseCallbacks;
| protected readonly primaryEvent = new RequestEvent<T>(this); |
protected readonly abortController = new AbortController();
protected constructor(callback: RequestCallback) {
super(callback);
}
static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {
const callbacks = {} as PromiseCallbacks;
const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {
callbacks.resolve = resolve;
callbacks.reject = reject;
});
request.klient = klient;
request.config = axiosConfig;
request.callbacks = callbacks;
request.config.signal = request.abortController.signal;
request.context = { ...request.context, ...context };
return request;
}
static isCancel(e: Error) {
return axios.isCancel(e);
}
cancel(): this {
this.abortController.abort();
return this;
}
execute(): this {
this.dispatcher
.dispatch(this.primaryEvent)
.then(() => {
this.doRequest();
})
.catch((e) => {
this.reject(e);
});
return this;
}
protected doRequest(): this {
if (!this.result) {
this.handler(this.config)
.then((r) => {
this.resolve(r);
})
.catch((e) => {
this.reject(e);
});
}
return this;
}
protected resolve(response: AxiosResponse<T>): Promise<void> {
this.result = response;
return this.dispatchResultEvent(RequestSuccessEvent).then(() => {
this.callbacks.resolve(this.result as AxiosResponse<T>);
});
}
protected reject(error: AxiosError): Promise<void> {
this.result = error;
return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {
this.callbacks.reject(this.result as AxiosError);
});
}
protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {
const event = new EventClass(this.primaryEvent);
return new Promise((resolve) => {
this.dispatcher.dispatch(event, false).then(() => {
if (event instanceof RequestCancelEvent) {
return resolve();
}
this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);
});
});
}
protected get dispatcher() {
return this.klient.dispatcher;
}
}
| src/services/request/request.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "export interface KlientRequestConfig extends AxiosRequestConfig {\n context?: RequestContext;\n}\nexport default class Request<T = unknown> extends Promise<AxiosResponse<T>> {\n context: RequestContext;\n config: KlientRequestConfig;\n result?: AxiosError | AxiosResponse;\n handler: (config: AxiosRequestConfig) => AxiosPromise<T>;\n protected klient: Klient;\n protected callbacks: PromiseCallbacks;",
"score": 0.9651116728782654
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.9245750904083252
},
{
"filename": "src/events/request/success.d.ts",
"retrieved_chunk": "import type { AxiosResponse } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestSuccessEvent<T = unknown> extends RequestEvent {\n relatedEvent: RequestEvent<T>;\n static NAME: string;\n constructor(relatedEvent: RequestEvent<T>);\n get response(): AxiosResponse<T>;\n get data(): T;\n}",
"score": 0.8838831782341003
},
{
"filename": "src/events/request/error.d.ts",
"retrieved_chunk": "import type { AxiosError } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestErrorEvent<T = unknown> extends RequestEvent<T> {\n relatedEvent: RequestEvent<T>;\n static NAME: string;\n constructor(relatedEvent: RequestEvent<T>);\n get error(): AxiosError;\n get response(): import(\"axios\").AxiosResponse<unknown, any> | undefined;\n get data(): unknown;\n}",
"score": 0.8775571584701538
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "}\nexport type ResolveRequest = (response: AxiosResponse) => void;\nexport type RejectRequest = (error: AxiosError) => void;\nexport type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;\ntype PromiseCallbacks = {\n resolve: ResolveRequest;\n reject: RejectRequest;\n};\ntype RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;\ntype RequestContext = Record<string, any>;",
"score": 0.8632115125656128
}
] | typescript | protected readonly primaryEvent = new RequestEvent<T>(this); |
import axios from 'axios';
import type { AxiosResponse, AxiosError, AxiosRequestConfig, AxiosPromise } from 'axios';
import RequestEvent from '../../events/request/request';
import RequestSuccessEvent from '../../events/request/success';
import RequestErrorEvent from '../../events/request/error';
import RequestDoneEvent from '../../events/request/done';
import RequestCancelEvent from '../../events/request/cancel';
import type Klient from '../..';
export type ResolveRequest = (response: AxiosResponse) => void;
export type RejectRequest = (error: AxiosError) => void;
export type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;
type PromiseCallbacks = { resolve: ResolveRequest; reject: RejectRequest };
type RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;
type RequestContext = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
export interface KlientRequestConfig extends AxiosRequestConfig {
context?: RequestContext;
}
/**
* Request is a Promise object able to dispatch events before/after axios execution.
* Theses events allow to access and make action on request config/result at any step of execution.
* The Request will be resolved/rejected only after all events be dispatched.
*
* The events workflow is describe below :
*
* 1) RequestEvent (dispatched with abortOnFailure strategy)
* 2) Axios execution
* 2.1) Optional : RequestCancelEvent - only if request is cancelled (will reject promise and skip next events)
* 3) RequestSuccessEvent OR RequestErrorEvent
* 4) RequestDoneEvent
*/
export default class Request<T = unknown> extends Promise<AxiosResponse<T>> {
context: RequestContext = { action: 'request' };
config: KlientRequestConfig = {};
result?: AxiosError | AxiosResponse;
// Allow override axios execution
handler: (config: AxiosRequestConfig) => AxiosPromise<T> = axios;
protected klient!: Klient;
protected callbacks!: PromiseCallbacks;
protected readonly primaryEvent = new RequestEvent<T>(this);
protected readonly abortController = new AbortController();
protected constructor(callback: RequestCallback) {
super(callback);
}
static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {
const callbacks = {} as PromiseCallbacks;
const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {
callbacks.resolve = resolve;
callbacks.reject = reject;
});
request.klient = klient;
request.config = axiosConfig;
request.callbacks = callbacks;
request.config.signal = request.abortController.signal;
request.context = { ...request.context, ...context };
return request;
}
static isCancel(e: Error) {
return axios.isCancel(e);
}
cancel(): this {
this.abortController.abort();
return this;
}
execute(): this {
this.dispatcher
.dispatch(this.primaryEvent)
.then(() => {
this.doRequest();
})
.catch((e) => {
this.reject(e);
});
return this;
}
protected doRequest(): this {
if (!this.result) {
this.handler(this.config)
.then((r) => {
this.resolve(r);
})
.catch((e) => {
this.reject(e);
});
}
return this;
}
protected resolve(response: AxiosResponse<T>): Promise<void> {
this.result = response;
return this.dispatchResultEvent(RequestSuccessEvent).then(() => {
this.callbacks.resolve(this.result as AxiosResponse<T>);
});
}
protected reject(error: AxiosError): Promise<void> {
this.result = error;
return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {
this.callbacks.reject(this.result as AxiosError);
});
}
protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {
| const event = new EventClass(this.primaryEvent); |
return new Promise((resolve) => {
this.dispatcher.dispatch(event, false).then(() => {
if (event instanceof RequestCancelEvent) {
return resolve();
}
this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);
});
});
}
protected get dispatcher() {
return this.klient.dispatcher;
}
}
| src/services/request/request.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " });\n return request;\n }\n isCancel(e: Error) {\n return this.model.isCancel(e);\n }\n protected prepare(config: KlientRequestConfig): KlientRequestConfig {\n return deepmerge.all([\n { baseURL: this.klient.url },\n (this.klient.parameters.get('request') as AxiosRequestConfig) || {},",
"score": 0.8355785608291626
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "}\nexport type ResolveRequest = (response: AxiosResponse) => void;\nexport type RejectRequest = (error: AxiosError) => void;\nexport type RequestCallback = (resolve: ResolveRequest, reject: RejectRequest) => void;\ntype PromiseCallbacks = {\n resolve: ResolveRequest;\n reject: RejectRequest;\n};\ntype RequestEventTypes = typeof RequestSuccessEvent | typeof RequestErrorEvent | typeof RequestCancelEvent;\ntype RequestContext = Record<string, any>;",
"score": 0.8311126232147217
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": " protected readonly primaryEvent: RequestEvent;\n protected readonly abortController: AbortController;\n protected constructor(callback: RequestCallback);\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T>;\n static isCancel(e: Error): boolean;\n cancel(): this;\n execute(): this;\n protected doRequest(): this;\n protected resolve(response: AxiosResponse<T>): Promise<void>;\n protected reject(error: AxiosError): Promise<void>;",
"score": 0.8227941989898682
},
{
"filename": "src/events/request/error.ts",
"retrieved_chunk": "import type { AxiosError } from 'axios';\nimport RequestEvent from './request';\nexport default class RequestErrorEvent<T = unknown> extends RequestEvent<T> {\n static NAME = 'request:error';\n constructor(public relatedEvent: RequestEvent<T>) {\n super(relatedEvent.request);\n }\n get error(): AxiosError {\n return this.request.result as AxiosError;\n }",
"score": 0.8111671209335327
},
{
"filename": "src/services/request/request.d.ts",
"retrieved_chunk": "export interface KlientRequestConfig extends AxiosRequestConfig {\n context?: RequestContext;\n}\nexport default class Request<T = unknown> extends Promise<AxiosResponse<T>> {\n context: RequestContext;\n config: KlientRequestConfig;\n result?: AxiosError | AxiosResponse;\n handler: (config: AxiosRequestConfig) => AxiosPromise<T>;\n protected klient: Klient;\n protected callbacks: PromiseCallbacks;",
"score": 0.8067469000816345
}
] | typescript | const event = new EventClass(this.primaryEvent); |
import Event from '../../events/event';
import DebugEvent from '../../events/debug';
import Listener from './listener';
import type Klient from '../../klient';
export type Callback<T extends Event> = (e: T) => Promise<void> | void;
export type Listeners = { [event: string]: Listener<never>[] };
export default class Dispatcher {
readonly listeners: Listeners = {};
constructor(protected readonly klient: Klient) {}
on<T extends Event>(event: string, callback: Callback<T>, priority = 0, once = false): this {
// Avoid duplication
if (this.findListenerIndex(event, callback) !== undefined) {
return this;
}
// Initialize listeners collection if not exists
this.listeners[event] = this.listeners[event] || [];
// Get reference to array containing listeners
const listeners = this.listeners[event];
// Build listener id (incremental)
const id = listeners.length ? Math.max(...listeners.map((l) => l.id)) + 1 : 0;
// Register the listener
listeners.push(new Listener(callback, priority, once, id));
// Listener are sorted in order they are defined
listeners.sort((a, b) => b.id - a.id);
// Sort by priority listeners binded to same event
// Lower priorities are first because we loop on collection from the end (see dispatch method)
listeners.sort((a, b) => a.priority - b.priority);
return this;
}
once<T extends Event>(event: string, callback: Callback<T>, priority = 0): this {
return this.on(event, callback, priority, true);
}
off<T extends Event>(event: string, callback: Callback<T>): this {
const index = this.findListenerIndex(event, callback);
if (index !== undefined) {
this.listeners[event].splice(index, 1);
}
return this;
}
/**
* Invoke all listeners attached to given event.
*
* @param abortOnFailure - Specify if listener failures must abort dispatch process.
*/
async dispatch(e: Event, abortOnFailure = true): Promise<void> {
const event = (e.constructor as typeof Event).NAME;
const listeners = this.listeners[event] || [];
this.debug('start', e, listeners);
// Use inverse loop because we need to remove listeners callable once
for (let i = listeners.length - 1, listener = null; i >= 0; i -= 1) {
listener = listeners[i];
if (Dispatcher.handleListenerSkipping(e, listener)) {
this.debug('skipped', e, listener);
continue;
}
if (listener.once) {
this.listeners[event].splice(i, 1);
}
try {
this.debug('invoking', e, listener);
// Wait for listener whose return a promise
await listener.invoke(e as never); // eslint-disable-line no-await-in-loop
this.debug('invoked', e, listener);
} catch (err) {
this.debug('failed', e, listener, err as Error);
if (abortOnFailure) {
// Reject promise on "abort on listener failure" strategy
return Promise.reject(err);
}
}
| if (!e.dispatch.propagation) { |
this.debug('stopped', e, listener);
// Stop listeners invokation
break;
}
}
this.debug('end', e, listeners);
return Promise.resolve();
}
protected findListenerIndex<T extends Event>(event: string, callback: Callback<T>): number | undefined {
const listeners = this.listeners[event] || [];
for (let i = 0, len = listeners.length; i < len; i += 1) {
if (listeners[i].callback === callback) {
return i;
}
}
return undefined;
}
protected static handleListenerSkipping(event: Event, listener: Listener<never>): boolean | void {
const { skipNextListeners, skipUntilListener } = event.dispatch;
if (skipNextListeners > 0) {
event.dispatch.skipNextListeners -= 1;
return true;
}
if (skipUntilListener) {
if (listener.id === skipUntilListener) {
event.dispatch.skipUntilListener = undefined;
return;
}
return true;
}
}
protected debug(
action: string,
relatedEvent: Event,
handler: Listener<never> | Listener<never>[],
error: Error | null = null
): void {
if (relatedEvent instanceof DebugEvent || !this.klient.debug) {
return;
}
this.dispatch(new DebugEvent(action, relatedEvent, handler, error), false);
}
}
| src/services/dispatcher/dispatcher.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " return new Promise((resolve) => {\n this.dispatcher.dispatch(event, false).then(() => {\n if (event instanceof RequestCancelEvent) {\n return resolve();\n }\n this.dispatcher.dispatch(new RequestDoneEvent(event), false).then(resolve);\n });\n });\n }\n protected get dispatcher() {",
"score": 0.8151763677597046
},
{
"filename": "src/services/request/factory.ts",
"retrieved_chunk": " this.requests.push(request);\n // Remove request when promise has been fulfilled\n request\n .then((r) => {\n this.removePendingRequest(request);\n return r;\n })\n .catch((e) => {\n this.removePendingRequest(request);\n return e;",
"score": 0.8124101161956787
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " this.abortController.abort();\n return this;\n }\n execute(): this {\n this.dispatcher\n .dispatch(this.primaryEvent)\n .then(() => {\n this.doRequest();\n })\n .catch((e) => {",
"score": 0.8122165203094482
},
{
"filename": "src/__tests__/debug.test.ts",
"retrieved_chunk": " })\n .catch((e) => {\n console.log(e);\n throw e;\n });\n klient.on(\n 'request',\n () => {\n throw new Error();\n },",
"score": 0.8021762371063232
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " this.reject(e);\n });\n return this;\n }\n protected doRequest(): this {\n if (!this.result) {\n this.handler(this.config)\n .then((r) => {\n this.resolve(r);\n })",
"score": 0.7848708033561707
}
] | typescript | if (!e.dispatch.propagation) { |
import * as deepmerge from 'deepmerge';
import type { AxiosRequestConfig } from 'axios';
import type Klient from '../../klient';
import Request from './request';
import type { KlientRequestConfig } from './request';
export default class RequestFactory {
model = Request;
// Requests are stocked during their execution only.
readonly requests: Request[] = [];
constructor(protected readonly klient: Klient) {}
request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
return this.createRequest<T>(urlOrConfig).execute();
}
file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {
const config = deepmerge(
{ responseType: 'blob', context: { action: 'file' } },
typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig
);
return this.request<Blob>(config).then(({ data }) => data);
}
cancelPendingRequests(): this {
for (let i = 0, len = this.requests.length; i < len; i += 1) {
this.requests[i].cancel();
}
return this;
}
createRequest<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {
const config = typeof urlOrConfig === 'string' ? { url: urlOrConfig } : urlOrConfig;
const request = this.model.new<T>(this.prepare(config), this.klient);
// Store request during pending state only
this.requests.push(request);
// Remove request when promise has been fulfilled
request
.then((r) => {
this.removePendingRequest(request);
return r;
})
.catch((e) => {
this.removePendingRequest(request);
return e;
});
return request;
}
isCancel(e: Error) {
return this.model.isCancel(e);
}
protected prepare(config: KlientRequestConfig): KlientRequestConfig {
return deepmerge.all([
{ baseURL: this.klient.url },
| (this.klient.parameters.get('request') as AxiosRequestConfig) || {},
config
]); |
}
protected removePendingRequest(request: Request) {
const i = this.requests.indexOf(request);
if (this.requests[i] instanceof Request) {
this.requests.splice(i, 1);
}
}
}
| src/services/request/factory.ts | klientjs-core-9a67a61 | [
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " request.config = axiosConfig;\n request.callbacks = callbacks;\n request.config.signal = request.abortController.signal;\n request.context = { ...request.context, ...context };\n return request;\n }\n static isCancel(e: Error) {\n return axios.isCancel(e);\n }\n cancel(): this {",
"score": 0.8420905470848083
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " protected constructor(callback: RequestCallback) {\n super(callback);\n }\n static new<T>({ context, ...axiosConfig }: KlientRequestConfig, klient: Klient): Request<T> {\n const callbacks = {} as PromiseCallbacks;\n const request = new this<T>((resolve: ResolveRequest, reject: RejectRequest) => {\n callbacks.resolve = resolve;\n callbacks.reject = reject;\n });\n request.klient = klient;",
"score": 0.8375077247619629
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " off<T extends Event>(event: string, callback: Callback<T>): this {\n this.dispatcher.off(event, callback);\n return this;\n }\n /** === Request === */\n request<T = unknown>(urlOrConfig: KlientRequestConfig | string): Request<T> {\n return this.factory.request(urlOrConfig);\n }\n get<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'GET', url });",
"score": 0.8269336223602295
},
{
"filename": "src/services/request/request.ts",
"retrieved_chunk": " });\n }\n protected reject(error: AxiosError): Promise<void> {\n this.result = error;\n return this.dispatchResultEvent(Request.isCancel(error) ? RequestCancelEvent : RequestErrorEvent).then(() => {\n this.callbacks.reject(this.result as AxiosError);\n });\n }\n protected dispatchResultEvent(EventClass: RequestEventTypes): Promise<void> {\n const event = new EventClass(this.primaryEvent);",
"score": 0.8225389719009399
},
{
"filename": "src/klient.ts",
"retrieved_chunk": " delete<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'DELETE', url });\n }\n head<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'HEAD', url });\n }\n options<T = unknown>(url: string, config?: KlientRequestConfig): Request<T> {\n return this.request<T>({ ...config, method: 'OPTIONS', url });\n }\n file(urlOrConfig: KlientRequestConfig | string): Promise<Blob> {",
"score": 0.811151385307312
}
] | typescript | (this.klient.parameters.get('request') as AxiosRequestConfig) || {},
config
]); |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
| extra.at = stack.parseLine(extra.stack.split('\n')[0])
} |
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " file,\n line: er.loc.line,\n column: er.loc.column + 1,\n }\n } else {\n // parse out the 'at' bit from the first line.\n extra.at = stack.parseLine(splitst[1])\n }\n extra.stack = stack.clean(splitst)\n }",
"score": 0.7886040210723877
},
{
"filename": "src/base.ts",
"retrieved_chunk": " } else if (!er.stack) {\n console.error(er)\n } else {\n if (message) {\n er.message = message\n }\n delete extra.stack\n delete extra.at\n console.error('%s: %s', er.name || 'Error', message)\n console.error(",
"score": 0.7828000783920288
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const res = { ...object }\n if (hasOwn(res, 'stack') && !hasOwn(res, 'at')) {\n res.at = stack.parseLine(res.stack.split('\\n')[0])\n }\n const file = res.at && res.at.file && resolve(res.at.file)\n if (\n !options.stackIncludesTap &&\n file &&\n file.includes(tapDir)\n ) {",
"score": 0.7763973474502563
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (!er || typeof er !== 'object') {\n extra.error = er\n return extra\n }\n // pull out error details\n const message = er.message ? er.message\n : er.stack ? er.stack.split('\\n')[0]\n : ''\n if (er.message) {\n try {",
"score": 0.7758283615112305
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " Object.defineProperty(er, 'message', {\n value: '',\n configurable: true\n })\n } catch {}\n }\n const st = er.stack && er.stack.substr(\n er._babel ? (message + er.codeFrame).length : 0)\n if (st) {\n const splitst = st.split('\\n')",
"score": 0.7758173942565918
}
] | typescript | extra.at = stack.parseLine(extra.stack.split('\n')[0])
} |
// This file is automatically generated, please do not edit
import { FinalResults } from 'tap-parser'
import parseTestArgs, {
TestArgs,
} from './parse-test-args.js'
import { TestBase, TestBaseOpts } from './test-base.js'
const copyToString = (v: Function) => ({
toString: Object.assign(() => v.toString(), {
toString: () => 'function toString() { [native code] }',
}),
})
import plugin0 from "./plugin/after-each.js"
import plugin1 from "./plugin/before-each.js"
import plugin2 from "./plugin/spawn.js"
import plugin3 from "./plugin/stdin.js"
type PI<O extends TestBaseOpts | any = any> =
| ((t: Test, opts: O) => Plug)
| ((t: Test) => Plug)
const plugins: PI[] = [
plugin0,
plugin1,
plugin2,
plugin3,
]
type Plug =
| TestBase
| { t: Test }
| ReturnType<typeof plugin0>
| ReturnType<typeof plugin1>
| ReturnType<typeof plugin2>
| ReturnType<typeof plugin3>
type PlugKeys =
| keyof TestBase
| 't'
| keyof ReturnType<typeof plugin0>
| keyof ReturnType<typeof plugin1>
| keyof ReturnType<typeof plugin2>
| keyof ReturnType<typeof plugin3>
type SecondParam<
T extends [any] | [any, any],
Fallback extends unknown = unknown
> = T extends [any, any] ? T[1] : Fallback
type Plugin0Opts = SecondParam<
Parameters<typeof plugin0>,
TestBaseOpts
>
type Plugin1Opts = SecondParam<
Parameters<typeof plugin1>,
TestBaseOpts
>
type Plugin2Opts = SecondParam<
Parameters<typeof plugin2>,
TestBaseOpts
>
type Plugin3Opts = SecondParam<
Parameters<typeof plugin3>,
TestBaseOpts
>
type TestOpts = TestBaseOpts
& Plugin0Opts
& Plugin1Opts
& Plugin2Opts
& Plugin3Opts
type TTest = TestBase
& ReturnType<typeof plugin0>
& ReturnType<typeof plugin1>
& ReturnType<typeof plugin2>
& ReturnType<typeof | plugin3>
export interface Test extends TTest { |
end(): this
t: Test
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null>
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null>
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null>
}
const applyPlugins = (base: Test): Test => {
const ext: Plug[] = [
...plugins.map(p => p(base, base.options)),
base,
]
const getCache = new Map<any, any>()
const t = new Proxy(base, {
has(_, p) {
for (const t of ext) {
if (Reflect.has(t, p)) return true
}
return false
},
ownKeys() {
const k: PlugKeys[] = []
for (const t of ext) {
const keys = Reflect.ownKeys(t) as PlugKeys[]
k.push(...keys)
}
return [...new Set(k)]
},
getOwnPropertyDescriptor(_, p) {
for (const t of ext) {
const prop = Reflect.getOwnPropertyDescriptor(t, p)
if (prop) return prop
}
return undefined
},
set(_, p, v) {
// check to see if there's any setters, and if so, set it there
// otherwise, just set on the base
for (const t of ext) {
let o: Object | null = t
while (o) {
if (Reflect.getOwnPropertyDescriptor(o, p)?.set) {
//@ts-ignore
t[p] = v
return true
}
o = Reflect.getPrototypeOf(o)
}
}
//@ts-ignore
base[p as keyof TestBase] = v
return true
},
get(_, p) {
// cache get results so t.blah === t.blah
// we only cache functions, so that getters aren't memoized
// Of course, a getter that returns a function will be broken,
// at least when accessed from outside the plugin, but that's
// a pretty narrow caveat, and easily documented.
if (getCache.has(p)) return getCache.get(p)
for (const plug of ext) {
if (p in plug) {
//@ts-ignore
const v = plug[p]
// Functions need special handling so that they report
// the correct toString and are called on the correct object
// Otherwise attempting to access #private props will fail.
if (typeof v === 'function') {
const f: (this: Plug, ...args: any) => any =
function (...args: any[]) {
const thisArg = this === t ? plug : this
return v.apply(thisArg, args)
}
const vv = Object.assign(f, copyToString(v))
const nameProp =
Reflect.getOwnPropertyDescriptor(v, 'name')
if (nameProp) {
Reflect.defineProperty(f, 'name', nameProp)
}
getCache.set(p, vv)
return vv
} else {
getCache.set(p, v)
return v
}
}
}
},
})
Object.assign(base, { t })
ext.unshift({ t })
return t
}
export class Test extends TestBase {
constructor(opts: TestOpts) {
super(opts)
return applyPlugins(this)
}
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.test)
}
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.todo)
}
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.skip = true
return this.sub(Test, extra, this.skip)
}
}
| src/test-built.ts | tapjs-core-edd7403 | [
{
"filename": "src/build.ts",
"retrieved_chunk": " T extends [any] | [any, any],\n Fallback extends unknown = unknown\n> = T extends [any, any] ? T[1] : Fallback\n${plugins\n .map(\n (_, i) => `type Plugin${i}Opts = SecondParam<\n Parameters<typeof plugin${i}>,\n TestBaseOpts\n>\\n`\n )",
"score": 0.7795549035072327
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{PLUGINS CODE START}}\ntype Plug = TestBase | { t: Test }\nconst plugins: PI[] = []\ntype PlugKeys = keyof TestBase | 't'\n//{{PLUGINS CODE END}}\n//{{OPTS START}}\ntype TestOpts = TestBaseOpts\n//{{OPTS END}}\n//{{TEST INTERFACE START}}\ntype TTest = TestBase",
"score": 0.7627729177474976
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " new (): T\n}\nexport type TapPlugin<\n B extends Object,\n O extends TestBaseOpts | any = any\n> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)\nexport interface TestBaseOpts extends BaseOpts {\n /**\n * The number of jobs to run in parallel. Defaults to 1\n */",
"score": 0.7532548904418945
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": "const copyToString = (v: Function) => ({\n toString: Object.assign(() => v.toString(), {\n toString: () => 'function toString() { [native code] }',\n }),\n})\n//{{PLUGIN IMPORT START}}\n//{{PLUGIN IMPORT END}}\ntype PI<O extends TestBaseOpts | any = any> =\n | ((t: Test, opts: O) => Plug)\n | ((t: Test) => Plug)",
"score": 0.7418386340141296
},
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": "}\nconst plugin: TapPlugin<StdinPlugin> = (t: TestBase) =>\n new StdinPlugin(t)\nexport default plugin",
"score": 0.7414115071296692
}
] | typescript | plugin3>
export interface Test extends TTest { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
| cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> { |
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/waiter.ts",
"retrieved_chunk": "export class Waiter {\n cb: null | ((w:Waiter)=>any)\n ready: boolean = false\n value: any = null\n resolved: boolean = false\n rejected: boolean = false\n done: boolean = false\n finishing: boolean = false\n expectReject: boolean\n promise: Promise<void>",
"score": 0.8605338335037231
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " ): Promise<FinalResults | null>\n todo(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n todo(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.856270432472229
},
{
"filename": "src/plugin/spawn.ts",
"retrieved_chunk": " spawn(\n cmd: string,\n options: SpawnOpts,\n name?: string\n ): Promise<FinalResults | null>\n spawn(\n cmd: string,\n args: string | string[],\n name?: string\n ): Promise<FinalResults | null>",
"score": 0.8479340672492981
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " t: Test\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.8476960062980652
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n skip(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n skip(\n extra: { [k: string]: any },\n cb?: (t: Test) => any",
"score": 0.8471311926841736
}
] | typescript | cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this | .threw(er)
return
} |
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8258577585220337
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": " this.value = value\n this.done = true\n this.finish()\n }).catch(er => this.reject(er))\n }\n reject (er:any) {\n if (this.done) {\n return\n }\n this.value = er",
"score": 0.8073476552963257
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // do we need this? couldn't we just call the Minipass\n this.output = ''\n this.indent = options.indent || ''\n this.name = options.name || '(unnamed test)'\n this.hook.runInAsyncScope(\n () =>\n (this.hookDomain = new Domain((er, type) => {\n if (!er || typeof er !== 'object')\n er = { error: er }\n er.tapCaught = type",
"score": 0.8041407465934753
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.setTimeout(0)\n options = options || {}\n options.expired = options.expired || this.name\n const threw = this.threw(new Error('timeout!'), options)\n if (threw) {\n this.emit('timeout', threw)\n }\n }\n runMain(cb: () => void) {\n this.debug('BASE runMain')",
"score": 0.8037567734718323
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.stream.end()\n return this\n }\n threw(er: any, extra?: any, proxy?: boolean) {\n this.hook.emitDestroy()\n this.hookDomain.destroy()\n if (typeof er === 'string') {\n er = { message: er }\n } else if (!er || typeof er !== 'object') {\n er = { error: er }",
"score": 0.8022634983062744
}
] | typescript | .threw(er)
return
} |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p. | name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
} |
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/test-point.ts",
"retrieved_chunk": "}\nconst tpMessage = (\n description: string,\n extra: { [k: string]: any },\n options: TestBaseOpts = {}\n): string => {\n let message = description ? ` - ${description}` : ''\n if (extra.skip) {\n message += ' # SKIP'\n if (typeof extra.skip === 'string') {",
"score": 0.8014518618583679
},
{
"filename": "src/base.ts",
"retrieved_chunk": " online(line: string) {\n this.debug('LINE %j', line, [this.name, this.indent])\n return this.write(this.indent + line)\n }\n write(\n c: ContiguousData,\n e?: Encoding | (() => any),\n cb?: () => any\n ) {\n if (this.buffered) {",
"score": 0.7904624342918396
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " test(cb?: (t: Test) => any): Promise<FinalResults | null>\n test(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,",
"score": 0.7867015600204468
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.todo)\n }\n skip(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any",
"score": 0.7830837368965149
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.7772746086120605
}
] | typescript | name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
} |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
| writeSubComment<T extends TestPoint | Base>(p: T) { |
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{TEST INTERFACE END}}\nexport interface Test extends TTest {\n end(): this\n t: Test\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(",
"score": 0.8096556067466736
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.8075931668281555
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.todo)\n }\n skip(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any",
"score": 0.8013673424720764
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " return t\n}\nexport class Test extends TestBase {\n constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },",
"score": 0.7986410856246948
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " test(cb?: (t: Test) => any): Promise<FinalResults | null>\n test(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,",
"score": 0.7968888282775879
}
] | typescript | writeSubComment<T extends TestPoint | Base>(p: T) { |
// This file is automatically generated, please do not edit
import { FinalResults } from 'tap-parser'
import parseTestArgs, {
TestArgs,
} from './parse-test-args.js'
import { TestBase, TestBaseOpts } from './test-base.js'
const copyToString = (v: Function) => ({
toString: Object.assign(() => v.toString(), {
toString: () => 'function toString() { [native code] }',
}),
})
import plugin0 from "./plugin/after-each.js"
import plugin1 from "./plugin/before-each.js"
import plugin2 from "./plugin/spawn.js"
import plugin3 from "./plugin/stdin.js"
type PI<O extends TestBaseOpts | any = any> =
| ((t: Test, opts: O) => Plug)
| ((t: Test) => Plug)
const plugins: PI[] = [
plugin0,
plugin1,
plugin2,
plugin3,
]
type Plug =
| TestBase
| { t: Test }
| ReturnType<typeof plugin0>
| ReturnType<typeof plugin1>
| ReturnType<typeof plugin2>
| ReturnType<typeof plugin3>
type PlugKeys =
| keyof TestBase
| 't'
| keyof ReturnType<typeof plugin0>
| keyof ReturnType<typeof plugin1>
| keyof ReturnType<typeof plugin2>
| keyof ReturnType<typeof plugin3>
type SecondParam<
T extends [any] | [any, any],
Fallback extends unknown = unknown
> = T extends [any, any] ? T[1] : Fallback
type Plugin0Opts = SecondParam<
Parameters<typeof plugin0>,
TestBaseOpts
>
type Plugin1Opts = SecondParam<
Parameters<typeof plugin1>,
TestBaseOpts
>
type Plugin2Opts = SecondParam<
Parameters<typeof plugin2>,
TestBaseOpts
>
type Plugin3Opts = SecondParam<
Parameters<typeof plugin3>,
TestBaseOpts
>
type TestOpts = TestBaseOpts
& Plugin0Opts
& Plugin1Opts
& Plugin2Opts
& Plugin3Opts
type TTest = TestBase
& ReturnType<typeof plugin0>
& ReturnType<typeof plugin1>
| & ReturnType<typeof plugin2>
& ReturnType<typeof plugin3>
export interface Test extends TTest { |
end(): this
t: Test
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null>
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null>
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null>
}
const applyPlugins = (base: Test): Test => {
const ext: Plug[] = [
...plugins.map(p => p(base, base.options)),
base,
]
const getCache = new Map<any, any>()
const t = new Proxy(base, {
has(_, p) {
for (const t of ext) {
if (Reflect.has(t, p)) return true
}
return false
},
ownKeys() {
const k: PlugKeys[] = []
for (const t of ext) {
const keys = Reflect.ownKeys(t) as PlugKeys[]
k.push(...keys)
}
return [...new Set(k)]
},
getOwnPropertyDescriptor(_, p) {
for (const t of ext) {
const prop = Reflect.getOwnPropertyDescriptor(t, p)
if (prop) return prop
}
return undefined
},
set(_, p, v) {
// check to see if there's any setters, and if so, set it there
// otherwise, just set on the base
for (const t of ext) {
let o: Object | null = t
while (o) {
if (Reflect.getOwnPropertyDescriptor(o, p)?.set) {
//@ts-ignore
t[p] = v
return true
}
o = Reflect.getPrototypeOf(o)
}
}
//@ts-ignore
base[p as keyof TestBase] = v
return true
},
get(_, p) {
// cache get results so t.blah === t.blah
// we only cache functions, so that getters aren't memoized
// Of course, a getter that returns a function will be broken,
// at least when accessed from outside the plugin, but that's
// a pretty narrow caveat, and easily documented.
if (getCache.has(p)) return getCache.get(p)
for (const plug of ext) {
if (p in plug) {
//@ts-ignore
const v = plug[p]
// Functions need special handling so that they report
// the correct toString and are called on the correct object
// Otherwise attempting to access #private props will fail.
if (typeof v === 'function') {
const f: (this: Plug, ...args: any) => any =
function (...args: any[]) {
const thisArg = this === t ? plug : this
return v.apply(thisArg, args)
}
const vv = Object.assign(f, copyToString(v))
const nameProp =
Reflect.getOwnPropertyDescriptor(v, 'name')
if (nameProp) {
Reflect.defineProperty(f, 'name', nameProp)
}
getCache.set(p, vv)
return vv
} else {
getCache.set(p, v)
return v
}
}
}
},
})
Object.assign(base, { t })
ext.unshift({ t })
return t
}
export class Test extends TestBase {
constructor(opts: TestOpts) {
super(opts)
return applyPlugins(this)
}
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.test)
}
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.todo)
}
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.skip = true
return this.sub(Test, extra, this.skip)
}
}
| src/test-built.ts | tapjs-core-edd7403 | [
{
"filename": "src/build.ts",
"retrieved_chunk": " T extends [any] | [any, any],\n Fallback extends unknown = unknown\n> = T extends [any, any] ? T[1] : Fallback\n${plugins\n .map(\n (_, i) => `type Plugin${i}Opts = SecondParam<\n Parameters<typeof plugin${i}>,\n TestBaseOpts\n>\\n`\n )",
"score": 0.7774625420570374
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{PLUGINS CODE START}}\ntype Plug = TestBase | { t: Test }\nconst plugins: PI[] = []\ntype PlugKeys = keyof TestBase | 't'\n//{{PLUGINS CODE END}}\n//{{OPTS START}}\ntype TestOpts = TestBaseOpts\n//{{OPTS END}}\n//{{TEST INTERFACE START}}\ntype TTest = TestBase",
"score": 0.7572762966156006
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " new (): T\n}\nexport type TapPlugin<\n B extends Object,\n O extends TestBaseOpts | any = any\n> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)\nexport interface TestBaseOpts extends BaseOpts {\n /**\n * The number of jobs to run in parallel. Defaults to 1\n */",
"score": 0.7500830292701721
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": "const copyToString = (v: Function) => ({\n toString: Object.assign(() => v.toString(), {\n toString: () => 'function toString() { [native code] }',\n }),\n})\n//{{PLUGIN IMPORT START}}\n//{{PLUGIN IMPORT END}}\ntype PI<O extends TestBaseOpts | any = any> =\n | ((t: Test, opts: O) => Plug)\n | ((t: Test) => Plug)",
"score": 0.736182451248169
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " ): Promise<FinalResults | null>\n skip(cb?: (t: Test) => any): Promise<FinalResults | null>\n skip(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null>\n}\nconst applyPlugins = (base: Test): Test => {\n const ext: Plug[] = [\n ...plugins.map(p => p(base, base.options)),\n base,",
"score": 0.7339662313461304
}
] | typescript | & ReturnType<typeof plugin2>
& ReturnType<typeof plugin3>
export interface Test extends TTest { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
| if (this.bail && !ok && !extra.skip && !extra.todo) { |
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " this.parser.on('result', () => this.counts.total++)\n this.parser.on('pass', () => this.counts.pass++)\n this.parser.on('todo', res => {\n this.counts.todo++\n this.lists.todo.push(res)\n })\n this.parser.on('skip', res => {\n // it is uselessly noisy to print out lists of tests skipped\n // because of a --grep or --only argument.\n if (/^filter: (only|\\/.*\\/)$/.test(res.skip)) return",
"score": 0.741902232170105
},
{
"filename": "src/stdin.ts",
"retrieved_chunk": " }\n threw(er: any, extra?: any, proxy?: boolean) {\n extra = super.threw(er, extra, proxy)\n Object.assign(this.options, extra)\n this.parser.abort(er.message, extra)\n this.parser.end()\n }\n}",
"score": 0.7367023229598999
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n }\n setupParser() {\n this.parser.on('line', l => this.online(l))\n this.parser.once('bailout', reason =>\n this.onbail(reason)\n )\n this.parser.on('complete', result =>\n this.oncomplete(result)\n )",
"score": 0.734722375869751
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.counts.skip++\n this.lists.skip.push(res)\n })\n this.parser.on('fail', res => {\n this.counts.fail++\n this.lists.fail.push(res)\n })\n }\n setTimeout(n: number) {\n if (n <= 0) {",
"score": 0.7247698307037354
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " this.proc.kill('SIGKILL')\n }\n this.parser.abort('test unfinished')\n this.callCb()\n }\n callCb() {\n if (this.cb) {\n this.cb()\n }\n this.cb = null",
"score": 0.7190718650817871
}
] | typescript | if (this.bail && !ok && !extra.skip && !extra.todo) { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
| this.hook.runInAsyncScope(cb, this, ...args)
} |
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/plugin/before-each.ts",
"retrieved_chunk": " const runMain = t.runMain\n t.runMain = (cb: () => void) => {\n this.#runBeforeEach(this.#t, () =>\n runMain.call(t, cb)\n )\n }\n }\n #onBeforeEach: ((t: Test) => void)[] = []\n beforeEach(fn: (t: Test) => void | Promise<void>) {\n this.#onBeforeEach.push(fn)",
"score": 0.8713345527648926
},
{
"filename": "src/plugin/after-each.ts",
"retrieved_chunk": " t.runMain = (cb: () => void) => {\n runMain.call(t, () => this.#runAfterEach(this.#t, cb))\n }\n }\n #onAfterEach: ((t: Test) => void)[] = []\n afterEach(fn: (t: Test) => void | Promise<void>) {\n this.#onAfterEach.push(fn)\n }\n #runAfterEach(who: TestBase, cb: () => void) {\n // run all the afterEach methods from the parent",
"score": 0.8640362024307251
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.start = hrtime.bigint()\n this.hook.runInAsyncScope(this.main, this, cb)\n }\n main(cb: () => void) {\n cb()\n }\n onbail(reason?: string) {\n this.bailedOut = reason || true\n this.emit('bailout', reason)\n }",
"score": 0.8134303092956543
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(",
"score": 0.8094044923782349
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.8066369891166687
}
] | typescript | this.hook.runInAsyncScope(cb, this, ...args)
} |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends | TestPoint | Base>(p: T) { |
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{TEST INTERFACE END}}\nexport interface Test extends TTest {\n end(): this\n t: Test\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(",
"score": 0.8122380971908569
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.8021538257598877
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " return t\n}\nexport class Test extends TestBase {\n constructor(opts: TestOpts) {\n super(opts)\n return applyPlugins(this)\n }\n test(\n name: string,\n extra: { [k: string]: any },",
"score": 0.801152765750885
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.todo)\n }\n skip(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any",
"score": 0.7953494787216187
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " test(cb?: (t: Test) => any): Promise<FinalResults | null>\n test(\n ...args: TestArgs<Test>\n ): Promise<FinalResults | null> {\n const extra = parseTestArgs(...args)\n extra.todo = true\n return this.sub(Test, extra, this.test)\n }\n todo(\n name: string,",
"score": 0.7940241694450378
}
] | typescript | TestPoint | Base>(p: T) { |
import stack from './stack'
import type {BaseOpts} from './base'
export default (er:any, extra?:{[k: string]:any}, options?:BaseOpts) => {
// the yaml module puts big stuff here, pluck it off
if (er.source && typeof er.source === 'object' && er.source.context)
er.source = { ...er.source, context: null }
// pull out all fields from options, other than anything starting
// with tapChild, or anything already set in the extra object.
extra = Object.fromEntries(Object.entries(options || {}).filter(([k]) =>
!/^tapChild/.test(k) && !(k in (extra || {}))))
if (!er || typeof er !== 'object') {
extra.error = er
return extra
}
// pull out error details
const message = er.message ? er.message
: er.stack ? er.stack.split('\n')[0]
: ''
if (er.message) {
try {
Object.defineProperty(er, 'message', {
value: '',
configurable: true
})
} catch {}
}
const st = er.stack && er.stack.substr(
er._babel ? (message + er.codeFrame).length : 0)
if (st) {
const splitst = st.split('\n')
if (er._babel && er.loc) {
const msplit = message.split(': ')
const f = msplit[0].trim()
extra.message = msplit.slice(1).join(': ')
.replace(/ \([0-9]+:[0-9]+\)$/, '').trim()
const file = f.indexOf(process.cwd()) === 0
? f.substr(process.cwd().length + 1) : f
if (file !== 'unknown')
delete er.codeFrame
extra.at = {
file,
line: er.loc.line,
column: er.loc.column + 1,
}
} else {
// parse out the 'at' bit from the first line.
| extra.at = stack.parseLine(splitst[1])
} |
extra.stack = stack.clean(splitst)
}
if (message) {
try {
Object.defineProperty(er, 'message', {
value: message,
configurable: true
})
} catch {}
}
if (er.name && er.name !== 'Error') {
extra.type = er.name
}
Object.assign(extra, Object.fromEntries(Object.entries(er).filter(([k]) =>
k !== 'message')))
return extra
}
| src/extra-from-error.ts | tapjs-core-edd7403 | [
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " // don't print locations in tap itself, that's almost never useful\n delete res.at\n }\n if (\n file &&\n res.at &&\n res.at.file &&\n res.at.line &&\n !res.source\n ) {",
"score": 0.8021737337112427
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " extra.at = stack.parseLine(extra.stack.split('\\n')[0])\n }\n if (\n !ok &&\n !extra.skip &&\n !extra.at &&\n typeof fn === 'function'\n ) {\n extra.at = stack.at(fn)\n if (!extra.todo) {",
"score": 0.8002074956893921
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " const content = tryReadFile(file)\n if (content) {\n const lines = content.split('\\n')\n if (res.at.line <= lines.length) {\n const startLine = Math.max(res.at.line - 2, 0)\n const endLine = Math.min(\n res.at.line + 2,\n lines.length\n )\n const caret =",
"score": 0.7996957302093506
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.769731342792511
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " : !ok\n if (diagnostic) {\n extra.diagnostic = true\n }\n this.count = n\n message = message + ''\n const res = { ok, message, extra }\n const tp = new TestPoint(ok, message, extra)\n // when we jump the queue, skip an extra line\n if (front) {",
"score": 0.7669562101364136
}
] | typescript | extra.at = stack.parseLine(splitst[1])
} |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp | = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) { |
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.85784512758255
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " } else if (arg === false) {\n // it's handy while developing to put a ! in front of a\n // function to temporarily make a test todo\n continue\n } else if (typeof arg !== 'undefined')\n throw new TypeError(\n 'unknown argument passed to parseTestArgs: ' +\n typeof arg\n )\n }",
"score": 0.8289674520492554
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "}\nconst tpMessage = (\n description: string,\n extra: { [k: string]: any },\n options: TestBaseOpts = {}\n): string => {\n let message = description ? ` - ${description}` : ''\n if (extra.skip) {\n message += ' # SKIP'\n if (typeof extra.skip === 'string') {",
"score": 0.8235094547271729
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": " this.done = true\n this.value = er\n // make it clear that this is a problem by doing\n // the opposite of what was requested.\n this.rejected = !this.expectReject\n return this.finish()\n }\n finish () {\n if (this.ready && this.done && !this.finishing) {\n this.finishing = true",
"score": 0.8140737414360046
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // a bit excessive.\n if (this.results) {\n const alreadyBailing = !this.results.ok && this.bail\n this.results.ok = false\n if (this.parent) {\n this.parent.threw(er, extra, true)\n } else if (alreadyBailing) {\n // we are already bailing out, and this is the top level,\n // just make our way hastily to the nearest exit.\n return",
"score": 0.8138232231140137
}
] | typescript | = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack | = stack.captureString(80, fn)
} |
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/test-point.ts",
"retrieved_chunk": " message += ' ' + esc(extra.skip)\n }\n } else if (extra.todo) {\n message += ' # TODO'\n if (typeof extra.todo === 'string') {\n message += ' ' + esc(extra.todo)\n }\n } else if (extra.time) {\n message += ' # time=' + extra.time + 'ms'\n }",
"score": 0.7987893223762512
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " file,\n line: er.loc.line,\n column: er.loc.column + 1,\n }\n } else {\n // parse out the 'at' bit from the first line.\n extra.at = stack.parseLine(splitst[1])\n }\n extra.stack = stack.clean(splitst)\n }",
"score": 0.7946867942810059
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " Object.defineProperty(er, 'message', {\n value: '',\n configurable: true\n })\n } catch {}\n }\n const st = er.stack && er.stack.substr(\n er._babel ? (message + er.codeFrame).length : 0)\n if (st) {\n const splitst = st.split('\\n')",
"score": 0.7912988662719727
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // do we need this? couldn't we just call the Minipass\n this.output = ''\n this.indent = options.indent || ''\n this.name = options.name || '(unnamed test)'\n this.hook.runInAsyncScope(\n () =>\n (this.hookDomain = new Domain((er, type) => {\n if (!er || typeof er !== 'object')\n er = { error: er }\n er.tapCaught = type",
"score": 0.7911160588264465
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " // don't print locations in tap itself, that's almost never useful\n delete res.at\n }\n if (\n file &&\n res.at &&\n res.at.file &&\n res.at.line &&\n !res.source\n ) {",
"score": 0.7909649610519409
}
] | typescript | = stack.captureString(80, fn)
} |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this | .name
if (this.#occupied && this.#occupied instanceof Base) { |
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " this.setTimeout(0)\n options = options || {}\n options.expired = options.expired || this.name\n const threw = this.threw(new Error('timeout!'), options)\n if (threw) {\n this.emit('timeout', threw)\n }\n }\n runMain(cb: () => void) {\n this.debug('BASE runMain')",
"score": 0.8398252129554749
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.8301317691802979
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " public args: string[]\n public stdio: StdioOptions\n public env: { [k: string]: string } | typeof process.env\n public proc: null | ChildProcess\n public cb: null | (() => void)\n constructor(options: SpawnOpts) {\n // figure out the name before calling super()\n const command = options.command\n if (!command) {\n throw new TypeError('no command provided')",
"score": 0.8169088959693909
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": " this.done = true\n this.value = er\n // make it clear that this is a problem by doing\n // the opposite of what was requested.\n this.rejected = !this.expectReject\n return this.finish()\n }\n finish () {\n if (this.ready && this.done && !this.finishing) {\n this.finishing = true",
"score": 0.806803286075592
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " if (p in plug) {\n //@ts-ignore\n const v = plug[p]\n // Functions need special handling so that they report\n // the correct toString and are called on the correct object\n // Otherwise attempting to access #private props will fail.\n if (typeof v === 'function') {\n const f: (this: Plug, ...args: any) => any =\n function (...args: any[]) {\n const thisArg = this === t ? plug : this",
"score": 0.8055765628814697
}
] | typescript | .name
if (this.#occupied && this.#occupied instanceof Base) { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
| this.threw(er)
return
} |
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " this.stream.end()\n return this\n }\n threw(er: any, extra?: any, proxy?: boolean) {\n this.hook.emitDestroy()\n this.hookDomain.destroy()\n if (typeof er === 'string') {\n er = { message: er }\n } else if (!er || typeof er !== 'object') {\n er = { error: er }",
"score": 0.8217122554779053
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " if (message) {\n try {\n Object.defineProperty(er, 'message', {\n value: message,\n configurable: true\n })\n } catch {}\n }\n if (er.name && er.name !== 'Error') {\n extra.type = er.name",
"score": 0.8205419182777405
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // do we need this? couldn't we just call the Minipass\n this.output = ''\n this.indent = options.indent || ''\n this.name = options.name || '(unnamed test)'\n this.hook.runInAsyncScope(\n () =>\n (this.hookDomain = new Domain((er, type) => {\n if (!er || typeof er !== 'object')\n er = { error: er }\n er.tapCaught = type",
"score": 0.8164570331573486
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " Object.defineProperty(er, 'message', {\n value: '',\n configurable: true\n })\n } catch {}\n }\n const st = er.stack && er.stack.substr(\n er._babel ? (message + er.codeFrame).length : 0)\n if (st) {\n const splitst = st.split('\\n')",
"score": 0.8061398267745972
},
{
"filename": "src/base.ts",
"retrieved_chunk": " } else if (!er.stack) {\n console.error(er)\n } else {\n if (message) {\n er.message = message\n }\n delete extra.stack\n delete extra.at\n console.error('%s: %s', er.name || 'Error', message)\n console.error(",
"score": 0.8005356788635254
}
] | typescript | this.threw(er)
return
} |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this | .write(message)
} else { |
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " const msg = format(...args).trim()\n console.error(\n prefix + msg.split('\\n').join(`\\n${prefix}`)\n )\n }\nexport interface BaseOpts {\n // parser-related options\n bail?: boolean\n strict?: boolean\n omitVersion?: boolean",
"score": 0.836342990398407
},
{
"filename": "src/diags.ts",
"retrieved_chunk": " typeof clean !== 'object' ||\n !Object.keys(clean).length\n ) {\n return ''\n }\n return (\n ' ---\\n' +\n yaml\n .stringify(clean)\n .split('\\n')",
"score": 0.8148785829544067
},
{
"filename": "src/base.ts",
"retrieved_chunk": " online(line: string) {\n this.debug('LINE %j', line, [this.name, this.indent])\n return this.write(this.indent + line)\n }\n write(\n c: ContiguousData,\n e?: Encoding | (() => any),\n cb?: () => any\n ) {\n if (this.buffered) {",
"score": 0.8032940626144409
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " Object.defineProperty(er, 'message', {\n value: '',\n configurable: true\n })\n } catch {}\n }\n const st = er.stack && er.stack.substr(\n er._babel ? (message + er.codeFrame).length : 0)\n if (st) {\n const splitst = st.split('\\n')",
"score": 0.7949972152709961
},
{
"filename": "src/build.ts",
"retrieved_chunk": "const swapTag = (\n src: string,\n tag: string,\n code: string\n): string => {\n const st = '//{{' + tag + ' START}}\\n'\n const et = '//{{' + tag + ' END}}\\n'\n const start = src.indexOf(st)\n const end = src.indexOf(et)\n return (",
"score": 0.7727634906768799
}
] | typescript | .write(message)
} else { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p. | extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) { |
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/spawn.ts",
"retrieved_chunk": " /* istanbul ignore next */ '0'\n ),\n TAP: '1',\n TAP_BAIL: this.bail ? '1' : '0',\n }\n this.proc = null\n this.cb = null\n }\n endAll() {\n if (this.proc) {",
"score": 0.807388186454773
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " } else if (arg === false) {\n // it's handy while developing to put a ! in front of a\n // function to temporarily make a test todo\n continue\n } else if (typeof arg !== 'undefined')\n throw new TypeError(\n 'unknown argument passed to parseTestArgs: ' +\n typeof arg\n )\n }",
"score": 0.7901462316513062
},
{
"filename": "src/base.ts",
"retrieved_chunk": " return f\n })\n if (errors.length) {\n this.errors = errors\n }\n this.onbeforeend()\n // XXX old tap had a check here to ensure that buffer and pipes\n // are cleared. But Minipass \"should\" do this now for us, so\n // this ought to be fine, but revisit if it causes problems.\n this.stream.end()",
"score": 0.7886586785316467
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.7826724052429199
},
{
"filename": "src/base.ts",
"retrieved_chunk": " this.threw(er)\n }))\n )\n this.debug = !!options.debug\n ? debug(this.name)\n : () => {}\n this.parser =\n options.parser ||\n new Parser({\n bail: this.bail,",
"score": 0.7789286375045776
}
] | typescript | extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this | .#occupied.timeout(options)
} else { |
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " this.setTimeout(0)\n options = options || {}\n options.expired = options.expired || this.name\n const threw = this.threw(new Error('timeout!'), options)\n if (threw) {\n this.emit('timeout', threw)\n }\n }\n runMain(cb: () => void) {\n this.debug('BASE runMain')",
"score": 0.8313875198364258
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.8089401125907898
},
{
"filename": "src/base.ts",
"retrieved_chunk": " if (this.timer) {\n clearTimeout(this.timer)\n }\n this.timer = undefined\n } else {\n this.timer = setTimeout(() => this.timeout(), n)\n this.timer.unref()\n }\n }\n timeout(options?: { [k: string]: any }) {",
"score": 0.8041328191757202
},
{
"filename": "src/plugin/spawn.ts",
"retrieved_chunk": " options = args\n args = []\n }\n options = options || {}\n if (options.name === undefined) {\n options.name = name\n }\n options.command = cmd\n options.args = args\n return this.#t.sub(Spawn, options, this.spawn)",
"score": 0.8009724020957947
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": " this.done = true\n this.value = er\n // make it clear that this is a problem by doing\n // the opposite of what was requested.\n this.rejected = !this.expectReject\n return this.finish()\n }\n finish () {\n if (this.ready && this.done && !this.finishing) {\n this.finishing = true",
"score": 0.7970117926597595
}
] | typescript | .#occupied.timeout(options)
} else { |
import stack from './stack'
import type {BaseOpts} from './base'
export default (er:any, extra?:{[k: string]:any}, options?:BaseOpts) => {
// the yaml module puts big stuff here, pluck it off
if (er.source && typeof er.source === 'object' && er.source.context)
er.source = { ...er.source, context: null }
// pull out all fields from options, other than anything starting
// with tapChild, or anything already set in the extra object.
extra = Object.fromEntries(Object.entries(options || {}).filter(([k]) =>
!/^tapChild/.test(k) && !(k in (extra || {}))))
if (!er || typeof er !== 'object') {
extra.error = er
return extra
}
// pull out error details
const message = er.message ? er.message
: er.stack ? er.stack.split('\n')[0]
: ''
if (er.message) {
try {
Object.defineProperty(er, 'message', {
value: '',
configurable: true
})
} catch {}
}
const st = er.stack && er.stack.substr(
er._babel ? (message + er.codeFrame).length : 0)
if (st) {
const splitst = st.split('\n')
if (er._babel && er.loc) {
const msplit = message.split(': ')
const f = msplit[0].trim()
extra.message = msplit.slice(1).join(': ')
.replace(/ \([0-9]+:[0-9]+\)$/, '').trim()
const file = f.indexOf(process.cwd()) === 0
? f.substr(process.cwd().length + 1) : f
if (file !== 'unknown')
delete er.codeFrame
extra.at = {
file,
line: er.loc.line,
column: er.loc.column + 1,
}
} else {
// parse out the 'at' bit from the first line.
extra.at = stack.parseLine(splitst[1])
}
extra.stack = stack | .clean(splitst)
} |
if (message) {
try {
Object.defineProperty(er, 'message', {
value: message,
configurable: true
})
} catch {}
}
if (er.name && er.name !== 'Error') {
extra.type = er.name
}
Object.assign(extra, Object.fromEntries(Object.entries(er).filter(([k]) =>
k !== 'message')))
return extra
}
| src/extra-from-error.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " er.stack.split(/\\n/).slice(1).join('\\n')\n )\n console.error(extra)\n }\n } else {\n this.parser.ok = false\n }\n return extra\n }\n passing() {",
"score": 0.8270148634910583
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " extra.at = stack.parseLine(extra.stack.split('\\n')[0])\n }\n if (\n !ok &&\n !extra.skip &&\n !extra.at &&\n typeof fn === 'function'\n ) {\n extra.at = stack.at(fn)\n if (!extra.todo) {",
"score": 0.8228073120117188
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " } else {\n extra.buffered = false\n }\n }\n extra.bail =\n extra.bail !== undefined ? extra.bail : this.bail\n extra.parent = this\n extra.stack = stack.captureString(80, caller)\n extra.context = this.context\n const t = new Class(extra)",
"score": 0.7782792448997498
},
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " // don't print locations in tap itself, that's almost never useful\n delete res.at\n }\n if (\n file &&\n res.at &&\n res.at.file &&\n res.at.line &&\n !res.source\n ) {",
"score": 0.7762150168418884
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " plan: this.#planEnd,\n },\n })\n Error.captureStackTrace(er, fn || undefined)\n this.threw(er)\n return\n }\n extra = extra || {}\n if (extra.expectFail) {\n ok = !ok",
"score": 0.7519410252571106
}
] | typescript | .clean(splitst)
} |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p. | name)
this.#processSubtest(p)
} else if (p === EOF) { |
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " // a bit excessive.\n if (this.results) {\n const alreadyBailing = !this.results.ok && this.bail\n this.results.ok = false\n if (this.parent) {\n this.parent.threw(er, extra, true)\n } else if (alreadyBailing) {\n // we are already bailing out, and this is the top level,\n // just make our way hastily to the nearest exit.\n return",
"score": 0.782485842704773
},
{
"filename": "src/plugin/spawn.ts",
"retrieved_chunk": " options = args\n args = []\n }\n options = options || {}\n if (options.name === undefined) {\n options.name = name\n }\n options.command = cmd\n options.args = args\n return this.#t.sub(Spawn, options, this.spawn)",
"score": 0.7817063331604004
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.7790562510490417
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": " this.done = true\n this.value = er\n // make it clear that this is a problem by doing\n // the opposite of what was requested.\n this.rejected = !this.expectReject\n return this.finish()\n }\n finish () {\n if (this.ready && this.done && !this.finishing) {\n this.finishing = true",
"score": 0.7758126854896545
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " } else if (arg === false) {\n // it's handy while developing to put a ! in front of a\n // function to temporarily make a test todo\n continue\n } else if (typeof arg !== 'undefined')\n throw new TypeError(\n 'unknown argument passed to parseTestArgs: ' +\n typeof arg\n )\n }",
"score": 0.7749419212341309
}
] | typescript | name)
this.#processSubtest(p)
} else if (p === EOF) { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w | : Waiter) => any,
expectReject: boolean = false
): Promise<void> { |
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/test-template.ts",
"retrieved_chunk": " ): Promise<FinalResults | null>\n todo(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n todo(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.8636196255683899
},
{
"filename": "src/waiter.ts",
"retrieved_chunk": "export class Waiter {\n cb: null | ((w:Waiter)=>any)\n ready: boolean = false\n value: any = null\n resolved: boolean = false\n rejected: boolean = false\n done: boolean = false\n finishing: boolean = false\n expectReject: boolean\n promise: Promise<void>",
"score": 0.8583386540412903
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n skip(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n skip(\n extra: { [k: string]: any },\n cb?: (t: Test) => any",
"score": 0.8579128980636597
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " t: Test\n test(\n name: string,\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n test(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>",
"score": 0.8573640584945679
},
{
"filename": "src/test-built.ts",
"retrieved_chunk": " ): Promise<FinalResults | null>\n skip(\n name: string,\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n skip(\n extra: { [k: string]: any },\n cb?: (t: Test) => any\n ): Promise<FinalResults | null>\n skip(cb?: (t: Test) => any): Promise<FinalResults | null>",
"score": 0.8526091575622559
}
] | typescript | : Waiter) => any,
expectReject: boolean = false
): Promise<void> { |
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
| async execute(text: string, command: Command): Promise<string[]> { |
const params = command.settings
const mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
const requestedMentor = mentorList[command.mentor]
const prompts = command.pattern.map((prompt) => {
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command.prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) {
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
| src/ai/model.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t{\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: newMentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n\tasync handleKeywordsInPrompt(prompt: string): Promise<string> {\n\t\t// Todo: return a prompt that do not contain the note to be inserted in the chat",
"score": 0.7768599390983582
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t.catch(async (error) => {\n\t\t\t\tconsole.log(\"error\", error)\n\t\t\t\t// Clear the input.\n\t\t\t\tthis.currentInput = \"\"\n\t\t\t\t// Display the error message.\n\t\t\t\tthis.displayedMessages.pop()\n\t\t\t\tthis.displayedMessages.push({\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: \"An error occurred. Please try again.\",\n\t\t\t\t})",
"score": 0.7474226951599121
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t\t\t\t\tresponse[0] // Only one possible response\n\t\t\t\t\t\t\t\t).open()\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Show an error\n\t\t\t\t\t\t\t\tnew Notice(\"Error: Could not get explanation.\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tnew Notice(\"Error: No text selected.\")\n\t\t\t\t}",
"score": 0.7409805059432983
},
{
"filename": "src/main.ts",
"retrieved_chunk": "\t\t\t\t\t\t\t\t\tredactedNote +\n\t\t\t\t\t\t\t\t\t\"\\n\\n___\\n\\n\"\n\t\t\t\t\t\t\t\teditor.replaceSelection(note)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// Show an error\n\t\t\t\t\t\t\t\tnew Notice(\"Error: Could not redact your note.\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})\n\t\t\t\t} else {\n\t\t\t\t\tnew Notice(\"Error: No text selected.\")",
"score": 0.7275749444961548
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\treturn prompt\n\t}\n\tasync handleSend() {\n\t\t// Don't send empty messages.\n\t\tif (this.currentInput === \"\") {\n\t\t\tnew Notice(\"Cannot send empty messages.\")\n\t\t\treturn\n\t\t}\n\t\t// Wait for the mentor to respond.\n\t\tif (",
"score": 0.7237493395805359
}
] | typescript | async execute(text: string, command: Command): Promise<string[]> { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n | === 0 && comment && !this.options.skip) { |
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " } else if (arg === false) {\n // it's handy while developing to put a ! in front of a\n // function to temporarily make a test todo\n continue\n } else if (typeof arg !== 'undefined')\n throw new TypeError(\n 'unknown argument passed to parseTestArgs: ' +\n typeof arg\n )\n }",
"score": 0.8579115271568298
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " let extra: { [k: string]: any } | null | undefined =\n undefined\n let cb: ((t: T) => any) | null | undefined = undefined\n // this only works if it's literally the 4th argument.\n // used internally.\n const defaultName = args[3] || ''\n for (let i = 0; i < 3 && i < args.length; i++) {\n const arg = args[i]\n if (\n name === undefined &&",
"score": 0.8290885090827942
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.8273049592971802
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " (typeof arg === 'string' || typeof arg === 'number')\n )\n name = '' + arg\n else if (arg && typeof arg === 'object') {\n extra = arg\n if (name === undefined) name = null\n } else if (typeof arg === 'function') {\n if (extra === undefined) extra = {}\n if (name === undefined) name = null\n cb = arg",
"score": 0.8145183324813843
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": " if (prop) return prop\n }\n return undefined\n },\n set(_, p, v) {\n // check to see if there's any setters, and if so, set it there\n // otherwise, just set on the base\n for (const t of ext) {\n let o: Object | null = t\n while (o) {",
"score": 0.8141140341758728
}
] | typescript | === 0 && comment && !this.options.skip) { |
// Inspired by `https://github.com/jmilldotdev/obsidian-gpt/blob/main/src/models/chatGPT.ts`
import { RequestUrlParam, request } from "obsidian"
import { pythonifyKeys } from "src/utils"
import { Command } from "./commands"
import { Individuals, Topics } from "./mentors"
import { Mentor, Message, supportedLanguage } from "../types"
export enum ModelType {
Default = "gpt-3.5-turbo",
GPT3516k = "gpt-3.5-turbo-16k",
GPT4 = "gpt-4",
Davinci = "text-davinci-003",
}
export interface GPTSettings {
maxTokens: number
temperature: number
topP: number
presencePenalty: number
frequencyPenalty: number
stop: string[]
}
export const defaultSettings: GPTSettings = {
maxTokens: 200,
temperature: 1.0,
topP: 1.0,
presencePenalty: 0,
frequencyPenalty: 0,
stop: [],
}
export class MentorModel {
apiUrl = `https://api.openai.com/v1/chat/completions`
id: string
mentor: Mentor
model: ModelType
apiKey: string
preferredLanguage: supportedLanguage
history: Message[]
suffix: string | undefined = undefined
headers
constructor(
id: string,
mentor: Mentor,
model: ModelType,
apiKey: string,
preferredLanguage: supportedLanguage,
suffix?: string
) {
this.id = id
this.mentor = mentor
this.model = model
this.apiKey = apiKey
this.preferredLanguage = preferredLanguage
this.history = [
{ role: "system", content: mentor.systemPrompt[preferredLanguage] },
]
this.suffix = suffix
this.headers = {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
}
}
async getCompletion(message: string): Promise<string> {
const params = this.mentor.settings
// Check that API Key is set
if (!this.apiKey) {
return "Please set your OpenAI API key in the settings."
}
// Check that the model is set
if (!this.model) {
return "Please set your OpenAI model in the settings."
}
// Check that the message is not empty
if (!message) {
return "Please enter a message."
}
const messages = [...this.history, { role: "user", content: message }]
const body = {
messages,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
this.history.push({ role: "user", content: message })
const answer = await request(requestUrlParam)
.then((response) => {
const answer =
JSON.parse(response)?.choices?.[0]?.message?.content
this.history.push({ role: "assistant", content: answer })
return answer
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
return answer
}
async execute(text: string, command: Command): Promise<string[]> {
const params = command.settings
const mentorList: Record<string, Mentor> = {
...Topics,
...Individuals,
}
const requestedMentor = mentorList[command.mentor]
| const prompts = command.pattern.map((prompt) => { |
return prompt[this.preferredLanguage].replace("*", text)
})
this.history = [
{
role: "system",
content: requestedMentor.systemPrompt[this.preferredLanguage],
},
command.prompt[this.preferredLanguage],
]
const answers: string[] = []
for (const prompt of prompts) {
this.history.push({ role: "user", content: prompt })
const body = {
messages: this.history,
model: this.model,
...pythonifyKeys(params),
stop: params.stop.length > 0 ? params.stop : undefined,
suffix: this.suffix,
}
const headers = this.headers
const requestUrlParam: RequestUrlParam = {
url: this.apiUrl,
method: "POST",
contentType: "application/json",
body: JSON.stringify(body),
headers,
}
const answer = await request(requestUrlParam)
.then((response) => {
return JSON.parse(response)?.choices?.[0]?.message?.content
})
.catch((err) => {
console.error(err)
return "I got an error when trying to reply."
})
this.history.push({ role: "assistant", content: answer })
answers.push(answer)
}
// Reset history
this.reset()
return answers
}
changeIdentity(id: string, newMentor: Mentor) {
this.id = id
this.mentor = newMentor
this.history = [
{
role: "system",
content: newMentor.systemPrompt[this.preferredLanguage],
},
]
}
reset() {
this.history = [
{
role: "system",
content: this.mentor.systemPrompt[this.preferredLanguage],
},
]
}
}
| src/ai/model.ts | clementpoiret-ai-mentor-b62d95a | [
{
"filename": "src/settings.ts",
"retrieved_chunk": "\t\tcontainerEl.createEl(\"h2\", { text: \"Settings for your mentor\" })\n\t\tconst mentorList: Record<string, Mentor> = {\n\t\t\t...Topics,\n\t\t\t...Individuals,\n\t\t}\n\t\tconst mentorIds = mentorList ? Object.keys(mentorList) : []\n\t\tnew Setting(containerEl)\n\t\t\t.setName(\"Language\")\n\t\t\t.setDesc(\"The language you'd like to talk to your mentor in.\")\n\t\t\t.addDropdown((dropdown) => {",
"score": 0.8048120737075806
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tclearButton.innerHTML = CleanIcon\n\t\tclearButton.onclick = () => this.handleClear()\n\t}\n\tasync onClose() {\n\t\t// Nothing to clean up.\n\t}\n\tasync handleMentorChange(id: string) {\n\t\tconst newMentor = this.mentorList[id]\n\t\tthis.mentor.changeIdentity(id, newMentor)\n\t\tthis.displayedMessages = [",
"score": 0.7582935690879822
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\tpreferredLanguage = \"en\"\n\tmodel: ModelType\n\tfirstOpen = true\n\t// isTyping = false\n\tdisplayedMessages: Message[] = []\n\t// Merge the two Record<string, Mentor> objects into one.\n\tmentorList: Record<string, Mentor> = {\n\t\t...Topics,\n\t\t...Individuals,\n\t}",
"score": 0.7431392669677734
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\tthis.preferredLanguage = preferredLanguage\n\t\tthis.model = model\n\t\t// Mentor selection.\n\t\tconst selectedMentor = this.mentorList[preferredMentorId]\n\t\tthis.mentor = new MentorModel(\n\t\t\tpreferredMentorId,\n\t\t\tselectedMentor,\n\t\t\tthis.model,\n\t\t\ttoken,\n\t\t\tpreferredLanguage",
"score": 0.7224317789077759
},
{
"filename": "src/components/chatview.ts",
"retrieved_chunk": "\t\t\t{\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: newMentor.firstMessage[this.preferredLanguage],\n\t\t\t},\n\t\t]\n\t\t// Refresh the view.\n\t\tawait this.onOpen()\n\t}\n\tasync handleKeywordsInPrompt(prompt: string): Promise<string> {\n\t\t// Todo: return a prompt that do not contain the note to be inserted in the chat",
"score": 0.7048652768135071
}
] | typescript | const prompts = command.pattern.map((prompt) => { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack.at(fn)
if (!extra.todo) {
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp. | message = tp.message.trimEnd() + '\n\n'
} |
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.8336870670318604
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": "}\nconst tpMessage = (\n description: string,\n extra: { [k: string]: any },\n options: TestBaseOpts = {}\n): string => {\n let message = description ? ` - ${description}` : ''\n if (extra.skip) {\n message += ' # SKIP'\n if (typeof extra.skip === 'string') {",
"score": 0.8121886253356934
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": " extra = extra || {}\n message = message\n .trim()\n .replace(/[\\n\\r]/g, ' ')\n .replace(/\\t/g, ' ')\n this.res = { ok, message, extra }\n this.extra = extra\n this.name = message\n this.message = tpMessage(esc(this.name), extra)\n }",
"score": 0.8118544816970825
},
{
"filename": "src/base.ts",
"retrieved_chunk": " // do we need this? couldn't we just call the Minipass\n this.output = ''\n this.indent = options.indent || ''\n this.name = options.name || '(unnamed test)'\n this.hook.runInAsyncScope(\n () =>\n (this.hookDomain = new Domain((er, type) => {\n if (!er || typeof er !== 'object')\n er = { error: er }\n er.tapCaught = type",
"score": 0.7984683513641357
},
{
"filename": "src/extra-from-error.ts",
"retrieved_chunk": " Object.defineProperty(er, 'message', {\n value: '',\n configurable: true\n })\n } catch {}\n }\n const st = er.stack && er.stack.substr(\n er._babel ? (message + er.codeFrame).length : 0)\n if (st) {\n const splitst = st.split('\\n')",
"score": 0.7971568703651428
}
] | typescript | message = tp.message.trimEnd() + '\n\n'
} |
// This file is automatically generated, please do not edit
import { FinalResults } from 'tap-parser'
import parseTestArgs, {
TestArgs,
} from './parse-test-args.js'
import { TestBase, TestBaseOpts } from './test-base.js'
const copyToString = (v: Function) => ({
toString: Object.assign(() => v.toString(), {
toString: () => 'function toString() { [native code] }',
}),
})
import plugin0 from "./plugin/after-each.js"
import plugin1 from "./plugin/before-each.js"
import plugin2 from "./plugin/spawn.js"
import plugin3 from "./plugin/stdin.js"
type PI<O extends TestBaseOpts | any = any> =
| ((t: Test, opts: O) => Plug)
| ((t: Test) => Plug)
const plugins: PI[] = [
plugin0,
plugin1,
plugin2,
plugin3,
]
type Plug =
| TestBase
| { t: Test }
| ReturnType<typeof plugin0>
| ReturnType<typeof plugin1>
| ReturnType<typeof plugin2>
| ReturnType<typeof plugin3>
type PlugKeys =
| keyof TestBase
| 't'
| keyof ReturnType<typeof plugin0>
| keyof ReturnType<typeof plugin1>
| keyof ReturnType<typeof plugin2>
| keyof ReturnType<typeof plugin3>
type SecondParam<
T extends [any] | [any, any],
Fallback extends unknown = unknown
> = T extends [any, any] ? T[1] : Fallback
type Plugin0Opts = SecondParam<
Parameters<typeof plugin0>,
TestBaseOpts
>
type Plugin1Opts = SecondParam<
Parameters<typeof plugin1>,
TestBaseOpts
>
type Plugin2Opts = SecondParam<
Parameters<typeof plugin2>,
TestBaseOpts
>
type Plugin3Opts = SecondParam<
Parameters<typeof plugin3>,
TestBaseOpts
>
type TestOpts = TestBaseOpts
& Plugin0Opts
& Plugin1Opts
& Plugin2Opts
& Plugin3Opts
type TTest = TestBase
& ReturnType<typeof plugin0>
& ReturnType<typeof plugin1>
& ReturnType<typeof plugin2>
& ReturnType | <typeof plugin3>
export interface Test extends TTest { |
end(): this
t: Test
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null>
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null>
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null>
}
const applyPlugins = (base: Test): Test => {
const ext: Plug[] = [
...plugins.map(p => p(base, base.options)),
base,
]
const getCache = new Map<any, any>()
const t = new Proxy(base, {
has(_, p) {
for (const t of ext) {
if (Reflect.has(t, p)) return true
}
return false
},
ownKeys() {
const k: PlugKeys[] = []
for (const t of ext) {
const keys = Reflect.ownKeys(t) as PlugKeys[]
k.push(...keys)
}
return [...new Set(k)]
},
getOwnPropertyDescriptor(_, p) {
for (const t of ext) {
const prop = Reflect.getOwnPropertyDescriptor(t, p)
if (prop) return prop
}
return undefined
},
set(_, p, v) {
// check to see if there's any setters, and if so, set it there
// otherwise, just set on the base
for (const t of ext) {
let o: Object | null = t
while (o) {
if (Reflect.getOwnPropertyDescriptor(o, p)?.set) {
//@ts-ignore
t[p] = v
return true
}
o = Reflect.getPrototypeOf(o)
}
}
//@ts-ignore
base[p as keyof TestBase] = v
return true
},
get(_, p) {
// cache get results so t.blah === t.blah
// we only cache functions, so that getters aren't memoized
// Of course, a getter that returns a function will be broken,
// at least when accessed from outside the plugin, but that's
// a pretty narrow caveat, and easily documented.
if (getCache.has(p)) return getCache.get(p)
for (const plug of ext) {
if (p in plug) {
//@ts-ignore
const v = plug[p]
// Functions need special handling so that they report
// the correct toString and are called on the correct object
// Otherwise attempting to access #private props will fail.
if (typeof v === 'function') {
const f: (this: Plug, ...args: any) => any =
function (...args: any[]) {
const thisArg = this === t ? plug : this
return v.apply(thisArg, args)
}
const vv = Object.assign(f, copyToString(v))
const nameProp =
Reflect.getOwnPropertyDescriptor(v, 'name')
if (nameProp) {
Reflect.defineProperty(f, 'name', nameProp)
}
getCache.set(p, vv)
return vv
} else {
getCache.set(p, v)
return v
}
}
}
},
})
Object.assign(base, { t })
ext.unshift({ t })
return t
}
export class Test extends TestBase {
constructor(opts: TestOpts) {
super(opts)
return applyPlugins(this)
}
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.test)
}
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.todo)
}
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.skip = true
return this.sub(Test, extra, this.skip)
}
}
| src/test-built.ts | tapjs-core-edd7403 | [
{
"filename": "src/build.ts",
"retrieved_chunk": " T extends [any] | [any, any],\n Fallback extends unknown = unknown\n> = T extends [any, any] ? T[1] : Fallback\n${plugins\n .map(\n (_, i) => `type Plugin${i}Opts = SecondParam<\n Parameters<typeof plugin${i}>,\n TestBaseOpts\n>\\n`\n )",
"score": 0.7815713882446289
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{PLUGINS CODE START}}\ntype Plug = TestBase | { t: Test }\nconst plugins: PI[] = []\ntype PlugKeys = keyof TestBase | 't'\n//{{PLUGINS CODE END}}\n//{{OPTS START}}\ntype TestOpts = TestBaseOpts\n//{{OPTS END}}\n//{{TEST INTERFACE START}}\ntype TTest = TestBase",
"score": 0.7656936645507812
},
{
"filename": "src/plugin/spawn.ts",
"retrieved_chunk": " }\n}\nconst plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>\n new SpawnPlugin(t)\nexport default plugin",
"score": 0.7463608384132385
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " new (): T\n}\nexport type TapPlugin<\n B extends Object,\n O extends TestBaseOpts | any = any\n> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)\nexport interface TestBaseOpts extends BaseOpts {\n /**\n * The number of jobs to run in parallel. Defaults to 1\n */",
"score": 0.744448184967041
},
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": "}\nconst plugin: TapPlugin<StdinPlugin> = (t: TestBase) =>\n new StdinPlugin(t)\nexport default plugin",
"score": 0.7428962588310242
}
] | typescript | <typeof plugin3>
export interface Test extends TTest { |
// This file is automatically generated, please do not edit
import { FinalResults } from 'tap-parser'
import parseTestArgs, {
TestArgs,
} from './parse-test-args.js'
import { TestBase, TestBaseOpts } from './test-base.js'
const copyToString = (v: Function) => ({
toString: Object.assign(() => v.toString(), {
toString: () => 'function toString() { [native code] }',
}),
})
import plugin0 from "./plugin/after-each.js"
import plugin1 from "./plugin/before-each.js"
import plugin2 from "./plugin/spawn.js"
import plugin3 from "./plugin/stdin.js"
type PI<O extends TestBaseOpts | any = any> =
| ((t: Test, opts: O) => Plug)
| ((t: Test) => Plug)
const plugins: PI[] = [
plugin0,
plugin1,
plugin2,
plugin3,
]
type Plug =
| TestBase
| { t: Test }
| ReturnType<typeof plugin0>
| ReturnType<typeof plugin1>
| ReturnType<typeof plugin2>
| ReturnType<typeof plugin3>
type PlugKeys =
| keyof TestBase
| 't'
| keyof ReturnType<typeof plugin0>
| keyof ReturnType<typeof plugin1>
| keyof ReturnType<typeof plugin2>
| keyof ReturnType<typeof plugin3>
type SecondParam<
T extends [any] | [any, any],
Fallback extends unknown = unknown
> = T extends [any, any] ? T[1] : Fallback
type Plugin0Opts = SecondParam<
Parameters<typeof plugin0>,
TestBaseOpts
>
type Plugin1Opts = SecondParam<
Parameters<typeof plugin1>,
TestBaseOpts
>
type Plugin2Opts = SecondParam<
Parameters<typeof plugin2>,
TestBaseOpts
>
type Plugin3Opts = SecondParam<
Parameters<typeof plugin3>,
TestBaseOpts
>
type TestOpts = TestBaseOpts
& Plugin0Opts
& Plugin1Opts
& Plugin2Opts
& Plugin3Opts
type TTest = TestBase
& ReturnType<typeof plugin0>
& ReturnType<typeof plugin1>
& ReturnType<typeof plugin2>
& ReturnType< | typeof plugin3>
export interface Test extends TTest { |
end(): this
t: Test
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null>
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null>
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null>
}
const applyPlugins = (base: Test): Test => {
const ext: Plug[] = [
...plugins.map(p => p(base, base.options)),
base,
]
const getCache = new Map<any, any>()
const t = new Proxy(base, {
has(_, p) {
for (const t of ext) {
if (Reflect.has(t, p)) return true
}
return false
},
ownKeys() {
const k: PlugKeys[] = []
for (const t of ext) {
const keys = Reflect.ownKeys(t) as PlugKeys[]
k.push(...keys)
}
return [...new Set(k)]
},
getOwnPropertyDescriptor(_, p) {
for (const t of ext) {
const prop = Reflect.getOwnPropertyDescriptor(t, p)
if (prop) return prop
}
return undefined
},
set(_, p, v) {
// check to see if there's any setters, and if so, set it there
// otherwise, just set on the base
for (const t of ext) {
let o: Object | null = t
while (o) {
if (Reflect.getOwnPropertyDescriptor(o, p)?.set) {
//@ts-ignore
t[p] = v
return true
}
o = Reflect.getPrototypeOf(o)
}
}
//@ts-ignore
base[p as keyof TestBase] = v
return true
},
get(_, p) {
// cache get results so t.blah === t.blah
// we only cache functions, so that getters aren't memoized
// Of course, a getter that returns a function will be broken,
// at least when accessed from outside the plugin, but that's
// a pretty narrow caveat, and easily documented.
if (getCache.has(p)) return getCache.get(p)
for (const plug of ext) {
if (p in plug) {
//@ts-ignore
const v = plug[p]
// Functions need special handling so that they report
// the correct toString and are called on the correct object
// Otherwise attempting to access #private props will fail.
if (typeof v === 'function') {
const f: (this: Plug, ...args: any) => any =
function (...args: any[]) {
const thisArg = this === t ? plug : this
return v.apply(thisArg, args)
}
const vv = Object.assign(f, copyToString(v))
const nameProp =
Reflect.getOwnPropertyDescriptor(v, 'name')
if (nameProp) {
Reflect.defineProperty(f, 'name', nameProp)
}
getCache.set(p, vv)
return vv
} else {
getCache.set(p, v)
return v
}
}
}
},
})
Object.assign(base, { t })
ext.unshift({ t })
return t
}
export class Test extends TestBase {
constructor(opts: TestOpts) {
super(opts)
return applyPlugins(this)
}
test(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
test(cb?: (t: Test) => any): Promise<FinalResults | null>
test(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.test)
}
todo(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
todo(cb?: (t: Test) => any): Promise<FinalResults | null>
todo(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.todo = true
return this.sub(Test, extra, this.todo)
}
skip(
name: string,
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
name: string,
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(
extra: { [k: string]: any },
cb?: (t: Test) => any
): Promise<FinalResults | null>
skip(cb?: (t: Test) => any): Promise<FinalResults | null>
skip(
...args: TestArgs<Test>
): Promise<FinalResults | null> {
const extra = parseTestArgs(...args)
extra.skip = true
return this.sub(Test, extra, this.skip)
}
}
| src/test-built.ts | tapjs-core-edd7403 | [
{
"filename": "src/build.ts",
"retrieved_chunk": " T extends [any] | [any, any],\n Fallback extends unknown = unknown\n> = T extends [any, any] ? T[1] : Fallback\n${plugins\n .map(\n (_, i) => `type Plugin${i}Opts = SecondParam<\n Parameters<typeof plugin${i}>,\n TestBaseOpts\n>\\n`\n )",
"score": 0.7752586603164673
},
{
"filename": "src/test-template.ts",
"retrieved_chunk": "//{{PLUGINS CODE START}}\ntype Plug = TestBase | { t: Test }\nconst plugins: PI[] = []\ntype PlugKeys = keyof TestBase | 't'\n//{{PLUGINS CODE END}}\n//{{OPTS START}}\ntype TestOpts = TestBaseOpts\n//{{OPTS END}}\n//{{TEST INTERFACE START}}\ntype TTest = TestBase",
"score": 0.760560929775238
},
{
"filename": "src/plugin/spawn.ts",
"retrieved_chunk": " }\n}\nconst plugin: TapPlugin<SpawnPlugin> = (t: TestBase) =>\n new SpawnPlugin(t)\nexport default plugin",
"score": 0.7388864755630493
},
{
"filename": "src/plugin/stdin.ts",
"retrieved_chunk": "}\nconst plugin: TapPlugin<StdinPlugin> = (t: TestBase) =>\n new StdinPlugin(t)\nexport default plugin",
"score": 0.7337811589241028
},
{
"filename": "src/test-base.ts",
"retrieved_chunk": " new (): T\n}\nexport type TapPlugin<\n B extends Object,\n O extends TestBaseOpts | any = any\n> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)\nexport interface TestBaseOpts extends BaseOpts {\n /**\n * The number of jobs to run in parallel. Defaults to 1\n */",
"score": 0.7331520318984985
}
] | typescript | typeof plugin3>
export interface Test extends TTest { |
// lifecycle methods like beforeEach, afterEach, teardown
// defined in plugins/lifecycle.ts
import Minipass from 'minipass'
import assert from 'node:assert'
import { hrtime } from 'node:process'
import { Readable } from 'node:stream'
import { format } from 'node:util'
import { CallSiteLike } from 'stack-utils'
import { FinalResults } from 'tap-parser'
import Deferred from 'trivial-deferred'
import { Base, BaseOpts } from './base.js'
import { esc } from './esc.js'
import stack from './stack.js'
import { TestPoint } from './test-point.js'
import { Waiter } from './waiter.js'
const queueEmpty = <T extends TestBase>(t: T) =>
t.queue.length === 0 ||
(t.queue.length === 1 &&
t.queue[0] === 'TAP version 14\n')
export interface ClassOf<T> {
new (): T
}
export type TapPlugin<
B extends Object,
O extends TestBaseOpts | any = any
> = ((t: TestBase, opts: O) => B) | ((t: TestBase) => B)
export interface TestBaseOpts extends BaseOpts {
/**
* The number of jobs to run in parallel. Defaults to 1
*/
jobs?: number
/**
* Test function called when this Test is executed
*/
cb?: (...args: any[]) => any
/**
* Flag to always/never show diagnostics. If unset, then
* diagnostics are shown for failing test points only.
*/
diagnostic?: boolean
}
const normalizeMessageExtra = (
defaultMessage: string,
message?: string | { [k: string]: any },
extra?: { [k: string]: any }
): [string, { [k: string]: any }] => {
if (typeof message === 'string') {
return [message || defaultMessage, extra || {}]
} else {
return [defaultMessage, message || {}]
}
}
/**
* Sigil for implicit end() calls that should not
* trigger an error if the user then calls t.end()
*/
const IMPLICIT = Symbol('implicit end')
/**
* Sigil to put in the queue to signal the end of all things
*/
const EOF = Symbol('EOF')
export type QueueEntry =
| string
| TestPoint
| Base
| typeof EOF
| Waiter
| [method: string, ...args: any[]]
/**
* The TestBaseBase class is the base class for all plugins,
* and eventually thus the Test class.
*
* This implements subtest functionality, TAP stream generation,
* lifecycle events, and only the most basic pass/fail assertions.
*
* All other features are added with plugins.
*/
export class TestBase extends Base {
// NB: generated pluginified Test class needs to declare over this
declare parent?: TestBase
promise?: Promise<any>
jobs: number
// #beforeEnd: [method: string | Symbol, ...args: any[]][] = []
subtests: Base[] = []
pool: Set<Base> = new Set()
queue: QueueEntry[] = ['TAP version 14\n']
cb?: (...args: any[]) => any
count: number = 0
ended: boolean = false
assertAt: CallSiteLike | null = null
assertStack: string | null = null
diagnostic: null | boolean = null
#planEnd: number = -1
#printedResult: boolean = false
#explicitEnded: boolean = false
#multiEndThrew: boolean = false
#n: number = 0
#noparallel: boolean = false
#occupied: null | Waiter | Base = null
#pushedEnd: boolean = false
#nextChildId: number = 1
#currentAssert: null | ((..._: any) => any) = null
#processing: boolean = false
#doingStdinOnly: boolean = false
/**
* true if the test has printed at least one TestPoint
*/
get printedResult(): boolean {
return this.#printedResult
}
constructor(options: TestBaseOpts) {
super(options)
this.jobs =
(options.jobs && Math.max(options.jobs, 1)) || 1
if (typeof options.diagnostic === 'boolean') {
this.diagnostic = options.diagnostic
}
if (options.cb) {
this.#setCB(options.cb)
}
}
#setCB<T extends TestBase>(this: T, cb: (t: T) => any) {
this.cb = (...args: any[]) =>
this.hook.runInAsyncScope(cb, this, ...args)
}
// TAP output generating methods
/**
* immediately exit this and all parent tests with a TAP
* Bail out! message.
*/
bailout(message?: string) {
if (this.parent && (this.results || this.ended)) {
this.parent.bailout(message)
} else {
this.#process()
message = message
? ' ' + ('' + esc(message)).trim()
: ''
message = message.replace(/[\r\n]/g, ' ')
this.parser.write('Bail out!' + message + '\n')
}
this.#end(IMPLICIT)
this.#process()
}
/**
* output a TAP comment, formatted like console.log()
*/
comment(...args: any[]) {
const body = format(...args)
const message =
('# ' + body.split(/\r?\n/).join('\n# ')).trim() +
'\n'
if (this.results) {
this.write(message)
} else {
this.queue.push(message)
}
this.#process()
}
/**
* Called when the test times out.
* Options are passed as diagnostics to the threw() method
*/
timeout(options: { [k: string]: any }) {
options = options || {}
options.expired = options.expired || this.name
if (this.#occupied && this.#occupied instanceof Base) {
this.#occupied.timeout(options)
} else {
super.timeout(options)
}
this.#end(IMPLICIT)
}
/**
* Set TAP pragma configs to affect the behavior of the parser.
* Only `strict` is supported by the parser.
*/
pragma(set: { [k: string]: boolean }) {
const p = Object.keys(set).reduce(
(acc, i) =>
acc + 'pragma ' + (set[i] ? '+' : '-') + i + '\n',
''
)
this.queue.push(p)
this.#process()
}
/**
* Specify the number of Test Points expected by this test.
* Outputs a TAP plan line.
*/
plan(n: number, comment?: string) {
if (this.bailedOut) {
return
}
if (this.#planEnd !== -1) {
throw new Error('Cannot set plan more than once')
}
if (typeof n !== 'number' || n < 0) {
throw new TypeError('plan must be a number')
}
// Cannot get any tests after a trailing plan, or a plan of 0
const ending = this.count !== 0 || n === 0
if (n === 0 && comment && !this.options.skip) {
this.options.skip = comment
}
this.#planEnd = n
comment = comment ? ' # ' + esc(comment.trim()) : ''
this.queue.push('1..' + n + comment + '\n')
if (ending) {
this.#end(IMPLICIT)
} else {
this.#process()
}
}
/**
* A passing (ok) Test Point
*/
pass(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.pass
this.printResult(
true,
...normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
)
return true
}
/**
* A failing (not ok) Test Point
*/
fail(message?: string, extra?: { [k: string]: any }) {
this.currentAssert = TestBase.prototype.fail
const [m, e] = normalizeMessageExtra(
'(unnamed test)',
message,
extra
)
this.printResult(false, m, e)
return !!(e.todo || e.skip)
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
get currentAssert() {
return this.#currentAssert
}
/**
* The current assertion being processed. May only be set if
* not already set.
*/
set currentAssert(fn: null | ((...a: any[]) => any)) {
if (!this.#currentAssert && typeof fn === 'function') {
this.#currentAssert = fn
}
}
/**
* Print a Test Point
*/
printResult(
ok: boolean,
message: string,
extra: { [k: string]: any },
front: boolean = false
) {
this.#printedResult = true
const n = this.count + 1
this.currentAssert = TestBase.prototype.printResult
const fn = this.#currentAssert
this.#currentAssert = null
if (this.#planEnd !== -1 && n > this.#planEnd) {
if (!this.passing()) return
const failMessage = this.#explicitEnded
? 'test after end() was called'
: 'test count exceeds plan'
const er = new Error(failMessage, {
cause: {
test: this.name,
plan: this.#planEnd,
},
})
Error.captureStackTrace(er, fn || undefined)
this.threw(er)
return
}
extra = extra || {}
if (extra.expectFail) {
ok = !ok
}
if (this.assertAt) {
extra.at = this.assertAt
this.assertAt = null
}
if (this.assertStack) {
extra.stack = this.assertStack
this.assertStack = null
}
if (typeof extra.stack === 'string' && !extra.at) {
extra.at = stack.parseLine(extra.stack.split('\n')[0])
}
if (
!ok &&
!extra.skip &&
!extra.at &&
typeof fn === 'function'
) {
extra.at = stack | .at(fn)
if (!extra.todo) { |
extra.stack = stack.captureString(80, fn)
}
}
const diagnostic =
typeof extra.diagnostic === 'boolean'
? extra.diagnostic
: typeof this.diagnostic === 'boolean'
? this.diagnostic
: extra.skip || extra.todo
? false
: !ok
if (diagnostic) {
extra.diagnostic = true
}
this.count = n
message = message + ''
const res = { ok, message, extra }
const tp = new TestPoint(ok, message, extra)
// when we jump the queue, skip an extra line
if (front) {
tp.message = tp.message.trimEnd() + '\n\n'
}
if (
this.#occupied &&
this.#occupied instanceof Waiter &&
this.#occupied.finishing
) {
front = true
}
if (front) {
if (
extra.tapChildBuffer ||
extra.tapChildBuffer === ''
) {
this.writeSubComment(tp)
this.parser.write(extra.tapChildBuffer)
}
this.emit('result', res)
this.parser.write(tp.ok + ++this.#n + tp.message)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.parser.write('Bail out! ' + message + '\n')
}
} else {
this.queue.push(tp)
if (this.bail && !ok && !extra.skip && !extra.todo) {
this.queue.push('Bail out! ' + message + '\n')
}
}
if (this.#planEnd === this.count) {
this.#end(IMPLICIT)
}
this.#process()
}
end(): this {
this.#end()
return super.end()
}
/**
* The leading `# Subtest` comment that introduces a child test
*/
writeSubComment<T extends TestPoint | Base>(p: T) {
const comment =
'# Subtest' +
(p.name ? ': ' + esc(p.name) : '') +
'\n'
this.parser.write(comment)
}
// end TAP otput generating methods
// flow control methods
/**
* Await the end of a Promise before proceeding.
* The supplied callback is called with the Waiter object.
*/
waitOn(
promise: Promise<any | void>,
cb: (w: Waiter) => any,
expectReject: boolean = false
): Promise<void> {
const w = new Waiter(
promise,
w => {
assert.equal(this.#occupied, w)
cb(w)
this.#occupied = null
this.#process()
},
expectReject
)
this.queue.push(w)
this.#process()
return w.promise
}
#end(implicit?: typeof IMPLICIT) {
if (this.#doingStdinOnly && implicit !== IMPLICIT)
throw new Error(
'cannot explicitly end while in stdinOnly mode'
)
this.debug('END implicit=%j', implicit === IMPLICIT)
if (this.ended && implicit === IMPLICIT) return
// beyond here we have to be actually done with things, or else
// the semantic checks on counts and such will be off.
if (!queueEmpty(this) || this.#occupied) {
if (!this.#pushedEnd) {
this.queue.push(['#end', implicit])
}
this.#pushedEnd = true
return this.#process()
}
this.ended = true
if (implicit !== IMPLICIT && !this.#multiEndThrew) {
if (this.#explicitEnded) {
this.#multiEndThrew = true
const er = new Error(
'test end() method called more than once'
)
Error.captureStackTrace(
er,
this.#currentAssert || this.#end
)
er.cause = {
test: this.name,
}
this.threw(er)
return
}
this.#explicitEnded = true
}
if (this.#planEnd === -1) {
this.debug(
'END(%s) implicit plan',
this.name,
this.count
)
this.plan(this.count)
}
this.queue.push(EOF)
this.#process()
}
#process() {
if (this.#processing) {
return this.debug(' < already processing')
}
this.debug(
'\nPROCESSING(%s)',
this.name,
this.queue.length
)
this.#processing = true
while (!this.#occupied) {
const p = this.queue.shift()
if (!p) {
this.debug('> end of queue')
break
}
if (p instanceof Base) {
this.debug('> subtest in queue', p.name)
this.#processSubtest(p)
} else if (p === EOF) {
this.debug(' > EOF', this.name)
// I AM BECOME EOF, DESTROYER OF STREAMS
this.parser.end()
} else if (p instanceof TestPoint) {
this.debug(' > TESTPOINT')
if (
p.extra.tapChildBuffer ||
p.extra.tapChildBuffer === ''
) {
this.writeSubComment(p)
this.parser.write(p.extra.tapChildBuffer)
}
this.emit('res', p.res)
this.parser.write(p.ok + ++this.#n + p.message)
} else if (typeof p === 'string') {
this.debug(' > STRING')
this.parser.write(p)
} else if (p instanceof Waiter) {
p.ready = true
this.#occupied = p
p.finish()
} else if (Array.isArray(p)) {
this.debug(' > METHOD')
const m = p.shift() as keyof this
if (typeof this[m] !== 'function') {
this.debug(
' > weird method not found in queue??',
m,
typeof this[m]
)
continue
}
const fn = (m === '#end' ? this.#end : this[m]) as (
...a: any[]
) => any
const ret = fn.call(this, ...p)
if (
ret &&
typeof ret === 'object' &&
typeof ret.then === 'function'
) {
// returned promise
ret.then(
() => {
this.#processing = false
this.#process()
},
(er: unknown) => {
this.#processing = false
this.threw(er)
}
)
return
}
/* c8 ignore start */
} else {
throw new Error('weird thing got in the queue')
}
/* c8 ignore stop */
}
while (
!this.#noparallel &&
this.pool.size < this.jobs
) {
const p = this.subtests.shift()
if (!p) {
break
}
if (!p.buffered) {
this.#noparallel = true
break
}
this.debug('start subtest', p)
this.emit('subtestStart', p)
this.pool.add(p)
if (this.bailedOut) {
this.#onBufferedEnd(p)
} else {
p.runMain(() => this.#onBufferedEnd(p))
}
}
this.debug(
'done processing',
this.queue,
this.#occupied
)
this.#processing = false
// just in case any tests ended, and we have sync stuff still
// waiting around in the queue to be processed
if (!this.#occupied && this.queue.length) {
this.#process()
}
}
#onBufferedEnd<T extends Base>(p: T) {
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
p.readyToProcess = true
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug(
'%s.#onBufferedEnd',
this.name,
p.name,
p.results.bailout
)
this.pool.delete(p)
p.options.tapChildBuffer = p.output || ''
p.options.stack = ''
if (p.time) p.options.time = p.time
if (this.#occupied === p) this.#occupied = null
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
#onIndentedEnd<T extends Base>(p: T) {
this.emit('subtestProcess', p)
p.ondone = p.constructor.prototype.ondone
p.results =
p.results || new FinalResults(true, p.parser)
this.debug('#onIndentedEnd', this.name, p.name)
this.#noparallel = false
const sti = this.subtests.indexOf(p)
if (sti !== -1) this.subtests.splice(sti, 1)
p.readyToProcess = true
p.options.time = p.time
const to = p.options.timeout
const dur =
to && p.passing() ? hrtime.bigint() - p.start : null
if (dur && to && dur > to) {
p.timeout()
} else {
p.setTimeout(0)
}
this.debug('#onIndentedEnd %s(%s)', this.name, p.name)
this.#occupied = null
this.debug(
'OIE(%s) b>shift into queue',
this.name,
this.queue
)
p.options.stack = ''
this.printResult(p.passing(), p.name, p.options, true)
this.debug(
'OIE(%s) shifted into queue',
this.name,
this.queue
)
p.deferred?.resolve(p.results)
this.emit('subtestEnd', p)
this.#process()
}
/**
* @internal
*/
main(cb: () => void) {
if (typeof this.options.timeout === 'number') {
this.setTimeout(this.options.timeout)
}
this.debug('MAIN pre', this)
const end = () => {
this.debug(' > implicit end for promise')
this.#end(IMPLICIT)
done()
}
const done = (er?: Error) => {
if (er) this.threw(er)
if (this.results || this.bailedOut) cb()
else this.ondone = () => cb()
}
// This bit of overly clever line-noise wraps the call to user-code
// in a try-catch. We can't rely on the domain for this yet, because
// the 'end' event can trigger a throw after the domain is unhooked,
// but before this is no longer the official "active test"
const ret = (() => {
if (!this.cb) return
try {
return this.cb(this)
} catch (er: any) {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'testFunctionThrow'
this.threw(er)
}
})()
if (ret && ret.then) {
this.promise = ret
ret.tapAbortPromise = done
ret.then(end, (er: any) => {
if (!er || typeof er !== 'object') {
er = { error: er }
}
er.tapCaught = 'returnedPromiseRejection'
done(er)
})
} else done()
this.debug('MAIN post', this)
}
#processSubtest<T extends Base>(p: T) {
this.debug(' > subtest')
this.#occupied = p
if (!p.buffered) {
this.emit('subtestStart', p)
this.debug(' > subtest indented')
p.stream.pipe(this.parser, { end: false })
this.writeSubComment(p)
this.debug('calling runMain', p.runMain.toString())
p.runMain(() => {
this.debug('in runMain', p.runMain.toString())
this.#onIndentedEnd(p)
})
} else if (p.readyToProcess) {
this.emit('subtestProcess', p)
this.debug(' > subtest buffered, finished')
// finished! do the thing!
this.#occupied = null
if (!p.passing() || !p.silent) {
this.printResult(
p.passing(),
p.name,
p.options,
true
)
}
} else {
this.#occupied = p
this.debug(' > subtest buffered, unfinished', p)
// unfinished buffered test.
// nothing to do yet, just leave it there.
this.queue.unshift(p)
}
}
/**
* Parse stdin as the only tap stream (ie, not as a child test)
* If used, then no other subtests or assertions are allowed.
*/
stdinOnly<T extends BaseOpts>(
extra?: T & { tapStream?: Readable | Minipass }
) {
const stream = ((extra && extra.tapStream) ||
process.stdin) as Minipass
if (!stream) {
throw new Error(
'cannot read stdin without stdin stream'
)
}
if (
this.queue.length !== 1 ||
this.queue[0] !== 'TAP version 14\n' ||
this.#processing ||
this.results ||
this.#occupied ||
this.pool.size ||
this.subtests.length
) {
throw new Error(
'Cannot use stdinOnly on a test in progress'
)
}
this.#doingStdinOnly = true
this.queue.length = 0
this.parser.on('child', p => {
// pretend to be a rooted parser, so it gets counts.
p.root = p
const t = new Base({
name: p.name,
parent: this,
parser: p,
bail: p.bail,
strict: p.strict,
omitVersion: p.omitVersion,
preserveWhitespace: p.preserveWhitespace,
childId: this.#nextChildId++,
})
this.emit('subtestAdd', t)
this.emit('subtestStart', t)
this.emit('subtestProcess', t)
p.on('complete', () => {
t.time = p.time
this.emit('subtestEnd', t)
})
})
stream.pause()
stream.pipe(this.parser)
stream.resume()
}
/**
* Mount a subtest, using this Test object as a harness.
* Exposed mainly so that it can be used by builtin plugins.
*
* @internal
*/
sub<T extends Base, O extends TestBaseOpts>(
Class: { new (options: O): T },
extra: O,
caller: (...a: any[]) => unknown
): Promise<FinalResults | null> {
if (this.bailedOut) return Promise.resolve(null)
if (this.results || this.ended) {
const er = new Error(
'cannot create subtest after parent test ends'
)
Error.captureStackTrace(er, caller)
this.threw(er)
return Promise.resolve(null)
}
extra.childId = this.#nextChildId++
if (this.shouldSkipChild(extra)) {
this.pass(extra.name, extra)
return Promise.resolve(null)
}
extra.indent = ' '
if (extra.buffered !== undefined) {
if (this.jobs > 1) {
extra.buffered = true
} else {
extra.buffered = false
}
}
extra.bail =
extra.bail !== undefined ? extra.bail : this.bail
extra.parent = this
extra.stack = stack.captureString(80, caller)
extra.context = this.context
const t = new Class(extra)
this.queue.push(t)
this.subtests.push(t)
this.emit('subtestAdd', t)
const d = new Deferred<FinalResults>()
t.deferred = d
this.#process()
return d.promise
}
/**
* Return true if the child test represented by the options object
* should be skipped. Extended by the grep/only filtering plugins.
*/
shouldSkipChild(extra: { [k: string]: any }) {
return !!(extra.skip || extra.todo)
}
// end flow control methods
}
| src/test-base.ts | tapjs-core-edd7403 | [
{
"filename": "src/clean-yaml-object.ts",
"retrieved_chunk": " // don't print locations in tap itself, that's almost never useful\n delete res.at\n }\n if (\n file &&\n res.at &&\n res.at.file &&\n res.at.line &&\n !res.source\n ) {",
"score": 0.7877728939056396
},
{
"filename": "src/parse-test-args.ts",
"retrieved_chunk": " (typeof arg === 'string' || typeof arg === 'number')\n )\n name = '' + arg\n else if (arg && typeof arg === 'object') {\n extra = arg\n if (name === undefined) name = null\n } else if (typeof arg === 'function') {\n if (extra === undefined) extra = {}\n if (name === undefined) name = null\n cb = arg",
"score": 0.7786747217178345
},
{
"filename": "src/spawn.ts",
"retrieved_chunk": " !code &&\n !signal\n ) {\n this.options.skip =\n this.results.plan.skipReason || true\n }\n if (code || signal) {\n if (this.results) {\n this.results.ok = false\n }",
"score": 0.7771495580673218
},
{
"filename": "src/base.ts",
"retrieved_chunk": " }\n if (this.name && !proxy) {\n er.test = this.name\n }\n const message = er.message\n if (!extra) {\n extra = extraFromError(er, extra, this.options)\n }\n // if we ended, we have to report it SOMEWHERE, unless we're\n // already in the process of bailing out, in which case it's",
"score": 0.7752927541732788
},
{
"filename": "src/test-point.ts",
"retrieved_chunk": " message += ' ' + esc(extra.skip)\n }\n } else if (extra.todo) {\n message += ' # TODO'\n if (typeof extra.todo === 'string') {\n message += ' ' + esc(extra.todo)\n }\n } else if (extra.time) {\n message += ' # time=' + extra.time + 'ms'\n }",
"score": 0.7730540037155151
}
] | typescript | .at(fn)
if (!extra.todo) { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.