Skip to content

Commit

Permalink
fix: sanitize object keys
Browse files Browse the repository at this point in the history
  • Loading branch information
davidenke committed Dec 17, 2024
1 parent 0ec1c26 commit 57c87a6
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/transformers/field-object.transform.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { CmsFieldBase, CmsFieldObject } from 'decap-cms-core';

import { getObjectKey } from '../utils/format.utils.js';
import type { Transformer } from '../utils/transform.utils.js';
import { transformField } from './field.transform.js';

Expand All @@ -8,7 +9,7 @@ export const transformObjectField: Transformer<CmsFieldBase & CmsFieldObject> =
fields = [],
}) => {
const results = fields.map(field => [field.name, transformField(field)] as const);
const compiled = `z.object({${results.map(([name, r]) => `${name}: ${r.compiled}`).join(',')}})`;
const compiled = `z.object({${results.map(([name, r]) => `${getObjectKey(name)}: ${r.compiled}`).join(',')}})`;
const dependencies = ['z', ...results.flatMap(([, { dependencies }]) => dependencies)];
return { compiled, dependencies };
};
7 changes: 7 additions & 0 deletions src/utils/format.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,10 @@ export async function formatCode(
export function escapeString(input: string): string {
return input.replace(/'/g, "\\'");
}

// object keys can either be strings or identifiers, the latter
// are more common and can be used without quotes
export function getObjectKey(name: string): string {
const isIdentifier = /^[a-zA-Z_$][\w$]*$/.test(name);
return isIdentifier ? name : `['${escapeString(name)}']`;
}

0 comments on commit 57c87a6

Please sign in to comment.