repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
moonlight | github_2023 | moonlight-mod | typescript | getConfig | function getConfig(ext: string) {
const val = config.extensions[ext];
if (val == null || typeof val === "boolean") return undefined;
return val.config;
} | // Duplicated in node-preload... oops | https://github.com/moonlight-mod/moonlight/blob/12cd3c869f2a9478b65033033d64bd82790396fd/packages/injector/src/index.ts#L244-L248 | 12cd3c869f2a9478b65033033d64bd82790396fd |
evmgateway | github_2023 | ensdomains | typescript | ArbProofService.getProofs | async getProofs(
block: ArbProvableBlock,
address: AddressLike,
slots: bigint[]
): Promise<string> {
const proof = await this.helper.getProofs(block.number, address, slots);
return AbiCoder.defaultAbiCoder().encode(
[
'tuple(bytes32 version, bytes32 sendRoot, uint64 nodeIndex,bytes rlpEncodedBlock)',
'tuple(bytes stateTrieWitness, bytes[] storageProofs)',
],
[
{
version:
'0x0000000000000000000000000000000000000000000000000000000000000000',
sendRoot: block.sendRoot,
nodeIndex: block.nodeIndex,
rlpEncodedBlock: block.rlpEncodedBlock
},
convertIntoMerkleTrieProof(proof)
]
);
} | /**
* @dev Fetches a set of proofs for the requested state slots.
* @param block A `ProvableBlock` returned by `getProvableBlock`.
* @param address The address of the contract to fetch data from.
* @param slots An array of slots to fetch data for.
* @returns A proof of the given slots, encoded in a manner that this service's
* corresponding decoding library will understand.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/arb-gateway/src/ArbProofService.ts#L56-L79 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | ArbProofService.getProvableBlock | public async getProvableBlock(): Promise<ArbProvableBlock> {
//Retrieve the latest pending node that has been committed to the rollup.
const nodeIndex = await this.rollup.latestNodeCreated()
const [l2blockRaw, sendRoot] = await this.getL2BlockForNode(nodeIndex)
const blockarray = [
l2blockRaw.parentHash,
l2blockRaw.sha3Uncles,
l2blockRaw.miner,
l2blockRaw.stateRoot,
l2blockRaw.transactionsRoot,
l2blockRaw.receiptsRoot,
l2blockRaw.logsBloom,
toBeHex(l2blockRaw.difficulty),
toBeHex(l2blockRaw.number),
toBeHex(l2blockRaw.gasLimit),
toBeHex(l2blockRaw.gasUsed),
toBeHex(l2blockRaw.timestamp),
l2blockRaw.extraData,
l2blockRaw.mixHash,
l2blockRaw.nonce,
toBeHex(l2blockRaw.baseFeePerGas)
]
//Rlp encode the block to pass it as an argument
const rlpEncodedBlock = ethers.encodeRlp(blockarray)
return {
rlpEncodedBlock,
sendRoot,
nodeIndex: nodeIndex,
number: toNumber(l2blockRaw.number)
}
} | /**
* Retrieves information about the latest provable block in the Arbitrum Rollup.
*
* @returns { Promise<ArbProvableBlock> } A promise that resolves to an object containing information about the provable block.
* @throws Throws an error if any of the underlying operations fail.
*
* @typedef { Object } ArbProvableBlock
* @property { string } rlpEncodedBlock - The RLP - encoded block information.
* @property { string } sendRoot - The send root of the provable block.
* @property { string } blockHash - The hash of the provable block.
* @property { number } nodeIndex - The index of the node corresponding to the provable block.
* @property { number } number - The block number of the provable block.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/arb-gateway/src/ArbProofService.ts#L93-L126 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | ArbProofService.getL2BlockForNode | private async getL2BlockForNode(nodeIndex: bigint): Promise<[Record<string, string>, string]> {
//We first check if we have the block cached
const cachedBlock = await this.cache.getBlock(nodeIndex)
if (cachedBlock) {
return [cachedBlock.block, cachedBlock.sendRoot]
}
//We fetch the node created event for the node index we just retrieved.
const nodeEventFilter = await this.rollup.filters.NodeCreated(nodeIndex);
const nodeEvents = await this.rollup.queryFilter(nodeEventFilter);
const assertion = (nodeEvents[0] as EventLog).args!.assertion
//Instead of using the AssertionHelper contract we can extract sendRoot from the assertion. Avoiding the deployment of the AssertionHelper contract and an additional RPC call.
const [blockHash, sendRoot] = assertion[1][0][0]
//The L1 rollup only provides us with the block hash. In order to ensure that the stateRoot we're using for the proof is indeed part of the block, we need to fetch the block. And provide it to the proof.
const l2blockRaw = await this.l2Provider.send('eth_getBlockByHash', [
blockHash,
false
]);
//Cache the block for future use
await this.cache.setBlock(nodeIndex, l2blockRaw, sendRoot)
return [l2blockRaw, sendRoot]
} | /**
* Fetches the corrospending L2 block for a given node index and returns it along with the send root.
* @param {bigint} nodeIndex - The index of the node for which to fetch the block.
* @returns {Promise<[Record<string, string>, string]>} A promise that resolves to a tuple containing the fetched block and the send root.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/arb-gateway/src/ArbProofService.ts#L132-L158 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | followSolidityMapping | function followSolidityMapping(slot: bigint, key: string) {
return BigInt(solidityPackedKeccak256(['bytes', 'uint256'], [key, slot]));
} | // traverse mapping at slot using key solidity-style | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/evm-gateway/src/EVMGateway.ts#L55-L57 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | uint256FromBytes | function uint256FromBytes(hex: string): bigint {
return hex === '0x' ? 0n : BigInt(hex.slice(0, 66));
} | // see: EVMProofHelper.uint256FromBytes() | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/evm-gateway/src/EVMGateway.ts#L60-L62 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | EVMGateway.createProofs | async createProofs(
address: string,
commands: string[],
constants: string[]
): Promise<string> {
const block = await this.proofService.getProvableBlock();
const requests: Promise<StorageElement>[] = [];
// For each request, spawn a promise to compute the set of slots required
for (let i = 0; i < commands.length; i++) {
requests.push(
this.getValueFromPath(
block,
address,
commands[i],
constants,
requests.slice()
)
);
}
// Resolve all the outstanding requests
const results = await Promise.all(requests);
const slots = Array.prototype.concat(
...results.map((result) => result.slots)
);
return this.proofService.getProofs(block, address, slots);
} | /**
*
* @param address The address to fetch storage slot proofs for
* @param paths Each element of this array specifies a Solidity-style path derivation for a storage slot ID.
* See README.md for details of the encoding.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/evm-gateway/src/EVMGateway.ts#L134-L159 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | EVMProofHelper.getStorageAt | getStorageAt(
blockNo: number,
address: AddressLike,
slot: bigint
): Promise<string> {
return this.provider.getStorage(address, slot, blockNo);
} | /**
* @dev Returns the value of a contract state slot at the specified block
* @param block A `ProvableBlock` returned by `getProvableBlock`.
* @param address The address of the contract to fetch data from.
* @param slot The slot to fetch.
* @returns The value in `slot` of `address` at block `block`
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/evm-gateway/src/EVMProofHelper.ts#L44-L50 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | EVMProofHelper.getProofs | async getProofs(
blockNo: number,
address: AddressLike,
slots: bigint[]
): Promise<StateProof> {
const args = [
address,
slots.map((slot) => toBeHex(slot, 32)),
'0x' + blockNo.toString(16),
];
const proofs: EthGetProofResponse = await this.provider.send(
'eth_getProof',
args
);
return {
stateTrieWitness: proofs.accountProof,
storageProofs: proofs.storageProof.map((proof) => proof.proof),
stateRoot: proofs.storageHash,
};
} | /**
* @dev Fetches a set of proofs for the requested state slots.
* @param block A `ProvableBlock` returned by `getProvableBlock`.
* @param address The address of the contract to fetch data from.
* @param slots An array of slots to fetch data for.
* @returns A proof of the given slots, encoded in a manner that this service's
* corresponding decoding library will understand.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/evm-gateway/src/EVMProofHelper.ts#L60-L79 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | L1ProofService.getProvableBlock | async getProvableBlock(): Promise<number> {
const block = await this.provider.getBlock('latest');
if (!block) throw new Error('No block found');
return block.number - 1;
} | /**
* @dev Returns an object representing a block whose state can be proven on L1.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/l1-gateway/src/L1ProofService.ts#L37-L41 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | L1ProofService.getStorageAt | getStorageAt(
block: L1ProvableBlock,
address: AddressLike,
slot: bigint
): Promise<string> {
return this.helper.getStorageAt(block, address, slot);
} | /**
* @dev Returns the value of a contract state slot at the specified block
* @param block A `ProvableBlock` returned by `getProvableBlock`.
* @param address The address of the contract to fetch data from.
* @param slot The slot to fetch.
* @returns The value in `slot` of `address` at block `block`
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/l1-gateway/src/L1ProofService.ts#L50-L56 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | L1ProofService.getProofs | async getProofs(
blockNo: L1ProvableBlock,
address: AddressLike,
slots: bigint[]
): Promise<string> {
const proof = await this.helper.getProofs(blockNo, address, slots);
const rpcBlock: JsonRpcBlock = await this.provider.send(
'eth_getBlockByNumber',
['0x' + blockNo.toString(16), false]
);
const block = Block.fromRPC(rpcBlock);
const blockHeader = encodeRlp(block.header.raw());
return AbiCoder.defaultAbiCoder().encode(
[
'tuple(uint256 blockNo, bytes blockHeader)',
'tuple(bytes stateTrieWitness, bytes[] storageProofs)',
],
[{ blockNo, blockHeader }, convertIntoMerkleTrieProof(proof)]
);
} | /**
* @dev Fetches a set of proofs for the requested state slots.
* @param block A `ProvableBlock` returned by `getProvableBlock`.
* @param address The address of the contract to fetch data from.
* @param slots An array of slots to fetch data for.
* @returns A proof of the given slots, encoded in a manner that this service's
* corresponding decoding library will understand.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/l1-gateway/src/L1ProofService.ts#L66-L85 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | OPProofService.getProvableBlock | async getProvableBlock(): Promise<OPProvableBlock> {
/**
* Get the latest output from the L2Oracle. We're building the proof with this batch
* We go a few batches backwards to avoid errors like delays between nodes
*
*/
const l2OutputIndex =
Number(await this.l2OutputOracle.latestOutputIndex()) - this.delay;
/**
* struct OutputProposal {
* bytes32 outputRoot;
* uint128 timestamp;
* uint128 l2BlockNumber;
* }
*/
const outputProposal = await this.l2OutputOracle.getL2Output(l2OutputIndex);
return {
number: outputProposal.l2BlockNumber,
l2OutputIndex: l2OutputIndex,
};
} | /**
* @dev Returns an object representing a block whose state can be proven on L1.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/op-gateway/src/OPProofService.ts#L52-L74 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | OPProofService.getStorageAt | getStorageAt(
block: OPProvableBlock,
address: AddressLike,
slot: bigint
): Promise<string> {
return this.helper.getStorageAt(block.number, address, slot);
} | /**
* @dev Returns the value of a contract state slot at the specified block
* @param block A `ProvableBlock` returned by `getProvableBlock`.
* @param address The address of the contract to fetch data from.
* @param slot The slot to fetch.
* @returns The value in `slot` of `address` at block `block`
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/op-gateway/src/OPProofService.ts#L83-L89 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | OPProofService.getProofs | async getProofs(
block: OPProvableBlock,
address: AddressLike,
slots: bigint[]
): Promise<string> {
const proof = await this.helper.getProofs(block.number, address, slots);
const rpcBlock: JsonRpcBlock = await this.l2Provider.send(
'eth_getBlockByNumber',
['0x' + block.number.toString(16), false]
);
const messagePasserStorageRoot = await this.getMessagePasserStorageRoot(
block.number
);
return AbiCoder.defaultAbiCoder().encode(
[
'tuple(uint256 l2OutputIndex, tuple(bytes32 version, bytes32 stateRoot, bytes32 messagePasserStorageRoot, bytes32 latestBlockhash) outputRootProof)',
'tuple(bytes stateTrieWitness, bytes[] storageProofs)',
],
[
{
blockNo: block.number,
l2OutputIndex: block.l2OutputIndex,
outputRootProof: {
version:
'0x0000000000000000000000000000000000000000000000000000000000000000',
stateRoot: rpcBlock.stateRoot,
messagePasserStorageRoot,
latestBlockhash: rpcBlock.hash,
},
},
convertIntoMerkleTrieProof(proof),
]
);
} | /**
* @dev Fetches a set of proofs for the requested state slots.
* @param block A `ProvableBlock` returned by `getProvableBlock`.
* @param address The address of the contract to fetch data from.
* @param slots An array of slots to fetch data for.
* @returns A proof of the given slots, encoded in a manner that this service's
* corresponding decoding library will understand.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/op-gateway/src/OPProofService.ts#L99-L133 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | ScrollProofService.getProofs | async getProofs(
block: ScrollProvableBlock,
address: AddressLike,
slots: bigint[]
): Promise<string> {
const { batch_index: batchIndex } = await (
await fetch(`${this.searchUrl}?keyword=${Number(block.number)}`)
).json();
const proof = await this.helper.getProofs(Number(block.number), address, slots);
const compressedProofs: string[] = [];
const accountProof: string = proof.stateTrieWitness;
for (let index = 0; index < proof.storageProofs.length; index++) {
const storageProof: string = proof.storageProofs[index];
compressedProofs[index] = concat([
`0x${accountProof.length.toString(16).padStart(2, "0")}`,
...accountProof,
`0x${storageProof.length.toString(16).padStart(2, "0")}`,
...storageProof,
]);
}
return AbiCoder.defaultAbiCoder().encode(
[
'tuple(uint256 batchIndex)',
'tuple(bytes[] storageProofs)',
],
[
{
batchIndex
},
{
storageProofs:compressedProofs
},
]
);
} | /**
* @dev Fetches a set of proofs for the requested state slots.
* @param block A `ProvableBlock` returned by `getProvableBlock`.
* @param address The address of the contract to fetch data from.
* @param slots An array of slots to fetch data for.
* @returns A proof of the given slots, encoded in a manner that this service's
* corresponding decoding library will understand.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/scroll-gateway/src/ScrollProofService.ts#L41-L75 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
evmgateway | github_2023 | ensdomains | typescript | ScrollProofService.getProvableBlock | public async getProvableBlock(): Promise<ScrollProvableBlock> {
const block = await this.l2Provider.send("eth_getBlockByNumber", ["finalized", false]);
if (!block) throw new Error('No block found');
return {
number: block.number
};
} | /**
* @dev Returns an object representing a block whose state can be proven on L1.
*/ | https://github.com/ensdomains/evmgateway/blob/5956d8c4be19230cbffa120f3023f338084b24a9/scroll-gateway/src/ScrollProofService.ts#L79-L85 | 5956d8c4be19230cbffa120f3023f338084b24a9 |
jsfe | github_2023 | json-schema-form-element | typescript | Jsf._handleKeydown | protected _handleKeydown(event: KeyboardEvent) {
console.log('cccccccccccccc');
const hasModifier =
event.metaKey || event.ctrlKey || event.shiftKey || event.altKey;
if (event.key === 'Enter' && !hasModifier) {
setTimeout(() => {
if (!event.defaultPrevented && !event.isComposing) {
console.log({ event });
const form = this.#formRef.value!;
// const valid = form.reportValidity();
let valid = true;
let firstInvalid: HTMLInputElement | undefined;
if (!form.noValidate) {
const elements = form.querySelectorAll<HTMLInputElement>('*');
// eslint-disable-next-line no-restricted-syntax
for (const element of elements) {
if (typeof element.reportValidity === 'function') {
if (!element.reportValidity()) {
valid = false;
if (!firstInvalid) firstInvalid = element;
}
}
}
if (firstInvalid) firstInvalid?.reportValidity();
}
this.submitCallback(this.data, valid);
}
});
}
} | /* When user hit "Enter" while in some adequate inputs */ | https://github.com/json-schema-form-element/jsfe/blob/1e082e4aa5d67617fd9a982d44ca031560404e16/packages/form/src/json-schema-form.ts#L354-L387 | 1e082e4aa5d67617fd9a982d44ca031560404e16 |
jsfe | github_2023 | json-schema-form-element | typescript | valueChangedCallback | const valueChangedCallback = (newValue?: unknown) => {
let finalValue = newValue;
if (finalValue === '') {
finalValue = undefined;
}
if (
schema?.type?.includes('null') &&
(typeof newValue === 'undefined' || newValue === '')
) {
finalValue = null;
}
handleChange(path, finalValue, schemaPath);
}; | // ---------------- | https://github.com/json-schema-form-element/jsfe/blob/1e082e4aa5d67617fd9a982d44ca031560404e16/packages/form/src/triage/primitive.ts#L68-L80 | 1e082e4aa5d67617fd9a982d44ca031560404e16 |
eslint-plugin-antfu | github_2023 | antfu | typescript | RuleCreator | function RuleCreator(urlCreator: (name: string) => string) {
// This function will get much easier to call when this is merged https://github.com/Microsoft/TypeScript/pull/26349
// TODO - when the above PR lands; add type checking for the context.report `data` property
return function createNamedRule<
TOptions extends readonly unknown[],
TMessageIds extends string,
>({
name,
meta,
...rule
}: Readonly<RuleWithMetaAndName<TOptions, TMessageIds>>): RuleModule<TOptions> {
return createRule<TOptions, TMessageIds>({
meta: {
...meta,
docs: {
...meta.docs,
url: urlCreator(name),
},
},
...rule,
})
}
} | /**
* Creates reusable function to create rules with default options and docs URLs.
*
* @param urlCreator Creates a documentation URL for a given rule name.
* @returns Function to create a rule with the docs URL format.
*/ | https://github.com/antfu/eslint-plugin-antfu/blob/b439efd572c5dbdba4e0f495a961262c2d0dd35e/src/utils.ts#L30-L52 | b439efd572c5dbdba4e0f495a961262c2d0dd35e |
eslint-plugin-antfu | github_2023 | antfu | typescript | createRule | function createRule<
TOptions extends readonly unknown[],
TMessageIds extends string,
>({
create,
defaultOptions,
meta,
}: Readonly<RuleWithMeta<TOptions, TMessageIds>>): RuleModule<TOptions> {
return {
create: ((
context: Readonly<RuleContext<TMessageIds, TOptions>>,
): RuleListener => {
const optionsWithDefault = context.options.map((options, index) => {
return {
...defaultOptions[index] || {},
...options || {},
}
}) as unknown as TOptions
return create(context, optionsWithDefault)
}) as any,
defaultOptions,
meta: meta as any,
}
} | /**
* Creates a well-typed TSESLint custom ESLint rule without a docs URL.
*
* @returns Well-typed TSESLint custom ESLint rule.
* @remarks It is generally better to provide a docs URL function to RuleCreator.
*/ | https://github.com/antfu/eslint-plugin-antfu/blob/b439efd572c5dbdba4e0f495a961262c2d0dd35e/src/utils.ts#L60-L83 | b439efd572c5dbdba4e0f495a961262c2d0dd35e |
eslint-plugin-antfu | github_2023 | antfu | typescript | exportType | function exportType<A, B extends A>() {} | // eslint-disable-next-line unused-imports/no-unused-vars, ts/explicit-function-return-type | https://github.com/antfu/eslint-plugin-antfu/blob/b439efd572c5dbdba4e0f495a961262c2d0dd35e/src/rules/consistent-list-newline.ts#L329-L329 | b439efd572c5dbdba4e0f495a961262c2d0dd35e |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.constructor | constructor(folderPath = '.codepilot') {
this._folderPath = folderPath;
} | /**
* Creates a new 'CodeIndex' instance.
* @param folderPath Optional. The path to the folder containing the index. Defaults to '.codepilot'.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L90-L92 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.config | public get config(): CodeIndexConfig | undefined {
return this._config;
} | /**
* Gets the current code index configuration.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L97-L99 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.folderPath | public get folderPath(): string {
return this._folderPath;
} | /**
* Gets the path to the folder containing the index.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L104-L106 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.keys | public get keys(): OpenAIKeys | undefined {
return this._keys;
} | /**
* Gets the current OpenAI keys.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L111-L113 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.add | public async add(config: Partial<CodeIndexConfig>): Promise<void> {
if (!await this.isCreated()) {
throw new Error('Index has not been created yet. Please run `codepilot create` first.');
}
// Ensure config loaded
const configPath = path.join(this.folderPath, 'config.json');
if (!this._config) {
this._config = JSON.parse(await fs.readFile(configPath, 'utf-8'));
}
// Clone config
const newConfig = Object.assign({}, this._config);
// Add sources
if (Array.isArray(config.sources)) {
config.sources.forEach(source => {
if (!newConfig.sources.includes(source)) {
newConfig.sources.push(source);
}
});
}
// Add extensions
if (Array.isArray(config.extensions)) {
if (!newConfig.extensions) {
newConfig.extensions = [];
}
config.extensions.forEach(extension => {
if (!newConfig.extensions!.includes(extension)) {
newConfig.extensions!.push(extension);
}
});
}
// Write config
await fs.writeFile(configPath, JSON.stringify(newConfig));
this._config = newConfig;
} | /**
* Adds sources and extensions to the index.
* @param config The configuration containing the sources and extensions to add.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L121-L159 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.create | public async create(keys: OpenAIKeys, config: CodeIndexConfig): Promise<void> {
// Delete folder if it exists
if (await fs.stat(this.folderPath).then(() => true).catch(() => false)) {
await fs.rm(this.folderPath, { recursive: true });
}
// Create folder
await fs.mkdir(this.folderPath);
try {
// Create config file
await fs.writeFile(path.join(this.folderPath, 'config.json'), JSON.stringify(config));
// Create keys file
await fs.writeFile(path.join(this.folderPath, 'vectra.keys'), JSON.stringify(keys));
// Create .gitignore file
await fs.writeFile(path.join(this.folderPath, '.gitignore'), 'vectra.keys');
this._config = config;
this._keys = keys;
// Create index
const index = await this.load();
await index.createIndex();
} catch(err: unknown) {
this._config = undefined;
this._keys = undefined;
await fs.rm(this.folderPath, { recursive: true });
throw new Error(`Error creating index: ${(err as any).toString()}`);
}
} | /**
* Creates a new code index.
* @param keys OpenAI keys to use.
* @param config Source code index configuration.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L168-L198 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.delete | public async delete(): Promise<void> {
await fs.rm(this.folderPath, { recursive: true });
this._config = undefined;
this._keys = undefined;
this._index = undefined;
} | /**
* Deletes the current code index.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L205-L210 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.hasKeys | public async hasKeys(): Promise<boolean> {
return await fs.stat(path.join(this.folderPath, 'vectra.keys')).then(() => true).catch(() => false);
} | /**
* Returns whether a `vectra.keys` file exists for the index.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L217-L219 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.isCreated | public async isCreated(): Promise<boolean> {
return await fs.stat(this.folderPath).then(() => true).catch(() => false);
} | /**
* Returns true if the index has been created.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L224-L226 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.load | public async load(): Promise<LocalDocumentIndex> {
if (!this._config) {
const configPath = path.join(this.folderPath, 'config.json');
this._config = JSON.parse(await fs.readFile(configPath, 'utf-8'));
}
if (!this._keys) {
const keysPath = path.join(this.folderPath, 'vectra.keys');
this._keys = JSON.parse(await fs.readFile(keysPath, 'utf-8'));
}
if (!this._index) {
const folderPath = path.join(this.folderPath, 'index');
const embeddings = new OpenAIEmbeddings(Object.assign({ model: 'text-embedding-ada-002' }, this._keys));
this._index = new LocalDocumentIndex({
folderPath,
embeddings,
});
}
return this._index;
} | /**
* Loads the current code index.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L233-L254 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.query | public async query(query: string, options?: DocumentQueryOptions): Promise<LocalDocumentResult[]> {
if (!await this.isCreated()) {
throw new Error('Index has not been created yet. Please run `codepilot create` first.');
}
if (!await this.hasKeys()) {
throw new Error("A local vectra.keys file couldn't be found. Please run `codepilot set --key <your OpenAI key>`.");
}
// Query document index
const index = await this.load();
return await index.queryDocuments(query, options);
} | /**
* Queries the code index.
* @param query Text to query the index with.
* @param options Optional. Options to use when querying the index.
* @returns Found documents.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L264-L275 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.rebuild | public async rebuild(): Promise<void> {
if (!await this.isCreated()) {
throw new Error('Index has not been created yet. Please run `codepilot create` first.');
}
if (!await this.hasKeys()) {
throw new Error("A local vectra.keys file couldn't be found. Please run `codepilot set --key <your OpenAI key>`.");
}
// Create fresh index
const index = await this.load();
if (await index.isCatalogCreated()) {
await index.deleteIndex();
}
await index.createIndex();
// Index files
const fetcher = new FileFetcher();
for (const source of this._config!.sources) {
await fetcher.fetch(source, async (uri, text, docType) => {
// Ignore binary files
if (IGNORED_FILES.includes(path.extname(uri))) {
return true;
}
// Ignore any disallowed extensions
if (this._config!.extensions && docType && !this._config!.extensions!.includes(docType)) {
return true;
}
// Upsert document
console.log(Colorize.progress(`adding: ${uri}`));
await index.upsertDocument(uri, text, docType);
return true;
});
}
} | /**
* Rebuilds the code index.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L282-L317 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.remove | public async remove(config: Partial<CodeIndexConfig>): Promise<void> {
if (!await this.isCreated()) {
throw new Error('Index has not been created yet. Please run `codepilot create` first.');
}
// Ensure config loaded
const configPath = path.join(this.folderPath, 'config.json');
if (!this._config) {
this._config = JSON.parse(await fs.readFile(configPath, 'utf-8'));
}
// Clone config
const newConfig = Object.assign({}, this._config);
// Remove sources
if (Array.isArray(config.sources)) {
newConfig.sources = newConfig.sources.filter(source => !config.sources!.includes(source));
}
// Remove extensions
if (Array.isArray(config.extensions)) {
newConfig.extensions = newConfig.extensions?.filter(extension => !config.extensions!.includes(extension));
}
// Write config
await fs.writeFile(configPath, JSON.stringify(newConfig));
this._config = newConfig;
} | /**
* Removes sources and extensions from the index.
* @param config The configuration containing the sources and extensions to remove.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L325-L352 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.setKeys | public async setKeys(keys: OpenAIKeys): Promise<void> {
if (!await this.isCreated()) {
throw new Error('Index has not been created yet. Please run `codepilot create` first.');
}
// Overwrite keys file
await fs.writeFile(path.join(this.folderPath, 'vectra.keys'), JSON.stringify(keys));
this._keys = keys;
} | /**
* Updates the OpenAI keys for the index.
* @param keys Keys to use.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L360-L368 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.setConfig | public async setConfig(config: Partial<CodeIndexConfig>): Promise<void> {
if (!await this.isCreated()) {
throw new Error('Index has not been created yet. Please run `codepilot create` first.');
}
// Ensure config loaded
const configPath = path.join(this.folderPath, 'config.json');
if (!this._config) {
this._config = JSON.parse(await fs.readFile(configPath, 'utf-8'));
}
// Clone config
const newConfig = Object.assign({}, this._config);
// Apply changes
if (config.model !== undefined) {
newConfig.model = config.model;
}
if (config.max_input_tokens !== undefined) {
newConfig.max_input_tokens = config.max_input_tokens;
}
if (config.max_tokens !== undefined) {
newConfig.max_tokens = config.max_tokens;
}
if (config.temperature !== undefined) {
newConfig.temperature = config.temperature;
}
// Write config
await fs.writeFile(configPath, JSON.stringify(newConfig));
this._config = newConfig;
} | /**
* Updates the code index configuration.
* @param config Settings to update.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L374-L405 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | CodeIndex.upsertDocument | public async upsertDocument(path: string): Promise<void> {
if (!await this.isCreated()) {
throw new Error('Index has not been created yet. Please run `codepilot create` first.');
}
if (!await this.hasKeys()) {
throw new Error("A local vectra.keys file couldn't be found. Please run `codepilot set --key <your OpenAI key>`.");
}
// Ensure index is loaded
const index = await this.load();
// Fetch document
const fetcher = new FileFetcher();
await fetcher.fetch(path, async (uri, text, docType) => {
// Upsert document
await index.upsertDocument(uri, text, docType);
return true;
});
} | /**
* Adds a document to the index.
* @param path Path to the document to add.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/CodeIndex.ts#L413-L431 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Codepilot.constructor | public constructor(index: CodeIndex) {
this._index = index;
} | /**
* Creates a new `Codepilot` instance.
* @param index The code index to use.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/Codepilot.ts#L19-L21 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Codepilot.index | public get index(): CodeIndex {
return this._index;
} | /**
* Gets the code index.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/Codepilot.ts#L26-L28 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Codepilot.addFunction | public addFunction<TArgs = Record<string, any>>(schema: ChatCompletionFunction, fn: (args: TArgs) => Promise<any>): this {
this._functions.set(schema.name, { schema, fn });
return this;
} | /**
* Registers a new function to be used in the chat completion.
* @remarks
* This is used to add new capabilities to Codepilot's chat feature
* @param name The name of the function.
* @param schema The schema of the function.
* @param fn The function to be executed.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/Codepilot.ts#L38-L41 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Codepilot.chat | public async chat(): Promise<void> {
// Create a readline interface object with the standard input and output streams
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Create model and wave
const model = this.createModel();
const wave = new AlphaWave({
model,
prompt: new Prompt([
new SystemMessage([
`You are an expert software developer.`,
`You are chatting with another developer who is asking for help with the project they're working on.`,
].join('\n')),
new SourceCodeSection(this._index, 0.6),
new ConversationHistory('history', 0.4),
new UserMessage('{{$input}}', 500)
])
});
// Define main chat loop
const _that = this;
async function respond(botMessage: string) {
async function completePrompt(input: string) {
// Route users message to wave
const result = await wave.completePrompt<string>(input);
switch (result.status) {
case 'success':
const message = result.message as Message<string>;
if (message.function_call) {
// Call function and add result to history
const entry = _that._functions.get(message.function_call.name!)!;
if (entry) {
const args = message.function_call.arguments ? JSON.parse(message.function_call.arguments) : {};
const result = await entry.fn(args);
wave.addFunctionResultToHistory(message.function_call.name!, result);
// Call back in with the function result
await completePrompt('');
} else {
respond(Colorize.error(`Function '${message.function_call.name}' was not found.`));
}
} else {
// Call respond to display response and wait for user input
await respond(Colorize.output(message.content!));
}
break;
default:
if (result.message) {
await respond(Colorize.error(`${result.status}: ${result.message}`));
} else {
await respond(Colorize.error(`A result status of '${result.status}' was returned.`));
}
break;
}
}
// Show the bots message
console.log(botMessage);
// Prompt the user for input
rl.question('User: ', async (input: string) => {
// Check if the user wants to exit the chat
if (input.toLowerCase() === 'exit') {
// Close the readline interface and exit the process
rl.close();
process.exit();
} else {
// Complete the prompt using the user's input
completePrompt(input);
}
});
}
// Start chat session
respond(Colorize.output(`Hello, how can I help you?`));
} | /**
* Starts the chat session and listens for user input.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/Codepilot.ts#L46-L124 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | SourceCodeSection.constructor | public constructor(index: CodeIndex, tokens: number = -1, userPrefix: string = 'user: ') {
super(tokens, true, '\n', userPrefix);
this._index = index;
} | /**
* Creates a new 'SourceCodeSection' instance.
* @param index Code index to use.
* @param tokens Optional. Sizing strategy for this section. Defaults to `auto`.
* @param userPrefix Optional. Prefix to use for text output. Defaults to `user: `.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/SourceCodeSection.ts#L16-L19 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Colorize.replaceLine | public static replaceLine(text: string): string {
return '\x1b[A\x1b[2K' + text;
} | /**
* Replaces the current line with the given text.
* @param text The text to replace the current line with.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/internals/Colorize.ts#L12-L14 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Colorize.error | public static error(error: Error|string): string {
if (typeof error === 'string') {
return `\x1b[31;1m${error}\x1b[0m`;
} else {
return `\x1b[31;1m${error.message}\x1b[0m`;
}
} | /**
* Renders the given text as error text.
* @param error Error text to render.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/internals/Colorize.ts#L20-L26 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Colorize.highlight | public static highlight(message: string): string {
return `\x1b[34;1m${message}\x1b[0m`;
} | /**
* Renders the given text with a highlight to call attention.
* @param message Text to highlight.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/internals/Colorize.ts#L32-L34 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Colorize.output | public static output(output: object | string, quote: string = '', units: string = ''): string {
if (typeof output === 'string') {
return `\x1b[32m${quote}${output}${quote}\x1b[0m`;
} else if (typeof output === 'object' && output !== null) {
return colorizer(output, {
pretty: true,
colors: {
BRACE: 'white',
BRACKET: 'white',
COLON: 'white',
COMMA: 'white',
STRING_KEY: 'white',
STRING_LITERAL: 'green',
NUMBER_LITERAL: 'blue',
BOOLEAN_LITERAL: 'blue',
NULL_LITERAL: 'blue'
}
});
} else if (typeof output == 'number') {
return `\x1b[34m${output}${units}\x1b[0m`;
} else {
return `\x1b[34m${output}\x1b[0m`;
}
} | /**
* Renders the given text as general output text.
* @param output Text to render.
* @param quote Optional. Quote to use for strings. Defaults to `''`.
* @param units Optional. Units to use for numbers. Defaults to `''`.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/internals/Colorize.ts#L42-L65 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Colorize.progress | public static progress(message: string): string {
return `\x1b[90m${message}\x1b[0m`;
} | /**
* Renders the given text as progress text.
* @param message Progress text to render.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/internals/Colorize.ts#L71-L73 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Colorize.title | public static title(title: string): string {
return `\x1b[35;1m${title}\x1b[0m`;
} | /**
* Renders the given text as a title.
* @param title Title text to render.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/internals/Colorize.ts#L79-L81 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Colorize.value | public static value(field: string, value: any, units: string = ''): string {
return `${field}: ${Colorize.output(value, '"', units)}`;
} | /**
* Renders the given text as a value.
* @param field Field name to render.
* @param value Value to render.
* @param units Optional. Units to use for numbers. Defaults to `''`.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/internals/Colorize.ts#L89-L91 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
codepilot | github_2023 | Stevenic | typescript | Colorize.warning | public static warning(warning: string): string {
return `\x1b[33m${warning}\x1b[0m`;
} | /**
* Renders the given text as a warning.
* @param warning Warning text to render.
*/ | https://github.com/Stevenic/codepilot/blob/cc568400c04a8641c1599dd3a03d0d1ae25d67c1/src/internals/Colorize.ts#L97-L100 | cc568400c04a8641c1599dd3a03d0d1ae25d67c1 |
zotero-better-authors | github_2023 | github-young | typescript | onPrefsEvent | async function onPrefsEvent(type: string, data: { [key: string]: any }) {
switch (type) {
case "load":
registerPrefsScripts(data.window);
break;
default:
return;
}
} | /**
* This function is just an example of dispatcher for Preference UI events.
* Any operations should be placed in a function to keep this funcion clear.
* @param type event type
* @param data event data
*/ | https://github.com/github-young/zotero-better-authors/blob/2928c60518ee2ff5f249225be2f92258940a02b7/src/hooks.ts#L58-L66 | 2928c60518ee2ff5f249225be2f92258940a02b7 |
zotero-better-authors | github_2023 | github-young | typescript | initLocale | function initLocale() {
const l10n = new (
typeof Localization === "undefined"
? ztoolkit.getGlobal("Localization")
: Localization
)([`${config.addonRef}-addon.ftl`], true);
addon.data.locale = {
current: l10n,
};
} | /**
* Initialize locale data
*/ | https://github.com/github-young/zotero-better-authors/blob/2928c60518ee2ff5f249225be2f92258940a02b7/src/utils/locale.ts#L8-L17 | 2928c60518ee2ff5f249225be2f92258940a02b7 |
zotero-better-authors | github_2023 | github-young | typescript | isWindowAlive | function isWindowAlive(win?: Window) {
return win && !Components.utils.isDeadWrapper(win) && !win.closed;
} | /**
* Check if the window is alive.
* Useful to prevent opening duplicate windows.
* @param win
*/ | https://github.com/github-young/zotero-better-authors/blob/2928c60518ee2ff5f249225be2f92258940a02b7/src/utils/window.ts#L8-L10 | 2928c60518ee2ff5f249225be2f92258940a02b7 |
zotero-better-authors | github_2023 | github-young | typescript | MyToolkit.constructor | constructor() {
super();
this.UI = new UITool(this);
// this.PreferencePane = new PreferencePaneManager(this);
} | // PreferencePane: PreferencePaneManager; | https://github.com/github-young/zotero-better-authors/blob/2928c60518ee2ff5f249225be2f92258940a02b7/src/utils/ztoolkit.ts#L40-L44 | 2928c60518ee2ff5f249225be2f92258940a02b7 |
keybr.com | github_2023 | aradzie | typescript | modMultiply | function modMultiply(a: number, b: number): number {
a = a >>> 0;
b = b >>> 0;
let r = 0;
for (let i = 0; i < 32; i++) {
if (((b >>> i) & 1) === 1) {
r += a << i;
}
}
return r >>> 0;
} | /**
* Multiply modulo 0xFFFFFFFF.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-binary/lib/secret.ts#L71-L81 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Output.length | get length(): number {
return this.#length + this.#separator.length;
} | /** Returns the number of characters accumulated in the output. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-code/lib/output.ts#L20-L22 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Output.remaining | get remaining(): number {
return this.#limit - (this.#length + this.#separator.length);
} | /** Returns the number of remaining characters before the limit is reached. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-code/lib/output.ts#L25-L27 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Output.separate | separate(text: string): this {
if (this.#text.length > 0) {
const { length } = text;
if (length > 0) {
if (this.#length + length > this.#limit) {
throw Output.Stop;
}
}
this.#separator = text;
}
return this;
} | /** Appends the given text, but only if followed by the `append(...)` method. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-code/lib/output.ts#L30-L41 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Output.append | append(text: string, cls: string | null = null): this {
if ((text === " " || text === "\n" || text === "\t") && cls == null) {
return this.separate(text);
}
const { length } = text;
if (length > 0) {
if (this.#length + this.#separator.length + length > this.#limit) {
throw Output.Stop;
}
if (this.#separator.length > 0) {
this.#text.push(this.#separator);
this.#length += this.#separator.length;
this.#separator = "";
}
this.#text.push(cls != null ? { cls, text } : text);
this.#length += length;
}
return this;
} | /** Appends the given text, or throws the stop error if the limit is reached. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-code/lib/output.ts#L44-L62 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Output.clear | clear(): this {
this.#text.length = 0;
this.#length = 0;
this.#separator = "";
return this;
} | /** Clears the accumulated text. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-code/lib/output.ts#L65-L70 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | DataDir.userSettingsFile | userSettingsFile(userId: number): string {
const s = String(userId).padStart(9, "0");
return this.dataPath(
"user_settings", //
s.substring(0, 3),
s.substring(3, 6),
s,
);
} | /**
* Returns the full path to a user settings file for the given user id.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-config/lib/datadir.ts#L15-L23 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | DataDir.userStatsFile | userStatsFile(userId: number): string {
const s = String(userId).padStart(9, "0");
return this.dataPath(
"user_stats", //
s.substring(0, 3),
s.substring(3, 6),
s,
);
} | /**
* Returns the full path to a user stats file for the given user id.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-config/lib/datadir.ts#L28-L36 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | undead | function undead(layout: CharacterDict): CharacterDict {
return Object.fromEntries(Object.entries(layout).map(([id, [a, b]]) => [id, [a, b]]));
} | /** Removes dead keys from the given keyboard layout. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-generators/lib/generate-layouts.ts#L96-L98 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Language.test | test = (v: string): boolean => {
for (const codePoint of toCodePoints(this.lowerCase(v))) {
if (!this.alphabet.includes(codePoint)) {
return false;
}
}
return true;
} | /**
* Checks whether the given string is composed only of the language letters,
* case-insensitive.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-keyboard/lib/language.ts | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Language.includes | includes(codePoint: CodePoint): boolean {
// We consider these Unicode ranges to contain letters only in a given script.
// The ranges were manually built from Unicode tables and may not be accurate.
switch (this.script) {
case "arabic":
return codePoint >= 0x0600 && codePoint <= 0x06ff;
case "cyrillic":
return codePoint >= 0x0400 && codePoint <= 0x04ff;
case "greek":
return codePoint >= 0x0370 && codePoint <= 0x03ff;
case "hebrew":
return codePoint >= 0x0590 && codePoint <= 0x05ff;
case "latin":
// A few Unicode blocks of the Latin script to include only
// a reasonable list of letter codepoints.
return (
(codePoint >= /* "A" */ 0x0041 && codePoint <= /* "Z" */ 0x005a) ||
(codePoint >= /* "a" */ 0x0061 && codePoint <= /* "z" */ 0x007a) ||
(codePoint >= /* "À" */ 0x00c0 && codePoint <= /* "Ö" */ 0x00d6) ||
(codePoint >= /* "Ø" */ 0x00d8 && codePoint <= /* "ö" */ 0x00f6) ||
(codePoint >= /* "ø" */ 0x00f8 && codePoint <= /* "ÿ" */ 0x00ff) ||
(codePoint >= /* "Ā" */ 0x0100 && codePoint <= /* "ſ" */ 0x017f) ||
(codePoint >= /* "ƀ" */ 0x0180 && codePoint <= /* "ɏ" */ 0x024f)
);
case "thai":
return codePoint >= 0x0e00 && codePoint <= 0x0e7f;
default:
return false;
}
} | /**
* Returns a value indicating whether the given code point
* can be a letter of this language.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-keyboard/lib/language.ts#L290-L319 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Timer.elapsed | get elapsed() {
return Timer.now() - this.started;
} | /**
* Returns a fractional number of milliseconds since this timer was created,
* monotonically increasing.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-lang/lib/timer.ts#L17-L19 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | confidenceOf | const confidenceOf = (key: LessonKey): number => {
return recoverKeys ? (key.confidence ?? 0) : (key.bestConfidence ?? 0);
}; | // Find the least confident of all included keys and focus on it. | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-lesson/lib/guided.ts#L96-L98 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Distribution.scale | scale(index: number): number {
const { length } = this.#samples;
index = Math.round(index * (length - 1));
if (index < 0) {
return 0;
}
if (index > length - 1) {
return length - 1;
}
return index;
} | /** Scales a value in range [0, 1] to a histogram index. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-math/lib/dist.ts#L62-L72 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Distribution.unscale | unscale(index: number): number {
const { length } = this.#samples;
index = Math.round(index);
if (index < 0) {
return 0;
}
if (index > length - 1) {
return 1;
}
return index / (length - 1);
} | /** Scales a histogram index to a value in range [0, 1]. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-math/lib/dist.ts#L75-L85 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | Filter.includes | includes(codePoint: CodePoint): boolean {
return this.codePoints == null || this.codePoints.has(codePoint);
} | /**
* Returns a value indicating whether the given codepoint
* is allowed by this filter.
*
* Empty filter allows all characters.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-phonetic-model/lib/filter.ts#L42-L44 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | modMultiply | function modMultiply(a: number, b: number): number {
a = a >>> 0;
b = b >>> 0;
let r = 0;
for (let n = 0; n < 32; n++) {
if (((b >>> n) & 1) === 1) {
r += a << n;
}
}
return r >>> 0;
} | /** Multiply modulo 0xFFFFFFFF. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-publicid/lib/index.ts#L172-L182 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | rng | const rng: RNGStream<Mark> = (): number => {
update();
const a = state0_hi;
const b = state0_lo;
return ((a >>> 5) * 0x4000000 + (b >>> 6)) * (1.0 / 0x20000000000000);
}; | /* Generates a random number on [0,1) with 53-bit resolution. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-rand/lib/rng/xorshift128plus.ts#L64-L69 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | DailyStatsMap.today | get today(): DailyStats {
return this.#today;
} | /** Summary stats for the results of today. May not exist in the iterated entries. */ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-result/lib/dailystats.ts#L37-L39 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | forwardEmulation | function forwardEmulation(
keyboard: Keyboard,
target: InputListener,
): InputListener {
const timeToType = new TimeToType();
return {
onKeyDown: (event) => {
timeToType.add(event);
const [mapped, codePoint] = fixKey(keyboard, event);
target.onKeyDown(mapped);
if (isTextInput(event.modifiers) && codePoint > 0x0000) {
target.onInput({
type: "input",
timeStamp: mapped.timeStamp,
inputType: "appendChar",
codePoint,
timeToType: timeToType.measure(event),
});
}
},
onKeyUp: (event) => {
timeToType.add(event);
const [mapped, codePoint] = fixKey(keyboard, event);
target.onKeyUp(mapped);
},
onInput: (event) => {
switch (event.inputType) {
case "appendLineBreak":
case "clearChar":
case "clearWord":
target.onInput(event);
break;
}
},
};
} | /**
* Expects the `code` property to be correct, changes the `key` property.
*
* We ignore the character codes reported by the OS and use our own layout
* tables to translate a physical key location to a character code.
*
* It is a convenience option that allows users not to care about the OS
* settings.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-textinput-events/lib/emulation.ts#L42-L77 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | reverseEmulation | function reverseEmulation(
keyboard: Keyboard,
target: InputListener,
): InputListener {
return {
onKeyDown: (event) => {
target.onKeyDown(fixCode(keyboard, event));
},
onKeyUp: (event) => {
target.onKeyUp(fixCode(keyboard, event));
},
onInput: (event) => {
target.onInput(event);
},
};
} | /**
* Expects the `key` property to be correct, changes the `code` property.
*
* Keyboard layout switching is done in hardware. It changes physical key
* locations to the QWERTY equivalents. So if the A key is pressed in a custom
* keyboard layout, the hardware will send the physical key location of the A
* letter in the QWERTY layout.
*
* We use a layout table and a character code as reported by the OS to fix
* the physical key location.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-textinput-events/lib/emulation.ts#L90-L105 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | fixKey | function fixKey(
keyboard: Keyboard,
{ type, timeStamp, code, key, modifiers }: IKeyboardEvent,
): [IKeyboardEvent, CodePoint] {
let codePoint = 0x0000;
const characters = keyboard.getCharacters(code);
if (characters != null) {
key = String.fromCodePoint(
(codePoint = characters.getCodePoint(toKeyModifier(modifiers)) ?? 0x0000),
);
}
return [{ type, timeStamp, code, key, modifiers }, codePoint];
} | /**
* Changes the character code using a physical key location.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-textinput-events/lib/emulation.ts#L110-L122 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | fixCode | function fixCode(
keyboard: Keyboard,
{ type, timeStamp, code, key, modifiers }: IKeyboardEvent,
): IKeyboardEvent {
if (key.length === 1) {
const combo = keyboard.getCombo(key.codePointAt(0) ?? 0x0000);
if (combo != null) {
code = combo.id;
}
}
return { type, timeStamp, code, key, modifiers };
} | /**
* Changes the physical key location using a character code.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-textinput-events/lib/emulation.ts#L127-L138 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | PlayerLoader.init | async init() {
if (this.#buffer != null && this.#player == null) {
try {
const context = getAudioContext();
if (context != null) {
const buffer = await context.decodeAudioData(this.#buffer);
const player = new WebAudioPlayer(context, buffer);
this.#buffer = null;
this.#player = player;
} else {
this.#buffer = null;
this.#player = nullPlayer;
}
} catch (err) {
this.#buffer = null;
this.#player = nullPlayer;
throw err;
}
}
return this.#player ?? nullPlayer;
} | /**
* Stage two: we convert the loaded sound data into players.
* We assume that at this point there was a user gesture
* and AudioContext is already available.
*/ | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/keybr-textinput-sounds/lib/internal/library.ts#L66-L86 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | LessonState.constructor | constructor(
progress: Progress,
onResult: (result: Result, textInput: TextInput) => void,
) {
this.#onResult = onResult;
this.settings = progress.settings;
this.lesson = progress.lesson;
this.textInputSettings = toTextInputSettings(this.settings);
this.textDisplaySettings = toTextDisplaySettings(this.settings);
this.keyStatsMap = progress.keyStatsMap.copy();
this.summaryStats = progress.summaryStats.copy();
this.streakList = progress.streakList.copy();
this.dailyGoal = progress.dailyGoal.copy();
this.lessonKeys = this.lesson.update(this.keyStatsMap);
this.#reset(this.lesson.generate(this.lessonKeys, Lesson.rng));
} | // Mutable. | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/page-practice/lib/practice/state/lesson-state.ts#L50-L65 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
keybr.com | github_2023 | aradzie | typescript | parseResults | async function parseResults(buffer: Buffer): Promise<Result[]> {
const results = [];
try {
for (const result of parseMessage(buffer)) {
if (result.validate()) {
results.push(result);
}
}
} catch (err: any) {
throw new BadRequestError(err.message);
}
return results;
} | // TODO Parse asynchronously in batches. | https://github.com/aradzie/keybr.com/blob/90308d2416ef01eecb9f2a19ef3025b34c030345/packages/server/lib/app/sync/controller.ts#L59-L71 | 90308d2416ef01eecb9f2a19ef3025b34c030345 |
rapidpages | github_2023 | rapidpages | typescript | showCanvas | const showCanvas = () => {
if (canvasRef.current) {
canvasRef.current.style.display = "block";
}
}; | // Imperative methods | https://github.com/rapidpages/rapidpages/blob/dc265352c6efe4be7ffd57686e75d29d4193326c/src/components/CanvasWrapper.tsx#L29-L33 | dc265352c6efe4be7ffd57686e75d29d4193326c |
rapidpages | github_2023 | rapidpages | typescript | startDrawing | const startDrawing = (event: React.MouseEvent<HTMLCanvasElement>) => {
setIsDrawing(true);
const rect = canvasRef.current!.getBoundingClientRect();
setLastPos({
x: event.clientX - rect.left,
y: event.clientY - rect.top,
});
}; | // Internal methods | https://github.com/rapidpages/rapidpages/blob/dc265352c6efe4be7ffd57686e75d29d4193326c/src/components/CanvasWrapper.tsx#L56-L63 | dc265352c6efe4be7ffd57686e75d29d4193326c |
rapidpages | github_2023 | rapidpages | typescript | compileCode | const compileCode = async () => {
const compiledCode = await compileTypescript(code);
setDom(compiledCode);
}; | // Compile and render the page | https://github.com/rapidpages/rapidpages/blob/dc265352c6efe4be7ffd57686e75d29d4193326c/src/components/PageEditor.tsx#L16-L19 | dc265352c6efe4be7ffd57686e75d29d4193326c |
rapidpages | github_2023 | rapidpages | typescript | handleResize | const handleResize = () => {
const iframe = iframeRef.current;
if (!iframe) return;
const { contentWindow } = iframeRef.current;
if (contentWindow) {
const { documentElement } = contentWindow.document;
const width = documentElement.clientWidth;
const height = documentElement.clientHeight;
setDimensions({ width, height });
}
}; | // We resize the canvas to fit the screen. This is not ideal, but it works for now. | https://github.com/rapidpages/rapidpages/blob/dc265352c6efe4be7ffd57686e75d29d4193326c/src/components/PageEditor.tsx#L22-L32 | dc265352c6efe4be7ffd57686e75d29d4193326c |
rapidpages | github_2023 | rapidpages | typescript | ComponentProvider | const ComponentProvider = ({ children }: ProviderProps) => {
const [tabs] = useState<Tab[]>([]);
return (
<ComponentContext.Provider
value={{
tabs,
setActiveTab: async () => {},
}}
>
{children}
</ComponentContext.Provider>
);
}; | // The provider for the ComponentContext | https://github.com/rapidpages/rapidpages/blob/dc265352c6efe4be7ffd57686e75d29d4193326c/src/context/ComponentProvider.tsx#L32-L45 | dc265352c6efe4be7ffd57686e75d29d4193326c |
rapidpages | github_2023 | rapidpages | typescript | babelCompile | const babelCompile = (code: string, filename: string) =>
transform(code, {
filename: filename,
plugins: [
[
"transform-modules-umd",
{
globals: { react: "React", "react-dom": "ReactDOM" },
},
],
],
presets: ["tsx", "react"],
}); | // Transforms the TSX code to JS | https://github.com/rapidpages/rapidpages/blob/dc265352c6efe4be7ffd57686e75d29d4193326c/src/utils/compiler.ts#L77-L89 | dc265352c6efe4be7ffd57686e75d29d4193326c |
Panora | github_2023 | panoratech | typescript | useCreateApiKeyConnection | const useCreateApiKeyConnection = () => {
const createApiKeyConnection = async (apiKeyConnectionData : IApiKeyConnectionDto) => {
const response = await fetch(
`${apiKeyConnectionData.api_url}/connections/basicorapikey/callback?state=${encodeURIComponent(JSON.stringify(apiKeyConnectionData.query))}`, {
method: 'POST',
body: JSON.stringify(apiKeyConnectionData.data),
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || "Unknown error occurred");
}
return response.json();
};
return useMutation({
mutationFn: createApiKeyConnection,
onSuccess: () => {
console.log("Successfull !!!!")
}
});
}; | // Adjusted useCreateApiKey hook to include a promise-returning function | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/apps/embedded-catalog/react/src/hooks/queries/useCreateApiKeyConnection.tsx#L21-L48 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | useCreateApiKeyConnection | const useCreateApiKeyConnection = () => {
const createApiKeyConnection = async (apiKeyConnectionData : IGConnectionDto) => {
const response = await fetch(
`${config.API_URL}/connections/basicorapikey/callback?state=${encodeURIComponent(JSON.stringify(apiKeyConnectionData.query))}`, {
method: 'POST',
body: JSON.stringify(apiKeyConnectionData.data),
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || "Unknown error occurred");
}
return response;
};
return useMutation({
mutationFn: createApiKeyConnection,
onSuccess: () => {
}
});
}; | // Adjusted useCreateApiKey hook to include a promise-returning function | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/apps/magic-link/src/hooks/queries/useCreateApiKeyConnection.tsx#L19-L43 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | DeleteApiKeyCell | const DeleteApiKeyCell = ({ row }: { row: any }) => {
const [dialogOpen, setDialogOpen] = useState(false);
const [confirmText, setConfirmText] = useState('');
const { deleteApiKeyPromise } = useDeleteApiKey();
const queryClient = useQueryClient();
const handleDelete = async () => {
if (confirmText.toLowerCase() === 'delete') {
try {
await toast.promise(
deleteApiKeyPromise({
id_api_key: row.original.id_api_key,
}),
{
loading: 'Deleting API key...',
success: 'API key deleted successfully',
error: 'Failed to delete API key'
}
);
queryClient.invalidateQueries({ queryKey: ['api-keys'] });
setDialogOpen(false);
} catch (error) {
console.error('Failed to delete API key:', error);
}
}
};
return (
<>
<Button
variant="ghost"
className="flex h-8 w-8 p-0 data-[state=open]:bg-muted"
onClick={() => setDialogOpen(true)}
>
<TrashIcon className="h-4 w-4 text-destructive" />
<span className="sr-only">Delete API key</span>
</Button>
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Confirm API Key Deletion</DialogTitle>
<DialogDescription>
This will permanently delete this API key. To confirm, please type "delete" below.
</DialogDescription>
</DialogHeader>
<Input
value={confirmText}
onChange={(e) => setConfirmText(e.target.value)} | // Create a proper React component for the actions cell | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/apps/webapp/src/components/ApiKeys/columns.tsx#L24-L72 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | onLogout | const onLogout = () => {
router.push('/b2c/login')
Cookies.remove("access_token")
setProfile(null)
setIdProject("")
queryClient.clear()
} | // const [currentTheme,SetCurrentTheme] = useState(theme) | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/apps/webapp/src/components/Nav/user-nav.tsx#L40-L46 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | 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) => callbackRef.current?.(...args)) as T,
[]
)
} | /**
* @see https://github.com/radix-ui/primitives/blob/main/packages/react/use-callback-ref/src/useCallbackRef.tsx
*/ | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/apps/webapp/src/hooks/use-callback-ref.ts#L11-L25 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | useCreateApiKey | const useCreateApiKey = () => {
const addApiKey = async (data: IApiKeyDto) => {
const response = await fetch(`${config.API_URL}/auth/api_keys`, {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${Cookies.get('access_token')}`,
},
});
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || "Unknown error occurred");
}
return response.json();
};
// Expose a promise-returning function alongside mutate
const createApiKeyPromise = (data: IApiKeyDto) => {
return new Promise(async (resolve, reject) => {
try {
const result = await addApiKey(data);
resolve(result);
} catch (error) {
reject(error);
}
});
};
return {
mutate: useMutation({
mutationFn: addApiKey,
}),
createApiKeyPromise,
};
}; | // Adjusted useCreateApiKey hook to include a promise-returning function | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/apps/webapp/src/hooks/create/useCreateApiKey.tsx#L12-L50 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | createApiKeyPromise | const createApiKeyPromise = (data: IApiKeyDto) => {
return new Promise(async (resolve, reject) => {
try {
const result = await addApiKey(data);
resolve(result);
} catch (error) {
reject(error);
}
});
}; | // Expose a promise-returning function alongside mutate | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/apps/webapp/src/hooks/create/useCreateApiKey.tsx#L32-L42 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | createCsPromise | const createCsPromise = (data: IConnectionStrategyDto) => {
return new Promise(async (resolve, reject) => {
try {
const result = await add(data);
resolve(result);
} catch (error) {
reject(error);
}
});
}; | // Expose a promise-returning function alongside mutate | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/apps/webapp/src/hooks/create/useCreateConnectionStrategy.tsx#L32-L42 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | useCreateApiKeyConnection | const useCreateApiKeyConnection = () => {
const createApiKeyConnection = async (
apiKeyConnectionData: IGConnectionDto
) => {
const response = await fetch(
`${
config.API_URL
}/connections/basicorapikey/callback?state=${encodeURIComponent(
JSON.stringify(apiKeyConnectionData.query)
)}`,
{
method: "POST",
body: JSON.stringify(apiKeyConnectionData.data),
headers: {
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || "Unknown error occurred");
}
return response;
};
return useMutation({
mutationFn: createApiKeyConnection,
onSuccess: () => {},
});
}; | // Adjusted useCreateApiKey hook to include a promise-returning function | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/apps/webapp/src/hooks/magic-link/useCreateApiKeyConnection.tsx#L17-L48 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | BullQueueService.getRealtimeWebhookReceiver | getRealtimeWebhookReceiver() {
return this.realTimeWebhookQueue;
} | // getters | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/@core-services/queues/shared.service.ts#L24-L26 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | CoreSyncRegistry.registerService | registerService(
category_vertical: string,
common_object: string,
service: IBaseSync,
) {
const compositeKey = this.createCompositeKey(
category_vertical,
common_object,
);
this.serviceMap.set(compositeKey, service);
} | // Register a service with a composite key | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/@core-services/registries/core-sync.registry.ts#L14-L24 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | CoreSyncRegistry.getService | getService(category_vertical: string, common_object: string): IBaseSync {
const compositeKey = this.createCompositeKey(
category_vertical,
common_object,
);
const service = this.serviceMap.get(compositeKey);
if (!service) {
this.logger.error(`Service not found for key: ${compositeKey}`);
throw new Error(
`Service not found for given keys: ${category_vertical}, ${common_object}`,
);
}
return service;
} | // Retrieve a service using the composite key | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/@core-services/registries/core-sync.registry.ts#L27-L40 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Panora | github_2023 | panoratech | typescript | CoreSyncRegistry.createCompositeKey | private createCompositeKey(
category_vertical: string,
common_object: string,
): string {
return `${category_vertical.trim().toLowerCase()}_${common_object
.trim()
.toLowerCase()}`;
} | // Utility method to create a consistent composite key from two strings | https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/@core-services/registries/core-sync.registry.ts#L43-L50 | c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.