repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
code-snippet-editor-plugin
github_2023
figma
typescript
downcase
function downcase(name: string) { return `${name.charAt(0).toLowerCase()}${name.slice(1)}`; }
/** * Lowercase the first character in a string * @param name the string to downcase * @returns downcased string */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L383-L385
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
numericGuard
function numericGuard(name = "") { if (name.charAt(0).match(/\d/)) { name = `N${name}`; } return name; }
/** * Ensure a string does not start with a number * @param name the string to guard that can start with a number * @returns string that starts with a letter */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L392-L397
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
capitalizedNameFromName
function capitalizedNameFromName(name = "") { name = numericGuard(name); return name .split(/[^a-zA-Z\d]+/g) .map(capitalize) .join(""); }
/** * Transform a string into a proper capitalized string that cannot start with a number * @param name the string to capitalize * @returns capitalized name */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L404-L410
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
sanitizePropertyName
function sanitizePropertyName(name: string) { name = name.replace(/#[^#]+$/g, ""); return downcase(capitalizedNameFromName(name).replace(/^\d+/g, "")); }
/** * A clean property name from a potentially gross string * @param name the name to sanitize * @returns a sanitized string */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L417-L420
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
getComponentNodeFromNode
function getComponentNodeFromNode( node: BaseNode ): ComponentNode | ComponentSetNode | null { const { type, parent } = node; const parentType = parent ? parent.type : ""; const isVariant = parentType === "COMPONENT_SET"; if (type === "COMPONENT_SET" || (type === "COMPONENT" && !isVariant)) { return node; } else if ( node.type === "COMPONENT" && node.parent && node.parent.type === "COMPONENT_SET" ) { return node.parent; } else if (type === "INSTANCE") { const { mainComponent } = node; return mainComponent ? mainComponent.parent && mainComponent.parent.type === "COMPONENT_SET" ? mainComponent.parent : mainComponent : null; } return null; }
/** * Get the appropriate topmost component node for a given node * @param node node to find the right component node for * @returns a component or component set node if it exists, otherwise null */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L427-L450
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
safeString
function safeString(string = "") { string = string.replace(/([^a-zA-Z0-9-_// ])/g, ""); if (!string.match(/^[A-Z0-9_]+$/)) { string = string.replace(/([A-Z])/g, " $1"); } return string .replace(/([a-z])([0-9])/g, "$1 $2") .replace(/([-_/])/g, " ") .replace(/ +/g, " ") .trim() .toLowerCase() .split(" ") .join("-"); }
/** * Turn any string into a safe, hyphenated lowercase string * @param string the string to transform * @returns the safe string */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/params.ts#L457-L470
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
valueIsCodegenLanguage
function valueIsCodegenLanguage( value: any ): value is CodegenResult["language"] { return CODEGEN_LANGUAGES.includes(value as CodegenResult["language"]); }
/** * Type safety function to return if the argument "value" is a valid CodegenResult["language"] * @param value the value to validate * @returns whether or not the value is a CodegenResult["language"] */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/pluginData.ts#L64-L68
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
objectIsCodegenResult
function objectIsCodegenResult(object: Object): object is CodegenResult { if (typeof object !== "object") return false; if (Object.keys(object).length !== 3) return false; if (!("title" in object && "code" in object && "language" in object)) return false; if (typeof object.title !== "string" || typeof object.code !== "string") return false; return valueIsCodegenLanguage(object.language); }
/** * Type safety function that validates if an object is a CodegenResult object * @param object the object to validate * @returns whether or not the object is a CodegenResult */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/pluginData.ts#L75-L83
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
arrayContainsCodegenResults
function arrayContainsCodegenResults(array: any): array is CodegenResult[] { let valid = true; if (Array.isArray(array)) { array.forEach((object) => { if (!objectIsCodegenResult(object)) { valid = false; } }); } else { valid = false; } return valid; }
/** * Type safety function that validates if an array is an array of CodeResult objects * @param array the array to validate * @returns whether or not the array is a CodegenResult[] */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/pluginData.ts#L90-L102
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
pluginDataStringAsValidCodegenResults
function pluginDataStringAsValidCodegenResults( pluginDataString: string ): CodegenResult[] | null { if (!pluginDataString) return null; try { const parsed = JSON.parse(pluginDataString); return arrayContainsCodegenResults(parsed) ? parsed : null; } catch (e) { return null; } }
/** * Given a JSON string from pluginData, return a valid CodegenResult[] or null if string is invalid * @param pluginDataString the string that may or may not be a JSON-stringified CodegenResult[] * @returns CodegenResult[] or null */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/pluginData.ts#L109-L119
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
unescapeBrackets
const unescapeBrackets = (line: string) => line.replace(/\\\{\{/g, "{{");
/** * Replacing escaped brackets with standard brackets. * Brackets only need to be escaped when used in a way that matches "{{...}}" * "\{{hi}}" becomes "{{hi}}" */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/snippets.ts#L27-L27
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
snippetTemplatesForNode
async function snippetTemplatesForNode( snippetNode: BaseNode, seenSnippetTemplates: { [k: string]: number }, globalTemplates: CodeSnippetGlobalTemplates, parentCodegenResult?: CodegenResult ) { const codegenResults = getCodegenResultsFromPluginData(snippetNode); const matchingTemplates = (templates: CodegenResult[]) => templates.filter( ({ title, language }) => !parentCodegenResult || (title === parentCodegenResult.title && language === parentCodegenResult.language) ); const matchingCodegenResults = matchingTemplates(codegenResults); const codegenResultTemplates: CodegenResult[] = []; if (matchingCodegenResults.length) { const seenKey = JSON.stringify(matchingCodegenResults); if (!seenSnippetTemplates[seenKey]) { seenSnippetTemplates[seenKey] = 1; codegenResultTemplates.push(...matchingCodegenResults); } } if (globalTemplates.components) { const componentTemplates = "key" in snippetNode ? globalTemplates.components[snippetNode.key] || [] : []; codegenResultTemplates.push(...matchingTemplates(componentTemplates)); } if ( !Object.keys(seenSnippetTemplates).length && !codegenResultTemplates.length && globalTemplates.types ) { const typeTemplates = globalTemplates.types[snippetNode.type] || []; const seenKey = JSON.stringify(typeTemplates); if (!seenSnippetTemplates[seenKey]) { seenSnippetTemplates[seenKey] = 1; const defaultTemplates = !typeTemplates.length && globalTemplates.types.DEFAULT ? globalTemplates.types.DEFAULT : []; codegenResultTemplates.push(...matchingTemplates(typeTemplates)); codegenResultTemplates.push(...matchingTemplates(defaultTemplates)); } } return codegenResultTemplates; }
/** * Process snippets for any node. Called multiple times up the lineage for component and instance nodes. * Instances have the same pluginData as their mainComponent, unless they have overridden the pluginData. * This tracks these duplicate cases in seenSnippetTemplates and filters them out. * @param snippetNode the node to check for templates in plugin data * @param seenSnippetTemplates a memo of seen snippet templates, so duplicates can be ignored * @param globalTemplates CodeSnippetGlobalTemplates object * @param parentCodegenResult If present, template language and title must match this. Used to filter out templates up front during recursion. * @returns Promise<void> will push into nodeSnippetTemplateDataArray. */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/snippets.ts#L188-L237
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
findChildrenSnippets
async function findChildrenSnippets( childrenSnippetParams: CodeSnippetParamsMap[], indent: string, recursionIndex: number, globalTemplates: CodeSnippetGlobalTemplates ): Promise<string> { const string: string[] = []; for (let childSnippetParams of childrenSnippetParams) { const snippetId = Object.keys(childSnippetParams.template)[0]; const template = childSnippetParams.template[snippetId]; if (template) { const hydrated = await hydrateCodeStringWithParams( template.code, childSnippetParams, snippetId, indent, recursionIndex, globalTemplates ); string.push(hydrated); } } return string.filter(Boolean).join("\n"); }
/** * * @param childrenSnippetParams an array of children snippet params map * @param indent indentation string * @param recursionIndex tracking recursion to prevent infinite loops * @param globalTemplates the CodeSnippetGlobalTemplates to reference * @returns a Promise that resolves a string of all children snippets with the right indentation. */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/snippets.ts#L431-L454
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
lineConditionalMatch
function lineConditionalMatch( line: string, params: CodeSnippetParams, templateChildren?: CodeSnippetParamsMap[] ): [RegExpMatchArray[], boolean] { /** * Line conditional statement matches. * {{?something=value}} * {{!something=value}} * {{?something}} * {{?something=value|something=other}} * {{?something=value&other=value}} */ const matches = [...line.matchAll(regexConditional)]; // No conditional statement on the line. This is valid. if (!matches.length) { return [[], true]; } let valid = true; matches.forEach((match) => { const [_, polarity, statements, matchSingle, matchOr, matchAnd] = match.map( (a) => (a ? a.trim() : a) ); const isNegative = polarity === "!"; const isPositive = polarity === "?"; const isSingle = Boolean(matchSingle); const isOr = Boolean(matchOr); const isAnd = Boolean(matchAnd); const subStatements = statements.split(isOr ? "|" : "&"); const results = subStatements.map((match) => { const matches = match.match(/([^=]+)(=([^\}]+))?/); if (matches) { const [_, symbol, equals, value] = matches; if (symbol === "figma.children") { if (!equals && templateChildren) { return Boolean(templateChildren.length); } return false; } else { const symbolIsDefined = symbol in params; const paramsMatch = params[symbol] === value; const presenceOnly = !Boolean(equals); return presenceOnly ? symbolIsDefined : paramsMatch; } } else { return false; } }); if (isNegative && results.includes(true)) { valid = false; } else if (isPositive) { if (isOr && !results.includes(true)) { valid = false; } else if ((isSingle || isAnd) && results.includes(false)) { valid = false; } } }); return [matches, valid]; }
/** * Handling any conditional statements and on a line of a template and determining whether or not to render. * No conditional statements is valid, and the line should render. * This only checks for conditional statements, symbols can still invalidate the line if the params dont exist. * @param line the line of snippet template to validate * @param params the params to use to validate or invalidate the line based on a conditional statement. * @returns array of the line's qualifing statements as RegExpMatchArray, and whether or not the line can render. */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/snippets.ts#L464-L529
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
code-snippet-editor-plugin
github_2023
figma
typescript
templatesIsCodeSnippetGlobalTemplates
function templatesIsCodeSnippetGlobalTemplates( templates: CodeSnippetGlobalTemplates | any ): templates is CodeSnippetGlobalTemplates { if (typeof templates === "object" && !Array.isArray(templates)) { const keys = Object.keys(templates); if (keys.find((k) => k !== "components" && k !== "types")) { return false; } return true; } return false; }
/** * Type safety function to indicate if item in clientStorage is CodeSnippetGlobalTemplates or not. * @param templates item in question * @returns whether or not the argument is CodeSnippetGlobalTemplates */
https://github.com/figma/code-snippet-editor-plugin/blob/ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09/src/templates.ts#L8-L19
ece47d8ccfa0f6ab6704ceab2cae11b8dc7d7c09
confluent-kafka-javascript
github_2023
confluentinc
typescript
token_refresh
async function token_refresh() { try { // Make a POST request to get the access token const response = await axios.post(issuerEndpointUrl, new URLSearchParams({ grant_type: 'client_credentials', client_id: oauthClientId, client_secret: oauthClientSecret, scope: scope }), { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); // Extract the token and expiration time from the response const token = response.data.access_token; const exp_seconds = Math.floor(Date.now() / 1000) + response.data.expires_in; const exp_ms = exp_seconds * 1000; const principal = 'admin'; // You can adjust this based on your needs const extensions = { traceId: '123', logicalCluster: kafkaLogicalCluster, identityPoolId: identityPoolId }; return { value: token, lifetime: exp_ms, principal, extensions }; } catch (error) { console.error('Failed to retrieve OAuth token:', error); throw new Error('Failed to retrieve OAuth token'); } }
// Only showing the producer, will be the same implementation for the consumer
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry-examples/src/kafka-oauth.ts#L17-L48
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RestError.constructor
constructor(message: string, status: number, errorCode: number) { super(message + "; Error code: " + errorCode); this.status = status; this.errorCode = errorCode; }
/** * Creates a new REST error. * @param message - The error message. * @param status - The HTTP status code. * @param errorCode - The error code. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rest-error.ts#L14-L18
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.constructor
constructor(config: ClientConfig) { this.clientConfig = config const cacheOptions = { max: config.cacheCapacity !== undefined ? config.cacheCapacity : 1000, ...(config.cacheLatestTtlSecs !== undefined && { ttl: config.cacheLatestTtlSecs * 1000 }) }; this.restService = new RestService(config.baseURLs, config.isForward, config.createAxiosDefaults, config.basicAuthCredentials, config.bearerAuthCredentials, config.maxRetries, config.retriesWaitMs, config.retriesMaxWaitMs); this.schemaToIdCache = new LRUCache(cacheOptions); this.idToSchemaInfoCache = new LRUCache(cacheOptions); this.infoToSchemaCache = new LRUCache(cacheOptions); this.latestToSchemaCache = new LRUCache(cacheOptions); this.schemaToVersionCache = new LRUCache(cacheOptions); this.versionToSchemaCache = new LRUCache(cacheOptions); this.metadataToSchemaCache = new LRUCache(cacheOptions); this.schemaToIdMutex = new Mutex(); this.idToSchemaInfoMutex = new Mutex(); this.infoToSchemaMutex = new Mutex(); this.latestToSchemaMutex = new Mutex(); this.schemaToVersionMutex = new Mutex(); this.versionToSchemaMutex = new Mutex(); this.metadataToSchemaMutex = new Mutex(); }
/** * Create a new Schema Registry client. * @param config - The client configuration. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L197-L222
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.register
async register(subject: string, schema: SchemaInfo, normalize: boolean = false): Promise<number> { const metadataResult = await this.registerFullResponse(subject, schema, normalize); return metadataResult.id; }
/** * Register a schema with the Schema Registry and return the schema ID. * @param subject - The subject under which to register the schema. * @param schema - The schema to register. * @param normalize - Whether to normalize the schema before registering. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L242-L246
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.registerFullResponse
async registerFullResponse(subject: string, schema: SchemaInfo, normalize: boolean = false): Promise<SchemaMetadata> { const cacheKey = stringify({ subject, schema: minimize(schema) }); return await this.infoToSchemaMutex.runExclusive(async () => { const cachedSchemaMetadata: SchemaMetadata | undefined = this.infoToSchemaCache.get(cacheKey); if (cachedSchemaMetadata) { return cachedSchemaMetadata; } subject = encodeURIComponent(subject); const response: AxiosResponse<SchemaMetadata> = await this.restService.handleRequest( `/subjects/${subject}/versions?normalize=${normalize}`, 'POST', schema ); this.infoToSchemaCache.set(cacheKey, response.data); return response.data; }); }
/** * Register a schema with the Schema Registry and return the full response. * @param subject - The subject under which to register the schema. * @param schema - The schema to register. * @param normalize - Whether to normalize the schema before registering. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L254-L273
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getBySubjectAndId
async getBySubjectAndId(subject: string, id: number, format?: string): Promise<SchemaInfo> { const cacheKey = stringify({ subject, id }); return await this.idToSchemaInfoMutex.runExclusive(async () => { const cachedSchema: SchemaInfo | undefined = this.idToSchemaInfoCache.get(cacheKey); if (cachedSchema) { return cachedSchema; } subject = encodeURIComponent(subject); let formatStr = format != null ? `&format=${format}` : ''; const response: AxiosResponse<SchemaInfo> = await this.restService.handleRequest( `/schemas/ids/${id}?subject=${subject}${formatStr}`, 'GET' ); this.idToSchemaInfoCache.set(cacheKey, response.data); return response.data; }); }
/** * Get a schema by subject and ID. * @param subject - The subject under which the schema is registered. * @param id - The schema ID. * @param format - The format of the schema. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L281-L300
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getId
async getId(subject: string, schema: SchemaInfo, normalize: boolean = false): Promise<number> { const cacheKey = stringify({ subject, schema: minimize(schema) }); return await this.schemaToIdMutex.runExclusive(async () => { const cachedId: number | undefined = this.schemaToIdCache.get(cacheKey); if (cachedId) { return cachedId; } subject = encodeURIComponent(subject); const response: AxiosResponse<SchemaMetadata> = await this.restService.handleRequest( `/subjects/${subject}?normalize=${normalize}`, 'POST', schema ); this.schemaToIdCache.set(cacheKey, response.data.id); return response.data.id; }); }
/** * Get the ID for a schema. * @param subject - The subject under which the schema is registered. * @param schema - The schema whose ID to get. * @param normalize - Whether to normalize the schema before getting the ID. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L308-L327
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getLatestSchemaMetadata
async getLatestSchemaMetadata(subject: string, format?: string): Promise<SchemaMetadata> { return await this.latestToSchemaMutex.runExclusive(async () => { const cachedSchema: SchemaMetadata | undefined = this.latestToSchemaCache.get(subject); if (cachedSchema) { return cachedSchema; } subject = encodeURIComponent(subject); let formatStr = format != null ? `?format=${format}` : ''; const response: AxiosResponse<SchemaMetadata> = await this.restService.handleRequest( `/subjects/${subject}/versions/latest${formatStr}`, 'GET' ); this.latestToSchemaCache.set(subject, response.data); return response.data; }); }
/** * Get the latest schema metadata for a subject. * @param subject - The subject for which to get the latest schema metadata. * @param format - The format of the schema. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L334-L352
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getSchemaMetadata
async getSchemaMetadata(subject: string, version: number, deleted: boolean = false, format?: string): Promise<SchemaMetadata> { const cacheKey = stringify({ subject, version, deleted }); return await this.versionToSchemaMutex.runExclusive(async () => { const cachedSchemaMetadata: SchemaMetadata | undefined = this.versionToSchemaCache.get(cacheKey); if (cachedSchemaMetadata) { return cachedSchemaMetadata; } subject = encodeURIComponent(subject); let formatStr = format != null ? `&format=${format}` : ''; const response: AxiosResponse<SchemaMetadata> = await this.restService.handleRequest( `/subjects/${subject}/versions/${version}?deleted=${deleted}${formatStr}`, 'GET' ); this.versionToSchemaCache.set(cacheKey, response.data); return response.data; }); }
/** * Get the schema metadata for a subject and version. * @param subject - The subject for which to get the schema metadata. * @param version - The version of the schema. * @param deleted - Whether to include deleted schemas. * @param format - The format of the schema. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L361-L381
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getLatestWithMetadata
async getLatestWithMetadata(subject: string, metadata: { [key: string]: string }, deleted: boolean = false, format?: string): Promise<SchemaMetadata> { const cacheKey = stringify({ subject, metadata, deleted }); return await this.metadataToSchemaMutex.runExclusive(async () => { const cachedSchemaMetadata: SchemaMetadata | undefined = this.metadataToSchemaCache.get(cacheKey); if (cachedSchemaMetadata) { return cachedSchemaMetadata; } subject = encodeURIComponent(subject); let metadataStr = ''; for (const key in metadata) { const encodedKey = encodeURIComponent(key); const encodedValue = encodeURIComponent(metadata[key]); metadataStr += `&key=${encodedKey}&value=${encodedValue}`; } let formatStr = format != null ? `&format=${format}` : ''; const response: AxiosResponse<SchemaMetadata> = await this.restService.handleRequest( `/subjects/${subject}/metadata?deleted=${deleted}&${metadataStr}${formatStr}`, 'GET' ); this.metadataToSchemaCache.set(cacheKey, response.data); return response.data; }); }
/** * Get the latest schema metadata for a subject with the given metadata. * @param subject - The subject for which to get the latest schema metadata. * @param metadata - The metadata to match. * @param deleted - Whether to include deleted schemas. * @param format - The format of the schema. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L390-L419
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getAllVersions
async getAllVersions(subject: string): Promise<number[]> { const response: AxiosResponse<number[]> = await this.restService.handleRequest( `/subjects/${subject}/versions`, 'GET' ); return response.data; }
/** * Get all versions of a schema for a subject. * @param subject - The subject for which to get all versions. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L425-L431
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getVersion
async getVersion(subject: string, schema: SchemaInfo, normalize: boolean = false, deleted: boolean = false): Promise<number> { const cacheKey = stringify({ subject, schema: minimize(schema), deleted }); return await this.schemaToVersionMutex.runExclusive(async () => { const cachedVersion: number | undefined = this.schemaToVersionCache.get(cacheKey); if (cachedVersion) { return cachedVersion; } subject = encodeURIComponent(subject); const response: AxiosResponse<SchemaMetadata> = await this.restService.handleRequest( `/subjects/${subject}?normalize=${normalize}&deleted=${deleted}`, 'POST', schema ); this.schemaToVersionCache.set(cacheKey, response.data.version); return response.data.version!; }); }
/** * Get the version of a schema for a subject. * @param subject - The subject for which to get the version. * @param schema - The schema for which to get the version. * @param normalize - Whether to normalize the schema before getting the version. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L439-L459
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getAllSubjects
async getAllSubjects(): Promise<string[]> { const response: AxiosResponse<string[]> = await this.restService.handleRequest( `/subjects`, 'GET' ); return response.data; }
/** * Get all subjects in the Schema Registry. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L464-L470
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.deleteSubject
async deleteSubject(subject: string, permanent: boolean = false): Promise<number[]> { await this.infoToSchemaMutex.runExclusive(async () => { this.infoToSchemaCache.forEach((_, key) => { const parsedKey = JSON.parse(key); if (parsedKey.subject === subject) { this.infoToSchemaCache.delete(key); } }); }); await this.schemaToVersionMutex.runExclusive(async () => { this.schemaToVersionCache.forEach((_, key) => { const parsedKey = JSON.parse(key); if (parsedKey.subject === subject) { this.schemaToVersionCache.delete(key); } }); }); await this.versionToSchemaMutex.runExclusive(async () => { this.versionToSchemaCache.forEach((_, key) => { const parsedKey = JSON.parse(key); if (parsedKey.subject === subject) { this.versionToSchemaCache.delete(key); } }); }); await this.idToSchemaInfoMutex.runExclusive(async () => { this.idToSchemaInfoCache.forEach((_, key) => { const parsedKey = JSON.parse(key); if (parsedKey.subject === subject) { this.idToSchemaInfoCache.delete(key); } }); }); subject = encodeURIComponent(subject); const response: AxiosResponse<number[]> = await this.restService.handleRequest( `/subjects/${subject}?permanent=${permanent}`, 'DELETE' ); return response.data; }
/** * Delete a subject from the Schema Registry. * @param subject - The subject to delete. * @param permanent - Whether to permanently delete the subject. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L477-L521
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.deleteSubjectVersion
async deleteSubjectVersion(subject: string, version: number, permanent: boolean = false): Promise<number> { return await this.schemaToVersionMutex.runExclusive(async () => { let metadataValue: SchemaMetadata | undefined; this.schemaToVersionCache.forEach((value, key) => { const parsedKey = JSON.parse(key); if (parsedKey.subject === subject && value === version) { this.schemaToVersionCache.delete(key); const infoToSchemaCacheKey = stringify({ subject: subject, schema: minimize(parsedKey.schema) }); this.infoToSchemaMutex.runExclusive(async () => { metadataValue = this.infoToSchemaCache.get(infoToSchemaCacheKey); if (metadataValue) { this.infoToSchemaCache.delete(infoToSchemaCacheKey); const cacheKeyID = stringify({ subject: subject, id: metadataValue.id }); this.idToSchemaInfoMutex.runExclusive(async () => { this.idToSchemaInfoCache.delete(cacheKeyID); }); } }); } }); const cacheKey = stringify({ subject: subject, version: version }); this.versionToSchemaMutex.runExclusive(async () => { this.versionToSchemaCache.delete(cacheKey); }); subject = encodeURIComponent(subject); const response: AxiosResponse<number> = await this.restService.handleRequest( `/subjects/${subject}/versions/${version}?permanent=${permanent}`, 'DELETE' ); return response.data; }); }
/** * Delete a version of a subject from the Schema Registry. * @param subject - The subject to delete. * @param version - The version to delete. * @param permanent - Whether to permanently delete the version. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L529-L566
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.testSubjectCompatibility
async testSubjectCompatibility(subject: string, schema: SchemaInfo): Promise<boolean> { subject = encodeURIComponent(subject); const response: AxiosResponse<isCompatibleResponse> = await this.restService.handleRequest( `/compatibility/subjects/${subject}/versions/latest`, 'POST', schema ); return response.data.is_compatible; }
/** * Test the compatibility of a schema with the latest schema for a subject. * @param subject - The subject for which to test compatibility. * @param schema - The schema to test compatibility. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L573-L582
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.testCompatibility
async testCompatibility(subject: string, version: number, schema: SchemaInfo): Promise<boolean> { subject = encodeURIComponent(subject); const response: AxiosResponse<isCompatibleResponse> = await this.restService.handleRequest( `/compatibility/subjects/${subject}/versions/${version}`, 'POST', schema ); return response.data.is_compatible; }
/** * Test the compatibility of a schema with a specific version of a subject. * @param subject - The subject for which to test compatibility. * @param version - The version of the schema for which to test compatibility. * @param schema - The schema to test compatibility. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L590-L599
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getCompatibility
async getCompatibility(subject: string): Promise<Compatibility> { subject = encodeURIComponent(subject); const response: AxiosResponse<CompatibilityLevel> = await this.restService.handleRequest( `/config/${subject}`, 'GET' ); return response.data.compatibilityLevel!; }
/** * Get the compatibility level for a subject. * @param subject - The subject for which to get the compatibility level. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L605-L613
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.updateCompatibility
async updateCompatibility(subject: string, update: Compatibility): Promise<Compatibility> { subject = encodeURIComponent(subject); const response: AxiosResponse<CompatibilityLevel> = await this.restService.handleRequest( `/config/${subject}`, 'PUT', { compatibility: update } ); return response.data.compatibility!; }
/** * Update the compatibility level for a subject. * @param subject - The subject for which to update the compatibility level. * @param update - The compatibility level to update to. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L620-L629
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getDefaultCompatibility
async getDefaultCompatibility(): Promise<Compatibility> { const response: AxiosResponse<CompatibilityLevel> = await this.restService.handleRequest( `/config`, 'GET' ); return response.data.compatibilityLevel!; }
/** * Get the default/global compatibility level. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L634-L640
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.updateDefaultCompatibility
async updateDefaultCompatibility(update: Compatibility): Promise<Compatibility> { const response: AxiosResponse<CompatibilityLevel> = await this.restService.handleRequest( `/config`, 'PUT', { compatibility: update } ); return response.data.compatibility!; }
/** * Update the default/global compatibility level. * @param update - The compatibility level to update to. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L646-L653
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getConfig
async getConfig(subject: string): Promise<ServerConfig> { subject = encodeURIComponent(subject); const response: AxiosResponse<ServerConfig> = await this.restService.handleRequest( `/config/${subject}`, 'GET' ); return response.data; }
/** * Get the config for a subject. * @param subject - The subject for which to get the config. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L659-L667
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.updateConfig
async updateConfig(subject: string, update: ServerConfig): Promise<ServerConfig> { const response: AxiosResponse<ServerConfig> = await this.restService.handleRequest( `/config/${subject}`, 'PUT', update ); return response.data; }
/** * Update the config for a subject. * @param subject - The subject for which to update the config. * @param update - The config to update to. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L674-L681
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.getDefaultConfig
async getDefaultConfig(): Promise<ServerConfig> { const response: AxiosResponse<ServerConfig> = await this.restService.handleRequest( `/config`, 'GET' ); return response.data; }
/** * Get the default/global config. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L686-L692
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.updateDefaultConfig
async updateDefaultConfig(update: ServerConfig): Promise<ServerConfig> { const response: AxiosResponse<ServerConfig> = await this.restService.handleRequest( `/config`, 'PUT', update ); return response.data; }
/** * Update the default/global config. * @param update - The config to update to. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L698-L705
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.clearLatestCaches
clearLatestCaches(): void { this.latestToSchemaCache.clear(); this.metadataToSchemaCache.clear(); }
/** * Clear the latest caches. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L710-L713
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.clearCaches
clearCaches(): void { this.schemaToIdCache.clear(); this.idToSchemaInfoCache.clear(); this.infoToSchemaCache.clear(); this.latestToSchemaCache.clear(); this.schemaToVersionCache.clear(); this.versionToSchemaCache.clear(); this.metadataToSchemaCache.clear(); }
/** * Clear all caches. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L718-L726
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.close
async close(): Promise<void> { this.clearCaches(); }
/** * Close the client. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L731-L733
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
SchemaRegistryClient.addToInfoToSchemaCache
async addToInfoToSchemaCache(subject: string, schema: SchemaInfo, metadata: SchemaMetadata): Promise<void> { const cacheKey = stringify({ subject, schema: minimize(schema) }); await this.infoToSchemaMutex.runExclusive(async () => { this.infoToSchemaCache.set(cacheKey, metadata); }); }
// Cache methods for testing
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/schemaregistry-client.ts#L736-L741
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
FieldEncryptionExecutor.register
static register(): FieldEncryptionExecutor { return this.registerWithClock(new Clock()) }
/** * Register the field encryption executor with the rule registry. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/encrypt-executor.ts#L71-L73
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
AwsKmsDriver.register
static register(): void { registerKmsDriver(new AwsKmsDriver()) }
/** * Register the AWS KMS driver with the KMS registry. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/awskms/aws-driver.ts#L19-L21
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
AzureKmsDriver.register
static register(): void { registerKmsDriver(new AzureKmsDriver()) }
/** * Register the Azure KMS driver with the KMS registry. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/azurekms/azure-driver.ts#L15-L17
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
DekRegistryClient.checkLatestDekInCache
async checkLatestDekInCache(kekName: string, subject: string, algorithm: string): Promise<boolean> { const cacheKey = stringify({ kekName, subject, version: -1, algorithm, deleted: false }); const cachedDek = this.dekCache.get(cacheKey); return cachedDek !== undefined; }
//Cache methods for testing
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/dekregistry/dekregistry-client.ts#L246-L250
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
GcpKmsDriver.register
static register(): void { registerKmsDriver(new GcpKmsDriver()) }
/** * Register the GCP KMS driver with the KMS registry. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/gcpkms/gcp-driver.ts#L16-L18
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
HcVaultDriver.register
static register(): void { registerKmsDriver(new HcVaultDriver()) }
/** * Register the HashiCorp Vault driver with the KMS registry. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/hcvault/hcvault-driver.ts#L13-L15
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
LocalKmsDriver.register
static register(): void { registerKmsDriver(new LocalKmsDriver()) }
/** * Register the local KMS driver with the KMS registry. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/localkms/local-driver.ts#L12-L14
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
AesGcm.encrypt
async encrypt(plaintext: Uint8Array, associatedData?: Uint8Array): Promise<Uint8Array> { Validators.requireUint8Array(plaintext); if (associatedData != null) { Validators.requireUint8Array(associatedData); } const iv = Random.randBytes(IV_SIZE_IN_BYTES); const alg: AesGcmParams = { 'name': 'AES-GCM', 'iv': iv, 'tagLength': TAG_SIZE_IN_BITS }; if (associatedData) { alg['additionalData'] = associatedData; } const ciphertext = await crypto.subtle.encrypt(alg, this.key, plaintext); return Bytes.concat(iv, new Uint8Array(ciphertext)); }
/** */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/tink/aes_gcm.ts#L37-L55
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
AesGcm.decrypt
async decrypt(ciphertext: Uint8Array, associatedData?: Uint8Array): Promise<Uint8Array> { Validators.requireUint8Array(ciphertext); if (ciphertext.length < IV_SIZE_IN_BYTES + TAG_SIZE_IN_BITS / 8) { throw new SecurityException('ciphertext too short'); } if (associatedData != null) { Validators.requireUint8Array(associatedData); } const iv = new Uint8Array(IV_SIZE_IN_BYTES); iv.set(ciphertext.subarray(0, IV_SIZE_IN_BYTES)); const alg: AesGcmParams = { 'name': 'AES-GCM', 'iv': iv, 'tagLength': TAG_SIZE_IN_BITS }; if (associatedData) { alg['additionalData'] = associatedData; } try { return new Uint8Array(await crypto.subtle.decrypt( alg, this.key, new Uint8Array(ciphertext.subarray(IV_SIZE_IN_BYTES)))); // Preserving old behavior when moving to // https://www.typescriptlang.org/tsconfig#useUnknownInCatchVariables // tslint:disable-next-line:no-any } catch (e: any) { throw new SecurityException(e.toString()); } }
/** */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/tink/aes_gcm.ts#L59-L88
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
AesSiv.encrypt
async encrypt(plaintext: Uint8Array, associatedData?: Uint8Array): Promise<Uint8Array> { let key = await SIV.importKey(this.key, "AES-CMAC-SIV", new SoftCryptoProvider()); return key.seal(plaintext, associatedData != null ? [associatedData] : []); }
/** */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/tink/aes_siv.ts#L22-L26
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
AesSiv.decrypt
async decrypt(ciphertext: Uint8Array, associatedData?: Uint8Array): Promise<Uint8Array> { let key = await SIV.importKey(this.key, "AES-CMAC-SIV", new SoftCryptoProvider()); return key.open(ciphertext, associatedData != null? [associatedData] : []); }
/** */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/tink/aes_siv.ts#L30-L34
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
Hmac.constructor
constructor( private readonly hash: string, private readonly key: CryptoKey, private readonly tagSize: number) { super(); }
/** * @param hash - accepted names are SHA-1, SHA-256 and SHA-512 * @param tagSize - the size of the tag */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/tink/hmac.ts#L28-L32
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
Hmac.computeMac
async computeMac(data: Uint8Array): Promise<Uint8Array> { Validators.requireUint8Array(data); const tag = await crypto.subtle.sign( {'name': 'HMAC', 'hash': {'name': this.hash}}, this.key, data); return new Uint8Array(tag.slice(0, this.tagSize)); }
/** */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/tink/hmac.ts#L36-L41
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
Hmac.verifyMac
async verifyMac(tag: Uint8Array, data: Uint8Array): Promise<boolean> { Validators.requireUint8Array(tag); Validators.requireUint8Array(data); const computedTag = await this.computeMac(data); return Bytes.isEqual(tag, computedTag); }
/** */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/encryption/tink/hmac.ts#L45-L50
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
JsonataExecutor.register
static register(): JsonataExecutor { const executor = new JsonataExecutor() RuleRegistry.registerRuleExecutor(executor) return executor }
/** * Register the JSONata rule executor with the rule registry. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/rules/jsonata/jsonata-executor.ts#L14-L18
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
AvroSerializer.constructor
constructor(client: Client, serdeType: SerdeType, conf: AvroSerializerConfig, ruleRegistry?: RuleRegistry) { super(client, serdeType, conf, ruleRegistry) this.schemaToTypeCache = new LRUCache<string, [Type, Map<string, string>]>({ max: this.conf.cacheCapacity ?? 1000 }) this.fieldTransformer = async (ctx: RuleContext, fieldTransform: FieldTransform, msg: any) => { return await this.fieldTransform(ctx, fieldTransform, msg) } for (const rule of this.ruleRegistry.getExecutors()) { rule.configure(client.config(), new Map<string, string>(Object.entries(conf.ruleConfig ?? {}))) } }
/** * Create a new AvroSerializer. * @param client - the schema registry client * @param serdeType - the type of the serializer * @param conf - the serializer configuration * @param ruleRegistry - the rule registry */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/avro.ts#L50-L59
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
AvroSerializer.serialize
override async serialize(topic: string, msg: any): Promise<Buffer> { if (this.client == null) { throw new Error('client is not initialized') } if (msg == null) { throw new Error('message is empty') } let schema: SchemaInfo | undefined = undefined // Don't derive the schema if it is being looked up in the following ways if (this.config().useSchemaId == null && !this.config().useLatestVersion && this.config().useLatestWithMetadata == null) { const avroSchema = AvroSerializer.messageToSchema(msg) schema = { schemaType: 'AVRO', schema: JSON.stringify(avroSchema), } } const [id, info] = await this.getId(topic, msg, schema) let avroType: avro.Type let deps: Map<string, string> [avroType, deps] = await this.toType(info) const subject = this.subjectName(topic, info) msg = await this.executeRules( subject, topic, RuleMode.WRITE, null, info, msg, getInlineTags(info, deps)) const msgBytes = avroType.toBuffer(msg) return this.writeBytes(id, msgBytes) }
/** * serialize is used to serialize a message using Avro. * @param topic - the topic to serialize the message for * @param msg - the message to serialize */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/avro.ts#L66-L94
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
AvroDeserializer.constructor
constructor(client: Client, serdeType: SerdeType, conf: AvroDeserializerConfig, ruleRegistry?: RuleRegistry) { super(client, serdeType, conf, ruleRegistry) this.schemaToTypeCache = new LRUCache<string, [Type, Map<string, string>]>({ max: this.conf.cacheCapacity ?? 1000 }) this.fieldTransformer = async (ctx: RuleContext, fieldTransform: FieldTransform, msg: any) => { return await this.fieldTransform(ctx, fieldTransform, msg) } for (const rule of this.ruleRegistry.getExecutors()) { rule.configure(client.config(), new Map<string, string>(Object.entries(conf.ruleConfig ?? {}))) } }
/** * Create a new AvroDeserializer. * @param client - the schema registry client * @param serdeType - the type of the deserializer * @param conf - the deserializer configuration * @param ruleRegistry - the rule registry */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/avro.ts#L156-L165
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
getInlineTagsRecursively
function getInlineTagsRecursively(ns: string, name: string, schema: any, tags: Map<string, Set<string>>): void { if (schema == null || typeof schema === 'string') { return } else if (Array.isArray(schema)) { for (let i = 0; i < schema.length; i++) { getInlineTagsRecursively(ns, name, schema[i], tags) } } else if (typeof schema === 'object') { const type = schema['type'] switch (type) { case 'array': getInlineTagsRecursively(ns, name, schema['items'], tags) break; case 'map': getInlineTagsRecursively(ns, name, schema['values'], tags) break; case 'record': let recordNs = schema['namespace'] let recordName = schema['name'] if (recordNs === undefined) { recordNs = impliedNamespace(name) } if (recordNs == null) { recordNs = ns } if (recordNs !== '' && !recordName.startsWith(recordNs)) { recordName = recordNs + '.' + recordName } const fields = schema['fields'] for (const field of fields) { const fieldTags = field['confluent:tags'] const fieldName = field['name'] if (fieldTags !== undefined && fieldName !== undefined) { tags.set(recordName + '.' + fieldName, new Set(fieldTags)) } const fieldType = field['type'] if (fieldType !== undefined) { getInlineTagsRecursively(recordNs, recordName, fieldType, tags) } } break; } } }
// iterate over the object and get all properties named 'confluent:tags'
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/avro.ts#L424-L467
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
BufferWrapper.writeVarInt
writeVarInt(n: number): void { let f, m if (n >= -1073741824 && n < 1073741824) { // Won't overflow, we can use integer arithmetic. m = n >= 0 ? n << 1 : (~n << 1) | 1 do { this.buf[this.pos] = m & 0x7f m >>= 7 } while (m && (this.buf[this.pos++] |= 0x80)) } else { // We have to use slower floating arithmetic. f = n >= 0 ? n * 2 : -n * 2 - 1 do { this.buf[this.pos] = f & 0x7f f /= 128 } while (f >= 1 && (this.buf[this.pos++] |= 0x80)) } this.pos++ }
// Adapted from avro-js
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/buffer-wrapper.ts#L15-L34
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
BufferWrapper.readVarInt
readVarInt(): number { let n = 0 let k = 0 let b, h, f, fk do { b = this.buf[this.pos++] h = b & 0x80 n |= (b & 0x7f) << k k += 7 } while (h && k < 28) if (h) { // Switch to float arithmetic, otherwise we might overflow. f = n fk = 268435456 // 2 ** 28. do { b = this.buf[this.pos++] f += (b & 0x7f) * fk fk *= 128 } while (b & 0x80) return (f % 2 ? -(f + 1) : f) / 2 } return (n >> 1) ^ -(n & 1) }
// Adapted from avro-js
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/buffer-wrapper.ts#L37-L62
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
JsonSerializer.constructor
constructor(client: Client, serdeType: SerdeType, conf: JsonSerializerConfig, ruleRegistry?: RuleRegistry) { super(client, serdeType, conf, ruleRegistry) this.schemaToTypeCache = new LRUCache<string, DereferencedJSONSchema>({ max: this.config().cacheCapacity ?? 1000 }) this.schemaToValidateCache = new LRUCache<string, ValidateFunction>({ max: this.config().cacheCapacity ?? 1000 }) this.fieldTransformer = async (ctx: RuleContext, fieldTransform: FieldTransform, msg: any) => { return await this.fieldTransform(ctx, fieldTransform, msg) } for (const rule of this.ruleRegistry.getExecutors()) { rule.configure(client.config(), new Map<string, string>(Object.entries(conf.ruleConfig ?? {}))) } }
/** * Creates a new JsonSerializer. * @param client - the schema registry client * @param serdeType - the serializer type * @param conf - the serializer configuration * @param ruleRegistry - the rule registry */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/json.ts#L69-L79
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
JsonSerializer.serialize
override async serialize(topic: string, msg: any): Promise<Buffer> { if (this.client == null) { throw new Error('client is not initialized') } if (msg == null) { throw new Error('message is empty') } let schema: SchemaInfo | undefined = undefined // Don't derive the schema if it is being looked up in the following ways if (this.config().useSchemaId == null && !this.config().useLatestVersion && this.config().useLatestWithMetadata == null) { const jsonSchema = JsonSerializer.messageToSchema(msg) schema = { schemaType: 'JSON', schema: JSON.stringify(jsonSchema), } } const [id, info] = await this.getId(topic, msg, schema) const subject = this.subjectName(topic, info) msg = await this.executeRules(subject, topic, RuleMode.WRITE, null, info, msg, null) const msgBytes = Buffer.from(JSON.stringify(msg)) if ((this.conf as JsonSerdeConfig).validate) { const validate = await this.toValidateFunction(info) if (validate != null && !validate(msg)) { throw new SerializationError('Invalid message') } } return this.writeBytes(id, msgBytes) }
/** * Serializes a message. * @param topic - the topic * @param msg - the message */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/json.ts#L86-L116
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
JsonDeserializer.constructor
constructor(client: Client, serdeType: SerdeType, conf: JsonDeserializerConfig, ruleRegistry?: RuleRegistry) { super(client, serdeType, conf, ruleRegistry) this.schemaToTypeCache = new LRUCache<string, DereferencedJSONSchema>({ max: this.config().cacheCapacity ?? 1000 }) this.schemaToValidateCache = new LRUCache<string, ValidateFunction>({ max: this.config().cacheCapacity ?? 1000 }) this.fieldTransformer = async (ctx: RuleContext, fieldTransform: FieldTransform, msg: any) => { return await this.fieldTransform(ctx, fieldTransform, msg) } for (const rule of this.ruleRegistry.getExecutors()) { rule.configure(client.config(), new Map<string, string>(Object.entries(conf.ruleConfig ?? {}))) } }
/** * Creates a new JsonDeserializer. * @param client - the schema registry client * @param serdeType - the deserializer type * @param conf - the deserializer configuration * @param ruleRegistry - the rule registry */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/json.ts#L167-L177
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
JsonDeserializer.deserialize
override async deserialize(topic: string, payload: Buffer): Promise<any> { if (!Buffer.isBuffer(payload)) { throw new Error('Invalid buffer') } if (payload.length === 0) { return null } const info = await this.getSchema(topic, payload) const subject = this.subjectName(topic, info) const readerMeta = await this.getReaderSchema(subject) let migrations: Migration[] = [] if (readerMeta != null) { migrations = await this.getMigrations(subject, info, readerMeta) } const msgBytes = payload.subarray(5) let msg = JSON.parse(msgBytes.toString()) if (migrations.length > 0) { msg = await this.executeMigrations(migrations, subject, topic, msg) } let target: SchemaInfo if (readerMeta != null) { target = readerMeta } else { target = info } msg = this.executeRules(subject, topic, RuleMode.READ, null, target, msg, null) if ((this.conf as JsonSerdeConfig).validate) { const validate = await this.toValidateFunction(info) if (validate != null && !validate(JSON.parse(msg))) { throw new SerializationError('Invalid message') } } return msg }
/** * Deserializes a message. * @param topic - the topic * @param payload - the message payload */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/json.ts#L184-L218
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
ProtobufSerializer.constructor
constructor(client: Client, serdeType: SerdeType, conf: ProtobufSerializerConfig, ruleRegistry?: RuleRegistry) { super(client, serdeType, conf, ruleRegistry) this.registry = conf.registry ?? createMutableRegistry() this.fileRegistry = createFileRegistry() this.schemaToDescCache = new LRUCache<string, DescFile>({ max: this.config().cacheCapacity ?? 1000 } ) this.descToSchemaCache = new LRUCache<string, SchemaInfo>({ max: this.config().cacheCapacity ?? 1000 } ) this.fieldTransformer = async (ctx: RuleContext, fieldTransform: FieldTransform, msg: any) => { return await this.fieldTransform(ctx, fieldTransform, msg) } for (const rule of this.ruleRegistry.getExecutors()) { rule.configure(client.config(), new Map<string, string>(Object.entries(conf.ruleConfig ?? {}))) } }
/** * Creates a new ProtobufSerializer. * @param client - the schema registry client * @param serdeType - the serializer type * @param conf - the serializer configuration * @param ruleRegistry - the rule registry */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/protobuf.ts#L117-L129
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
ProtobufSerializer.serialize
override async serialize(topic: string, msg: any): Promise<Buffer> { if (this.client == null) { throw new Error('client is not initialized') } if (msg == null) { throw new Error('message is empty') } const typeName = msg.$typeName if (typeName == null) { throw new SerializationError('message type name is empty') } const messageDesc = this.registry.getMessage(typeName) if (messageDesc == null) { throw new SerializationError('message descriptor not in registry') } let schema: SchemaInfo | undefined = undefined // Don't derive the schema if it is being looked up in the following ways if (this.config().useSchemaId == null && !this.config().useLatestVersion && this.config().useLatestWithMetadata == null) { const fileDesc = messageDesc.file schema = await this.getSchemaInfo(fileDesc) } const [id, info] = await this.getId(topic, msg, schema, 'serialized') const subject = this.subjectName(topic, info) msg = await this.executeRules(subject, topic, RuleMode.WRITE, null, info, msg, null) const msgIndexBytes = this.toMessageIndexBytes(messageDesc) const msgBytes = Buffer.from(toBinary(messageDesc, msg)) return this.writeBytes(id, Buffer.concat([msgIndexBytes, msgBytes])) }
/** * Serializes a message. * @param topic - the topic * @param msg - the message */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/protobuf.ts#L136-L167
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
ProtobufDeserializer.constructor
constructor(client: Client, serdeType: SerdeType, conf: ProtobufDeserializerConfig, ruleRegistry?: RuleRegistry) { super(client, serdeType, conf, ruleRegistry) this.fileRegistry = createFileRegistry() this.schemaToDescCache = new LRUCache<string, DescFile>({ max: this.config().cacheCapacity ?? 1000 } ) this.fieldTransformer = async (ctx: RuleContext, fieldTransform: FieldTransform, msg: any) => { return await this.fieldTransform(ctx, fieldTransform, msg) } for (const rule of this.ruleRegistry.getExecutors()) { rule.configure(client.config(), new Map<string, string>(Object.entries(conf.ruleConfig ?? {}))) } }
/** * Creates a new ProtobufDeserializer. * @param client - the schema registry client * @param serdeType - the deserializer type * @param conf - the deserializer configuration * @param ruleRegistry - the rule registry */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/protobuf.ts#L353-L363
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
ProtobufDeserializer.deserialize
override async deserialize(topic: string, payload: Buffer): Promise<any> { if (!Buffer.isBuffer(payload)) { throw new Error('Invalid buffer') } if (payload.length === 0) { return null } const info = await this.getSchema(topic, payload, 'serialized') const fd = await this.toFileDesc(this.client, info) const [bytesRead, msgIndexes] = this.readMessageIndexes(payload.subarray(5)) const messageDesc = this.toMessageDescFromIndexes(fd, msgIndexes) const subject = this.subjectName(topic, info) const readerMeta = await this.getReaderSchema(subject, 'serialized') const msgBytes = payload.subarray(5 + bytesRead) let msg = fromBinary(messageDesc, msgBytes) // Currently JavaScript does not support migration rules // because of lack of support for DynamicMessage let target: SchemaInfo if (readerMeta != null) { target = readerMeta } else { target = info } msg = await this.executeRules(subject, topic, RuleMode.READ, null, target, msg, null) return msg }
/** * Deserializes a message. * @param topic - the topic * @param payload - the message payload */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/protobuf.ts#L370-L399
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.registerExecutor
public registerExecutor(ruleExecutor: RuleExecutor): void { this.ruleExecutors.set(ruleExecutor.type(), ruleExecutor) }
/** * registerExecutor is used to register a new rule executor. * @param ruleExecutor - the rule executor to register */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L27-L29
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.getExecutor
public getExecutor(name: string): RuleExecutor | undefined { return this.ruleExecutors.get(name) }
/** * getExecutor fetches a rule executor by a given name. * @param name - the name of the rule executor to fetch */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L35-L37
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.getExecutors
public getExecutors(): RuleExecutor[] { return Array.from(this.ruleExecutors.values()) }
/** * getExecutors fetches all rule executors */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L42-L44
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.registerAction
public registerAction(ruleAction: RuleAction): void { this.ruleActions.set(ruleAction.type(), ruleAction) }
/** * registerAction is used to register a new rule action. * @param ruleAction - the rule action to register */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L50-L52
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.getAction
public getAction(name: string): RuleAction | undefined { return this.ruleActions.get(name) }
/** * getAction fetches a rule action by a given name. * @param name - the name of the rule action to fetch */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L58-L60
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.getActions
public getActions(): RuleAction[] { return Array.from(this.ruleActions.values()) }
/** * getActions fetches all rule actions */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L65-L67
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.registerOverride
public registerOverride(ruleOverride: RuleOverride): void { this.ruleOverrides.set(ruleOverride.type, ruleOverride) }
/** * registerOverride is used to register a new rule override. * @param ruleOverride - the rule override to register */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L73-L75
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.getOverride
public getOverride(name: string): RuleOverride | undefined { return this.ruleOverrides.get(name) }
/** * getOverride fetches a rule override by a given name. * @param name - the name of the rule override to fetch */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L81-L83
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.getOverrides
public getOverrides(): RuleOverride[] { return Array.from(this.ruleOverrides.values()) }
/** * getOverrides fetches all rule overrides */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L88-L90
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.clear
public clear(): void { this.ruleExecutors.clear() this.ruleActions.clear() this.ruleOverrides.clear() }
/** * clear clears all registered rules */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L95-L99
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.getGlobalInstance
public static getGlobalInstance(): RuleRegistry { return RuleRegistry.globalInstance }
/** * getGlobalInstance fetches the global instance of the rule registry */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L104-L106
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.registerRuleExecutor
public static registerRuleExecutor(ruleExecutor: RuleExecutor): void { RuleRegistry.globalInstance.registerExecutor(ruleExecutor) }
/** * registerRuleExecutor is used to register a new rule executor globally. * @param ruleExecutor - the rule executor to register */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L112-L114
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.registerRuleAction
public static registerRuleAction(ruleAction: RuleAction): void { RuleRegistry.globalInstance.registerAction(ruleAction) }
/** * registerRuleAction is used to register a new rule action globally. * @param ruleAction - the rule action to register */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L120-L122
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleRegistry.registerRuleOverride
public static registerRuleOverride(ruleOverride: RuleOverride): void { RuleRegistry.globalInstance.registerOverride(ruleOverride) }
/** * registerRuleOverride is used to register a new rule override globally. * @param ruleOverride - the rule override to register */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/rule-registry.ts#L128-L130
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleError.constructor
constructor(message?: string) { super(message) }
/** * Creates a new rule error. * @param message - The error message. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/serde.ts#L25-L27
26710e6ec5c8ff8415f2d01dddabb811327c6cde
confluent-kafka-javascript
github_2023
confluentinc
typescript
RuleConditionError.constructor
constructor(rule: Rule) { super(RuleConditionError.error(rule)) this.rule = rule }
/** * Creates a new rule condition error. * @param rule - The rule. */
https://github.com/confluentinc/confluent-kafka-javascript/blob/26710e6ec5c8ff8415f2d01dddabb811327c6cde/schemaregistry/serde/serde.ts#L805-L808
26710e6ec5c8ff8415f2d01dddabb811327c6cde
clash-nyanpasu
github_2023
libnyanpasu
typescript
upsert
const upsert = async (value: IVerge[K]) => { if (!data) { return } await update.mutateAsync({ [key]: value }) }
/** * Updates a specific setting value in the Verge configuration * @param value - The new value to be set for the specified key * @returns void * @remarks This function will not execute if the data is not available */
https://github.com/libnyanpasu/clash-nyanpasu/blob/ac0d0fc2b7e28c99d9d635fe89be6673597749ca/frontend/interface/src/ipc/use-settings.ts#L116-L122
ac0d0fc2b7e28c99d9d635fe89be6673597749ca
clash-nyanpasu
github_2023
libnyanpasu
typescript
uploadAssets
async function uploadAssets(releaseId: number, assets: string[]) { const GITHUB_TOKEN = process.env.GITHUB_TOKEN if (!GITHUB_TOKEN) { throw new Error('GITHUB_TOKEN is required') } const github = getOctokit(GITHUB_TOKEN) // Determine content-length for header to upload asset const contentLength = (filePath: string) => fs.statSync(filePath).size for (const assetPath of assets) { const headers = { 'content-type': 'application/zip', 'content-length': contentLength(assetPath), } const ext = path.extname(assetPath) const filename = path.basename(assetPath).replace(ext, '') const assetName = path.dirname(assetPath).includes(`target${path.sep}debug`) ? `${filename}-debug${ext}` : `${filename}${ext}` consola.start(`Uploading ${assetName}...`) try { await github.rest.repos.uploadReleaseAsset({ headers, name: assetName, // https://github.com/tauri-apps/tauri-action/pull/45 // @ts-expect-error error TS2322: Type 'Buffer' is not assignable to type 'string'. data: fs.readFileSync(assetPath), owner: context.repo.owner, repo: context.repo.repo, release_id: releaseId, }) consola.success(`Uploaded ${assetName}`) } catch (error) { consola.error( 'Failed to upload release asset', error instanceof Error ? error.message : error, ) } } }
// From tauri-apps/tauri-action
https://github.com/libnyanpasu/clash-nyanpasu/blob/ac0d0fc2b7e28c99d9d635fe89be6673597749ca/scripts/osx-aarch64-upload.ts#L66-L109
ac0d0fc2b7e28c99d9d635fe89be6673597749ca
clash-nyanpasu
github_2023
libnyanpasu
typescript
contentLength
const contentLength = (filePath: string) => fs.statSync(filePath).size
// Determine content-length for header to upload asset
https://github.com/libnyanpasu/clash-nyanpasu/blob/ac0d0fc2b7e28c99d9d635fe89be6673597749ca/scripts/osx-aarch64-upload.ts#L74-L74
ac0d0fc2b7e28c99d9d635fe89be6673597749ca
clash-nyanpasu
github_2023
libnyanpasu
typescript
resolvePortable
async function resolvePortable() { if (process.platform !== 'win32') return const buildDir = path.join( RUST_ARCH === 'x86_64' ? 'backend/target/release' : `backend/target/${RUST_ARCH}-pc-windows-msvc/release`, ) const configDir = path.join(buildDir, '.config') if (!(await fs.pathExists(buildDir))) { throw new Error('could not found the release dir') } await fs.ensureDir(configDir) await fs.createFile(path.join(configDir, 'PORTABLE')) const zip = new AdmZip() let mainEntryPath = path.join(buildDir, 'Clash Nyanpasu.exe') if (!(await fs.pathExists(mainEntryPath))) { mainEntryPath = path.join(buildDir, 'clash-nyanpasu.exe') } zip.addLocalFile(mainEntryPath) zip.addLocalFile(path.join(buildDir, 'clash.exe')) zip.addLocalFile(path.join(buildDir, 'mihomo.exe')) zip.addLocalFile(path.join(buildDir, 'mihomo-alpha.exe')) zip.addLocalFile(path.join(buildDir, 'nyanpasu-service.exe')) zip.addLocalFile(path.join(buildDir, 'clash-rs.exe')) zip.addLocalFile(path.join(buildDir, 'clash-rs-alpha.exe')) zip.addLocalFolder(path.join(buildDir, 'resources'), 'resources') if (fixedWebview) { const webviewPath = (await fs.readdir(TAURI_APP_DIR)).find((file) => file.includes('WebView2'), ) if (!webviewPath) { throw new Error('WebView2 runtime not found') } zip.addLocalFolder( path.join(TAURI_APP_DIR, webviewPath), path.basename(webviewPath), ) } zip.addLocalFolder(configDir, '.config') const { version } = packageJson const zipFile = `Clash.Nyanpasu_${version}_${RUST_ARCH}${fixedWebview ? '_fixed-webview' : ''}_portable.zip` zip.writeZip(zipFile) consola.success('create portable zip successfully') // push release assets if (process.env.GITHUB_TOKEN === undefined) { throw new Error('GITHUB_TOKEN is required') } const options = { owner: context.repo.owner, repo: context.repo.repo } const github = getOctokit(process.env.GITHUB_TOKEN) consola.info('upload to ', process.env.TAG_NAME || `v${version}`) const { data: release } = await github.rest.repos.getReleaseByTag({ ...options, tag: process.env.TAG_NAME || `v${version}`, }) consola.debug(colorize`releaseName: {green ${release.name}}`) await github.rest.repos.uploadReleaseAsset({ ...options, release_id: release.id, name: zipFile, // @ts-expect-error data is Buffer should work fine data: zip.toBuffer(), }) }
/// Script for ci
https://github.com/libnyanpasu/clash-nyanpasu/blob/ac0d0fc2b7e28c99d9d635fe89be6673597749ca/scripts/portable.ts#L14-L92
ac0d0fc2b7e28c99d9d635fe89be6673597749ca
clash-nyanpasu
github_2023
libnyanpasu
typescript
resolvePublish
async function resolvePublish() { const flag = process.argv[2] ?? 'patch' const tauriJson = await fs.readJSON(TAURI_APP_CONF_PATH) const tauriNightlyJson = await fs.readJSON(TAURI_NIGHTLY_APP_CONF_PATH) let [a, b, c] = packageJson.version.split('.').map(Number) if (flag === 'major') { a += 1 b = 0 c = 0 } else if (flag === 'minor') { b += 1 c = 0 } else if (flag === 'patch') { c += 1 } else throw new Error(`invalid flag "${flag}"`) const nextVersion = `${a}.${b}.${c}` const nextNightlyVersion = `${a}.${b}.${c + 1}` packageJson.version = nextVersion tauriJson.package.version = nextVersion tauriNightlyJson.package.version = nextNightlyVersion // 发布更新前先写更新日志 // const nextTag = `v${nextVersion}`; // await resolveUpdateLog(nextTag); await fs.writeJSON(PACKAGE_JSON_PATH, packageJson, { spaces: 2, }) await fs.writeJSON(TAURI_APP_CONF_PATH, tauriJson, { spaces: 2, }) await fs.writeJSON(TAURI_NIGHTLY_APP_CONF_PATH, tauriNightlyJson, { spaces: 2, }) // overrides mono repo package.json for (const monoRepoPath of MONO_REPO_PATHS) { const monoRepoPackageJsonPath = path.join(monoRepoPath, 'package.json') const monoRepoPackageJson = await fs.readJSON(monoRepoPackageJsonPath) monoRepoPackageJson.version = nextVersion await fs.writeJSON(monoRepoPackageJsonPath, monoRepoPackageJson, { spaces: 2, }) } // execSync("git add ./package.json"); // execSync(`git add ${TAURI_APP_CONF_PATH}`); // execSync(`git commit -m "v${nextVersion}"`); // execSync(`git tag -a v${nextVersion} -m "v${nextVersion}"`); // execSync(`git push`); // execSync(`git push origin v${nextVersion}`); // consola.success(`Publish Successfully...`); console.log(nextVersion) }
// publish
https://github.com/libnyanpasu/clash-nyanpasu/blob/ac0d0fc2b7e28c99d9d635fe89be6673597749ca/scripts/publish.ts#L23-L79
ac0d0fc2b7e28c99d9d635fe89be6673597749ca
clash-nyanpasu
github_2023
libnyanpasu
typescript
resolveUpdater
async function resolveUpdater() { if (process.env.GITHUB_TOKEN === undefined) { throw new Error('GITHUB_TOKEN is required') } consola.start('start to generate updater files') const options = { owner: context.repo.owner, repo: context.repo.repo, } const github = getOctokit(process.env.GITHUB_TOKEN) consola.debug('resolve latest pre-release files...') // latest pre-release tag const { data: latestPreRelease } = await github.rest.repos.getReleaseByTag({ ...options, tag: 'pre-release', }) const shortHash = await execSync(`git rev-parse --short pre-release`) .toString() .replace('\n', '') .replace('\r', '') consola.info(`latest pre-release short hash: ${shortHash}`) const updateData = { name: `v${tauriNightly.version}-alpha+${shortHash}`, notes: 'Nightly build. Full changes see commit history.', pub_date: new Date().toISOString(), platforms: { win64: { signature: '', url: '' }, // compatible with older formats linux: { signature: '', url: '' }, // compatible with older formats darwin: { signature: '', url: '' }, // compatible with older formats 'darwin-aarch64': { signature: '', url: '' }, 'darwin-intel': { signature: '', url: '' }, 'darwin-x86_64': { signature: '', url: '' }, 'linux-x86_64': { signature: '', url: '' }, // "linux-aarch64": { signature: "", url: "" }, // "linux-armv7": { signature: "", url: "" }, 'windows-x86_64': { signature: '', url: '' }, 'windows-i686': { signature: '', url: '' }, 'windows-aarch64': { signature: '', url: '' }, }, } const promises = latestPreRelease.assets.map(async (asset) => { const { name, browser_download_url: browserDownloadUrl } = asset function isMatch(name: string, extension: string, arch: string) { return ( name.endsWith(extension) && name.includes(arch) && (argv.fixedWebview ? name.includes('fixed-webview') : !name.includes('fixed-webview')) ) } // win64 url if (isMatch(name, '.nsis.zip', 'x64')) { updateData.platforms.win64.url = browserDownloadUrl updateData.platforms['windows-x86_64'].url = browserDownloadUrl } // win64 signature if (isMatch(name, '.nsis.zip.sig', 'x64')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms.win64.signature = sig updateData.platforms['windows-x86_64'].signature = sig } // win32 url if (isMatch(name, '.nsis.zip', 'x86')) { updateData.platforms['windows-i686'].url = browserDownloadUrl } // win32 signature if (isMatch(name, '.nsis.zip.sig', 'x86')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms['windows-i686'].signature = sig } // win arm64 url if (isMatch(name, '.nsis.zip', 'arm64')) { updateData.platforms['windows-aarch64'].url = browserDownloadUrl } // win arm64 signature if (isMatch(name, '.nsis.zip.sig', 'arm64')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms['windows-aarch64'].signature = sig } // darwin url (intel) if (name.endsWith('.app.tar.gz') && !name.includes('aarch')) { updateData.platforms.darwin.url = browserDownloadUrl updateData.platforms['darwin-intel'].url = browserDownloadUrl updateData.platforms['darwin-x86_64'].url = browserDownloadUrl } // darwin signature (intel) if (name.endsWith('.app.tar.gz.sig') && !name.includes('aarch')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms.darwin.signature = sig updateData.platforms['darwin-intel'].signature = sig updateData.platforms['darwin-x86_64'].signature = sig } // darwin url (aarch) if (name.endsWith('aarch64.app.tar.gz')) { updateData.platforms['darwin-aarch64'].url = browserDownloadUrl } // darwin signature (aarch) if (name.endsWith('aarch64.app.tar.gz.sig')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms['darwin-aarch64'].signature = sig } // linux url if (name.endsWith('.AppImage.tar.gz')) { updateData.platforms.linux.url = browserDownloadUrl updateData.platforms['linux-x86_64'].url = browserDownloadUrl } // linux signature if (name.endsWith('.AppImage.tar.gz.sig')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms.linux.signature = sig updateData.platforms['linux-x86_64'].signature = sig } }) await Promise.allSettled(promises) consola.info(updateData) consola.debug('generate updater metadata...') // maybe should test the signature as well // delete the null field Object.entries(updateData.platforms).forEach(([key, value]) => { if (!value.url) { consola.error(`failed to parse release for "${key}"`) delete updateData.platforms[key as keyof typeof updateData.platforms] } }) // 生成一个代理github的更新文件 // 使用 https://hub.fastgit.xyz/ 做github资源的加速 const updateDataNew = JSON.parse( JSON.stringify(updateData), ) as typeof updateData Object.entries(updateDataNew.platforms).forEach(([key, value]) => { if (value.url) { updateDataNew.platforms[key as keyof typeof updateData.platforms].url = getGithubUrl(value.url) } else { consola.error(`updateDataNew.platforms.${key} is null`) } }) // update the update.json consola.debug('update updater files...') let updateRelease try { const { data } = await github.rest.repos.getReleaseByTag({ ...options, tag: UPDATE_TAG_NAME, }) updateRelease = data } catch (err) { consola.error(err) consola.error('failed to get release by tag, create one') const { data } = await github.rest.repos.createRelease({ ...options, tag_name: UPDATE_TAG_NAME, name: upperFirst(camelCase(UPDATE_TAG_NAME)), body: 'files for programs to check for updates', prerelease: true, }) updateRelease = data } // delete the old assets for (const asset of updateRelease.assets) { if ( argv.fixedWebview ? asset.name === UPDATE_FIXED_WEBVIEW_FILE : asset.name === UPDATE_JSON_FILE ) { await github.rest.repos.deleteReleaseAsset({ ...options, asset_id: asset.id, }) } if ( argv.fixedWebview ? asset.name === UPDATE_FIXED_WEBVIEW_PROXY : asset.name === UPDATE_JSON_PROXY ) { await github.rest.repos .deleteReleaseAsset({ ...options, asset_id: asset.id }) .catch((err) => { consola.error(err) }) // do not break the pipeline } } // upload new assets await github.rest.repos.uploadReleaseAsset({ ...options, release_id: updateRelease.id, name: argv.fixedWebview ? UPDATE_FIXED_WEBVIEW_FILE : UPDATE_JSON_FILE, data: JSON.stringify(updateData, null, 2), }) // cache the files if cache path is provided await saveToCache( argv.fixedWebview ? UPDATE_FIXED_WEBVIEW_FILE : UPDATE_JSON_FILE, JSON.stringify(updateData, null, 2), ) await github.rest.repos.uploadReleaseAsset({ ...options, release_id: updateRelease.id, name: argv.fixedWebview ? UPDATE_FIXED_WEBVIEW_PROXY : UPDATE_JSON_PROXY, data: JSON.stringify(updateDataNew, null, 2), }) // cache the proxy file if cache path is provided await saveToCache( argv.fixedWebview ? UPDATE_FIXED_WEBVIEW_PROXY : UPDATE_JSON_PROXY, JSON.stringify(updateDataNew, null, 2), ) consola.success('updater files updated') }
/// generate update.json
https://github.com/libnyanpasu/clash-nyanpasu/blob/ac0d0fc2b7e28c99d9d635fe89be6673597749ca/scripts/updater-nightly.ts#L33-L261
ac0d0fc2b7e28c99d9d635fe89be6673597749ca
clash-nyanpasu
github_2023
libnyanpasu
typescript
getSignature
async function getSignature(url: string) { const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream' }, }) return response.text() }
// get the signature file content
https://github.com/libnyanpasu/clash-nyanpasu/blob/ac0d0fc2b7e28c99d9d635fe89be6673597749ca/scripts/updater-nightly.ts#L276-L283
ac0d0fc2b7e28c99d9d635fe89be6673597749ca
clash-nyanpasu
github_2023
libnyanpasu
typescript
resolveUpdater
async function resolveUpdater() { if (process.env.GITHUB_TOKEN === undefined) { throw new Error('GITHUB_TOKEN is required') } const options = { owner: context.repo.owner, repo: context.repo.repo } const github = getOctokit(process.env.GITHUB_TOKEN) const { data: tags } = await github.rest.repos.listTags({ ...options, per_page: 10, page: 1, }) // get the latest publish tag const tag = tags.find((t) => t.name.startsWith('v')) if (!tag) throw new Error('could not found the latest tag') consola.debug(colorize`latest tag: {gray.bold ${tag.name}}`) const { data: latestRelease } = await github.rest.repos.getReleaseByTag({ ...options, tag: tag.name, }) let updateLog: string | null = null try { updateLog = await resolveUpdateLog(tag.name) } catch (err) { consola.error(err) } const updateData = { name: tag.name, notes: UPDATE_RELEASE_BODY || updateLog || latestRelease.body, pub_date: new Date().toISOString(), platforms: { win64: { signature: '', url: '' }, // compatible with older formats linux: { signature: '', url: '' }, // compatible with older formats darwin: { signature: '', url: '' }, // compatible with older formats 'darwin-aarch64': { signature: '', url: '' }, 'darwin-intel': { signature: '', url: '' }, 'darwin-x86_64': { signature: '', url: '' }, 'linux-x86_64': { signature: '', url: '' }, // "linux-aarch64": { signature: "", url: "" }, // "linux-armv7": { signature: "", url: "" }, 'windows-x86_64': { signature: '', url: '' }, 'windows-i686': { signature: '', url: '' }, 'windows-aarch64': { signature: '', url: '' }, }, } const promises = latestRelease.assets.map(async (asset) => { const { name, browser_download_url: browserDownloadUrl } = asset function isMatch(name: string, extension: string, arch: string) { return ( name.endsWith(extension) && name.includes(arch) && (argv.fixedWebview ? name.includes('fixed-webview') : !name.includes('fixed-webview')) ) } // win64 url if (isMatch(name, '.nsis.zip', 'x64')) { updateData.platforms.win64.url = browserDownloadUrl updateData.platforms['windows-x86_64'].url = browserDownloadUrl } // win64 signature if (isMatch(name, '.nsis.zip.sig', 'x64')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms.win64.signature = sig updateData.platforms['windows-x86_64'].signature = sig } // win32 url if (isMatch(name, '.nsis.zip', 'x86')) { updateData.platforms['windows-i686'].url = browserDownloadUrl } // win32 signature if (isMatch(name, '.nsis.zip.sig', 'x86')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms['windows-i686'].signature = sig } // win arm64 url if (isMatch(name, '.nsis.zip', 'arm64')) { updateData.platforms['windows-aarch64'].url = browserDownloadUrl } // win arm64 signature if (isMatch(name, '.nsis.zip.sig', 'arm64')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms['windows-aarch64'].signature = sig } // darwin url (intel) if (name.endsWith('.app.tar.gz') && !name.includes('aarch')) { updateData.platforms.darwin.url = browserDownloadUrl updateData.platforms['darwin-intel'].url = browserDownloadUrl updateData.platforms['darwin-x86_64'].url = browserDownloadUrl } // darwin signature (intel) if (name.endsWith('.app.tar.gz.sig') && !name.includes('aarch')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms.darwin.signature = sig updateData.platforms['darwin-intel'].signature = sig updateData.platforms['darwin-x86_64'].signature = sig } // darwin url (aarch) if (name.endsWith('aarch64.app.tar.gz')) { updateData.platforms['darwin-aarch64'].url = browserDownloadUrl } // darwin signature (aarch) if (name.endsWith('aarch64.app.tar.gz.sig')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms['darwin-aarch64'].signature = sig } // linux url if (name.endsWith('.AppImage.tar.gz')) { updateData.platforms.linux.url = browserDownloadUrl updateData.platforms['linux-x86_64'].url = browserDownloadUrl } // linux signature if (name.endsWith('.AppImage.tar.gz.sig')) { const sig = await getSignature(browserDownloadUrl) updateData.platforms.linux.signature = sig updateData.platforms['linux-x86_64'].signature = sig } }) await Promise.allSettled(promises) consola.info(updateData) // maybe should test the signature as well // delete the null field Object.entries(updateData.platforms).forEach(([key, value]) => { if (!value.url) { consola.error(`failed to parse release for "${key}"`) delete updateData.platforms[key as keyof typeof updateData.platforms] } }) // 生成一个代理github的更新文件 // 使用 https://hub.fastgit.xyz/ 做github资源的加速 const updateDataNew = JSON.parse( JSON.stringify(updateData), ) as typeof updateData Object.entries(updateDataNew.platforms).forEach(([key, value]) => { if (value.url) { updateDataNew.platforms[key as keyof typeof updateData.platforms].url = getGithubUrl(value.url) } else { consola.error(`updateDataNew.platforms.${key} is null`) } }) // update the update.json const { data: updateRelease } = await github.rest.repos.getReleaseByTag({ ...options, tag: UPDATE_TAG_NAME, }) // delete the old assets for (const asset of updateRelease.assets) { if ( argv.fixedWebview ? asset.name === UPDATE_FIXED_WEBVIEW_FILE : asset.name === UPDATE_JSON_FILE ) { await github.rest.repos.deleteReleaseAsset({ ...options, asset_id: asset.id, }) } if ( argv.fixedWebview ? asset.name === UPDATE_FIXED_WEBVIEW_PROXY : asset.name === UPDATE_JSON_PROXY ) { await github.rest.repos .deleteReleaseAsset({ ...options, asset_id: asset.id }) .catch((err) => { consola.error(err) }) // do not break the pipeline } } // upload new assets await github.rest.repos.uploadReleaseAsset({ ...options, release_id: updateRelease.id, name: argv.fixedWebview ? UPDATE_FIXED_WEBVIEW_FILE : UPDATE_JSON_FILE, data: JSON.stringify(updateData, null, 2), }) // cache the files if cache path is provided await saveToCache( argv.fixedWebview ? UPDATE_FIXED_WEBVIEW_FILE : UPDATE_JSON_FILE, JSON.stringify(updateData, null, 2), ) await github.rest.repos.uploadReleaseAsset({ ...options, release_id: updateRelease.id, name: argv.fixedWebview ? UPDATE_FIXED_WEBVIEW_PROXY : UPDATE_JSON_PROXY, data: JSON.stringify(updateDataNew, null, 2), }) // cache the proxy file if cache path is provided await saveToCache( argv.fixedWebview ? UPDATE_FIXED_WEBVIEW_PROXY : UPDATE_JSON_PROXY, JSON.stringify(updateDataNew, null, 2), ) }
/// generate update.json
https://github.com/libnyanpasu/clash-nyanpasu/blob/ac0d0fc2b7e28c99d9d635fe89be6673597749ca/scripts/updater.ts#L32-L250
ac0d0fc2b7e28c99d9d635fe89be6673597749ca
clash-nyanpasu
github_2023
libnyanpasu
typescript
getSignature
async function getSignature(url: string) { const response = await fetch(url, { method: 'GET', headers: { 'Content-Type': 'application/octet-stream' }, }) return response.text() }
// get the signature file content
https://github.com/libnyanpasu/clash-nyanpasu/blob/ac0d0fc2b7e28c99d9d635fe89be6673597749ca/scripts/updater.ts#L266-L273
ac0d0fc2b7e28c99d9d635fe89be6673597749ca
clash-nyanpasu
github_2023
libnyanpasu
typescript
Resolve.wintun
public async wintun() { const { platform } = process let arch: string = this.options.arch || 'x64' if (platform !== 'win32') return switch (arch) { case 'x64': arch = 'amd64' break case 'ia32': arch = 'x86' break case 'arm': arch = 'arm' break case 'arm64': arch = 'arm64' break default: throw new Error(`unsupported arch ${arch}`) } const url = 'https://www.wintun.net/builds/wintun-0.14.1.zip' const hash = '07c256185d6ee3652e09fa55c0b673e2624b565e02c4b9091c79ca7d2f24ef51' const tempDir = path.join(TEMP_DIR, 'wintun') const tempZip = path.join(tempDir, 'wintun.zip') // const wintunPath = path.join(tempDir, "wintun/bin/amd64/wintun.dll"); const targetPath = path.join(TAURI_APP_DIR, 'resources', 'wintun.dll') if (!this.options?.force && (await fs.pathExists(targetPath))) return await fs.mkdirp(tempDir) if (!(await fs.pathExists(tempZip))) { await downloadFile(url, tempZip) } // check hash const hashBuffer = await fs.readFile(tempZip) const sha256 = crypto.createHash('sha256') sha256.update(hashBuffer) const hashValue = sha256.digest('hex') if (hashValue !== hash) { throw new Error(`wintun. hash not match ${hashValue}`) } // unzip const zip = new AdmZip(tempZip) zip.extractAllTo(tempDir, true) // recursive list path for debug use const files = (await fs.readdir(tempDir, { recursive: true })).filter( (file) => file.includes('wintun.dll'), ) consola.debug(colorize`{green wintun} founded dlls: ${files}`) const file = files.find((file) => file.includes(arch)) if (!file) { throw new Error(`wintun. not found arch ${arch}`) } const wintunPath = path.join(tempDir, file.toString()) if (!(await fs.pathExists(wintunPath))) { throw new Error(`path not found "${wintunPath}"`) } // prepare resource dir await fs.mkdirp(path.dirname(targetPath)) await fs.copyFile(wintunPath, targetPath) await fs.remove(tempDir) consola.success(colorize`resolve {green wintun.dll} finished`) }
/** * only Windows * get the wintun.dll (not required) */
https://github.com/libnyanpasu/clash-nyanpasu/blob/ac0d0fc2b7e28c99d9d635fe89be6673597749ca/scripts/utils/resolve.ts#L67-L146
ac0d0fc2b7e28c99d9d635fe89be6673597749ca
sun-panel
github_2023
hslr-s
typescript
naiveStyleOverride
function naiveStyleOverride() { const meta = document.createElement('meta') meta.name = 'naive-ui-style' document.head.appendChild(meta) }
/** Tailwind's Preflight Style Override */
https://github.com/hslr-s/sun-panel/blob/25f46209d97ae7bd6de29c39f93fd4d83932eb06/src/plugins/assets.ts#L8-L12
25f46209d97ae7bd6de29c39f93fd4d83932eb06