Code Monkey home page Code Monkey logo

fern-typescript's Introduction


header

TypeScript Generator

Contributors Pulls-opened Pulls-merged

Discord

This repository contains the source for the various generators that produce TypeScript artifacts for Fern:

  • fernapi/fern-typescript-node-sdk
  • fernapi/fern-typescript-browser-sdk
  • fernapi/fern-typescript-express

The TypeScript generators are written in TypeScript. We strongly emphasize idiomatic code generation that feels hand-written and is friendly to read.

Fern handles transforming an API definition -- either an OpenAPI or Fern specification -- into Fern intermediate representation. IR is a normalized, Fern-specific definition of an API containing its endpoints, models, errors, authentication scheme, version, and more. Then the TypeScript generator takes over and turns the IR into production-ready code.

What is Fern?

Fern is an open source toolkit for designing, building, and consuming REST APIs. With Fern, you can generate client libraries, API documentation and boilerplate for your backend server.

Head over to the official Fern website for more information, or head over to our Documentation to dive straight in and find out what Fern can do for you!

Generating TypeScript

This generator is used via the Fern CLI, by defining one of the aforementioned TypeScript artifacts as a generator:

- name: fernapi/fern-typescript-node-sdk
  version: 0.7.1
  output:
    location: npm
    url: npm.buildwithfern.com
    package-name: "@my-org/petstore"

By default, Fern runs the generators in the cloud. To run a generator on your local machine, using the --local flag for fern generate. This will run the generator locally in a Docker container, allowing you to inspect its logs and output. Read more.

Configuration

You can customize the behavior of generators in generators.yml:

default-group: local
groups:
  local:
    generators:
      - name: fernapi/fern-typescript-node-sdk
        version: 0.7.1
        config: # <--
          useBrandedStringAliases: true

SDK Configuration

The Node SDK and Browser SDK generators support the following options:

useBrandedStringAliases

Type: boolean

Default: false

When enabled, string aliases are generated as branded strings. This makes each alias feel like its own type and improves compile-time safety.

View example
# fern definition

types:
  MyString: string
  OtherString: string
// generated code

export type MyString = string & { __MyString: void };
export const MyString = (value: string): MyString => value as MyString;

export type OtherString = string & { __OtherString: void };
export const OtherString = (value: string): OtherString => value as OtherString;
// consuming the generated type

function printMyString(s: MyString): void {
  console.log("MyString: " + s);
}

// doesn't compile, "foo" is not assignable to MyString
printMyString("foo");

const otherString = OtherString("other-string");
// doesn't compile, otherString is not assignable to MyString
printMyString(otherString);

// compiles
const myString = MyString("my-string");
printMyString(myString);

When useBrandedStringAliases is disabled (the default), string aliases are generated as normal TypeScript aliases:

// generated code

export type MyString = string;

export type OtherString = string;

neverThrowErrors

Type: boolean

Default: false

When enabled, the client doesn't throw errors when a non-200 response is received from the server. Instead, the response is wrapped in an ApiResponse.

const response = await client.callEndpoint(...);
if (response.ok) {
  console.log(response.body)
} else {
  console.error(respons.error)
}

namespaceExport

Type: string

By default, the exported namespace and client are named based on the organization and API names in the Fern Definition.

import { AcmeApi, AcmeApiClient } from "@acme/node";

To customize these names, you can use namepaceExport:

# generators.yml
config:
  namespaceExport: Acme
import { Acme, AcmeClient } from "@acme/node";

outputEsm

Type: boolean

Default: false

By default, the generated TypeScript targets CommonJS. Set outputEsm to true to target esnext instead.

outputSourceFiles

Type: boolean

Default: false

Note: This only applies when dumping code locally. This configuration is ignored when publishing to Github or npm.

When enabled, the generator outputs raw TypeScript files.

When disabled (the default), the generator outputs .js and d.ts files.

includeCredentialsOnCrossOriginRequests

Type: boolean

Default: false

When enabled, withCredentials is set to true when making network requests.

allowCustomFetcher

Type: boolean

Default: false

When enabled, the generated client allows the end user to specify a custom fetcher implementation.

const acme = new AcmeClient({
  fetcher: (args) => {
    ...
  },
});

requireDefaultEnvironment

