Skip to content

Commit

Permalink
fix: Bundling and make utils isomorphic
Browse files Browse the repository at this point in the history
  • Loading branch information
p10ns11y committed Nov 10, 2024
1 parent 6ca47ae commit 9bf5a25
Show file tree
Hide file tree
Showing 11 changed files with 442 additions and 51 deletions.
3 changes: 3 additions & 0 deletions jest.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,7 @@ export default {
},
extensionsToTreatAsEsm: ['.ts', '.tsx'],
coverageReporters: ['json-summary'],
// moduleNameMapper: {
// '^@adaptate/utils/(.*)$': '<rootDir>/packages/utils/src/$1',
// },
};
8 changes: 5 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,17 @@
"README.md"
],
"scripts": {
"test": "node --experimental-vm-modules --no-warnings node_modules/jest/bin/jest.js --coverage",
"build": "turbo run build"
"test": "vitest",
"build": "turbo run build",
"coveragebadge": "npx make-coverage-badge --output-path ./coverage-badge.svg"
},
"devDependencies": {
"@types/jest": "^29.5.14",
"@types/node": "^22.9.0",
"jest": "^29.7.0",
"ts-jest": "^29.2.5",
"turbo": "^2.2.3"
"turbo": "^2.2.3",
"vitest": "^2.1.4"
},
"description": "Dynamic and Adaptable Model Validator Using Zod, Interoperable with OpenAPI",
"keywords": [
Expand Down
6 changes: 3 additions & 3 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@
"README.md"
],
"exports": {
".": {
"types": "./src/index.ts",
"default": "./build/index.es.js"
"./*": {
"types": "./src/*.ts",
"default": "./build/*.es.js"
}
},
"description": "Dynamic and Adaptable Model Validator Using Zod, Interoperable with OpenAPI",
Expand Down
29 changes: 24 additions & 5 deletions packages/core/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import { describe, it, expect } from 'vitest';

import { z } from 'zod';

import {
getDereferencedOpenAPIDocument,
openAPISchemaToZod,
Expand Down Expand Up @@ -82,7 +85,7 @@ describe('makeSchemaRequired', () => {

expect(() => transformedSchema.parse(invalidDataMissingName))
.toThrowErrorMatchingInlineSnapshot(`
"[
[ZodError: [
{
"code": "invalid_type",
"expected": "string",
Expand All @@ -105,7 +108,7 @@ describe('makeSchemaRequired', () => {
],
"message": "Required"
}
]"
]]
`);

// Re transforming the schema with different config
Expand All @@ -129,7 +132,7 @@ describe('makeSchemaRequired', () => {
expect(() => baseSchema.parse(invalidDataItems)).toThrow();
expect(() => transformedSchema.parse(invalidDataItems))
.toThrowErrorMatchingInlineSnapshot(`
"[
[ZodError: [
{
"code": "invalid_type",
"expected": "string",
Expand All @@ -152,7 +155,7 @@ describe('makeSchemaRequired', () => {
],
"message": "Expected array, received string"
}
]"
]]
`);

// TODO: Update code after evaluating the case of list of objects at top level
Expand Down Expand Up @@ -215,6 +218,22 @@ describe('makeSchemaRequired', () => {
dereferencedOpenAPIDocument['components']['schemas']['Category']
);

try {
// Intentionally not mocking the fetch call
let dereferencedOpenAPIDocumentFromWeb =
await getDereferencedOpenAPIDocument(
'https://raw.githubusercontent.com/p10ns11y/adaptate/refs/heads/main/packages/core/src/fixtures/base-schema.yml',
'',
'browser'
);

expect(dereferencedOpenAPIDocumentFromWeb).toEqual(
dereferencedOpenAPIDocument
);
} catch (e) {
console.log('Network failure or', (e as any)?.message);
}

let yetAnotherTransformedSchema = makeSchemaRequired(dataZodSchema, config);

expect(() =>
Expand Down Expand Up @@ -315,7 +334,7 @@ describe('makeSchemaRequired', () => {
expect(() =>
makeSchemaRequired(invalidSchema, config)
).toThrowErrorMatchingInlineSnapshot(
`"The given schema must be a Zod object."`
`[Error: The given schema must be a Zod object.]`
);
});

Expand Down
Binary file added packages/utils/images/import-fix.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 9 additions & 14 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@
"check-types": "tsc --noEmit"
},
"dependencies": {
"@apidevtools/json-schema-ref-parser": "^11.7.2",
"@apidevtools/swagger-parser": "^10.1.0",
"js-yaml": "^4.1.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@apidevtools/swagger-parser": "^10.1.0",
"@types/js-yaml": "^4.0.9",
"js-yaml": "^4.1.0",
"vite": "^5.4.10"
},
"peerDependencies": {
Expand All @@ -41,20 +42,14 @@
],
"exports": {
".": {
"types": "./src/index.ts",
"types": "./src/index",
"import": "./build/index.js",
"default": "./build/index.es.js"
},
"./openapi": {
"import": {
"types": "./src/openapi.ts",
"default": "./src/openapi.ts"
},
"require": {
"types": "./src/openapi.ts",
"default": "./build/openapi.es.js"
},
"types": "./src/openapi.ts",
"default": "./build/openapi.es.js"
"./*": {
"types": "./src/*.ts",
"import": "./build/*.js",
"default": "./build/*.es.js"
}
},
"description": "Dynamic and Adaptable Model Validator Using Zod, Interoperable with OpenAPI",
Expand Down
14 changes: 8 additions & 6 deletions packages/utils/src/__tests__/openapi.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { describe, it, expect } from 'vitest';

import { z } from 'zod';

import {
Expand Down Expand Up @@ -316,11 +318,11 @@ describe('getDereferencedOpenAPIDocument', () => {
},
}
`);
});

expect(() =>
getDereferencedOpenAPIDocument(import.meta.url, '../fixtures/unknown.yml')
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Error reading OpenAPI document: ENOENT: no such file or directory, open '/Users/peram/code/adaptate/packages/utils/src/fixtures/unknown.yml'"`
);
await expect(() =>
getDereferencedOpenAPIDocument(import.meta.url, '../fixtures/unknown.yml')
).rejects.toThrowErrorMatchingInlineSnapshot(
`[Error: Error reading OpenAPI document: ENOENT: no such file or directory, open '/Users/peram/code/adaptate/packages/utils/src/fixtures/unknown.yml']`
);
});
});
16 changes: 16 additions & 0 deletions packages/utils/src/load-yaml.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import yaml from 'js-yaml';

export async function getYamlContent(fileURL: string, relativePath: string) {
let fs = await import('node:fs');
let path = await import('node:path');
let { fileURLToPath } = await import('node:url');
let { dirname } = path;
let fileURLPath = fileURLToPath(fileURL);
let callerDirectoryName = dirname(fileURLPath);
let yamlFilePath = path.resolve(callerDirectoryName, relativePath);
let openapiDocument = yaml.load(
fs.readFileSync(yamlFilePath, 'utf8')
) as string;

return openapiDocument;
}
48 changes: 35 additions & 13 deletions packages/utils/src/openapi.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import SwaggerParser from '@apidevtools/swagger-parser';
import yaml from 'js-yaml';

import { z, ZodTypeAny, ZodArray, ZodObject } from 'zod';
Expand Down Expand Up @@ -79,23 +78,46 @@ export function zodToOpenAPISchema(schema: ZodTypeAny): any {
return {};
}

async function fetchYamlContent(fileURL: string, relativePath: string) {
let fileURLPath = fileURL + relativePath;
let response = await globalThis.fetch(fileURLPath, {
headers: {
'Content-Type': 'text/yaml',
},
});
let openapiDocument = yaml.load(await response.text());

return openapiDocument;
}

export async function getDereferencedOpenAPIDocument(
fileURL: string,
relativePath: string
relativePath: string = '',
environment: 'server' | 'browser' = 'server'
) {
let openapiDocument = JSON.stringify({});

let isNode = globalThis.process?.versions?.node || environment === 'server';
let isBrowser = globalThis?.window?.document || environment === 'browser';

try {
let fs = await import('node:fs');
let path = await import('node:path');
let { fileURLToPath } = await import('node:url');
let { dirname } = path;
let fileURLPath = fileURLToPath(fileURL);
let callerDirectoryName = dirname(fileURLPath);
let yamlFilePath = path.resolve(callerDirectoryName, relativePath);
const openapiDocument = yaml.load(
fs.readFileSync(yamlFilePath, 'utf8')
) as string;
if (isBrowser) {
openapiDocument = (await fetchYamlContent(
fileURL,
relativePath
)) as string;
} else if (isNode) {
let { getYamlContent } = await import('./load-yaml.ts');

openapiDocument = await getYamlContent(fileURL, relativePath);
}
// https://github.com/APIDevTools/json-schema-reader/blob/main/src/index.ts#L21
// let SwaggerParser = await import('@apidevtools/swagger-parser');
let SwaggerParser = await import('@apidevtools/json-schema-ref-parser');

const dereferenced = await SwaggerParser.dereference(openapiDocument);
const dereferenced = await SwaggerParser.default.dereference(
openapiDocument
);

return dereferenced;
} catch (error) {
Expand Down
37 changes: 36 additions & 1 deletion packages/utils/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,53 @@
// vite.config.js
// import { fileURLToPath } from 'node:url';

import { defineConfig } from 'vite';
import { builtinModules } from 'module';

// let yamlLoader = fileURLToPath(new URL('src/load-yaml.ts', import.meta.url));

// import { nodeResolve } from '@rollup/plugin-node-resolve';
// import commonjs from '@rollup/plugin-commonjs';

export default defineConfig({
// plugins: [
// nodeResolve({
// // browser: true,
// preferBuiltins: true,
// }),
// commonjs({
// preferBuiltins: true,
// // browser: true,
// }),
// ],
// plugins: [
// nodeResolve({
// preferBuiltins: true,
// browser: false,
// }),
// commonjs(),
// ],
// resolve: {
// preferBuiltins: true,
// browser: false,
// },
build: {
target: 'esnext',
ssr: true,
outDir: 'build',
// minify: false,
lib: {
entry: ['src/index.ts', 'src/openapi.ts'],
formats: ['es'],
fileName: (format, entryName) => `${entryName}.${format}.js`,
types: 'src/index.d.ts',
},
rollupOptions: {
external: ['zod'],
external: ['zod', ...builtinModules],
},
},
// external: [/load\-yaml/],
// optimizeDeps: {
// include: ['@apidevtools/swagger-parser', 'js-yaml'],
// },
});
Loading

0 comments on commit 9bf5a25

Please sign in to comment.