npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@denosaurs/typefetch

v0.0.30

Published

📤 Magically generate `fetch` types from OpenAPI schemas for zero-cost browser-native api clients

Downloads

195

Readme

TypeFetch

I dream of proper meta-programming in the wild west of ECMAScript. A parallel universe where ECMAScript had types, macros, and a proper module system. Where modules work regardless of environment and runtime. Where interfacing with the system is standardized, and code from server runtimes work in the browser. But alas, we are stuck in this bad joke of a universe where TypeScript is the next best thing. So, I present to you, TypeFetch, a tool for generating zero-cost type-safe fetch clients from OpenAPI schemas. It works everywhere you can call fetch, and anywhere you can use TypeScript.

Usage

To use TypeFetch, you need to have an OpenAPI schema. You can either provide a local file path or a URL to the schema (which can be either json or yaml), then all you need to do is run the cli using deno, node, or any other JavaScript runtime supported by the jsr registry.

deno run -A jsr:@denosaurs/typefetch
Usage: typefetch [OPTIONS] <PATH>

Options:
  -h, --help                           Print this help message
  -V, --version                        Print the version of TypeFetch
  -o, --output    <PATH>               Output file path                                                   (default: typefetch.d.ts)
      --config    <PATH>               File path to the tsconfig.json file
      --import    <PATH>               Import path for TypeFetch                                          (default: https://raw.githubusercontent.com/denosaurs/typefetch/main)
      --base-urls <URLS>               A comma separated list of custom base urls for paths to start with
      --include-server-urls            Include server URLs from the schema in the generated paths         (default: true)
      --include-absolute-url           Include absolute URLs in the generated paths                       (default: false)
      --include-relative-url           Include relative URLs in the generated paths                       (default: false)
      --experimental-urlsearchparams   Enable the experimental fully typed URLSearchParams type           (default: false)

Example

deno run -A jsr:@denosaurs/typefetch https://api.jsr.io/.well-known/openapi

This will generate a typefetch.d.ts file in the current directory, which will modify the global scope and the type definitions for the fetch function and all types defined within the schema. For example:

declare global {
  ...
  /**
   * Returns a list of packages
   * @summary List packages
   */
  function fetch(
    input: `https://api.jsr.io/packages` | `/packages`,
    init?: Omit<RequestInit, "method" | "body" | "headers"> & {
      method: "GET";
    },
  ): Promise<
    & Omit<
      Response,
      "ok" | "status" | "arrayBuffer" | "blob" | "formData" | "json" | "text"
    >
    & (
      | ({
        ok: true;
        status: 200;
        json(): Promise<{ items: Package[]; total: number }>;
        text(): Promise<JSONString<{ items: Package[]; total: number }>>;
      })
      | ({
        ok: false;
        status: 400;
        json(): Promise<Error>;
        text(): Promise<JSONString<Error>>;
      })
    )
  >;
  ...
}

Which now allows you to use the fetch function with the https://api.jsr.io/packages endpoint as following:

const response = await fetch("https://api.jsr.io/packages");

// The ok and status properties work as discriminators here to narrow the
// types of the response. That way the json and text methods are made
// type-safe.
if (response.ok) {
  console.assert(response.status === 200);

  const { items, total } = await response.json();
  // even this works because we augment the global JSON object!
  const { items, total } = JSON.parse(await response.text());
} else {
  console.assert(response.status === 400);

  const error = await response.json();
  // or
  const error = JSON.parse(await response.text());
}

Maintainers

Contributing

Pull request, issues and feedback are very welcome. Code style is formatted with deno fmt and commit messages are done following Conventional Commits spec.

Please use it! And let us know if you have any issues, feedback or requests.

Licence

Copyright 2024, the Denosaurs team. All rights reserved. MIT license.