Skip to content

🎥 Make videos programmatically with React

stringify default props in a good way

Jonny Burgerb62c84e2b987
diff --git a/packages/cli/src/codemods/stringify-with-path.ts b/packages/cli/src/codemods/stringify-with-path.ts
new file mode 100644
index 0000000000..985a2338f2
--- /dev/null
+++ b/packages/cli/src/codemods/stringify-with-path.ts
@@ -0,0 +1,72 @@
+type Path = (string | number)[];
+
+const doesMatchPath = (path1: Path, enumPaths: Path[]) => {
+ return enumPaths.some((p) =>
+ path1.every((item, index) => {
+ if (p[index] === '[]' && !Number.isNaN(Number(item))) {
+ return true;
+ }
+
+ if (p[index] === '{}' && typeof item === 'string') {
+ return true;
+ }
+
+ return item === p[index];
+ })
+ );
+};
+
+export const stringifyDefaultProps = ({
+ props,
+ enumPath,
+}: {
+ props: unknown;
+ enumPath: Path[];
+}) =>
+ JSON.stringify(
+ props,
+ replacerWithPath(function (key, value, path) {
+ /* Don't replace with arrow function */ const item = this[key];
+ if (item instanceof Date) {
+ return `__REMOVEQUOTE__new Date('${item.toISOString()}')__REMOVEQUOTE__`;
+ }
+
+ if (typeof this[key] === 'string' && doesMatchPath(path, enumPath)) {
+ return `${this[key]}__ADD_AS_CONST__`;
+ }
+
+ return value;
+ })
+ )
+ .replace(/"__REMOVEQUOTE__/g, '')
+ .replace(/__REMOVEQUOTE__"/g, '')
+ .replace(/__ADD_AS_CONST__"/g, '" as const');
+
+function replacerWithPath(
+ replacer: (
+ this: Record<string, unknown>,
+ field: string,
+ value: unknown,
+ path: (string | number)[]
+ ) => unknown
+) {
+ const m = new Map();
+
+ return function (
+ this: Record<string, unknown>,
+ field: string,
+ value: unknown
+ ) {
+ const path = [m.get(this), field].flat(1);
+ if (value === Object(value)) {
+ m.set(value, path);
+ }
+
+ return replacer.call(
+ this,
+ field,
+ value,
+ path.filter((item) => typeof item !== 'undefined' && item !== '')
+ );
+ };
+}
diff --git a/packages/cli/src/codemods/update-default-props.ts b/packages/cli/src/codemods/update-default-props.ts
index 9a234483da..c14cae30b7 100644
--- a/packages/cli/src/codemods/update-default-props.ts
+++ b/packages/cli/src/codemods/update-default-props.ts
@@ -1,3 +1,5 @@
+import {stringifyDefaultProps} from './stringify-with-path';
+
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
type PrettierType = typeof import('prettier');
@@ -92,26 +94,6 @@ const findTerminators = (input: string, position: number) => {
return Infinity;
};
-const stringifyDefaultProps = (props: unknown) => {
- // Don't replace with arrow function
- return JSON.stringify(props, function (key, value) {
- if (this[key] instanceof Date) {
- return `__REMOVEQUOTE__new Date('${new Date(
- this[key]
- ).toISOString()}')__REMOVEQUOTE__`;
- }
-
- if (typeof this[key] === 'string') {
- return `${this[key]}__ADD_AS_CONST__`;
- }
-
- return value;
- })
- .replace(/"__REMOVEQUOTE__/g, '')
- .replace(/__REMOVEQUOTE__"/g, '')
- .replace(/__ADD_AS_CONST__"/g, '" as const');
-};
-
// TODO: Add more sanity checks
export const updateDefaultProps = async ({
input,
@@ -154,7 +136,7 @@ export const updateDefaultProps = async ({
const newFile =
input.substring(0, startPos) +
- stringifyDefaultProps(newDefaultProps) +
+ stringifyDefaultProps({props: newDefaultProps}) +
input.substring(endPos);
const configFilePath = await resolveConfigFile();
diff --git a/packages/cli/src/editor/components/RenderModal/SchemaEditor/extract-enum-json-paths.ts b/packages/cli/src/editor/components/RenderModal/SchemaEditor/extract-enum-json-paths.ts
new file mode 100644
index 0000000000..1a7a19ac66
--- /dev/null
+++ b/packages/cli/src/editor/components/RenderModal/SchemaEditor/extract-enum-json-paths.ts
@@ -0,0 +1,171 @@
+import type {z} from 'zod';
+import type {ZodType} from '../../get-zod-if-possible';
+
+export const extractEnumJsonPaths = (
+ schema: Zod.ZodTypeAny,
+ zodRuntime: ZodType,
+ currentPath: (string | number)[]
+): (string | number)[][] => {
+ const def = schema._def;
+ const typeName = def.typeName as z.ZodFirstPartyTypeKind;
+
+ switch (typeName) {
+ case zodRuntime.ZodFirstPartyTypeKind.ZodObject: {
+ const shape = (def as z.ZodObjectDef).shape();
+ const keys = Object.keys(shape);
+ return keys
+ .map((key) => {
+ return extractEnumJsonPaths(shape[key], zodRuntime, [
+ ...currentPath,
+ key,
+ ]);
+ })
+ .flat(1);
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodArray: {
+ return extractEnumJsonPaths((def as z.ZodArrayDef).type, zodRuntime, [
+ ...currentPath,
+ '[]',
+ ]);
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodUnion: {
+ return (def as z.ZodUnionDef).options
+ .map((option) => {
+ return extractEnumJsonPaths(option, zodRuntime, currentPath);
+ })
+ .flat(1);
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: {
+ return (def as z.ZodDiscriminatedUnionDef<string>).options
+ .map((op) => {
+ return extractEnumJsonPaths(op, zodRuntime, currentPath);
+ })
+ .flat(1);
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodLiteral: {
+ return [currentPath];
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodEffects: {
+ return extractEnumJsonPaths(
+ (def as z.ZodEffectsDef).schema,
+ zodRuntime,
+ currentPath
+ );
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodIntersection: {
+ const {left, right} = def as z.ZodIntersectionDef;
+ const leftValue = extractEnumJsonPaths(left, zodRuntime, currentPath);
+
+ const rightValue = extractEnumJsonPaths(right, zodRuntime, currentPath);
+
+ return [...leftValue, ...rightValue];
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodTuple: {
+ return (def as z.ZodTupleDef).items
+ .map((item, i) =>
+ extractEnumJsonPaths(item, zodRuntime, [...currentPath, i])
+ )
+ .flat(1);
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodRecord: {
+ const values = extractEnumJsonPaths(
+ (def as z.ZodRecordDef).valueType,
+ zodRuntime,
+ [...currentPath, '{}']
+ );
+ return values;
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodFunction: {
+ throw new Error('Cannot create a value for type function');
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodEnum: {
+ return [currentPath];
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodNativeEnum: {
+ return [];
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodOptional: {
+ const defType = def as z.ZodOptionalDef;
+ const value = extractEnumJsonPaths(
+ defType.innerType,
+ zodRuntime,
+ currentPath
+ );
+ return value;
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodNullable: {
+ const defType = def as z.ZodNullableDef;
+ const value = extractEnumJsonPaths(
+ defType.innerType,
+ zodRuntime,
+ currentPath
+ );
+ return value;
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodDefault: {
+ const defType = def as z.ZodDefaultDef;
+ return extractEnumJsonPaths(defType.innerType, zodRuntime, currentPath);
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodCatch: {
+ const defType = def as z.ZodCatchDef;
+ return extractEnumJsonPaths(defType.innerType, zodRuntime, currentPath);
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodPromise: {
+ return [];
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodBranded: {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const defType = def as z.ZodBrandedDef<any>;
+ const value = extractEnumJsonPaths(defType.type, zodRuntime, currentPath);
+ return value;
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodPipeline: {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const defType = def as z.ZodPipelineDef<any, any>;
+ const value = extractEnumJsonPaths(defType.out, zodRuntime, currentPath);
+ return value;
+ }
+
+ case zodRuntime.ZodFirstPartyTypeKind.ZodString:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodNumber:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodBigInt:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodBoolean:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodNaN:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodDate:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodSymbol:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodUndefined:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodNull:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodAny:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodUnknown:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodNever:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodVoid:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodMap: // Maps are not serializable
+ case zodRuntime.ZodFirstPartyTypeKind.ZodLazy:
+ case zodRuntime.ZodFirstPartyTypeKind.ZodSet: {
+ // Sets are not serializable
+
+ return [];
+ }
+
+ default:
+ throw new Error('Not implemented: ' + typeName);
+ }
+};
diff --git a/packages/cli/src/test/extract-zod-enums.test.ts b/packages/cli/src/test/extract-zod-enums.test.ts
new file mode 100644
index 0000000000..1d8af67ded
--- /dev/null
+++ b/packages/cli/src/test/extract-zod-enums.test.ts
@@ -0,0 +1,65 @@
+import {expect, test} from 'vitest';
+// eslint-disable-next-line @typescript-eslint/no-restricted-imports
+import {z} from 'zod';
+import {extractEnumJsonPaths} from '../editor/components/RenderModal/SchemaEditor/extract-enum-json-paths';
+
+test('Extract Zod enums', () => {
+ expect(
+ extractEnumJsonPaths(
+ z.object({
+ enums: z.enum(['a', 'b', 'c']),
+ }),
+ z,
+ []
+ )
+ ).toStrictEqual([['enums']]);
+});
+
+test('Extract Zod enums #2', () => {
+ expect(
+ extractEnumJsonPaths(
+ z.object({
+ enums: z.enum(['a', 'b', 'c']),
+ nested: z.object({
+ second: z.enum(['a', 'b', 'c']),
+ }),
+ arrays: z.array(z.enum(['a', 'b', 'c'])),
+ union: z.object({hi: z.enum(['a'])}).or(z.object({abc: z.enum(['b'])})),
+ discriminatedUnion: z
+ .discriminatedUnion('status', [
+ z.object({status: z.literal('failed'), error: z.enum(['yo'])}),
+ z.object({status: z.literal('success'), data: z.enum(['ya'])}),
+ ])
+ .refine((x) => x.status === 'success', {path: ['status']}),
+ intersection: z.intersection(
+ z.object({a: z.enum(['a'])}),
+ z.object({b: z.enum(['b'])})
+ ),
+ tuples: z.tuple([z.enum(['a']), z.enum(['b'])]).optional(),
+ abc: z
+ .record(z.enum(['a', 'b', 'c']))
+ .nullable()
+ .default({}),
+ branded: z.object({a: z.enum(['a'])}).brand('branded'),
+ }),
+ z,
+ []
+ )
+ ).toStrictEqual([
+ ['enums'],
+ ['nested', 'second'],
+ ['arrays', '[]'],
+ ['union', 'hi'],
+ ['union', 'abc'],
+ ['discriminatedUnion', 'status'],
+ ['discriminatedUnion', 'error'],
+ ['discriminatedUnion', 'status'],
+ ['discriminatedUnion', 'data'],
+ ['intersection', 'a'],
+ ['intersection', 'b'],
+ ['tuples', 0],
+ ['tuples', 1],
+ ['abc', '{}'],
+ ['branded', 'a'],
+ ]);
+});
diff --git a/packages/cli/src/test/stringify-default-props.test.ts b/packages/cli/src/test/stringify-default-props.test.ts
new file mode 100644
index 0000000000..6b7c837760
--- /dev/null
+++ b/packages/cli/src/test/stringify-default-props.test.ts
@@ -0,0 +1,41 @@
+import {expect, test} from 'vitest';
+// eslint-disable-next-line @typescript-eslint/no-restricted-imports
+import {z} from 'zod';
+import {stringifyDefaultProps} from '../codemods/stringify-with-path';
+import {createZodValues} from '../editor/components/RenderModal/SchemaEditor/create-zod-values';
+import {extractEnumJsonPaths} from '../editor/components/RenderModal/SchemaEditor/extract-enum-json-paths';
+
+test('Should stringify default props correctly', () => {
+ const result = stringifyDefaultProps({
+ props: {
+ abc: 'def',
+ newDate: new Date('2022-01-02'),
+ },
+ enumPath: [],
+ });
+ expect(result).toBe(
+ `{"abc":"def","newDate":new Date('2022-01-02T00:00:00.000Z')}`
+ );
+});
+
+test('Should stringify default props correctly', () => {
+ const schema = z.object({
+ abc: z.enum(['hi', 'there']),
+ array: z.array(z.enum(['hi', 'there'])),
+ notAnEnum: z.string(),
+ });
+
+ const values = createZodValues(schema, z, null);
+ expect(values).toStrictEqual({
+ abc: 'hi',
+ array: ['hi'],
+ notAnEnum: '',
+ });
+ const enumPaths = extractEnumJsonPaths(schema, z, []);
+ expect(enumPaths).toStrictEqual([['abc'], ['array', '[]']]);
+
+ const result = stringifyDefaultProps({props: values, enumPath: enumPaths});
+ expect(result).toBe(
+ `{"abc":"hi" as const,"array":["hi" as const],"notAnEnum":""}`
+ );
+});