repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelTokens.eosString
public get eosString(): string | null { this._ensureNotDisposed(); const eosToken = this.eos; if (eosToken == null) return null; if (this._eosString == null) this._eosString = this._model.getTokenString(eosToken); return this._eosString; }
/** * @returns The EOS (End Of Sequence) token text representation. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L902-L914
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelTokens.eotString
public get eotString(): string | null { this._ensureNotDisposed(); const eotToken = this.eot; if (eotToken == null) return null; if (this._eotString == null) this._eotString = this._model.getTokenString(eotToken); return this._eotString; }
/** * @returns The EOT (End Of Turn) token text representation. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L919-L931
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelTokens.sepString
public get sepString(): string | null { this._ensureNotDisposed(); const sepToken = this.sep; if (sepToken == null) return null; if (this._sepString == null) this._sepString = this._model.getTokenString(sepToken); return this._sepString; }
/** * @returns The SEP (Sentence Separator) token text representation. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L936-L948
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelTokens.nlString
public get nlString(): string | null { this._ensureNotDisposed(); const nlToken = this.nl; if (nlToken == null) return null; if (this._nlString == null) this._nlString = this._model.getTokenString(nlToken); return this._nlString; }
/** * @returns The NL (New Line) token text representation. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L953-L965
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelTokens.shouldPrependBosToken
public get shouldPrependBosToken(): boolean { this._ensureNotDisposed(); if (this._shouldPrependBosToken == null) this._shouldPrependBosToken = this.bos != null && this._model.shouldPrependBosToken(); return this._shouldPrependBosToken; }
/** * @returns Whether we should prepend a BOS (Beginning Of Sequence) token for evaluations with this model. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L970-L977
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelTokens.shouldAppendEosToken
public get shouldAppendEosToken(): boolean { this._ensureNotDisposed(); if (this._shouldAppendEosToken == null) this._shouldAppendEosToken = this.bos != null && this._model.shouldAppendEosToken(); return this._shouldAppendEosToken; }
/** * @returns Whether we should append an EOS (End Of Sequence) token for evaluations with this model. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L982-L989
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelTokens._create
public static _create(model: AddonModel, disposedState: DisposedState) { return new LlamaModelTokens(model, disposedState); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L998-L1000
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelInfillTokens.prefix
public get prefix(): Token | null { this._ensureNotDisposed(); if (this._prefixToken == null) this._prefixToken = this._resolveSpecialToken(this._model.prefixToken(), ["<fim_prefix>"]); if (this._prefixToken === -1) return null; return this._prefixToken; }
/** * @returns The beginning of infill prefix token. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L1021-L1031
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelInfillTokens.middle
public get middle(): Token | null { this._ensureNotDisposed(); if (this._middleToken == null) this._middleToken = this._resolveSpecialToken(this._model.middleToken(), ["<fim_middle>"]); if (this._middleToken === -1) return null; return this._middleToken; }
/** * @returns The beginning of infill middle token. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L1036-L1046
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelInfillTokens.suffix
public get suffix(): Token | null { this._ensureNotDisposed(); if (this._suffixToken == null) this._suffixToken = this._resolveSpecialToken(this._model.suffixToken(), ["<fim_suffix>"]); if (this._suffixToken === -1) return null; return this._suffixToken; }
/** * @returns The beginning of infill suffix token. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L1051-L1061
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelInfillTokens.prefixString
public get prefixString(): string | null { this._ensureNotDisposed(); const prefixToken = this.prefix; if (prefixToken == null) return null; if (this._prefixString == null) this._prefixString = this._model.getTokenString(prefixToken); return this._pref...
/** * @returns The beginning of infill prefix token as a string. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L1066-L1078
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelInfillTokens.middleString
public get middleString(): string | null { this._ensureNotDisposed(); const middleToken = this.middle; if (middleToken == null) return null; if (this._middleString == null) this._middleString = this._model.getTokenString(middleToken); return this._midd...
/** * @returns The beginning of infill middle token as a string. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L1083-L1095
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelInfillTokens.suffixString
public get suffixString(): string | null { this._ensureNotDisposed(); const suffixToken = this.suffix; if (suffixToken == null) return null; if (this._suffixString == null) this._suffixString = this._model.getTokenString(suffixToken); return this._suff...
/** * @returns The beginning of infill suffix token as a string. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L1100-L1112
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelInfillTokens._resolveSpecialToken
private _resolveSpecialToken(token: Token, fallbackTexts: string[]): Token { if (token != null && token !== -1) return token; for (const text of fallbackTexts) { const tokens = this._model.tokenize(text, true); if (tokens.length !== 1) continue; ...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L1121-L1134
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaModelInfillTokens._create
public static _create(model: AddonModel, disposedState: DisposedState) { return new LlamaModelInfillTokens(model, disposedState); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/LlamaModel.ts#L1137-L1139
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
TokenAttributes._hasAttribute
private _hasAttribute(attribute: TokenAttribute) { return (this._attributes & attribute) === attribute; }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/utils/TokenAttributes.ts#L72-L74
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
TokenAttributes._create
public static _create(token: Token, attributes: TokenAttribute) { return new TokenAttributes(token, attributes); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/evaluator/LlamaModel/utils/TokenAttributes.ts#L77-L79
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsights.getWarnings
public getWarnings(modelFilePath?: string) { const warnings: string[] = []; const modelFilePathText = (modelFilePath != null && modelFilePath !== "") ? ` ("${getReadablePath(modelFilePath)}")` : ""; if (this._ggufFileInfo?.metadata?.tokenizer?.ggml?.model === "gpt2" && ...
/** * Get warnings about the model file that would affect its usage. * * Most of these warnings are also generated by `llama.cpp` */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsights.ts#L35-L53
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsights.trainContextSize
public get trainContextSize() { return this._ggufFileInfo.architectureMetadata.context_length; }
/** The context size the model was trained on */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsights.ts#L64-L66
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsights.embeddingVectorSize
public get embeddingVectorSize() { return this._ggufFileInfo.architectureMetadata.embedding_length; }
/** The size of an embedding vector the model can produce */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsights.ts#L69-L71
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsights.estimateContextResourceRequirements
public estimateContextResourceRequirements({ contextSize, modelGpuLayers, batchSize, sequences, isEmbeddingContext = false, includeGraphOverhead = true, flashAttention = false }: { contextSize: number, modelGpuLayers: number, batchSize?: number, sequences?: number, isEmbeddingContext?: boolean, ...
/** * Estimates the memory required to create a context of the given parameters based on the implementation details of `llama.cpp`. * The calculation doesn't include a precise estimation of the graph overhead memory, so it uses a rough estimate for that. * The estimation for the graph overhead memory wil...
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsights.ts#L154-L351
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
estimateGraphOverheadMemory
const estimateGraphOverheadMemory = () => { const s1MB = Math.pow(1024, 2); const tensorInfo = this._ggufFileInfo.fullTensorInfo ?? []; let defaultCalculationAdjustment = 0; if (batchSize == null) return 0; if (this._ggufFileInfo.metadata.ge...
// Estimates the memory allocated by `ggml_backend_sched_reserve` in `llama_new_context_with_model` in `llama.cpp`.
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsights.ts#L220-L320
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsights._getTensorResourceSplit
public _getTensorResourceSplit(gpuLayers: number): { cpu: GgufTensorInfo[], gpu: GgufTensorInfo[] } { const tensorInfo = this._ggufFileInfo.fullTensorInfo ?? []; const architecture = this._ggufFileInfo.metadata?.general?.architecture; if (gpuLayers === 0) { retur...
/** * Get the split tensor resources for CPU and GPU based on the number of GPU layers * @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsights.ts#L357-L430
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsights._determineNumberOfLayersFromTensorInfo
public _determineNumberOfLayersFromTensorInfo(): number { const layerNumbers = new Set<number>(); for (const singleTensorInfo of (this._ggufFileInfo.fullTensorInfo ?? [])) { const {layerNumber} = parseTensorName(singleTensorInfo.name); if (layerNumber != null) l...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsights.ts#L433-L444
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsights._getFileLayers
public _getFileLayers() { return this._ggufFileInfo.architectureMetadata.block_count ?? this._determineNumberOfLayersFromTensorInfo(); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsights.ts#L447-L449
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsights._estimateKvMemorySizeInBytes
public _estimateKvMemorySizeInBytes(contextSize: number, layers: number) { // source: `llama_kv_cache_init` in `llama.cpp` const nHead = this._ggufFileInfo.architectureMetadata.attention?.head_count ?? 0; const nEmbd = this._ggufFileInfo.architectureMetadata.embedding_length ?? 0; const ...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsights.ts#L452-L488
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsights.from
public static async from(ggufFileInfo: GgufFileInfo, llama?: Llama) { let resolvedLlama = llama; if (resolvedLlama == null) resolvedLlama = await getLlamaWithoutBackend(); return new GgufInsights(ggufFileInfo, resolvedLlama); }
/** * @param ggufFileInfo * @param llama - If you already have a `Llama` instance, pass it to reuse it for the `GgufInsights` instance. * If you don't pass a `Llama` instance, a basic `Llama` instance is created as a fallback - it's a slim instance that * doesn't instantiate a `llama.cpp` backend, s...
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsights.ts#L497-L503
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsightsConfigurationResolver.resolveAndScoreConfig
public async resolveAndScoreConfig({ targetGpuLayers, targetContextSize, embeddingContext = false, flashAttention = false, useMmap = this._ggufInsights._llama.supportsMmap }: { targetGpuLayers?: number | "max", targetContextSize?: number, embeddingCont...
/** * Resolve the best configuration for loading a model and creating a context using the current hardware. * * Specifying a `targetGpuLayers` and/or `targetContextSize` will ensure the resolved configuration matches those values, * but note it can lower the compatibility score if the hardware doesn...
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsightsConfigurationResolver.ts#L37-L81
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsightsConfigurationResolver.scoreModelConfigurationCompatibility
public async scoreModelConfigurationCompatibility({ contextSize = Math.min(4096, this._ggufInsights.trainContextSize ?? 4096), embeddingContext = false, flashAttention = false, maximumFittedContextSizeMultiplier = 100, maximumUnfitConfigurationResourceMultiplier = 100, fo...
/** * Score the compatibility of the model configuration with the current GPU and VRAM state. * Assumes a model is loaded with the default `"auto"` configurations. * Scored based on the following criteria: * - The number of GPU layers that can be offloaded to the GPU (only if there's a GPU. If there...
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsightsConfigurationResolver.ts#L104-L366
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsightsConfigurationResolver.resolveContextContextSize
public async resolveContextContextSize(contextSize: LlamaContextOptions["contextSize"], { modelGpuLayers, batchSize, modelTrainContextSize, flashAttention = false, getVramState = (() => this._ggufInsights._llama._vramOrchestrator.getMemoryState()), getRamState = (async ()...
/** * Resolve a context size option for the given options and constraints. * * If there's no context size that can fit the available resources, an `InsufficientMemoryError` is thrown. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsightsConfigurationResolver.ts#L397-L437
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
GgufInsightsConfigurationResolver._create
public static _create(ggufInsights: GgufInsights) { return new GgufInsightsConfigurationResolver(ggufInsights); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/gguf/insights/GgufInsightsConfigurationResolver.ts#L440-L442
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
DisposeGuard._isDisposeActivated
private _isDisposeActivated(): boolean { if (this._disposeActivated) return true; return [...this._parentDisposeGuardsLocks.keys()].some((parent) => parent._isDisposeActivated()); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/DisposeGuard.ts#L69-L74
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
DisposeGuard._activateLocksIfNeeded
private _activateLocksIfNeeded() { if (this._preventionHandles > 0) return; while (this._awaitingDisposeLockCallbacks.length > 0) { this._disposeActivated = true; this._awaitingDisposeLockCallbacks.shift()!(); } }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/DisposeGuard.ts#L77-L85
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
DisposeGuard._updateParentDisposeGuardLocks
private _updateParentDisposeGuardLocks(onlyAllowRemoval: boolean = false) { if (this._preventionHandles === 0) { for (const parent of this._parentDisposeGuardsLocks.keys()) { const parentLock = this._parentDisposeGuardsLocks.get(parent); if (parentLock == null) ...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/DisposeGuard.ts#L88-L107
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
DisposeGuard._hasAwaitingDisposeLocks
private _hasAwaitingDisposeLocks(): boolean { if (this._awaitingDisposeLockCallbacks.length > 0) return true; return [...this._parentDisposeGuardsLocks.keys()].some((parent) => parent._hasAwaitingDisposeLocks()); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/DisposeGuard.ts#L110-L115
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
DisposalPreventionHandle._create
public static _create(dispose: () => void) { return new DisposalPreventionHandle(dispose); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/DisposeGuard.ts#L145-L147
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaText.constructor
public constructor(...values: readonly LlamaTextInputValue[]) { // the constructor logic is copied to `LlamaTextConstructor` to make the constructor callable as a normal function this.values = createHistoryFromStringsAndValues(values); }
/** * Can also be called without `new` */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/LlamaText.ts#L22-L25
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaText.joinValues
public joinValues(separator: LlamaText | LlamaTextValue) { const newValues: LlamaTextValue[] = []; for (let i = 0; i < this.values.length; i++) { newValues.push(this.values[i]!); if (i !== this.values.length - 1) { if (isLlamaText(separator)) ...
/** * Joins the values with the given separator. * * Note that the values are squashed when they are loaded into the `LlamaText`, so the separator is not added between adjacent strings. * * To add the separator on values before squashing them, use `LlamaText.joinValues` instead. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/LlamaText.ts#L51-L66
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaText.fromTokens
public static fromTokens(tokenizer: Tokenizer, tokens: Token[]): LlamaText { // assigned to `LlamaTextConstructor` manually to expose this static method const res: (string | SpecialToken | SpecialTokensText)[] = []; const pendingTokens: Token[] = []; const addPendingTokens = () => { ...
/** * Attempt to convert tokens to a `LlamaText` while preserving special tokens. * * Non-standard special tokens that don't have a text representation are ignored. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/LlamaText.ts#L312-L360
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
LlamaText.joinValues
public static joinValues(separator: LlamaText | string, values: readonly LlamaTextInputValue[]): LlamaText { // assigned to `LlamaTextConstructor` manually to expose this static method const newValues: (LlamaTextInputValue | LlamaText)[] = []; for (let i = 0; i < values.length; i++) { ...
/** * Join values with the given separator before squashing adjacent strings inside the values */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/LlamaText.ts#L365-L380
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
SpecialTokensText.wrapIf
public static wrapIf(shouldWrap: boolean, value: string): SpecialTokensText | string { if (shouldWrap) return new SpecialTokensText(value); else return value; }
/** * Wraps the value with a `SpecialTokensText` only if `shouldWrap` is true */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/LlamaText.ts#L510-L515
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
StopGenerationDetector.hasTriggeredStops
public get hasTriggeredStops() { return this._triggeredStops.size > 0; }
/** Whether there are some stops that have been found and triggered. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/StopGenerationDetector.ts#L129-L131
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
StopGenerationDetector.hasInProgressStops
public get hasInProgressStops() { return this._activeChecks.size > 0; }
/** Whether there are some stops that have been found, but not triggered yet. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/StopGenerationDetector.ts#L134-L136
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
StopGenerationDetector.getTriggeredStops
public getTriggeredStops() { const res: TriggeredStop<T>[] = []; for (const [triggerPart, triggeredStop] of this._triggeredStops.entries()) { res.push({ stopTrigger: triggerPart.completesTrigger!, events: Array.from(triggerPart.completeEvents ?? new Set()), ...
/** Gets the stops that have been found and triggered. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/StopGenerationDetector.ts#L139-L152
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
StopGenerationDetector.getDisregardedPossibilitiesCountForAGeneration
public getDisregardedPossibilitiesCountForAGeneration({ text, tokens, startNewChecks }: { text: string, tokens: Token[], /** Setting this to `true` implies that `triggerMustStartWithGeneration` is also `true` */ startNewChecks: boolean }) { let res = 0; for (con...
/** * For a given generation, get the number of possibilities that would be disregarded if the generation is recorded. * * Calling this function does not change the state of the detector. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/StopGenerationDetector.ts#L179-L213
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
StopGenerationDetector._addFoundStop
private _addFoundStop( part: TriggerPart<T>, remainingGeneration?: string | Token[], queuedTokenReleaseLock?: QueuedTokenReleaseLock ) { if (!this._triggeredStops.has(part)) this._triggeredStops.set(part, { remainingGenerations: new Set(), ...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/StopGenerationDetector.ts#L216-L234
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
StopGenerationDetector._getCountOfPossibleTriggersToBeDisregarded
private _getCountOfPossibleTriggersToBeDisregarded(initialPart: TriggerPart<T> | undefined, value: string | Token[]) { if (initialPart == null) return 0; let part: TriggerPart<T> | undefined = initialPart; let res = 0; for (let i = 0; i < value.length && part != null; i++) ...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/StopGenerationDetector.ts#L237-L263
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
StopGenerationDetector._checkTriggerPart
private _checkTriggerPart(check: TriggerCheck<T> | undefined, value: string | Token[]) { if (check == null) return false; let part: TriggerPart<T> | undefined = check.currentPart; for (let i = 0; i < value.length && part != null; i++) { const item = value[i]!; ...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/StopGenerationDetector.ts#L266-L302
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ThreadsSplitter.constructor
public constructor(maxThreads: number) { this.maxThreads = Math.floor(Math.max(0, maxThreads)); this._removeWantedThreads = this._removeWantedThreads.bind(this); this._removeThreadDemand = this._removeThreadDemand.bind(this); }
/** * Set to `0` to disable the limit * @param maxThreads */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/ThreadsSplitter.ts#L15-L20
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ThreadsSplitter._getUpdatedActiveThreads
public _getUpdatedActiveThreads(inUsed: number, wanted: number, demanded: number) { const initialActiveThreads = this._activeThreads; if (inUsed > wanted) this._activeThreads -= inUsed - wanted; const idealThreads = this._calculateIdealProportion(wanted, demanded); let alloc...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/ThreadsSplitter.ts#L40-L70
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ThreadsSplitter._waitForFreeThread
public _waitForFreeThread() { return new Promise<void>((resolve) => this._threadFreeCallbacks.push(resolve)); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/ThreadsSplitter.ts#L94-L96
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ThreadsSplitter._addWantedThreads
public _addWantedThreads(wantedThreads: number) { this._totalWantedThreads += wantedThreads; }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/ThreadsSplitter.ts#L99-L101
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ThreadsSplitter._removeWantedThreads
public _removeWantedThreads(wantedThreads: number) { this._totalWantedThreads -= wantedThreads; }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/ThreadsSplitter.ts#L104-L106
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ThreadsSplitter._addThreadDemand
public _addThreadDemand(demandedThreads: number) { this._threadDemands.add(demandedThreads); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/ThreadsSplitter.ts#L109-L111
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ThreadsSplitter._removeThreadDemand
public _removeThreadDemand(demandedThreads: number) { const isHighestDemand = this._threadDemands.maxNumber === demandedThreads; this._threadDemands.remove(demandedThreads); if (demandedThreads !== 0 && isHighestDemand && this._threadDemands.maxNumber !== demandedThreads) { while (t...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/ThreadsSplitter.ts#L114-L122
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
QueuedTokenRelease._create
public static _create(tokens: Token[], text: string) { return new QueuedTokenRelease(tokens, text); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/TokenStreamRegulator.ts#L201-L203
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
QueuedTokenReleaseLock._create
public static _create(length: number, locks: Set<QueuedTokenReleaseLock>) { return new QueuedTokenReleaseLock(length, locks); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/TokenStreamRegulator.ts#L239-L241
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
UnsupportedError.constructor
public constructor(message: string = "UnsupportedError") { super(message); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/UnsupportedError.ts#L3-L5
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ModelDownloader.entrypointFilename
public get entrypointFilename() { return this._entrypointFilename!; }
/** * The filename of the entrypoint file that should be used to load the model. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L246-L248
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ModelDownloader.entrypointFilePath
public get entrypointFilePath() { return path.join(this._dirPath, this.entrypointFilename); }
/** * The full path to the entrypoint file that should be used to load the model. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L253-L255
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ModelDownloader.splitBinaryParts
public get splitBinaryParts() { return this._splitBinaryParts; }
/** * If the model is binary spliced from multiple parts, this will return the number of those binary parts. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L260-L262
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ModelDownloader.totalFiles
public get totalFiles() { return this._totalFiles!; }
/** * The total number of files that will be saved to the directory. * For split files, this will be the number of split parts, as multiple files will be saved. * For binary-split files, this will be 1, as the parts will be spliced into a single file. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L269-L271
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ModelDownloader.download
public async download({ signal }: { signal?: AbortSignal } = {}) { if (signal?.aborted) throw signal.reason; const onAbort = () => { signal?.removeEventListener("abort", onAbort); this.cancel(); }; if (signal != null) ...
/** * @returns The path to the entrypoint file that should be used to load the model */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L288-L323
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
CombinedModelDownloader._onDownloadProgress
private _onDownloadProgress() { this._onProgress?.({ totalSize: this.totalSize, downloadedSize: this.downloadedSize }); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L343-L348
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ModelDownloader.resolveTryHeaders
private async resolveTryHeaders() { if (this._tokens == null) return; pushAll(this._tryHeaders, await resolveModelFileAccessTokensTryHeaders(this._modelUrl, this._tokens, this._headers)); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L351-L356
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ModelDownloader._init
public async _init() { await this.resolveTryHeaders(); const binarySplitPartUrls = resolveBinarySplitGgufPartUrls(this._modelUrl); await fs.ensureDir(this._dirPath); if (binarySplitPartUrls instanceof Array) { this._downloader = await downloadFile({ partURLs:...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L359-L439
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
ModelDownloader._create
public static async _create(options: ModelDownloaderOptions) { const { modelUri, modelUrl, dirPath = cliModelsDirectory, fileName, _showUriResolvingProgress = false } = options as ModelDownloaderOptions & { modelUri?: string, modelUrl?: string }; const...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L442-L502
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
CombinedModelDownloader.constructor
private constructor(downloaders: ModelDownloader[], options?: CombinedModelDownloaderOptions) { const { showCliProgress = false, onProgress, parallelDownloads = 4 } = options ?? {}; this._downloaders = Object.freeze(downloaders); this._showCliProgress...
/** * When combining `ModelDownloader` instances, the following options on each individual `ModelDownloader` are ignored: * - `showCliProgress` * - `onProgress` * - `parallelDownloads` * * To set any of those options for the combined downloader, you have to pass them to the combined downlo...
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L537-L550
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
CombinedModelDownloader.download
public async download({ signal }: { signal?: AbortSignal } = {}) { if (signal?.aborted) throw signal.reason; const onAbort = () => { signal?.removeEventListener("abort", onAbort); this.cancel(); }; if (signal != null) ...
/** * @returns The paths to the entrypoint files that should be used to load the models */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L569-L604
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
CombinedModelDownloader.entrypointFilenames
public get entrypointFilenames() { return this._downloaders.map((downloader) => downloader.entrypointFilename); }
/** * The filename of the entrypoint files that should be used to load the models. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L613-L615
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
CombinedModelDownloader.entrypointFilePaths
public get entrypointFilePaths() { return this._downloaders.map((downloader) => downloader.entrypointFilePath); }
/** * The full paths to the entrypoint files that should be used to load the models. */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L620-L622
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
CombinedModelDownloader.totalFiles
public get totalFiles() { return this._downloaders .map((downloader) => downloader.totalFiles) .reduce((acc, totalFiles) => acc + totalFiles, 0); }
/** * The accumulation of `totalFiles` of all the model downloaders */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L627-L631
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
CombinedModelDownloader._init
public async _init() { this._downloader = await downloadSequence( { cliProgress: this._showCliProgress, cliStyle: isCI ? "ci" : "fancy", parallelDownloads: this._parallelDownloads }, ...this._downloaders.flatMap((downloader) => ...
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L654-L663
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
CombinedModelDownloader._create
public static _create(downloaders: ModelDownloader[], options?: CombinedModelDownloaderOptions) { return new CombinedModelDownloader(downloaders, options); }
/** @internal */
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/src/utils/createModelDownloader.ts#L666-L668
63a106627e1a8664ac335526c987522c94e87ce2
node-llama-cpp
github_2023
withcatai
typescript
onScroll
function onScroll() { isScrollAnchoredRef.current = isScrolledToTheBottom(); }
// anchor scroll to bottom
https://github.com/withcatai/node-llama-cpp/blob/63a106627e1a8664ac335526c987522c94e87ce2/templates/electron-typescript-react/src/App/App.tsx#L32-L34
63a106627e1a8664ac335526c987522c94e87ce2
relivator-nextjs-template
github_2023
blefnk
typescript
useCallbackRef
function useCallbackRef<T extends (...args: never[]) => unknown>( callback: T | undefined, ): T { const callbackRef = React.useRef(callback); React.useEffect(() => { callbackRef.current = callback; }); // https://github.com/facebook/react/issues/19240 return React.useMemo( () => ((...args) => call...
/** * @see https://github.com/radix-ui/primitives/blob/main/packages/react/use-callback-ref/src/useCallbackRef.tsx */
https://github.com/blefnk/relivator-nextjs-template/blob/ed5484c46e0cf41888c6798fe337f5953fc629f5/src/hooks/use-callback-ref.ts#L11-L25
ed5484c46e0cf41888c6798fe337f5953fc629f5
relivator-nextjs-template
github_2023
blefnk
typescript
handleSeedingError
async function handleSeedingError(error: unknown, taskName: string) { consola.error(`❌ Failed to ${taskName}:`, error); const confirmSkip = await consola.prompt( `Failed to ${taskName}. Do you want to skip and continue?`, { type: "confirm" }, ); if (!confirmSkip) { throw error; } }
// Utility function to handle errors with user prompt
https://github.com/blefnk/relivator-nextjs-template/blob/ed5484c46e0cf41888c6798fe337f5953fc629f5/src/server/actions/seed.ts#L20-L29
ed5484c46e0cf41888c6798fe337f5953fc629f5
nolyfill
github_2023
SukkaW
typescript
promisify
function promisify(orig: Function): Function { if (typeof orig !== 'function') { const error = new TypeError('The "original" argument must be of type function') as NodeJS.ErrnoException; error.code = 'ERR_INVALID_ARG_TYPE'; error.toString = function value() { return `${this.name}[${this.code}]: ${th...
// eslint-disable-next-line @typescript-eslint/ban-types -- overload signature
https://github.com/SukkaW/nolyfill/blob/23f983b13a36558c2f895e5e4f970d219a3790a6/packages/data/es-shim-like/src/util.promisify.ts#L53-L124
23f983b13a36558c2f895e5e4f970d219a3790a6
nolyfill
github_2023
SukkaW
typescript
isGeneratorFunction
function isGeneratorFunction(fn: unknown): fn is Function { if (typeof fn !== 'function') return false; if (isFnRegex.test(Function.prototype.toString.call(fn))) return true; return Object.getPrototypeOf(fn) === GeneratorFunction; }
// eslint-disable-next-line @typescript-eslint/ban-types -- any function
https://github.com/SukkaW/nolyfill/blob/23f983b13a36558c2f895e5e4f970d219a3790a6/packages/data/single-file/src/is-generator-function.ts#L5-L9
23f983b13a36558c2f895e5e4f970d219a3790a6
nolyfill
github_2023
SukkaW
typescript
specifierIncluded
function specifierIncluded(current: string, specifier: string) { const nodeParts = current.split('.'); const parts = specifier.split(' '); const op = parts.length > 1 ? parts[0] : '='; const versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); for (let i = 0; i < 3; ++i) { const cur = Numb...
/** is-core-module version range parser */
https://github.com/SukkaW/nolyfill/blob/23f983b13a36558c2f895e5e4f970d219a3790a6/packages/manual/is-core-module/rollup.config.ts#L72-L93
23f983b13a36558c2f895e5e4f970d219a3790a6
measure
github_2023
measure-sh
typescript
updateChildrenVisibility
function updateChildrenVisibility( parentId: string, parentVisibility: SpanVisibility ) { const children = childrenMap.get(parentId) || [] const newVisibility = parentVisibility === SpanVisibility.Expanded ? SpanVisibility.Expanded : SpanVisibility.Hidden f...
// Helper function to recursively update visibility of children
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/components/trace_viz.tsx#L174-L191
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
storeSession
const storeSession = (session: MSRSession) => { if (!globalThis.localStorage) { throw new Error("localStorage is not available"); } localStorage.setItem(sessionKey, JSON.stringify(session)); }
/** * Stores a session to local storage * * @param session measure session object */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L38-L44
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
loadSession
const loadSession = (key: string): MSRSession | undefined => { if (!globalThis.localStorage) { throw new Error("localStorage is not available") } const value = localStorage.getItem(key); if (!value) { return } return JSON.parse(value); }
/** * Load measure session from storage * * @param key storage item key * @returns MSRSession | undefined */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L52-L63
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
base64UrlDecode
const base64UrlDecode = (input: string) => { let base64 = input .replace(/-/g, '+') .replace(/_/g, '/'); switch (base64.length % 4) { case 2: base64 += '=='; break; case 4: base64 += '='; break; } return atob(base64); }
/** * Decode a URL safe base64 string. * * See: https://en.wikipedia.org/wiki/Base64#URL_applications */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L70-L85
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
decodeOAuthState
const decodeOAuthState = (input: string): OAuthState => { return JSON.parse(base64UrlDecode(input)); }
/** * Decode encoded OAuth value * * @param input encoded oauth state string * @returns OAuthState */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L93-L95
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
storeSessionFromURL
const storeSessionFromURL = (currURL: string) => { const url = new URL(currURL); let hash = url.hash; if (!hash.includes("access_token") && !hash.includes("refresh_token")) { return } hash = hash.substring(1); const params = new URLSearchParams(hash); const access_token = params.get('access_token')...
/** * Probe, extract and store session info from a URL. * * @param currURL URL to extract session from */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L102-L131
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
base64UrlEncode
const base64UrlEncode = (input: string) => { let base64 = btoa(input); return base64 .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, ''); }
/** * Encode a string into URL safe base64. * * See: https://en.wikipedia.org/wiki/Base64#URL_applications */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L138-L144
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
getRandomValues
const getRandomValues = (len: number) => { const arr = crypto.getRandomValues(new Uint8Array(len)); return Array.from(arr, byte => byte.toString(16).padStart(2, '0')).join(''); }
/** * Generate a random string of len bytes. * * @param len size of bytes to generate * @returns string */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L152-L155
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
validateJWT
const validateJWT = (token: string) => { const { header, payload } = decodeJWT(token); const now = Math.round(Date.now() / 1000); return header.alg === 'HS256' && header.typ === 'JWT' && now <= payload.exp; }
/** * Validate JWT header and expiration * * @param token JWT string * @returns bool */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L177-L181
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
needsRefresh
const needsRefresh = (token: string) => { const { payload: { exp } } = decodeJWT(token); const now = Math.round(Date.now() / 1000); return exp < now + 5 * 60; }
/** * Checks if a token should be refreshed * if token is going to expire within 5 mins. * * @param token JWT token string * @returns bool */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L190-L194
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
clearSession
const clearSession = () => { if (!globalThis.localStorage) { return } localStorage.removeItem(sessionKey); }
/** * Remove session from browser * storage. * * @returns void */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L237-L243
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
refreshSession
const refreshSession = async (): Promise<MSRSession> => { const session = loadSession(sessionKey); if (!session) { throw new Error("couldn't retrive session"); } const res = await fetch(`${apiOrigin}/auth/refresh`, { method: 'POST', headers: { 'Authorization': `Bearer ${session.refresh_token}...
/** * Refresh active session. * * @returns Promise */
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L270-L290
9023d315a6945964c2dd340086087a30614059f5
measure
github_2023
measure-sh
typescript
getEndpoint
const getEndpoint = (resource: string | Request | URL) => { let urlString: string; if (resource instanceof Request) { urlString = resource.url; } else if (resource instanceof URL) { urlString = resource.toString(); } else { urlString = resource; } try { const url = new ...
// Extract base endpoint from a URL, stripping query parameters
https://github.com/measure-sh/measure/blob/9023d315a6945964c2dd340086087a30614059f5/frontend/dashboard/app/utils/auth/auth.ts#L334-L353
9023d315a6945964c2dd340086087a30614059f5
devdb-vscode
github_2023
damms005
typescript
DevDbViewProvider.openTableAtCurrentCursor
public openTableAtCurrentCursor() { if (!isTablesLoaded()) { return showEmptyTablesNotification() } const word = getWordUnderCursor() if (!word) return; let tableName = Case.snake(word); if (!tableExists(tableName)) { tableName = plural(tableName); if (!tableExists(tableName)) { return vsco...
/** * Gets the word at the current cursor location and opens the table in the DevDb view */
https://github.com/damms005/devdb-vscode/blob/8efde0f9fc7b5c9932326da68db16936f442c328/src/devdb-view-provider.ts#L81-L100
8efde0f9fc7b5c9932326da68db16936f442c328
devdb-vscode
github_2023
damms005
typescript
findObjectStart
function findObjectStart(text: string, position: number): number { let depth = 0; let index = position; while (index >= 0) { const char = text[index]; if (char === '}') depth++; if (char === '{') { depth--; if (depth < 0) return index; } index--; } return -1; }
/** * Find the start of the JSON object containing the given position */
https://github.com/damms005/devdb-vscode/blob/8efde0f9fc7b5c9932326da68db16936f442c328/src/services/config-error-service.ts#L67-L82
8efde0f9fc7b5c9932326da68db16936f442c328
devdb-vscode
github_2023
damms005
typescript
findObjectEnd
function findObjectEnd(text: string, position: number): number { let depth = 0; let index = position; while (index < text.length) { const char = text[index]; if (char === '{') depth++; if (char === '}') { depth--; if (depth < 0) return index; } index++; } return -1; }
/** * Find the end of the JSON object containing the given position */
https://github.com/damms005/devdb-vscode/blob/8efde0f9fc7b5c9932326da68db16936f442c328/src/services/config-error-service.ts#L87-L102
8efde0f9fc7b5c9932326da68db16936f442c328
devdb-vscode
github_2023
damms005
typescript
matchesConfig
function matchesConfig(objText: string, config: ConfigType): boolean { try { const obj = JSON.parse(objText); switch (config.type) { case 'sqlite': return obj.path === (config as SqliteConfig).path; case 'mysql': case 'mariadb': return obj.name === (config as MysqlConfig).name && obj.databa...
/** * Check if a JSON object string matches the given config based on unique identifiers */
https://github.com/damms005/devdb-vscode/blob/8efde0f9fc7b5c9932326da68db16936f442c328/src/services/config-error-service.ts#L107-L134
8efde0f9fc7b5c9932326da68db16936f442c328
devdb-vscode
github_2023
damms005
typescript
getAvailableProviders
async function getAvailableProviders() { log('Starting to get available providers...'); const availableProviders = await Promise.all(providers.map(async (provider) => { log(`Checking provider: ${provider.name}`); if (provider.boot) await provider.boot() try { const canBeUsed = await provider.canBeUsedInCur...
/** * Returns a list of all providers that can be used in the current workspace. */
https://github.com/damms005/devdb-vscode/blob/8efde0f9fc7b5c9932326da68db16936f442c328/src/services/messenger.ts#L68-L100
8efde0f9fc7b5c9932326da68db16936f442c328
devdb-vscode
github_2023
damms005
typescript
hasValidSyntax
function hasValidSyntax(node: Node): boolean { if (!node.kind) { return false; } // Recursively check children if ('children' in node && Array.isArray(node.children)) { return node.children.every(hasValidSyntax); } if ('body' in node && Array.isArray(node.body)) { return node.body.every(hasValidSy...
// Check for complete syntax
https://github.com/damms005/devdb-vscode/blob/8efde0f9fc7b5c9932326da68db16936f442c328/src/services/codelens/laravel/query-explain-checker-service.ts#L126-L140
8efde0f9fc7b5c9932326da68db16936f442c328
devdb-vscode
github_2023
damms005
typescript
getSuccessfulConnectionOrPort
async function getSuccessfulConnectionOrPort(dialect: Dialect, host: string, username: string, password: string, database: string): Promise<Sequelize | number | undefined> { if (await hasLaravelSailDockerComposeFile()) { const dockerPort = await getPortFromDockerCompose(dialect) if (dockerPort) { const connec...
/** * A user ran into a bug whereby Sails was configured i.e. FORWARD_DB_PORT was defined. * At same time, DB_PORT was defined. However, latter was actually used in project and * former was just an obsolete config dangling around. This broke DevDb because we were * connecting with Sails config first if found, then ...
https://github.com/damms005/devdb-vscode/blob/8efde0f9fc7b5c9932326da68db16936f442c328/src/services/laravel/env-file-parser.ts#L79-L94
8efde0f9fc7b5c9932326da68db16936f442c328