repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
cloudypad
github_2023
PierreBeucher
typescript
humanReadableArgs
const humanReadableArgs = (obj?: any, parentKey?: string): string => { if(obj === undefined){ return "" } return Object.keys(obj).map(key => { // If parent key is not empty, add a dot between parent key and current key ...
// Shamelessly generated by IA and edited/commented by hand
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/provisioner.ts#L103-L138
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
ConfigManager.constructor
constructor(dataRootDir?: string) { this.dataRootDir = dataRootDir ?? DataRootDirManager.getEnvironmentDataRootDir() this.configPath = path.join(this.dataRootDir, 'config.yml') }
/** * Do not call constructor directly. Use getInstance() instead. * @param dataRootDir Do not use default dataRootDir. */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/config/manager.ts#L61-L64
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
ConfigManager.init
init(): void { if (!fs.existsSync(this.configPath)) { this.logger.info(`CLI config not found at ${this.configPath}. Creating default config...`) const initConfig = lodash.merge( {}, BASE_DEFAULT_CONFIG, { ...
/** * Initialize configuration if needed: * - Create default config.yml in root data dir if none already exists, prompting user for details * - If one already exists, parse it */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/config/manager.ts#L78-L101
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateInitializer.initializeState
public async initializeState(): Promise<InstanceStateV1> { const instanceName = this.args.input.instanceName const input = this.args.input this.logger.debug(`Initializing a new instance with config ${JSON.stringify(input)}`) // Create the initial state const initialState: Inst...
/** * Initialize instance: * - Prompt for common and provisioner-specific configs * - Initialize state * - Run provision * - Run configuration * - Optionally pair instance * @param opts */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/initializer.ts#L30-L59
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateLoader.instanceExists
async instanceExists(instanceName: string): Promise<boolean> { const instanceDir = this.getInstanceDir(instanceName) const instanceStateV1Path = this.getInstanceStatePath(instanceName) this.logger.debug(`Checking instance ${instanceName} in directory ${instanceStateV1Path} at ${instanceDir}`) ...
/** * Check an instance exists. An instance is considering existing if the folder * ${dataRootDir}/instances/<instance_name> exists and contains a state. */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/loader.ts#L49-L56
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateLoader.loadRawInstanceState
private async loadRawInstanceState(instanceName: string): Promise<unknown> { this.logger.debug(`Loading instance state ${instanceName}`) if (!(await this.instanceExists(instanceName))) { throw new Error(`Instance named '${instanceName}' does not exist.`) } const instanceSta...
/** * Load raw instance state from disk. Loaded state is NOT type-checked. * First try to load state V1, then State V0 before failing */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/loader.ts#L62-L78
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateLoader.loadAndMigrateInstanceState
async loadAndMigrateInstanceState(instanceName: string): Promise<InstanceStateV1> { await new StateMigrator({ dataRootDir: this.dataRootDir }).ensureInstanceStateV1(instanceName) // state is unchecked, any is acceptable at this point // eslint-disable-next-line @typescript-eslint/no-explicit-an...
/** * Load and migrate an instance state to the latest version safely (by validating schema and throwing on error) * This method should be called before trying to parse the state for a provider */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/loader.ts#L84-L97
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateMigrator.needMigration
async needMigration(instanceName: string): Promise<boolean>{ const v0InstancePath = this.getInstanceStateV0Path(instanceName) this.logger.debug(`Checking if instance ${instanceName} needs migration using ${v0InstancePath}`) if(fs.existsSync(this.getInstanceDir(instanceName)) && fs.existsSync(...
/** * * @param instanceName */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/migrator.ts#L23-L34
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateMigrator.doMigrateStateV0toV1
private async doMigrateStateV0toV1(rawState: any): Promise<AnyInstanceStateV1>{ const stateV0 = rawState as InstanceStateV0 const name = stateV0.name // Transform provider const providerV0 = stateV0.provider let stateV1: AnyInstanceStateV1 let providerName: CLOUDYPAD_...
// eslint-disable-next-line @typescript-eslint/no-explicit-any
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/migrator.ts#L70-L287
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateWriter.instanceName
instanceName(): string { return this.state.name }
/** * @returns instance name for managed State */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/writer.ts#L66-L68
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateWriter.cloneState
cloneState(): ST { return lodash.cloneDeep(this.state) }
/** * Return a clone of managed State. */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/writer.ts#L73-L75
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateWriter.persistStateNow
async persistStateNow(){ await this.updateState(this.state) }
/** * Persist managed State on disk. */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/writer.ts#L80-L82
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
StateWriter.destroyInstanceStateDirectory
async destroyInstanceStateDirectory(){ await this.removeInstanceDir() }
/** * Effectively destroy instance state and it's directory */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/core/state/writer.ts#L123-L125
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
awsPulumiProgram
async function awsPulumiProgram(): Promise<Record<string, any> | void> { const config = new pulumi.Config(); const instanceType = config.require("instanceType"); const rootVolumeSizeGB = config.requireNumber("rootVolumeSizeGB"); const publicIpType = config.require("publicIpType"); const publicKeyCo...
/* eslint-disable @typescript-eslint/no-explicit-any */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/aws/pulumi.ts#L239-L321
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
azurePulumiProgram
async function azurePulumiProgram(): Promise<Record<string, any> | void> { const config = new pulumi.Config() const vmSize = config.require("vmSize") const publicKeyContent = config.require("publicSshKeyContent") const rootDiskSizeGB = config.requireNumber("rootDiskSizeGB") const rootDiskType = conf...
/* eslint-disable @typescript-eslint/no-explicit-any */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/azure/pulumi.ts#L214-L259
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
gcpPulumiProgram
async function gcpPulumiProgram(): Promise<Record<string, any> | void> { const gcpConfig = new pulumi.Config("gcp") const projectId = gcpConfig.require("project") const config = new pulumi.Config() const machineType = config.require("machineType") const acceleratorType = config.require("accelerato...
/* eslint-disable @typescript-eslint/no-explicit-any */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/gcp/pulumi.ts#L228-L276
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PaperspaceClient.getPublicIp
async getPublicIp(ip: string): Promise<PaperspaceIp | undefined>{ // GET:public-ips/{ip} not available on Paperspace API // Searching with list instead const ips = await this.listPublicIps() return ips.find(item => item.ip == ip) }
/** * Try to get a Public IP. * @param ip * @returns IP or undefined if IP not found */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/client.ts#L147-L153
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PaperspaceClient.deleteMachine
async deleteMachine(machineId: string, releasePublicIp?: boolean): Promise<void> { try { if(releasePublicIp){ const m = await this.getMachine(machineId) if(m.publicIp && m.publicIpType == paperspace.MachinesList200ResponseItemsInnerPublicIpTypeEnum.Static) { ...
/** * Delete a Paperspace machine. If machine has a static public IP and releasePublicIp is true, static IP is released as well. * Otherwise public IP (if any) attached to machine is left untouched. * @param machineId * @param releasePublicIp * @returns */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/client.ts#L194-L215
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AuthenticationApi.authSession
public authSession(options?: RawAxiosRequestConfig) { return AuthenticationApiFp(this.configuration).authSession(options).then((request) => request(this.axios, this.basePath)); }
/** * Get the current session. If a user is not logged in, this will be null. Otherwise, it will contain the current team and user. * @summary Get the current session * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof AuthenticationApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L1517-L1519
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesCreate
public machinesCreate(machinesCreateRequest: MachinesCreateRequest, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesCreate(machinesCreateRequest, options).then((request) => request(this.axios, this.basePath)); }
/** * Creates a new machine. * @summary Create a machine * @param {MachinesCreateRequest} machinesCreateRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2118-L2120
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesDelete
public machinesDelete(id: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesDelete(id, options).then((request) => request(this.axios, this.basePath)); }
/** * Deletes a single machine by ID. * @summary Delete a machine * @param {string} id The ID of the machine to delete. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2130-L2132
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesGet
public machinesGet(id: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesGet(id, options).then((request) => request(this.axios, this.basePath)); }
/** * Fetches a single machine by ID. * @summary Get a machine * @param {string} id The ID of the machine to fetch. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2142-L2144
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesList
public machinesList(after?: string, limit?: number, orderBy?: MachinesListOrderByEnum, order?: MachinesListOrderEnum, name?: string, region?: PublicIpsListRegionParameter, agentType?: string, machineType?: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesList(after, lim...
/** * Fetches a list of machines. * @summary List machines * @param {string} [after] Fetch the next page of results after this cursor. * @param {number} [limit] The number of items to fetch after this page. * @param {MachinesListOrderByEnum} [orderBy] Order results by one of these fields. ...
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2161-L2163
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesRestart
public machinesRestart(id: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesRestart(id, options).then((request) => request(this.axios, this.basePath)); }
/** * Restarts a machine. * @summary Restart a machine * @param {string} id The ID of the machine to restart. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2173-L2175
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesStart
public machinesStart(id: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesStart(id, options).then((request) => request(this.axios, this.basePath)); }
/** * Starts a machine. * @summary Start a machine * @param {string} id The ID of the machine to start. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2185-L2187
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesStop
public machinesStop(id: string, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesStop(id, options).then((request) => request(this.axios, this.basePath)); }
/** * Stops a machine. * @summary Stop a machine * @param {string} id The ID of the machine to stop. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2197-L2199
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
MachineApi.machinesUpdate
public machinesUpdate(id: string, machinesUpdateRequest: MachinesUpdateRequest, options?: RawAxiosRequestConfig) { return MachineApiFp(this.configuration).machinesUpdate(id, machinesUpdateRequest, options).then((request) => request(this.axios, this.basePath)); }
/** * Updates a machine. * @summary Update a machine * @param {string} id The ID of the machine to update. * @param {MachinesUpdateRequest} machinesUpdateRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof MachineApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2210-L2212
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PublicIPsApi.publicIpsAssign
public publicIpsAssign(ip: string, publicIpsAssignRequest: PublicIpsAssignRequest, options?: RawAxiosRequestConfig) { return PublicIPsApiFp(this.configuration).publicIpsAssign(ip, publicIpsAssignRequest, options).then((request) => request(this.axios, this.basePath)); }
/** * Assigns a public IP to a machine. * @summary Assign a public IP * @param {string} ip The IP address of the public IP. * @param {PublicIpsAssignRequest} publicIpsAssignRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PublicIPsApi...
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2564-L2566
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PublicIPsApi.publicIpsClaim
public publicIpsClaim(publicIpsClaimRequest: PublicIpsClaimRequest, options?: RawAxiosRequestConfig) { return PublicIPsApiFp(this.configuration).publicIpsClaim(publicIpsClaimRequest, options).then((request) => request(this.axios, this.basePath)); }
/** * Claims a public IP. * @summary Claim a public IP * @param {PublicIpsClaimRequest} publicIpsClaimRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PublicIPsApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2576-L2578
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PublicIPsApi.publicIpsList
public publicIpsList(after?: string, limit?: number, orderBy?: PublicIpsListOrderByEnum, order?: PublicIpsListOrderEnum, region?: PublicIpsListRegionParameter, options?: RawAxiosRequestConfig) { return PublicIPsApiFp(this.configuration).publicIpsList(after, limit, orderBy, order, region, options).then((request)...
/** * Fetches a list of public IPs. * @summary List public IPs * @param {string} [after] Fetch the next page of results after this cursor. * @param {number} [limit] The number of items to fetch after this page. * @param {PublicIpsListOrderByEnum} [orderBy] Order results by one of these fields. ...
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2592-L2594
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
PublicIPsApi.publicIpsRelease
public publicIpsRelease(ip: string, options?: RawAxiosRequestConfig) { return PublicIPsApiFp(this.configuration).publicIpsRelease(ip, options).then((request) => request(this.axios, this.basePath)); }
/** * Releases a public IP. * @summary Release a public IP * @param {string} ip The IP address of the public IP. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof PublicIPsApi */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/api.ts#L2604-L2606
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
objectEntries
function objectEntries(object: Record<string, any>): Array<[string, any]> { return Object.keys(object).map(key => [key, object[key]]); }
/** * Ponyfill for Object.entries */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/common.ts#L159-L161
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
objectFromEntries
function objectFromEntries(entries: any): Record<string, any> { return [...entries].reduce((object, [key, val]) => { object[key] = val; return object; }, {}); }
/** * Ponyfill for Object.fromEntries */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/common.ts#L166-L171
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
Configuration.isJsonMime
public isJsonMime(mime: string): boolean { const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); }
/** * Check if the given MIME is a JSON MIME. * JSON MIME examples: * application/json * application/json; charset=UTF8 * APPLICATION/JSON * application/vnd.company+json * @param mime - MIME (Multipurpose Internet Mail Extensions) * @return True if the given MIME is JSON,...
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/providers/paperspace/client/generated-api/configuration.ts#L106-L109
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AwsClient.getCurrentRegion
static async getCurrentRegion(): Promise<string | undefined> { // AWS SDK V3 does not provide an easy way to get current region // Use this method taken from https://github.com/aws/aws-sdk-js-v3/discussions/4488 try { return await loadConfig(NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CO...
/** * Return currently set region (as identified by AWS SDK). * @returns currently configured region - undefined if not region currently set */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/tools/aws.ts#L39-L48
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AwsClient.getQuota
async getQuota(quotaCode: string): Promise<number | undefined> { try { this.logger.debug(`Checking quota code ${quotaCode} in region: ${this.region}`) const command = new GetServiceQuotaCommand({ ServiceCode: 'ec2', QuotaCode: quotaCo...
/** * Get quota value for a given quota code * @param quotaCode quota code to check * @returns quota value if available, undefined if not */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/tools/aws.ts#L227-L244
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AwsClient.getInstanceTypeDetails
async getInstanceTypeDetails(instanceTypes: string[]): Promise<InstanceTypeInfo[]> { try { const internalInstanceTypes = stringsToInstanceTypes(instanceTypes) const command = new DescribeInstanceTypesCommand({ InstanceTypes: internalInstanceTypes, }) ...
/** * Fetch instance type details from AWS (vCPU, memory...) * @param instanceTypes instance types to fetch details for * @returns instance type details */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/tools/aws.ts#L251-L269
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AwsClient.filterAvailableInstanceTypes
async filterAvailableInstanceTypes(instanceTypes: string[]): Promise<string[]> { try { const internalInstanceTypes = stringsToInstanceTypes(instanceTypes) const command = new DescribeInstanceTypeOfferingsCommand({ LocationType: "region", Filters: [ ...
/** * Filter instance types that are available in client's region * @param instanceTypes instance types to filter * @returns instance types available in client's region */
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/tools/aws.ts#L276-L300
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
AnalyticsManager.get
static get(): AnalyticsClient { if(AnalyticsManager.client){ return AnalyticsManager.client } if(process.env.CLOUDYPAD_ANALYTICS_DISABLE === "true" || process.env.CLOUDYPAD_ANALYTICS_DISABLE === "1") { AnalyticsManager.logger.debug(`Initializing NoOp AnalyticsClient as ...
/** * Build an AnalyticsManager using current global configuration. * Returned instance is a singleton initialized the firs time this function is called. * * On first call, create an analytics client following: * - If CLOUDYPAD_ANALYTICS_DISABLE is true, a dummy no-op client is created * ...
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/src/tools/analytics/manager.ts#L23-L71
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
getTestWriter
async function getTestWriter(): Promise<{ dataDir: string, writer: StateWriter<AwsInstanceStateV1> }> { const dataDir = mkdtempSync(path.join(tmpdir(), 'statewriter-test-')) const loader = new StateLoader({ dataRootDir: path.resolve(__dirname, "v1-root-data-dir")}) const state = await loader.lo...
// create a test writer using a temp directory as data dir
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/test/unit/core/state/writer.spec.ts#L17-L30
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
cloudypad
github_2023
PierreBeucher
typescript
loadResultPersistedState
function loadResultPersistedState(dataDir: string){ const filePath = path.resolve(path.join(dataDir, "instances", instanceName, "state.yml")) return yaml.load(fs.readFileSync(filePath, 'utf-8')) }
// Load state from given data dir to compare with expected result
https://github.com/PierreBeucher/cloudypad/blob/f476990dedf0a856b1a8ce7dc82d28382ca67f7c/test/unit/core/state/writer.spec.ts#L33-L36
f476990dedf0a856b1a8ce7dc82d28382ca67f7c
ai-playground
github_2023
rokbenko
typescript
handleDialogClose
const handleDialogClose = () => { setLoadingAssistants(false); setLoadingThread(false); onClose(); };
// Function to close the dialog
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L49-L53
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
assistantsFunction
const assistantsFunction = async (e: any) => { e.preventDefault(); setLoadingAssistants(true); try { const response = await fetch(`/api/listAssistants`, { method: "GET", headers: { "Content-Type": "application/json", }, }); if (response.ok) { con...
// Function to fetch and list all assistants
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L56-L89
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
threadFunction
const threadFunction = async (e: any) => { e.preventDefault(); setLoadingThread(true); try { const response = await fetch(`api/createThread`, { method: "POST", headers: { "Content-Type": "application/json", }, }); if (response.ok) { const getResp...
// Function to create a new thread
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L92-L125
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
formatUnixTimestamp
const formatUnixTimestamp = ( timestamp: number, locale: string, timeZone: string ) => { const milliseconds = timestamp * 1000; return new Intl.DateTimeFormat(locale, { year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second...
// Function to format Unix timestamp to a readable date
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L128-L143
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
copyToClipboard
const copyToClipboard = async (text: string, idType: string) => { try { await copy(text); setSnackbarOpen(true); setSnackbarSeverity("success"); setSnackbarMessage(`${idType} ID copied to clipboard`); } catch (error) { console.error("Error copying to clipboard:", error); setS...
// Function to copy text to clipboard
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L146-L158
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
handleSnackbarClose
const handleSnackbarClose = ( event: React.SyntheticEvent | Event, reason?: string ) => { if (reason === "clickaway") { return; } setSnackbarOpen(false); };
// Function to handle Snackbar close event
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L161-L169
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
mapSeverityToAlertColor
const mapSeverityToAlertColor = (severity: string): AlertColor => { switch (severity) { case "success": return "success"; case "error": return "error"; case "warning": return "warning"; case "info": return "info"; default: return "info"; } ...
// Function to map severity to Alert color
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/components/dialog.tsx#L172-L185
3c229d9f10fefba1a24b70b13b2bb956d64914ec
ai-playground
github_2023
rokbenko
typescript
delay
const delay = (ms: any) => new Promise((resolve) => setTimeout(resolve, ms));
// Function to introduce a delay using promises
https://github.com/rokbenko/ai-playground/blob/3c229d9f10fefba1a24b70b13b2bb956d64914ec/openai-tutorials/3-GUI_personal_math_tutor/src/pages/api/openai.ts#L15-L15
3c229d9f10fefba1a24b70b13b2bb956d64914ec
beakjs
github_2023
mme
typescript
hasParentWithClass
const hasParentWithClass = (element: Element, className: string): boolean => { while (element && element !== document.body) { if (element.classList.contains(className)) { return true; } element = element.parentElement!; } return false; };
// Function to check if the target has the parent with a given class
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/packages/react/src/Window.tsx#L128-L136
c837e84da19082ae6ed977381548efb74930d678
beakjs
github_2023
mme
typescript
readVersionFile
function readVersionFile(filePath: string): string { return fs.readFileSync(filePath, "utf8").trim(); }
// This function reads the VERSION file and returns the version string
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/scripts/sync-versions.ts#L22-L24
c837e84da19082ae6ed977381548efb74930d678
beakjs
github_2023
mme
typescript
readPackageJson
function readPackageJson(filePath: string): any { return JSON.parse(fs.readFileSync(filePath, "utf8")); }
// This function reads a package.json file and returns its content as a JSON object
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/scripts/sync-versions.ts#L27-L29
c837e84da19082ae6ed977381548efb74930d678
beakjs
github_2023
mme
typescript
writePackageJson
function writePackageJson(filePath: string, content: any): void { fs.writeFileSync(filePath, JSON.stringify(content, null, 2) + "\n"); }
// This function writes the updated JSON content back to the package.json file
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/scripts/sync-versions.ts#L32-L34
c837e84da19082ae6ed977381548efb74930d678
beakjs
github_2023
mme
typescript
updatePackageData
function updatePackageData( rootPackageJson: any, targetPackageJson: any, newVersion: string ): boolean { let hasChanged = false; // Update version if (newVersion && targetPackageJson.version !== newVersion) { targetPackageJson.version = newVersion; hasChanged = true; } // Update dependencies ...
// This function updates the version and dependencies in targetPackageJson using the versions from rootPackageJson
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/scripts/sync-versions.ts#L37-L71
c837e84da19082ae6ed977381548efb74930d678
beakjs
github_2023
mme
typescript
updateVersionsAndDependencies
function updateVersionsAndDependencies(): void { const newVersion = readVersionFile(versionFilePath); const rootPackageJson = readPackageJson(rootPackageJsonPath); otherPackageJsonPaths.forEach((packageJsonPath) => { try { const targetPackageJson = readPackageJson(packageJsonPath); const hasChang...
// Main function to update version and dependencies versions in all package.json files
https://github.com/mme/beakjs/blob/c837e84da19082ae6ed977381548efb74930d678/scripts/sync-versions.ts#L74-L97
c837e84da19082ae6ed977381548efb74930d678
btime-desktop
github_2023
sajjadmrx
typescript
withPrototype
function withPrototype(obj: Record<string, any>) { const protos = Object.getPrototypeOf(obj) for (const [key, value] of Object.entries(protos)) { if (Object.prototype.hasOwnProperty.call(obj, key)) continue if (typeof value === 'function') { // Some native APIs, like `NodeJS.EventEmitter['on']`, don't work i...
// `exposeInMainWorld` can't detect attributes and methods of `prototype`, manually patching it.
https://github.com/sajjadmrx/btime-desktop/blob/4f1f048aff969bad4d6f05c677ea7d661c92d9c1/electron/preload.ts#L11-L25
4f1f048aff969bad4d6f05c677ea7d661c92d9c1
btime-desktop
github_2023
sajjadmrx
typescript
domReady
function domReady( condition: DocumentReadyState[] = ['complete', 'interactive'], ) { return new Promise((resolve) => { if (condition.includes(document.readyState)) { resolve(true) } else { document.addEventListener('readystatechange', () => { if (condition.includes(document.readyState)) { resolve(...
// --------- Preload scripts loading ---------
https://github.com/sajjadmrx/btime-desktop/blob/4f1f048aff969bad4d6f05c677ea7d661c92d9c1/electron/preload.ts#L28-L42
4f1f048aff969bad4d6f05c677ea7d661c92d9c1
btime-desktop
github_2023
sajjadmrx
typescript
useLoading
function useLoading() { const className = 'loaders-css__square-spin' const styleContent = ` @keyframes square-spin { 25% { transform: perspective(100px) rotateX(180deg) rotateY(0); } 50% { transform: perspective(100px) rotateX(180deg) rotateY(180deg); } 75% { transform: perspective(100px) rotateX(0) rotateY(180...
/** * https://tobiasahlin.com/spinkit * https://connoratherton.com/loaders * https://projects.lukehaas.me/css-loaders * https://matejkustec.github.io/SpinThatShit */
https://github.com/sajjadmrx/btime-desktop/blob/4f1f048aff969bad4d6f05c677ea7d661c92d9c1/electron/preload.ts#L63-L110
4f1f048aff969bad4d6f05c677ea7d661c92d9c1
btime-desktop
github_2023
sajjadmrx
typescript
toHex
const toHex = (value: number) => value.toString(16).padStart(2, '0')
// Convert RGB back to hex
https://github.com/sajjadmrx/btime-desktop/blob/4f1f048aff969bad4d6f05c677ea7d661c92d9c1/src/weather/components/weather-card.component.tsx#L192-L192
4f1f048aff969bad4d6f05c677ea7d661c92d9c1
vscode-ui-sketcher
github_2023
pAIrprogio
typescript
crc
const crc: CRCCalculator<Uint8Array> = (current, previous) => { let crc = previous === 0 ? 0 : ~~previous! ^ -1; for (let index = 0; index < current.length; index++) { crc = TABLE[(crc ^ current[index]) & 0xff] ^ (crc >>> 8); } return crc ^ -1; };
// crc32, https://github.com/alexgorbatchev/crc/blob/master/src/calculators/crc32.ts
https://github.com/pAIrprogio/vscode-ui-sketcher/blob/bcbced57d6465bd0b9d379dae2641103c95abb9a/ui-sketcher-webview/src/lib/png.ts#L58-L66
bcbced57d6465bd0b9d379dae2641103c95abb9a
pr-stats
github_2023
naver
typescript
msToTime
const msToTime = ( duration: number, ): { days: number; hours: number; minutes: number; seconds: number; } => { if (!duration) { return { days: -1, hours: -1, minutes: -1, seconds: -1, }; } const seconds = Math.floor((durat...
/** * pr-stats * Copyright (c) 2023-present NAVER Corp. * Apache-2.0 */
https://github.com/naver/pr-stats/blob/cb9b122926af0d118c690ddd313cbe4d9334729b/src/util/time.ts#L7-L35
cb9b122926af0d118c690ddd313cbe4d9334729b
nextjs-live-transcription
github_2023
deepgram-starters
typescript
connectToDeepgram
const connectToDeepgram = async (options: LiveSchema, endpoint?: string) => { const key = await getApiKey(); const deepgram = createClient(key); const conn = deepgram.listen.live(options, endpoint); conn.addListener(LiveTranscriptionEvents.Open, () => { setConnectionState(LiveConnectionState.OPE...
/** * Connects to the Deepgram speech recognition service and sets up a live transcription session. * * @param options - The configuration options for the live transcription session. * @param endpoint - The optional endpoint URL for the Deepgram service. * @returns A Promise that resolves when the connec...
https://github.com/deepgram-starters/nextjs-live-transcription/blob/474b3dfb8eb3bad6ac997c02ba63c82650ad995c/app/context/DeepgramContextProvider.tsx#L56-L71
474b3dfb8eb3bad6ac997c02ba63c82650ad995c
server
github_2023
interval
typescript
getWorkers
function getWorkers(): number { const workers = Math.floor(os.cpus().length / 2 - 1) if (workers < 1) return 1 return workers }
/** * Reserve one core to run the web app when performing parallel tests. * * The default is NUM_CORES / 2, which is good on fast machines but can starve * the server on slower or throttled ones. We reduce that by one by default. * * This can be overridden using the `--workers` command line argument if * calling...
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/playwright.config.ts#L54-L60
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
createDevOrg
async function createDevOrg() { console.log('Creating dev org...') await upsertUser({ id: ADMIN_USER_ID, email: ADMIN_USER_EMAIL, password: encryptPassword(ADMIN_USER_PASSWORD), firstName: 'Admin', lastName: 'User', }) const acme = await upsertOrg({ id: 'RQ1FQoNTFCYe-W8RTGF1u', slu...
/** * Creates an organization for local development. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/prisma/seed.ts#L167-L347
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
createIntervalOrg
async function createIntervalOrg() { console.log('Creating internal Interval org...') const interval = await upsertOrg({ name: 'Interval', owner: { connect: { id: ADMIN_USER_ID, }, }, private: { create: {} }, id: 'URobaKdFwHieImSKFO37D', slug: 'interval', environment...
/** * Creates an internal "Interval" organization containing actions for * managing the Interval instance. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/prisma/seed.ts#L353-L429
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
useLoginRedirect
function useLoginRedirect() { const location = useLocation() const { loginRedirect: stateRedirect } = (location.state as Record<string, string | undefined | null>) || {} const setRecoilRedirect = useSetRecoilState(redirectAfterLogin) // updates recoil + localStorage if a redirect is found in the location s...
// Reads `loginRedirect` from the location state and adds it to recoil + localStorage
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/components/LoginRedirect.tsx#L15-L27
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
IVDialogWrapper
const IVDialogWrapper = (props: IVDialogProps) => { const dialog = useDialogState({ visible: true, }) return ( <div className="fixed inset-0 flex items-center justify-center"> <IVButton theme="primary" label="Open dialog" onClick={dialog.show} /> <IVDialog {...props} dialog={dialog} /> </...
/** * Dialogs are controlled by the `useDialogState` hook, so every story here * must use `DialogWrapper`. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/components/IVDialog/IVDialog.stories.tsx#L10-L21
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
applySortingAndFiltering
function applySortingAndFiltering(state: TableState) { if (!state.isFullTableInMemory) return state let filtered: BaseTableRecord<any>[] = state.data // filtering is always performed on the host when remote state is supported. if (!state.isRemote) { filtered = filterRows({ queryTerm: state.searchQue...
/** * Sorts and filters rows if the full table is in memory. * We do this outside of the reducer so we don't have to store * a copy of the unmodified data set in the state. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/components/IVTable/useTable.ts#L431-L456
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
prepareEmail
async function prepareEmail<T extends TemplateData>({ to, template, templateProps, subjectBuilder, }: PrepareEmailProps<T>): Promise<PreparedEmail> { const emailRenderProps = { ...templateProps, APP_URL: env.APP_URL } const from = env.EMAIL_FROM const subject = subjectBuilder(templateProps) const html ...
/** * Prepares an email to pass to a sender, such as Postmark. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/emails/sender.ts#L84-L97
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
sendResponse
function sendResponse( statusCode: number, returns: z.input<(typeof ENQUEUE_ACTION)['returns']> ) { res.status(statusCode).send(returns) }
// To ensure correct return type
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/api/actions.ts#L18-L23
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
sendResponse
function sendResponse( statusCode: number, returns: z.input<(typeof DEQUEUE_ACTION)['returns']> ) { res.status(statusCode).send(returns) }
// To ensure correct return type
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/api/actions.ts#L115-L120
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
randInt
function randInt(min, max) { return Math.floor(Math.random() * (max - min) + min) }
// src: https://futurestud.io/tutorials/generate-a-random-number-in-range-with-javascript-node-js
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/api/auth/ghost/generateRandomSlug.ts#L279-L281
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
randEl
function randEl(arr: string[]) { return arr[Math.floor(Math.random() * arr.length)] }
// https://stackoverflow.com/a/5915122
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/api/auth/ghost/generateRandomSlug.ts#L284-L286
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
shouldSkip
function shouldSkip(url: string): boolean { if (url.includes('/static/')) { return true } if (url.includes('hot-update.js')) { return true } return false }
// Skip some paths that are related to the static react app
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/middleware/requestLogger.ts#L14-L22
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
permissionsCodeToConfig
async function permissionsCodeToConfig({ access, organizationId, }: { access?: AccessControlDefinition | null organizationId: string }): Promise<{ availability: ActionAvailability | undefined teamPermissions: GroupPermissionDefinition[] | undefined warnings: string[] }> { const warnings: string[] = [] ...
/** * Converts code-based permissions into values for writing to the database. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/utils/actions.ts#L744-L802
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
canAccessEntityInTree
function canAccessEntityInTree( groupsMap: Map<string, ActionGroupLookupResult>, groupSlug: string ) { const group = groupsMap.get(groupSlug) if (group && group.canRun) return true if (group && group.actions.length > 0) return true const nestedGroups = Array.from(groupsMap.keys()).filter(slug => slug...
/** * Determines whether the user can access a group, actions in that group, * or any groups & their actions nested within the `groupSlug`. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/server/utils/actions.ts#L843-L864
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
userCanAccessAction
function userCanAccessAction( action: Prisma.ActionGetPayload<{ include: { metadata: { include: { accesses: true } } } }>, accessLevel: ActionAccessLevel ): boolean | undefined { // Should only receive own from backend if (action.developerId) return true if (action.metadata?.archivedAt) return false ...
/** * Determines whether the user can run the given action. * Does not check whether the user can run actions at all, do that elsewhere. * * Relies on the backend only returning their own development actions, and * only returning the user's own ActionAccesses. * * Returns `undefined` if availability is set to OR...
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/utils/actions.ts#L135-L159
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
getStyle
function getStyle(element: HTMLElement, prop: string) { return window.getComputedStyle(element, null).getPropertyValue(prop) }
// based on https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/utils/getTextWidth.ts#L2-L4
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
getNavPath
function getNavPath(path: string) { return path.replace(/^\/dashboard\/[0-9A-Za-z+_-]*/, '') }
/** * Returns the rest of the path after the `/dashboard/:orgSlug` prefix. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/utils/navigation.ts#L25-L27
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
triggerSubmit
function triggerSubmit(ev: KeyboardEvent) { const isModifierKeyPressed = didReportAsAppleDevice ? ev.metaKey : ev.ctrlKey if (isModifierKeyPressed && ev.key === 'Enter' && enabled) { formRef.current?.requestSubmit() } }
/* This seems convoluted (using formRef to call requestSubmit) but it's "on purpose:" - The value of onSubmit is _really_ unstable. The functions it calls like onRespond are not memoized - It's "safe" because it ensures CMD+Enter does _exactly_ what clicking "submit" would do */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/utils/useSubmitFormWithShortcut.ts#L16-L24
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
authMiddleware
function authMiddleware(req: Request, res: Response, next?: NextFunction) { const header = req.header('Authorization') const token = header?.split(' ')[1] if (token === encryptPassword(env.WSS_API_SECRET)) { next?.() return } res.status(401) res.end() }
// Very basic authentication layer that uses a shared secret
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/wss/index.ts#L20-L30
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
initializationFailure
function initializationFailure( message: string, sdkAlert?: SdkAlert ) { if (!sdkName || !sdkVersion) return null if (sdkName === NODE_SDK_NAME && sdkVersion >= '0.18.0') { return { type: 'error' as const, ...
/** * Returns an error response if the SDK supports it, or null otherwise indicating a general failure supported by all SDKs. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/wss/wss.ts#L541-L556
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
server
github_2023
interval
typescript
checkForUnreachableHosts
async function checkForUnreachableHosts() { try { // Do this with a raw query in order to use database time // instead of server time. await prisma.$queryRaw` update "HostInstance" set status = 'UNREACHABLE' where status = 'ONLINE' and "updatedAt" < (now() - '00:01:00'::interval) ` ...
/** * Set all hosts as UNREACHABLE if they haven't been touched * in the last minute. The periodic heartbeat will bump * this while the host is connected. */
https://github.com/interval/server/blob/e83ae439fb87cbc68fc0c765c4a7719dcfc16be9/src/wss/wss.ts#L2832-L2853
e83ae439fb87cbc68fc0c765c4a7719dcfc16be9
code-snippet-editor-plugin
github_2023
figma
typescript
performImport
function performImport(data: CodegenResultTemplatesByComponentKey) { const componentsByKey = getComponentsInFileByKey(); let componentCount = 0; for (let componentKey in data) { const component = componentsByKey[componentKey]; if (component) { componentCount++; setCodegenResultsInPluginData(co...
/** * Import code snippet templates into components in bulk via JSON. * https://github.com/figma/code-snippet-editor-plugin#importexport * @param data CodegenResultTemplatesByComponentKey * @returns void */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/bulk.ts#L21-L33
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
performExport
function performExport() { const data: CodegenResultTemplatesByComponentKey = {}; const components = findComponentNodesInFile(); components.forEach((component) => { const codegenResults = getCodegenResultsFromPluginData(component); if (codegenResults && codegenResults.length) { data[component.key] =...
/** * Export code snippet templates, posting stringified CodegenResultTemplatesByComponentKey to UI * https://github.com/figma/code-snippet-editor-plugin#importexport * @returns void */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/bulk.ts#L40-L54
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
findComponentNodesInFile
function findComponentNodesInFile() { if (figma.currentPage.parent) { return ( figma.currentPage.parent.findAllWithCriteria({ types: ["COMPONENT", "COMPONENT_SET"], }) || [] ); } return []; }
/** * Find all component and component set nodes in a file * @returns array of all components and component sets in a file. */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/bulk.ts#L60-L69
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
getComponentsInFileByKey
function getComponentsInFileByKey() { const components = findComponentNodesInFile(); const data: ComponentsByComponentKey = {}; components.forEach((component) => (data[component.key] = component)); return data; }
/** * Find all components and component sets in a file and return object of them by key. * @returns ComponentsByComponentKey */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/bulk.ts#L75-L80
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
initializeCodegenMode
function initializeCodegenMode() { /** * The preferences change event is fired when settings change from the codegen settings menu. * We only respond to this event when the user selects "Open Editor" * This is configured in manifest.json "codegenPreferences" as the "editor" action. */ figma.codegen.on("...
/** * In codegen mode (running in Dev Mode), the plugin returns codegen, * and can also open a UI "editor" for managing snippet templates. */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L23-L133
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
initializeDesignMode
function initializeDesignMode() { figma.ui.on("message", async (event: EventFromBulk) => { if (event.type === "BULK_INITIALIZE") { handleCurrentSelection(); } else if (event.type === "BULK_EXPORT") { bulk.performExport(); } else if (event.type === "BULK_IMPORT") { bulk.performImport(even...
/** * Running in design mode, we can perform bulk operations like import/export from JSON * and helpers for loading node data and component data. */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L139-L155
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
openCodeSnippetEditorUI
function openCodeSnippetEditorUI() { const { x, y, width, height } = figma.viewport.bounds; const absWidth = width * figma.viewport.zoom; const absHeight = height * figma.viewport.zoom; const finalWidth = Math.round( Math.max(Math.min(absWidth, 400), Math.min(absWidth * 0.6, 700)) ); const finalHeight =...
/** * This attempts to open the editor UI in a large, but unobtrusive way. * Real important math right here (jk, totally arbitrary). */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L161-L176
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
openTemplateUI
async function openTemplateUI() { figma.showUI(__uiFiles__.templates, { width: 600, height: 600, themeColors: true, }); const templates = (await getGlobalTemplatesFromClientStorage()) || "{}"; const message: EventToTemplates = { type: "TEMPLATES_INITIALIZE", templates }; figma.ui.postMessage(messa...
/** * Opening the UI for templates and sending a message with the initial template data */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L180-L189
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
codegenResultsFromNodeSnippetTemplateDataArray
function codegenResultsFromNodeSnippetTemplateDataArray( nodeSnippetTemplateDataArray: NodeSnippetTemplateData[], isDetailsMode: boolean ) { const codegenResult: CodegenResult[] = []; nodeSnippetTemplateDataArray.forEach((nodeSnippetTemplateData) => { const { codegenResultArray, codegenResultRawTemplatesArr...
/** * Final assembly of the codegen result that will include raw templates when in "details mode" * Can have additional things appended to it conditionally, but this yields the main snippet array. * https://github.com/figma/code-snippet-editor-plugin#details-mode * @param nodeSnippetTemplateDataArray the compiled c...
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L199-L221
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
handleCurrentSelection
function handleCurrentSelection() { const node = figma.currentPage.selection[0]; try { const nodePluginData = node ? getCodegenResultsFromPluginData(node) : null; const nodeId = node ? node.id : null; const nodeType = node ? node.type : null; const message: EventToEditor = { type: "EDITOR_SELE...
/** * Whenever the selection changes, we want to send information to an open UI if one exists. * Using try/catch as a lazy version of open UI detection. * @returns currently selected node */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/code.ts#L228-L246
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
paramsFromNode
async function paramsFromNode( node: BaseNode, propertiesOnly = false ): Promise<CodeSnippetParamsMap> { const { componentPropValuesMap, instanceParamsMap } = await componentPropertyDataFromNode(node); const params: CodeSnippetParams = {}; const paramsRaw: CodeSnippetParams = {}; for (let key in compone...
/** * Return the code snippet params for a node. * https://github.com/figma/code-snippet-editor-plugin#params * @param node the node we want params for * @param propertiesOnly a boolean flag to only return component property params * (only true when getting instance swap child properties) * @returns Promise that...
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L15-L60
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
componentPropertyDataFromNode
async function componentPropertyDataFromNode(node: BaseNode) { const componentPropObject = componentPropObjectFromNode(node); const componentPropValuesMap: ComponentPropValuesMap = {}; const isDefinitions = isComponentPropertyDefinitionsObject(componentPropObject); const instanceParamsMap: { [k: string]: Co...
/** * Given a node, find all the relevant component property data, including from instance swap property instances. * @param node the node to get component property data from * @returns componentPropValuesMap containing component property values * and instanceParamsMap object containing property params for instanc...
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L152-L188
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
nameFromFoundInstanceSwapNode
function nameFromFoundInstanceSwapNode(node: BaseNode | null) { return node && node.parent && node.parent.type === "COMPONENT_SET" ? node.parent.name : node ? node.name : ""; }
/** * Find the appropriate component name for an instance swap instance node * @param node implicitly an instance node to find a name for * @returns a name as a string */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L195-L201
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
initialParamsFromNode
async function initialParamsFromNode( node: BaseNode ): Promise<CodeSnippetParamsMap> { const componentNode = getComponentNodeFromNode(node); const css = await node.getCSSAsync(); const autolayout = "inferredAutoLayout" in node ? node.inferredAutoLayout : undefined; const paramsRaw: CodeSnippetParams = { ...
/** * Generate initial CodeSnippetParamsMap for a node, including autolayout, node, component, css, and variables. * Component property params are combined with this map later. * @param node node to generate initial params for * @returns Promise resolving an initial CodeSnippetParamsMap for the provided node */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L209-L323
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
isComponentPropertyDefinitionsObject
function isComponentPropertyDefinitionsObject( object: ComponentProperties | ComponentPropertyDefinitions ): object is ComponentPropertyDefinitions { return ( object[Object.keys(object)[0]] && "defaultValue" in object[Object.keys(object)[0]] ); }
/** * A util for typesafety that determines if an object * that can be ComponentProperties or ComponentPropertyDefinitions is the latter * @param object the object in question, ComponentProperties or ComponentPropertyDefinitions * @returns whether or not the object is ComponentProperties or ComponentPropertyDefini...
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L331-L338
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
componentPropObjectFromNode
function componentPropObjectFromNode( node: BaseNode ): ComponentProperties | ComponentPropertyDefinitions { if (node.type === "INSTANCE") return node.componentProperties; if (node.type === "COMPONENT_SET") return node.componentPropertyDefinitions; if (node.type === "COMPONENT") { if (node.parent && node.pa...
/** * Finding the right component property value object from the current node. * @param node the node in question, ignored if not component-like. * @returns ComponentProperties or ComponentPropertyDefinitions */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L345-L367
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
capitalize
function capitalize(name: string) { return `${name.charAt(0).toUpperCase()}${name.slice(1)}`; }
/** * Uppercase the first character in a string * @param name the string to capitalize * @returns capitalized string */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L374-L376
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09