repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
extension-bootc
github_2023
podman-desktop
typescript
getPodmanCli
function getPodmanCli(): string { const customBinaryPath = getCustomBinaryPath(); if (customBinaryPath) { return customBinaryPath; } if (isWindows()) { return 'podman.exe'; } return 'podman'; }
// Below functions are borrowed from the podman extension
https://github.com/podman-desktop/extension-bootc/blob/d5bbd58a824131ca533ababcc2e7b35ff86c264b/packages/backend/src/machine-utils.ts#L154-L164
d5bbd58a824131ca533ababcc2e7b35ff86c264b
extension-bootc
github_2023
podman-desktop
typescript
handleStdError
function handleStdError(e: unknown): void { if (e instanceof Error && 'stderr' in e) { throw new Error(typeof e.stderr === 'string' ? e.stderr : 'Unknown error'); } else { throw new Error('Unknown error'); } }
// Error handling function
https://github.com/podman-desktop/extension-bootc/blob/d5bbd58a824131ca533ababcc2e7b35ff86c264b/packages/backend/src/vm-manager.ts#L305-L311
d5bbd58a824131ca533ababcc2e7b35ff86c264b
extension-bootc
github_2023
podman-desktop
typescript
aggregateLeaves
function aggregateLeaves(object: unknown): string[] { if (!object) { return []; } else if (typeof object === 'string') { return [object]; } else if (Array.isArray(object)) { return object.flatMap(element => aggregateLeaves(element)); } else if (typeof object === 'object') { return Object.values(...
// Aggregate all leaves of a given object
https://github.com/podman-desktop/extension-bootc/blob/d5bbd58a824131ca533ababcc2e7b35ff86c264b/packages/frontend/src/lib/upstream/search-util.ts#L34-L46
d5bbd58a824131ca533ababcc2e7b35ff86c264b
cella
github_2023
cellajs
typescript
isPGliteDatabase
const isPGliteDatabase = (_db: unknown): _db is PgliteDatabase => !!env.PGLITE;
// import { sdk } from './tracing';
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/index.ts#L16-L16
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
docs
const docs = (app: OpenAPIHono<Env>) => { const registry = app.openAPIRegistry; const tags = commonModulesList.concat(appModulesList); registry.registerComponent('securitySchemes', 'cookieAuth', { type: 'apiKey', in: 'cookie', name: `${config.slug}-session-${config.apiVersion}`, description: ...
/** * Generate OpenAPI documentation using hono/zod-openapi and scalar/hono-api-reference * * @link https://github.com/scalar/scalar/blob/main/documentation/configuration.md */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/lib/docs.ts#L31-L67
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
sendSSE
const sendSSE = (userId: string, eventName: string, data: Record<string, unknown>): void => { const stream = streams.get(userId); if (!stream) return; stream.writeSSE({ event: eventName, data: JSON.stringify(data), retry: 5000, }); };
// SSE is used to send real-time updates to the client. Useful for simple updates such as an updated entity or a notification.
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/lib/sse.ts#L4-L13
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
isOAuthEnabled
function isOAuthEnabled(provider: EnabledOauthProvider): boolean { if (!enabledStrategies.includes('oauth')) return false; return enabledOauthProviders.includes(provider); }
// Check if oauth provider is enabled by config
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/modules/auth/handlers.ts#L62-L65
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
isAuthStrategy
const isAuthStrategy = (strategy: string): strategy is (typeof allSupportedStrategies)[number] => { const [, ...elseStrategies] = supportedAuthStrategies; const allSupportedStrategies = [...supportedOauthProviders, ...elseStrategies]; return (allSupportedStrategies as string[]).includes(strategy); };
// Type guard to check if strategy is supported
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/modules/auth/helpers/session.ts#L19-L23
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
validateAuthStrategy
const validateAuthStrategy = (strategy: string) => (isAuthStrategy(strategy) ? strategy : null);
// Validate auth strategy
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/modules/auth/helpers/session.ts#L26-L26
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
fetchMenuItemsForSection
const fetchMenuItemsForSection = async (section: EntityRelations) => { let submenu: MenuItem[] = []; const mainTable = entityTables[section.entity]; const mainEntityIdField = entityIdFields[section.entity]; const entity = await db .select({ slug: mainTable.slug, id: ...
// Fetch function for each menu section, including handling submenus
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/modules/me/handlers.ts#L72-L121
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
data
const data = async () => { const result = await entityRelations.reduce( async (accPromise, section) => { const acc = await accPromise; if (!memberships.length) { acc[section.menuSectionName] = []; return acc; } // Fetch menu items for the cu...
// Build the menu data asynchronously
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/modules/me/handlers.ts#L124-L141
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
AdaptedMembershipAdapter.adapt
adapt(memberships: any[]): Membership[] { return memberships.map((m) => ({ contextName: m.type?.toLowerCase() || '', contextKey: m[`${m.type?.toLowerCase() || ''}Id`], roleName: m.role, ancestors: { organization: m.organizationId, }, })); }
// biome-ignore lint/suspicious/noExplicitAny: The format of the membership object may vary.
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/permissions/permission-manager.ts#L46-L55
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
AdaptedSubjectAdapter.adapt
adapt(s: any): Subject { return { name: s.entity, key: s.id, ancestors: { organization: s.organizationId, }, }; }
// biome-ignore lint/suspicious/noExplicitAny: The format of the subject can vary depending on the subject.
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/backend/src/permissions/permission-manager.ts#L69-L77
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
getGitCommandType
function getGitCommandType(command: string): GitCommandType { if (command.startsWith('merge')) return 'merge'; if (command.startsWith('diff')) return 'diff'; return 'other'; }
// Helper to determine the type of Git command for custom handling
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/create-cella/src/utils/run-git-command.ts#L11-L15
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
isGitCommandSuccess
function isGitCommandSuccess(gitCommand: GitCommandType, code: number | null, errOutput: string): boolean { if (gitCommand === 'merge') return code === 0 || (code === 1 && !errOutput); if (gitCommand === 'diff') return code === 0 || (code === 2 && !errOutput); return code === 0; }
// Helper to check if a Git command is successful
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/create-cella/src/utils/run-git-command.ts#L18-L22
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
extractFromJson
async function extractFromJson(configFile: string): Promise<Config> { try { const fileContent = await readFile(configFile, 'utf-8'); const config: Config = JSON.parse(fileContent); return extractConfig(config); } catch (error) { return { divergedFile: null, ignoreFile: null, ignoreList: [], forks: ...
// Function to extract paths from .json (simple key-value pairs)
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/config-file.ts#L20-L29
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
extractUsingDynamicImport
async function extractUsingDynamicImport(configFile: string): Promise<Config> { try { const { config } = await import(resolve(configFile)) as { config: Config }; return extractConfig(config); } catch (error) { return { divergedFile: null, ignoreFile: null, ignoreList: [], forks: [], problems: [`Error d...
// Function to extract paths using dynamic import for ES modules
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/config-file.ts#L32-L40
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
fileExists
async function fileExists(filePath: string): Promise<boolean> { try { await access(filePath); return true; } catch { return false; } }
// Helper function to check if a file exists
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/ignore-patterns.ts#L10-L17
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
extractFromIgnoreFile
async function extractFromIgnoreFile(ignoreFile: string): Promise<string[]> { const content = await readFile(ignoreFile, 'utf-8'); return content.split(/\r?\n/).filter(Boolean); }
// Extract patterns from the ignore file
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/ignore-patterns.ts#L20-L23
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
extractFromIgnoreList
function extractFromIgnoreList(ignoreList: IgnoreList): string[] { return Array.isArray(ignoreList) ? ignoreList : ignoreList ? ignoreList.split(',') : []; }
// Extract patterns from the ignore list
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/ignore-patterns.ts#L26-L32
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
patternToRegex
function patternToRegex(pattern: string): RegExp { // Escape special regex characters and convert wildcards const escapedPattern = pattern .replace(/([.*+?^${}()|[\]\\])/g, '\\$1') // Escape special characters .replace(/\\\*/g, '.*') // Convert '*' to '.*' .replace(/\\\?/g, '.'); ...
// Helper function to convert ignore patterns to regular expressions
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/ignore-patterns.ts#L48-L56
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
getGitCommandType
function getGitCommandType(command: string): GitCommandType { if (command.startsWith('merge')) return 'merge'; if (command.startsWith('diff')) return 'diff'; return 'other'; }
// Helper to determine the type of Git command for custom handling
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/run-git-command.ts#L11-L15
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
isGitCommandSuccess
function isGitCommandSuccess(gitCommand: GitCommandType, code: number | null, errOutput: string): boolean { if (gitCommand === 'merge') return code === 0 || (code === 1 && !errOutput); if (gitCommand === 'diff') return code === 0 || (code === 2 && !errOutput); return code === 0; }
// Helper to check if a Git command is successful
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/cli/sync-cella/src/utils/run-git-command.ts#L18-L22
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
useBodyClass
function useBodyClass(classMappings: { [key: string]: boolean }) { // Memoize classMappings to prevent unnecessary re-renders const stableClassMappings = useMemo(() => classMappings, [JSON.stringify(classMappings)]); useEffect(() => { const bodyClassList = document.body.classList; const classNames = Obje...
/** * Custom hook to conditionally add/remove body classes based on the provided class mappings. * * This hook allows you to dynamically update the body's class list based on a set of class mappings. * It will add classes to the body if their corresponding value in `classMappings` is `true`, and remove them if `fal...
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-body-class.ts#L12-L38
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
getMatchedBreakpoints
const getMatchedBreakpoints = () => { const width = window.innerWidth; let matched = sortedBreakpoints[0]; // Default to first breakpoint for (let i = 1; i < sortedBreakpoints.length; i++) { const prevBreakpointSize = Number.parseInt(breakpoints[sortedBreakpoints[i - 1]], 10); const currentBreakpointSize...
// Function to get the matched breakpoint based on window width
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-breakpoints.tsx#L13-L29
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
updateGlobalBreakpoint
const updateGlobalBreakpoint = () => { const newBreakpoint = getMatchedBreakpoints(); if (newBreakpoint !== currentBreakpoint) { currentBreakpoint = newBreakpoint; for (const listener of listeners) { listener(newBreakpoint); } } };
// Function to update global breakpoint state (runs only when necessary)
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-breakpoints.tsx#L32-L40
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
useDoubleClick
const useDoubleClick = ({ ref, latency = 300, excludeIds = [], allowedTargets = [], onSingleClick = () => null, onDoubleClick = () => null, }: UseDoubleClickOptions) => { useEffect(() => { const clickRef = ref.current; if (!clickRef) return; let clickCount = 0; const handleClick = (e: Eve...
/** * A simple React hook for differentiating single and double clicks on the same component. * * @param ref - Dom node to watch for double clicks * @param latency - The amount of time (in milliseconds) to wait before differentiating a single from a double click, default 300 * @param onSingleClick - A callback fun...
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-double-click.tsx#L22-L76
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
useFocusById
const useFocusById = (id: string) => { useEffect(() => { const element = document.getElementById(id); if (!element) return; element.focus(); }, [id]); };
/** * Hook to focus an element by its ID. * * @param id - The ID of the element to focus. * */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-focus-by-id.tsx#L9-L15
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
useHideElementsById
const useHideElementsById = (ids: string[]): void => { useEffect(() => { const hiddenElements: HTMLElement[] = []; for (let i = 0; i < ids.length; i++) { const element = document.getElementById(ids[i]); if (element) { element.style.display = 'none'; hiddenElements.push(element); ...
/** * useHideElementsById - A custom React hook to hide elements by their IDs. * * @param ids - An array of element IDs to hide. */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-hide-elements-by-id.tsx#L8-L26
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
useLazyComponent
function useLazyComponent<T extends ComponentType<any>>(importFunc: () => Promise<{ default: T }>, delay: number): LazyExoticComponent<T> | null { const [Component, setComponent] = useState<LazyExoticComponent<T> | null>(null); useEffect(() => { const timer = setTimeout(() => { importFunc().then((module)...
/** * Lazily loads a component after a specified delay. * * @param importFunc - Function returning a promise for the component. * @param delay - Delay in milliseconds before loading. * @returns Lazily loaded component. */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-lazy-component.tsx#L11-L26
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
useScrollTo
const useScrollTo = (scrollToRef: React.RefObject<HTMLElement>) => { useEffect(() => { if (scrollToRef.current) { window.scrollTo({ top: scrollToRef.current.offsetTop, }); } }, [scrollToRef]); };
/** * Custom hook to scroll to a specific HTML element. * It automatically scrolls the window to the element's position when the reference is updated. * * @param scrollToRef - A ref pointing to the HTML element to scroll to. */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-scroll-to.tsx#L9-L17
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
useSearchParams
const useSearchParams = <T extends Record<string, string | string[] | undefined>>({ from, defaultValues, saveDataInSearch = true, }: SearchParams<T>) => { const navigate = useNavigate(); const params = useParams(from ? { from, strict: true } : { strict: false }); const search = useSearch(from ? { from, stri...
/** * Hook to manage and synchronize search parameters (query string) with the URL. * * @template T - The type of search parameters (query string). * @param from - The route identifier (optional). If provided, the hook is scoped to that route. * @param defaultValues - Default values for search parameters (optional...
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-search-params.tsx#L26-L109
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
parseHotkey
function parseHotkey(hotkey: string): Hotkey { const keys = hotkey === '+' ? ['+'] : hotkey .toLowerCase() .split('+') .map((part) => part.trim()); const modifiers: KeyboardModifiers = { alt: keys.includes('alt'), ctrl: keys.includes('ctrl'), meta: keys.inc...
// Parses a hotkey string into a Hotkey object with modifiers and a key
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-hot-keys/helpers.ts#L16-L43
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
isExactHotkey
function isExactHotkey(hotkey: Hotkey, event: KeyboardEvent): boolean { const { alt, ctrl, meta, mod, shift, key } = hotkey; const { altKey, ctrlKey, metaKey, shiftKey, key: pressedKey } = event; // Check modifiers if (alt !== altKey || (mod && !(ctrlKey || metaKey)) || ctrl !== ctrlKey || meta !== metaKey || ...
// Checks if the given KeyboardEvent matches the specified hotkey
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-hot-keys/helpers.ts#L46-L61
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
getHotkeyMatcher
function getHotkeyMatcher(hotkey: string): CheckHotkeyMatch { return (event) => isExactHotkey(parseHotkey(hotkey), event); }
// check if a KeyboardEvent matches the specified hotkey string
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-hot-keys/helpers.ts#L64-L66
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
shouldFireEvent
function shouldFireEvent(event: KeyboardEvent, tagsToIgnore: string[], triggerOnContentEditable = false) { if (event.target instanceof HTMLElement) { if (triggerOnContentEditable) { return !tagsToIgnore.includes(event.target.tagName); } return !event.target.isContentEditable && !tagsToIgnore.include...
// Determines whether the event should trigger the hotkey handler based on the target element and settings
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/hooks/use-hot-keys/helpers.ts#L75-L83
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
formatRowData
const formatRowData = <R extends Row>(row: R, column: Column) => { // Handle special cases if ((column.key === 'adminCount' || column.key === 'memberCount') && 'counts' in row && 'memberships' in row.counts) { const key = column.key.replace('Count', 's'); return row.counts.memberships[key]; } const date...
// Format data for a single row based on column configuration
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/export.ts#L101-L112
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
formatBodyData
const formatBodyData = <R extends Row>(rows: R[], columns: Column[]): (string | number)[][] => { return rows.map((row) => columns.map((column) => formatRowData(row, column))); };
// Format the body data based on column definitions
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/export.ts#L115-L117
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
filterColumns
const filterColumns = (column: Column) => { if ('visible' in column && column.key !== 'checkbox-column') return column.visible; return false; };
// Filter columns based on visibility
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/export.ts#L120-L123
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
serialiseCellValue
function serialiseCellValue(value: unknown) { if (typeof value === 'string') { const formattedValue = value.replace(/"/g, '""'); return formattedValue.includes(',') ? `"${formattedValue}"` : formattedValue; } return value; }
// Serialize cell values for CSV export
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/export.ts#L126-L132
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
downloadFile
function downloadFile(fileName: string, data: Blob) { const downloadLink = document.createElement('a'); downloadLink.download = fileName; const url = URL.createObjectURL(data); downloadLink.href = url; downloadLink.click(); URL.revokeObjectURL(url); }
// Trigger file download in the browser
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/export.ts#L135-L142
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
prepareFilesForOffline
const prepareFilesForOffline = async (files: { [key: string]: UppyFile<UppyMeta, UppyBody> }) => { console.warn('Files will be stored offline in indexedDB.'); // Save to local storage asynchronously await LocalFileStorage.addFiles(files); // Prepare successful files for manual `complete` event con...
// Prepare files for offline storage
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/imado.ts#L63-L72
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
fallbackMessages
const fallbackMessages = (t: (typeof i18n)['t']) => ({ 400: t('error:bad_request_action'), 401: t('error:unauthorized_action'), 403: t('error:forbidden_action'), 404: t('error:not_found'), 429: t('error:too_many_requests'), });
/** * Fallback messages for common 400 errors */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/query-client.ts#L13-L19
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
handleOnlineStatus
function handleOnlineStatus() { onlineManager.setOnline(navigator.onLine); }
/** * Handle online status */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/router.ts#L11-L13
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
createIDBPersister
function createIDBPersister(idbValidKey: IDBValidKey = 'reactQuery') { return { persistClient: async (client: PersistedClient) => { await set(idbValidKey, client); }, restoreClient: async () => { return await get<PersistedClient>(idbValidKey); }, removeClient: async () => { await...
/** * Create an IndexedDB persister for react-query */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/lib/router.ts#L47-L59
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
fetchFile
const fetchFile = async () => { try { const file = await LocalFileStorage.getFile(key); if (file && isMounted.current) { const blob = new Blob([file.data], { type: fileType || 'application/octet-stream' }); const newUrl = URL.createObjectURL(blob); setBlobUrl(key, new...
// Fetch the file from indexedDB and create a blob URL
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/attachments/use-local-file.ts#L30-L42
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
parseRawAttachment
const parseRawAttachment = (rawAttachment: RawAttachment): Attachment => { const columnEntries = Object.entries(attachmentsTableColumns); const attachment = {} as unknown as Attachment; for (const key of objectKeys(rawAttachment)) { const columnEntry = columnEntries.find(([, columnName]) => columnName === key...
// TODO use comments in this file and explain code better
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/attachments/table/helpers/use-sync.ts#L42-L52
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
openUploadDialog
const openUploadDialog = () => { if (!onlineManager.isOnline()) return toaster(t('common:action.offline.text'), 'warning'); dialog( <Suspense> <UploadUppy isPublic uploadType="personal" plugins={['webcam', 'image-editor']} imageMode="avatar" callb...
// Open the upload dialog
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/attachments/upload/upload-avatar.tsx
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
OauthOptions
const OauthOptions = ({ actionType = 'signIn' }: OauthOptionsProps) => { const { t } = useTranslation(); const { mode } = useThemeStore(); const { token, redirect } = useSearch({ from: AuthenticateRoute.id }); const [loading, setLoading] = useState(false); const redirectPath = redirect?.startsWith('/') ? re...
/** * Display OAuth options to sign in, sign up, accept invitation * * @param actionType The action type to perform */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/auth/oauth-options.tsx#L31-L83
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
PassKeyOption
const PassKeyOption = ({ email, actionType = 'signIn' }: PassKeyOptionProps) => { const { t } = useTranslation(); const navigate = useNavigate(); const { mode } = useThemeStore(); const { redirect } = useSearch({ from: AuthenticateRoute.id }); const redirectPath = redirect?.startsWith('/') ? redirect : confi...
// TODO: split passkeyAuth into separate file
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/auth/passkey-option.tsx#L17-L39
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
SignOut
const SignOut = () => { const { t } = useTranslation(); const navigate = useNavigate(); useEffect(() => { signOutUser().then(() => { flushStoresAndCache(); toaster(t('common:success.signed_out'), 'success'); navigate({ to: '/about', replace: true }); }); }, []); return null; };
// Sign out user and clear all stores and query cache
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/auth/sign-out.tsx#L24-L37
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
isAllowedSlashMenu
const isAllowedSlashMenu = (item: string, allowedTypes: (CellaCustomBlockTypes | BasicBlockTypes)[]) => { const allowedBlockTypes: readonly string[] = allowedTypes; const allowedType = menusTitleToAllowedType[item as MenusItemsTitle]; return allowedType && allowedBlockTypes.includes(allowedType); };
// Filter function to check if the MenusItemsTitle has an allowed type
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/blocknote/helpers.tsx#L35-L39
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
handleDragStart
const handleDragStart = ({ dataTransfer, clientY }: React.DragEvent) => { blockDragStart?.({ dataTransfer, clientY }, block); };
// Wrapper to match the signature of onDragStart
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/blocknote/custom-side-menu/drag-handle-button.tsx#L39-L41
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
handleButtonClick
const handleButtonClick = (e: React.MouseEvent) => e.preventDefault();
// Prevent form submission when clicking the drag handle button
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/blocknote/custom-side-menu/drag-handle-button.tsx#L44-L44
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
setSortColumns
const setSortColumns = (newSortColumns: SortColumn[]) => { if (newSortColumns.length === 0) return setSearch({ sort: undefined, order: undefined }); setSearch({ sort: newSortColumns[0].columnKey, order: newSortColumns[0].direction === 'ASC' ? 'asc' : 'desc', }); };
// Use setSearch to set sort and order in URL
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/data-table/sort-columns.ts#L16-L22
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
SheetsStateObserver.notifySubscribers
subscribe = (subscriber: (action: SheetAction & SheetT) => void) => { this.subscribers.push(subscriber); return () => { this.subscribers = this.subscribers.filter((sub) => sub !== subscriber); }; }
// Remove a sheet by its ID or clear all sheets (with optionally an exluded) and notify subscribers
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/sheeter/state.ts
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
reconnect
const reconnect = () => { if (source) source.close(); // Close old if it exists const newSource = createSource(true); setSource(newSource); };
// Closes old source, creates new
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/common/sse/provider.tsx#L19-L23
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
skipStep
const skipStep = (e: { preventDefault: () => void }) => { e.preventDefault(); if (onDefaultBoardingSteps[activeStep].id === 'organization' && !hasOrganizations) { dialog(<SkipOrganization />, { className: 'md:max-w-xl', title: `${t('common:skip')} ${t('common:create_resource', { resource: ...
// Ask to confirm
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/home/onboarding/footer.tsx#L25-L35
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
backStep
const backStep = (e: { preventDefault: () => void }) => { e.preventDefault(); prevStep(); };
// prevent accidental submit
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/home/onboarding/footer.tsx#L40-L43
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
updateCounts
const updateCounts = (newSelected: InvitedMember[], newTotal: number | undefined) => { if (newTotal !== total) setTotal(newTotal); if (!arraysHaveSameElements(selected, newSelected)) setSelected(newSelected); };
// Update total and selected counts
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/memberships/invited-members-table/index.tsx#L35-L38
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
onRowsChange
const onRowsChange = (changedRows: Member[], { indexes, column }: RowsChangeData<Member>) => { if (!onlineManager.isOnline()) return toaster(t('common:action.offline.text'), 'warning'); if (column.key !== 'role') return setRows(changedRows); // If role is changed, update membership for (const ...
// Update rows
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/memberships/members-table/table.tsx#L47-L69
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
filterItems
const filterItems = (items: UserMenuItem[]): UserMenuItem[] => items.flatMap((item) => { const isMatch = item.name.toLowerCase().includes(lowerCaseTerm); const filteredSubmenu = item.submenu ? filterItems(item.submenu) : []; return isMatch ? [item, ...filteredSubmenu] : filteredSub...
// Flatten menu items and submenus
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/navigation/menu-sheet/search-input.tsx#L29-L34
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
onRowsChange
const onRowsChange = (changedRows: User[], { indexes, column }: RowsChangeData<User>) => { if (!onlineManager.isOnline()) return toaster(t('common:action.offline.text'), 'warning'); for (const index of indexes) if (column.key === 'role') { const newUser = changedRows[index]; cons...
// Update user role
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/modules/users/table/table.tsx#L36-L51
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
prefetchMenuItems
const prefetchMenuItems = async (items: UserMenuItem[]) => { for (const item of items) { if (isCancelled) return; if (item.membership.archived) continue; // Skip this item but continue with others for (const query of queriesToMap(item)) { prefetchQuery(query); ...
// Recursively prefetch menu items
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/index.tsx#L44-L58
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
deepEqual
const deepEqual = (value1: any, value2: any): boolean => { // Check if both values are the same reference if (value1 === value2) return true; // If either value is null or not an object, they're not equal if (value1 === null || value2 === null || typeof value1 !== 'object' || typeof value2 !== 'object') return...
// biome-ignore lint/suspicious/noExplicitAny: any is used to infer the type of the compare values
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/helpers/compare-query-keys.ts#L20-L46
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
getExact
const getExact = <T>(passedQueryKey: QueryKey): [QueryKey, InfiniteQueryData<T> | QueryData<T> | undefined][] => { return [[passedQueryKey, queryClient.getQueryData<InfiniteQueryData<T> | QueryData<T>>(passedQueryKey)]]; };
/** * Retrieves query data for a given query key. * * @param passedQueryKey - Query key to search for similar queries. * @returns An array with query key and its corresponding data. */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/helpers/mutate-query.ts#L122-L124
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
updateArrayItems
const updateArrayItems = <T extends ItemData>(items: T[], dataItems: T[], action: QueryDataActions) => { // Determine how to handle dataItems in the items array based on action type switch (action) { case 'create': { // Filter out already existing items based on their IDs const existingIds = items.m...
/** * Helper function to update an array of items based on the action. * * @param items - Current items to update. * @param dataItems - Items to merge into current items. * @param action - `"create" | "update" | "delete" | "updateMembership"` * @returns The updated array of items. */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/hooks/use-mutate-query-data/helpers.ts#L128-L163
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
updateItem
const updateItem = <T extends ItemData>(prevItem: T, newItem: T, action: QueryDataActions) => { // Determine how to handle dataItems in the items array based on action type switch (action) { case 'update': return { ...prevItem, ...newItem }; case 'updateMembership': { // update the membership f...
/** * Helper function to update a single item based on the action. * * @param prevItem - Previous item to update. * @param newItem - New item to merge. * @param action - `"create" | "update" | "delete" | "updateMembership"` * @returns The updated item. */
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/hooks/use-mutate-query-data/helpers.ts#L173-L189
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
dataMutation
function dataMutation(items: ItemData[] | EntityData[] | ContextEntityData[], action: QueryDataActions, entity?: Entity, keyToOperateIn?: string) { const passedQueryData = queryClient.getQueryData(passedQueryKey); const passedQuery: [QueryKey, unknown] = [passedQueryKey, passedQueryData]; const similarQuer...
// mutation function
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/query/hooks/use-mutate-query-data/index.tsx#L39-L60
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
cella
github_2023
cellajs
typescript
generateNumber
function generateNumber(id: string) { if (!id) return null; for (let i = id.length - 1; i >= 0; i--) { const char = id[i].toLowerCase(); if (Number.parseInt(char) >= 0 && Number.parseInt(char) <= 9) { return Number.parseInt(char) % 10; } if (char >= 'a' && char <= 'z') { return (char.ch...
// Generate a number from a string (ie. to choose a color)
https://github.com/cellajs/cella/blob/99695fe84ed346d91cd7e35b804c7ccce9e96f7b/frontend/src/utils/number-to-color-class.ts#L4-L17
99695fe84ed346d91cd7e35b804c7ccce9e96f7b
prettify-ts
github_2023
mylesmmurphy
typescript
getTypeTree
function getTypeTree (type: ts.Type, depth: number, visited: Set<ts.Type>): TypeTree { const typeName = checker.typeToString(type, undefined, typescript.TypeFormatFlags.NoTruncation) const apparentType = checker.getApparentType(type) if (depth >= options.maxDepth || isPrimitiveType(type) || options.skippedTypeNa...
/** * Recursively get type information by building a TypeTree object from the given type */
https://github.com/mylesmmurphy/prettify-ts/blob/4a4414df3aad32f34265d01b5881d57d720a61ac/packages/typescript-plugin/src/type-tree/index.ts#L75-L225
4a4414df3aad32f34265d01b5881d57d720a61ac
prettify-ts
github_2023
mylesmmurphy
typescript
sortUnionTypes
function sortUnionTypes (a: ts.Type, b: ts.Type): number { const primitiveTypesOrder = ['string', 'number', 'bigint', 'boolean', 'symbol'] const falsyTypesOrder = ['null', 'undefined'] const aIntrinsicName = isIntrinsicType(a) ? a.intrinsicName : '' const bIntrinsicName = isIntrinsicType(b) ? b.intrinsicName :...
/** * Sort union types by intrinsic types order, following ts quick info order * Ex. * string, number, bigint, { a: string }, null, undefined */
https://github.com/mylesmmurphy/prettify-ts/blob/4a4414df3aad32f34265d01b5881d57d720a61ac/packages/typescript-plugin/src/type-tree/index.ts#L262-L303
4a4414df3aad32f34265d01b5881d57d720a61ac
podman-desktop-extension-ai-lab
github_2023
containers
typescript
CatalogManager.init
init(): void { // Creating a json watcher this.#jsonWatcher = new JsonWatcher(this.getUserCatalogPath(), { version: CatalogFormat.CURRENT, recipes: [], models: [], categories: [], }); this.#jsonWatcher.onContentUpdated(content => this.onUserCatalogUpdate(content)); this.#json...
/** * The init method will start a watcher on the user catalog.json */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/catalogManager.ts#L62-L72
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
CatalogManager.importUserModels
async importUserModels(localModels: LocalModelImportInfo[]): Promise<void> { const userCatalogPath = this.getUserCatalogPath(); let content: ApplicationCatalog; // check if we already have an existing user's catalog if (fs.existsSync(userCatalogPath)) { const raw = await promises.readFile(userCat...
/** * This method is used to imports user's local models. * @param localModels the models to imports */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/catalogManager.ts#L195-L241
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
CatalogManager.removeUserModel
async removeUserModel(modelId: string): Promise<void> { const userCatalogPath = this.getUserCatalogPath(); if (!fs.existsSync(userCatalogPath)) { throw new Error('User catalog does not exist.'); } const raw = await promises.readFile(userCatalogPath, 'utf-8'); const content = sanitize(JSON.par...
/** * Remove a model from the user's catalog. * @param modelId */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/catalogManager.ts#L247-L270
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
CatalogManager.getUserCatalogPath
private getUserCatalogPath(): string { return path.resolve(this.appUserDirectory, USER_CATALOG); }
/** * Return the path to the user catalog */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/catalogManager.ts#L275-L277
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
GitManager.getRepositoryStatus
async getRepositoryStatus(directory: string): Promise<{ modified: string[]; created: string[]; deleted: string[]; clean: boolean; }> { const status = await git.statusMatrix({ fs, dir: directory, }); const FILE = 0, HEAD = 1, WORKDIR = 2, STAGE = 3; const...
/* see https://isomorphic-git.org/docs/en/statusMatrix * * - The HEAD status is either absent (0) or present (1). * - The WORKDIR status is either absent (0), identical to HEAD (1), or different from HEAD (2). * - The STAGE status is either absent (0), identical to HEAD (1), identical to WORKDIR (2), or dif...
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/gitManager.ts#L74-L106
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
ModelsManager.requestDownloadModel
async requestDownloadModel(model: ModelInfo, labels?: { [key: string]: string }): Promise<string> { // Create a task to follow progress const task: Task = this.createDownloadTask(model, labels); // Check there is no existing downloader running const existingDownloader = this.#downloaders.get(model.id);...
/** * This method will resolve when the provided model will be downloaded. * * This can method can be call multiple time for the same model, it will reuse existing downloader and wait on * their completion. * @param model * @param labels */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/modelsManager.ts#L253-L289
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PlaygroundV2Manager.submitSystemPrompt
private submitSystemPrompt(conversationId: string, content: string): void { this.#conversationRegistry.submit(conversationId, { content: content, role: 'system', id: this.#conversationRegistry.getUniqueId(), timestamp: Date.now(), } as SystemPrompt); this.telemetry.logUsage('playgrou...
/** * Add a system prompt to an existing conversation. * @param conversationId the conversation to append the system prompt to. * @param content the content of the system prompt */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/playgroundV2Manager.ts#L147-L157
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PlaygroundV2Manager.setSystemPrompt
setSystemPrompt(conversationId: string, content: string | undefined): void { const conversation = this.#conversationRegistry.get(conversationId); if (content === undefined || content.length === 0) { this.#conversationRegistry.removeMessage(conversationId, conversation.messages[0].id); this.telemetr...
/** * Given a conversation, update the system prompt. * If none exists, it will create one, otherwise it will replace the content with the new one * @param conversationId the conversation id to set the system id * @param content the new system prompt to use */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/playgroundV2Manager.ts#L165-L188
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PlaygroundV2Manager.submit
async submit(conversationId: string, userInput: string, options?: ModelOptions): Promise<number> { const conversation = this.#conversationRegistry.get(conversationId); const servers = this.inferenceManager.getServers(); const server = servers.find(s => s.models.map(mi => mi.id).includes(conversation.modelI...
/** * @param conversationId * @param userInput the user input * @param options the model configuration */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/playgroundV2Manager.ts#L195-L274
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PlaygroundV2Manager.processStream
private async processStream(conversationId: string, stream: Stream<ChatCompletionChunk>): Promise<void> { const conversation = this.#conversationRegistry.get(conversationId); const messageId = this.#conversationRegistry.getUniqueId(); const start = Date.now(); this.#conversationRegistry.submit(conversa...
/** * Given a Stream from the OpenAI library update and notify the publisher * @param conversationId * @param stream */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/playgroundV2Manager.ts#L295-L320
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PlaygroundV2Manager.getFormattedMessages
private getFormattedMessages(conversationId: string): ChatCompletionMessageParam[] { const conversation = this.#conversationRegistry.get(conversationId); if (!conversation) throw new Error(`conversation with id ${conversationId} does not exist.`); return conversation.messages .filter(m => isChatMessa...
/** * Transform the ChatMessage interface to the OpenAI ChatCompletionMessageParam * @private */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/playgroundV2Manager.ts#L326-L339
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PodmanConnection.execute
execute(connection: ContainerProviderConnection, args: string[], options?: RunOptions): Promise<RunResult> { const podman = extensions.getExtension('podman-desktop.podman'); if (!podman) { console.warn('cannot find podman extension api'); return this.executeLegacy(args, options); } const po...
/** * Execute the podman cli with the arguments provided * * @example * ``` * const result = await podman.execute(connection, ['machine', 'ls', '--format=json']); * ``` * @param connection * @param args * @param options */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L74-L89
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PodmanConnection.executeSSH
executeSSH(connection: ContainerProviderConnection, args: string[], options?: RunOptions): Promise<RunResult> { return this.execute(connection, ['machine', 'ssh', this.getNameLegacyCompatibility(connection), ...args], options); }
/** * Execute a command inside the podman machine * * @example * ``` * const result = await podman.executeSSH(connection, ['ls', '/dev']); * ``` * @param connection * @param args * @param options */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L102-L104
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PodmanConnection.executeLegacy
protected executeLegacy(args: string[], options?: RunOptions): Promise<RunResult> { return process.exec(getPodmanCli(), [...args], options); }
/** * Before 1.13, the podman extension was not exposing any api. * * Therefore, to support old version we need to get the podman executable ourself * @deprecated */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L112-L114
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PodmanConnection.getNameLegacyCompatibility
protected getNameLegacyCompatibility(connection: ContainerProviderConnection): string { return getPodmanMachineName(connection); }
/** * Before 1.13, the {@link ContainerProviderConnection.name} field was used as friendly user * field also. * * Therefore, we could have `Podman Machine Default` as name, where the real machine was `podman-machine-default`. * @param connection * @deprecated */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L124-L126
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PodmanConnection.getContainerProviderConnectionInfo
getContainerProviderConnectionInfo(): ContainerProviderConnectionInfo[] { const output: ContainerProviderConnectionInfo[] = []; for (const [providerId, connections] of Array.from(this.#providers.entries())) { output.push( ...connections.map( (connection): ContainerProviderConnectionInfo...
/** * This method flatten the */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L135-L153
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PodmanConnection.getProviderContainerConnection
protected getProviderContainerConnection(connection: ContainerProviderConnection): ProviderContainerConnection { const providers: ProviderContainerConnection[] = provider.getContainerConnections(); const podmanProvider = providers .filter(({ connection }) => connection.type === 'podman') .find(prov...
/** * This method allow us to get the ProviderContainerConnection given a ContainerProviderConnection * @param connection * @protected */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L171-L180
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PodmanConnection.getVMType
async getVMType(name?: string): Promise<VMType> { const { stdout } = await process.exec(getPodmanCli(), ['machine', 'list', '--format', 'json']); const parsed: unknown = JSON.parse(stdout); if (!Array.isArray(parsed)) throw new Error('podman machine list provided a malformed response'); if (parsed.leng...
/** * Get the VMType of the podman machine * @param name the machine name, from {@link ContainerProviderConnection} * @deprecated should uses the `getContainerProviderConnectionInfo()` */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L262-L282
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
PodmanConnection.getConnectionByEngineId
async getConnectionByEngineId(engineId: string): Promise<ContainerProviderConnection> { const connections = Array.from(this.#providers.values()).flat(); for (const connection of connections) { const infos = await containerEngine.listInfos({ provider: connection }); if (infos.length === 0) continue; ...
/** * This method return the ContainerProviderConnection corresponding to an engineId * @param engineId */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/podmanConnection.ts#L304-L313
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
ApplicationManager.initApplication
private async initApplication( connection: ContainerProviderConnection, recipe: Recipe, model: ModelInfo, labels: Record<string, string> = {}, ): Promise<PodInfo> { // clone the recipe await this.recipeManager.cloneRecipe(recipe, { ...labels, 'model-id': model.id }); // get model by downl...
/** * This method will execute the following tasks * - git clone * - git checkout * - register local repository * - download models * - upload models * - build containers * - create pod * * @param connection * @param recipe * @param model * @param labels * @private */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/application/applicationManager.ts#L175-L218
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
ApplicationManager.runApplication
protected async runApplication(podInfo: PodInfo, labels?: { [key: string]: string }): Promise<void> { const task = this.taskRegistry.createTask('Starting AI App', 'loading', labels); // it starts the pod try { await this.podManager.startPod(podInfo.engineId, podInfo.Id); // check if all contai...
/** * Given an ApplicationPodInfo, start the corresponding pod * @param podInfo * @param labels */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/application/applicationManager.ts#L225-L248
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
ApplicationManager.stopApplication
async stopApplication(recipeId: string, modelId: string): Promise<PodInfo> { // clear existing tasks this.clearTasks(recipeId, modelId); // get the application pod const appPod = await this.getApplicationPod(recipeId, modelId); // if the pod is already stopped skip if (appPod.Status === 'Exite...
/** * Stop the pod with matching recipeId and modelId * @param recipeId * @param modelId */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/application/applicationManager.ts#L435-L468
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
ApplicationManager.startApplication
async startApplication(recipeId: string, modelId: string): Promise<void> { this.clearTasks(recipeId, modelId); const pod = await this.getApplicationPod(recipeId, modelId); return this.runApplication(pod, { 'recipe-id': recipeId, 'model-id': modelId, }); }
/** * Utility method to start a pod using (recipeId, modelId) * @param recipeId * @param modelId */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/application/applicationManager.ts#L475-L483
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
ApplicationManager.removeApplication
async removeApplication(recipeId: string, modelId: string): Promise<void> { const appPod = await this.stopApplication(recipeId, modelId); const remoteTask = this.taskRegistry.createTask(`Removing AI App`, 'loading', { 'recipe-id': recipeId, 'model-id': modelId, }); // protect the task t...
/** * Method that will stop then remove a pod corresponding to the recipe and model provided * @param recipeId * @param modelId */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/application/applicationManager.ts#L641-L663
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
InferenceManager.dispose
dispose(): void { this.cleanDisposables(); this.#servers.clear(); this.#initialized = false; }
/** * Cleanup the manager */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L77-L81
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
InferenceManager.cleanDisposables
private cleanDisposables(): void { this.#disposables.forEach(disposable => disposable.dispose()); }
/** * Clean class disposables */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L86-L88
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
InferenceManager.getServers
public getServers(): InferenceServer[] { return Array.from(this.#servers.values()); }
/** * Get the Inference servers */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L93-L95
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7
podman-desktop-extension-ai-lab
github_2023
containers
typescript
InferenceManager.get
public get(containerId: string): InferenceServer | undefined { return this.#servers.get(containerId); }
/** * return an inference server * @param containerId the containerId of the inference server */
https://github.com/containers/podman-desktop-extension-ai-lab/blob/acc28f4dac6ba1a6b6d39720e6721d150e76e5f7/packages/backend/src/managers/inference/inferenceManager.ts#L101-L103
acc28f4dac6ba1a6b6d39720e6721d150e76e5f7