fastify / fastify-type-provider-typebox

A Type Provider for Typebox
MIT License
154 stars 27 forks source link

Cannot access 'Object' before initialization #187

Open Priyanku-oss opened 2 weeks ago

Priyanku-oss commented 2 weeks ago

Prerequisites

Fastify version

5.1.0

Plugin version

No response

Node.js version

20.10.0

Operating system

macOS

Operating system version (i.e. 20.04, 11.3, 10)

15.0.1

Description

I am trying to use typebox with fastify to include type support for api request types and response types and also autogenerate swgger documentation

Here is my index.ts code:

// Import the framework and instantiate it
import Fastify, { FastifyRequest, FastifyReply } from "fastify";
import AutoLoad from "@fastify/autoload";
import path from "path";
import Swagger from "@fastify/swagger";
import SwaggerUi from "@fastify/swagger-ui";
import healthCheckRouter from "./routes/healthcheck.routes";
import { TypeBoxTypeProvider } from "@fastify/type-provider-typebox";

const fastify = Fastify({
  logger: true,
}).withTypeProvider<TypeBoxTypeProvider>();

fastify.register(Swagger);
fastify.register(SwaggerUi, {
  routePrefix: "/documentation",
});

// Auto loading the routes using the Autoload pluggin
fastify.register(AutoLoad, {
  dir: `${__dirname}/routes`,
  options: {
    prefix: "/api/v1",
  },
});

// Base route for test
fastify.get("/", async function handler(request, reply) {
  return "Welcome to Express & TypeScript Server";
});

fastify.ready(() => {
  // generating swagger doc when the server is ready
  const openApiSpec = fastify.swagger();
  const fs = require("fs");
  const outputPath = path.join(__dirname, "../../../apiSpec.json");

  fs.writeFileSync(outputPath, JSON.stringify(openApiSpec, null, 2));
  console.log("OpenAPI specification saved to openapi.json");
});

// Run the server!
const port = 3000;
fastify
  .listen({ port })
  .then(() => {
    console.log(`Server is Fire at http://localhost:${port}`);
  })
  .catch((err) => {
    fastify.log.error(err);
    process.exit(1);
  });

And i am keeping my auth routes in auth.routes.ts file like this:

import {
  FastifyInstance,
  FastifyPluginOptions,
  RequestGenericInterface,
} from "fastify";
import { signup } from "../controllers/auth/auth.controller";
import {
  SignupSchemaJSON,
  SignupSchemaType,
} from "../controllers/auth/auth.schema";

const authRouter = async (fastify: FastifyInstance) => {
  fastify.post(
    "/auth/signup",
    {
      schema: {
        body: SignupSchemaJSON,
      },
    },
    signup
  );
};

export default authRouter;

And my auth route schemas:

import { Static, Type } from "@sinclair/typebox";

export const SignupSchemaJSON = Type.Object({
  name: Type.String(),
  mail: Type.Optional(Type.String({ format: "email" })),
});

export type SignupSchemaType = Static<typeof SignupSchemaJSON>;

When i try to run the server, using index.ts i get this error:

{"level":50,"time":1730966926503,"pid":54361,"hostname":"Priyankus-MacBook-Air.local","err":{"type":"ReferenceError","message":"Cannot access 'Object' before initialization","stack":"ReferenceError: Cannot access 'Object' before initialization\n at Object.<anonymous> (/Users/priyankuhazarika/Developer/Personal/csim/node_modules/@sinclair/typebox/build/cjs/parse/runtime.js:3:1)\n at Module._compile (node:internal/modules/cjs/loader:1376:14)\n at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)\n at Object.require.extensions.<computed> [as .js] (/Users/priyankuhazarika/Developer/Personal/csim/node_modules/ts-node/src/index.ts:1608:43)\n at Module.load (node:internal/modules/cjs/loader:1207:32)\n at Function.Module._load (node:internal/modules/cjs/loader:1023:12)\n at Module.require (node:internal/modules/cjs/loader:1235:19)\n at require (node:internal/modules/helpers:176:18)\n at Object.<anonymous> (/Users/priyankuhazarika/Developer/Personal/csim/node_modules/@sinclair/typebox/build/cjs/parse/parse.js:7:19)\n at Module._compile (node:internal/modules/cjs/loader:1376:14)"},"msg":"Cannot access 'Object' before initialization"}

Link to code that reproduces the bug

No response

Expected Behavior

The Swagger should autogenerate the auth request schemas and the server should run fine

Uzlopak commented 2 weeks ago

Can you provide a repository with your reproduction, so that we can just clone it and then try to investigate it?

priyankuhazarika commented 2 weeks ago

@Uzlopak check out this repo: https://github.com/priyankuhazarika/c-sim > packages > backend

sinclairzx81 commented 2 weeks ago

@Priyanku-oss Hi. This issue should be resolved on TypeBox 0.33.21. There was a CJS specific issue introduced on 0.33.20 which was hot fixed around the time you submitted this issue. Try refreshing your packages ensuring you are pulling the latest versions.

If you run into any problems, feel free to ping me on this thread. Hope this helps S