Type: boolean

Default: false

When enabled, the generated client doesn't allow the user to specify a server URL.

When disabled (the default), the generated client includes an option to override the server URL:

const acme = new AcmeClient({
  environment: "localhost:8080",
});

defaultTimeoutInSeconds

Type: number

Default: 60

The default timeout for network requests. In the generated client, this can be overridden at the request level.

skipResponseValidation

Type: boolean

Default: false

By default, the client will throw an error if the response from the server doesn't match the expected type (based on how the response is modeled in the Fern Definition).

If skipResponseValidation is enabled, the client will never throw if the response is misshapen. Rather, the client will log the issue using console.warn and return the data (casted to the expected response type).

extraDependencies

Type: map<string, string>

Default: {}

Note: This only applies when publishing to Github.

You can use extraDependencies to specify extra dependencies in the generated package.json. This is useful when you utilize .fernignore to supplement the generated client with custom code.

# generators.yml
config:
  extraDependencies:
    jest: "^29.6.1"

treatUnknownAsAny

Type: boolean

Default: false

In Fern, there's an unknown type that represents data that isn't knowable at runtime. By default, these types are generated into TypeScript as the unknown type.

When treatUnknownAsAny is enabled, unknown types from Fern are generated into TypeScript using any.

noSerdeLayer

Type: boolean

Default: false

By default, the generated client includes a layer for serializing requests and deserializing responses. This has three benefits:

  1. The client validates requests and response at runtime, client-side.

  2. The client can support complex types, like Date and Set.

  3. The generated types can stray from the wire/JSON representation to be more idiomatic. For example, when noSerdeLayer is disabled, all properties are camelCase, even if the server is expecting snake_case.

When noSerdeLayer is enabled, no (de-)serialization code is generated. The client uses JSON.parse() and JSON.stringify() instead.

noOptionalProperties

Type: boolean

Default: false

By default, Fern's optional<> properties will translate to optional TypeScript properties:

Person:
  properties:
    name: string
    age: optional<integer>
interface Person {
  name: string;
  age?: number;
}

When noOptionalProperties is enabled, the generated properties are never optional. Instead, the type is generated with | undefined:

interface Person {
  name: string;
  age: number | undefined;
}

Express Configuration

The following options are supported when generating an Express backend:

useBrandedStringAliases

See useBrandedStringAliases under SDK Configuration

treatUnknownAsAny

See treatUnknownAsAny under SDK Configuration

noSerdeLayer

See noSerdeLayer under SDK Configuration

outputSourceFiles

See outputSourceFiles under SDK Configuration

areImplementationsOptional

Type: boolean

Default: false

By default, the generated register() will require an implementatiion for every service defined in your Fern Definition.

If areImplementationsOptional is enabled, then register() won't require any implementations. Note that this is mildly dangerous, if you forget to include an implementation, then your server behavior may drift from your docs and clients.

doNotHandleUnrecognizedErrors

Type: boolean

Default: false

By default, if you throw a non-Fern error in your endpoint handler, it will be caught by generated code and a 500 response will be returned. No details from the error will be leaked to the client.

If doNotHandleUnrecognizedErrors is enabled and you throw a non-Fern error, the error will be caught and passed on with next(error). It's your responsibility to set up error-catching middleware that handles the error and returns a response to the client.

Dependencies

The generated TypeScript code has the following dependencies:

If you are packaging your code manually, make sure to include them in your package.json.

Releases

All generator releases are published in the Releases section of the GitHub repository. You can directly use these version numbers in your generator configuration files.

For instance, if you want to use version 0.7.1 of the Node SDK generator:

default-group: local
groups:
  local:
    generators:
      - name: fernapi/fern-typescript-node-sdk
        version: 0.7.1
        output:
          location: local-file-system
          path: ../../generated/typescript

Fern will handle the rest automatically.

Contributing

We greatly value community contributions. All the work on Fern generators happens right here on GitHub, both Fern developers and community contributors work together through submitting code via Pull Requests. See the contribution guidelines in CONTRIBUTING on how you can contribute to Fern!

fern-typescript's People

Contributors

aevitas avatar dannysheridan avatar dsinghvi avatar johnwiseheart avatar mscolnick avatar zachkirsch avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.