Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add optionalPrams properties in JSON data #59

Merged
merged 7 commits into from
Jul 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions src/third-parties/google-analytics/data.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,21 @@
"scripts": [
{
"url": "https://www.googletagmanager.com/gtag/js",
"params": ["id", "l"],
"params": ["id"],
"optionalParams": {
"l": null
},
"strategy": "worker",
"location": "head",
"action": "append",
"key": "gtag"
},
{
"code": "window['{{l}}']=window['{{l}}']||[];window['{{l}}'].push({'js':new Date()});window['{{l}}'].push({'config':'{{id}}'})",
"params": ["id", "l"],
"code": "window[{{l}}]=window[{{l}}]||[];window[{{l}}].push({'js':new Date()});window[{{l}}].push({'config':{{id}}})",
"params": ["id"],
"optionalParams": {
"l": "dataLayer"
},
"strategy": "worker",
"location": "head",
"action": "append",
Expand Down
11 changes: 8 additions & 3 deletions src/third-parties/google-tag-manager/data.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,20 @@
"scripts": [
{
"url": "https://www.googletagmanager.com/gtm.js",
"params": ["id", "l"],
"params": ["id"],
"optionalParams": {
"l": null
},
"strategy": "worker",
"location": "head",
"action": "append",
"key": "gtm"
},
{
"code": "window['{{l}}']=window['{{l}}']||[];window['{{l}}'].push({'gtm.start':new Date().getTime(),event:'gtm.js'});",
"params": ["l"],
"code": "window[{{l}}]=window[{{l}}]||[];window[{{l}}].push({'gtm.start':new Date().getTime(),event:'gtm.js'});",
"optionalParams": {
"l": "dataLayer"
},
"strategy": "worker",
"location": "head",
"action": "append",
Expand Down
1 change: 1 addition & 0 deletions src/types/type-declarations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export type HtmlAttributes = {

type ScriptBase = {
params?: Array<string>;
optionalParams?: Record<string, string | number | undefined | null>;
strategy: ScriptStrategy;
location: ScriptLocation;
action: ScriptAction;
Expand Down
132 changes: 130 additions & 2 deletions src/utils/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { formatUrl, createHtml, formatData } from '.';
import type { Data, ExternalScript } from '../types';
import { formatUrl, createHtml, formatData, formatCode } from '.';
import type { CodeBlock, Data, ExternalScript } from '../types';

describe('Utils', () => {
describe('formatUrl', () => {
Expand All @@ -14,6 +14,26 @@ describe('Utils', () => {
const newUrl = formatUrl(oldUrl, requiredParams, args);
expect(newUrl).toEqual('https://example.com/?unit=imperial&type=main');
});

it('should add default value', () => {
const oldUrl = 'https://example.com';
const requiredParams = ['unit', 'type'];
const args = {
unit: 'imperial',
};
const optionalParams = {
type: 'main',
};

const newUrl = formatUrl(
oldUrl,
requiredParams,
args,
undefined,
optionalParams,
);
expect(newUrl).toEqual('https://example.com/?unit=imperial&type=main');
});
});

describe('createHtml', () => {
Expand Down Expand Up @@ -230,5 +250,113 @@ describe('Utils', () => {
);
expect(result.scripts).toEqual(undefined);
});

it('should replace with default values when needed', () => {
const data = {
id: 'third-party',
description: 'Description',
html: {
element: 'iframe',
attributes: {
loading: 'lazy',
src: {
url: 'https://www.google.com/maps/embed/v1/place',
slugParam: 'mode',
params: ['key'],
},
},
},
scripts: [
{
code: 'window[{{hello}}]=window[{{hello}}]||[];console.log({{world}})',
optionalParams: {
hello: 'hoho',
},
params: ['world'],
strategy: 'worker',
location: 'head',
action: 'append',
key: 'setup',
} as CodeBlock,
],
};

const result = formatData(data, {
test: 'hello',
world: 'earth',
key: 404,
});
const script = result.scripts![0] as CodeBlock;
expect(script.code).toEqual(
'window["hoho"]=window["hoho"]||[];console.log("earth")',
);
expect(result.html).toEqual(
'<iframe loading="lazy" src="https://www.google.com/maps/embed/v1/place?key=404" test="hello"></iframe>',
);
});
});

describe('formatCode', () => {
const inputs = [
// string
{
input: 'window[{{l}}]=window[{{l}}]||[];',
params: {
l: 'some-datalayer',
},
output: `window["some-datalayer"]=window["some-datalayer"]||[];`,
},
// number
{
input: '{{number}}+1',
params: {
number: 4,
},
output: `4+1`,
},
// boolean
{
input: '{{bool}}',
params: {
bool: false,
},
output: `false`,
},
// boolean
{
input: '{{val}}',
params: {
val: null,
},
output: `null`,
},
// undefined
{
input: 'window[{{l}}]=window[{{l}}]||[];',
output: `window[undefined]=window[undefined]||[];`,
},
];

it.each(inputs)(
'should replace the input and stringify it',
({ input, output, params }) => {
expect(formatCode(input, params)).toEqual(output);
},
);

it.each(inputs)(
'should replace the input and stringify it with the default value',
({ input, output, params }) => {
expect(formatCode(input, undefined, params)).toEqual(output);
},
);

it('should replace the input and stringify it with the default value', () => {
const input = 'window[{{l}}]=window[{{l}}]||[];';

expect(
formatCode(input, { l: 'test' }, { l: 'dataLayer' }),
).toMatchInlineSnapshot(`"window["test"]=window["test"]||[];"`);
});
});
});
30 changes: 26 additions & 4 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export function formatUrl(
params?: string[],
args?: Inputs,
slug?: Inputs,
optionalParams?: Inputs,
) {
const newUrl =
slug && Object.keys(slug).length > 0
Expand All @@ -39,15 +40,25 @@ export function formatUrl(
if (params && args) {
params.forEach((param: string) => {
if (args[param]) newUrl.searchParams.set(param, args[param]);
else if (optionalParams?.[param]) {
newUrl.searchParams.set(param, optionalParams?.[param]);
}
});
}

return newUrl.toString();
}

export function formatCode(code: string, args?: Inputs) {
export function formatCode(
code: string,
args?: Inputs,
optionalParams?: Inputs,
) {
return code.replace(/{{(.*?)}}/g, (match) => {
return args?.[match.split(/{{|}}/).filter(Boolean)[0]];
const name = match.split(/{{|}}/).filter(Boolean)[0];
return JSON.stringify(
args && name in args ? args?.[name] : optionalParams?.[name],
);
});
}

Expand Down Expand Up @@ -96,6 +107,7 @@ export function formatData(data: Data, args: Inputs): Output {
(acc, script) => [
...acc,
...(Array.isArray(script.params) ? script.params : []),
...(script.optionalParams ? Object.keys(script.optionalParams) : []),
],
[] as string[],
);
Expand Down Expand Up @@ -143,11 +155,21 @@ export function formatData(data: Data, args: Inputs): Output {
return isExternalScript(script)
? {
...script,
url: formatUrl(script.url, script.params, scriptUrlParamInputs),
url: formatUrl(
script.url,
allScriptParams,
scriptUrlParamInputs,
undefined,
script.optionalParams,
),
}
: {
...script,
code: formatCode(script.code, scriptUrlParamInputs),
code: formatCode(
script.code,
scriptUrlParamInputs,
script.optionalParams,
),
};
})
: undefined,
Expand Down
Loading