From 8435fb496c55d4398ab9be8dc4c30004064b92fd Mon Sep 17 00:00:00 2001 From: Roman <491247+moltar@users.noreply.github.com> Date: Mon, 11 Dec 2023 14:18:49 +0000 Subject: [PATCH] feat(templating): adds encodeBase64 handlebars helper (#26197) Co-authored-by: Rhys Arkins Co-authored-by: Michael Kriese --- docs/usage/templates.md | 8 ++++++++ lib/util/template/index.spec.ts | 24 ++++++++++++++++++++++++ lib/util/template/index.ts | 4 ++++ 3 files changed, 36 insertions(+) diff --git a/docs/usage/templates.md b/docs/usage/templates.md index e72e7182576e454..f355135754ea026 100644 --- a/docs/usage/templates.md +++ b/docs/usage/templates.md @@ -59,6 +59,14 @@ In the example above `depName` is the string you want to decode. Read the [MDN Web Docs, decodeURIComponent()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) to learn more. +### encodeBase64 + +If you want to convert a string to Base64, use the built-in function `encodeBase64` like this: + +`{{{encodeBase64 body}}}` + +In the example above `body` is the string you want to transform into a Base64-encoded value. + ### replace The `replace` helper replaces _all_ found strings matching the given regex with the replacement string. diff --git a/lib/util/template/index.spec.ts b/lib/util/template/index.spec.ts index 308de5619311125..0b86af09154cf1d 100644 --- a/lib/util/template/index.spec.ts +++ b/lib/util/template/index.spec.ts @@ -219,6 +219,30 @@ describe('util/template/index', () => { }); }); + describe('base64 encoding', () => { + it('encodes values', () => { + const output = template.compile( + '{{{encodeBase64 "@fsouza/prettierd"}}}', + undefined as never, + ); + expect(output).toBe('QGZzb3V6YS9wcmV0dGllcmQ='); + }); + + it('handles null values gracefully', () => { + const output = template.compile('{{{encodeBase64 packageName}}}', { + packageName: null, + }); + expect(output).toBe(''); + }); + + it('handles undefined values gracefully', () => { + const output = template.compile('{{{encodeBase64 packageName}}}', { + packageName: undefined, + }); + expect(output).toBe(''); + }); + }); + describe('equals', () => { it('equals', () => { const output = template.compile( diff --git a/lib/util/template/index.ts b/lib/util/template/index.ts index 228dbea040bee63..f9a7c2152173506 100644 --- a/lib/util/template/index.ts +++ b/lib/util/template/index.ts @@ -8,6 +8,10 @@ import { regEx } from '../regex'; handlebars.registerHelper('encodeURIComponent', encodeURIComponent); handlebars.registerHelper('decodeURIComponent', decodeURIComponent); +handlebars.registerHelper('encodeBase64', (str: string) => + Buffer.from(str ?? '').toString('base64'), +); + handlebars.registerHelper('stringToPrettyJSON', (input: string): string => JSON.stringify(JSON.parse(input), null, 2), );