Giter Club home page Giter Club logo

types's Introduction

Typescript Type Definitions for WebGPU

This package defines Typescript types (.d.ts) for the upcoming WebGPU standard.

Use this package to augment the ambient "dom" type definitions with the new definitions for WebGPU.

API style docs

This repo also generates typedoc docs here: https://gpuweb.github.io/types

What are declaration files?

See the TypeScript handbook.

How can I use them?

Install

  • npm: npm install --save-dev @webgpu/types
  • yarn: yarn add --dev @webgpu/types
  • pnpm: pnpm add -D @webgpu/types

If you are on TypeScript < 5.1, you will also need to install @types/dom-webcodecs as a sibling dependency. The version you need depends on the TypeScript version; see the tests for examples.

Configure

Since this package is outside DefinitelyTyped, the dependency won't be picked up automatically. There are several ways to add a additional TypeScript type definition dependencies to your TypeScript project:

TypeScript tsc and tsc-based bundlers

In tsconfig.json:

{
  // ...
  "compilerOptions": {
    // ...
    "types": ["@webgpu/types"]
  }
}

Or you can use typeRoots:

{
  // ...
  "compilerOptions": {
    // ...
    "typeRoots": ["./node_modules/@webgpu/types", "./node_modules/@types"]
  }
}

Inline in TypeScript

This may work better if your toolchain doesn't read tsconfig.json.

/// <reference types="@webgpu/types" />

Webpack

If you use Webpack and the options above aren't sufficient (this has not been verified), you may need the following in webpack.config.js:

"types": ["@webgpu/types"]

Others?

Please contribute a PR to add instructions for other setups or improve existing instructions. :)

How to update these types

  • Make sure the submodule is checked out: git submodule update --init
  • Pull gpuweb changes: pushd gpuweb && git checkout main && git pull && popd
  • Install dependencies: npm ci
  • Bug workaround: paste the copies.bs contents in place of its include in index.bs (generator doesn't support includes).
  • Generate generated/index.d.ts: npm run generate
  • Open a diff between generated/index.d.ts and dist/index.d.ts. The generated file is tracked by Git so you can see what has changed. Update the latter according to changes from the former. Note the generated/ and dist/ files are not the same. See below for intentional differences.
  • Format the result: npm run format

Intentional differences between generator output and final result

Most or all of these should be fixed in the generator over time.

  • Array changed to Iterable for WebIDL sequences in argument positions.
  • any changed to object for WebIDL object.
  • | SharedArrayBuffer added for [AllowShared] BufferSource.

The following differences are TODO: should be changed in the final result.

  • Deprecated items should be removed.

The following differences will remain.

  • onuncapturederror strongly typed.
  • getContext definitions.
  • GPUExtent3DStrict and GPUOrigin2DStrict.

Publish a new npm package version

(only for people who have npm publish access)

  • One line cmd to copy-n-paste (for ssh git user, and you'd better know what you are doing, if it failed at certain steps, you might need to clean up git tags before trying again)
    • git checkout main && git pull [email protected]:gpuweb/types.git main && git submodule update --init && npm version patch && git push [email protected]:gpuweb/types.git main --tags && npm publish
  • Separate steps (better for publishing for the first time)
    • Make sure you are in the upstream repo, not your forked one. And make sure you are synced to latest commit intended for publish
      • git checkout main
      • git pull https://github.com/gpuweb/types.git main
        • (If you are using HTTPS regularly. You can use remote names like origin, just make sure you are referring to the right repo)
      • git submodule update --init
    • Create the version tag and commit, and push
      • npm version patch
      • git push https://github.com/gpuweb/types.git main --tags
    • publish the package
      • npm publish --otp=<code>
        • Replace <code> with the one-time password from your authenticator, since two-factors authentication is required to publish.
        • If you are doing for the first time, you will do npm adduser first and it will guide you through adding the npm account.

types's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

types's Issues

Cannot find name 'VideoFrame'.

I'm trying to make my first steps with WebGPU using TypeScript/Angular and wanted to user you types. However upon calling ng serve I'll get the two errors:

Error: node_modules/@webgpu/types/dist/index.d.ts:85:7 - error TS2304: Cannot find name 'VideoFrame'.
Error: node_modules/@webgpu/types/dist/index.d.ts:811:7 - error TS2304: Cannot find name 'VideoFrame'.

Suggested by this post, I already tried to install @types/dom-webcodecs as well, without success.
Can somebody suggest a solution to this ?

Build broken due to const in namespace

The upstream spec uses recent WebIDL syntax for const items inside namespaces. We need to fix this to make the autogeneration work again.

This may just need newer webidl2 dependencies to be rolled (transitively in webidl2ts and bikeshed-to-ts) or it may require small fixes in those packages.

GPUOrigin2D is a subtype of GPUOrigin3D

This means it's possible to accidentally pass a GPUOrigin3D where a GPUOrigin2D was required. Which is technically allowed, but a likely bug.

I think we should use a Strict version, GPUOrigin2DStrict, similar to GPUExtent3DStrict.

Errors when using types with a web worker.

It seems like the types definition only works cleanly when used with the "dom" library. If you attempt to use it with the "webworker" library like so...

// Partial tsconfig.json
{
  "compilerOptions": {
    "lib": ["esnext", "webworker"],
    "typeRoots": [
      "./node_modules/@webgpu/types",
    ],
  }
}

Then you get the following errors:

node_modules/@webgpu/types/dist/index.d.ts:745:11 - error TS2304: Cannot find name 'HTMLVideoElement'.

745   source: HTMLVideoElement;
              ~~~~~~~~~~~~~~~~

node_modules/@webgpu/types/dist/index.d.ts:770:7 - error TS2304: Cannot find name 'HTMLVideoElement'.

770     | HTMLVideoElement
          ~~~~~~~~~~~~~~~~

These can be ignored by setting "skipLibCheck": true in the tsconfig, but ideally that should not be necessary to use the types in any valid environment.

I will note that it's not clear to me why HTMLVideoElement is the thing that it's latching onto here. HTMLCanvasElement would seem to have the same issue, as it's only exposed on window as well.

Consider two versions of types: one matching IDL exactly, and one that's stronger

(Long term probably)

The CTS needs the types to match IDL exactly, otherwise they can prevent us from writing tests for certain behavior.

Other projects may prefer stronger guarantees in cases where TypeScript can express something WebIDL cannot (e.g. disabling use of the constructor on GPUDevice, or perhaps allowing only one of the variants of GPUBindGroupLayoutEntry). There will be places we have to be careful not to be excessively strict, though (like allowing only tuples instead of arrays, or only GPUExtensionName instead of string, would be annoying).

Why constant variables name haven't preffix 'GPU'

For example:
image
The name is AddressMode, however in docs, most of these constant variables start with 'GPU' like this:
image

So is it a right way to define constant variables without preffix 'GPU' in d.ts file?

Polish the type definitions generator

A while back I wrote this document describing a potential project to fix a few bugs in the generator for WebGPU's TypeScript type definitions to make it more maintainable. I filed these as separate issues on bikeshed-to-ts, so this is essentially a tracking issue for those - see issues for details, see doc for summary.

https://docs.google.com/document/d/1MVPbUakXBKwvAd5CN3BJd2Ems5OhYhFt5pKpvrw8SN4/edit?usp=sharing&resourcekey=0-wdToK40p4UEnBKMNguYNmw

Types not compatible with TypeScript `exactOptionalPropertyTypes` option

In TypeScript, by default, if you have an optional field like:
{ x?: number }
then it allows any of:
{ x: 5 }, { x: undefined }, {}

There is an option called exactOptionalPropertyTypes, which makes { x: undefined } invalid, allowing only:
{ x: 5 }, {}

However { x: undefined } is allowed by the rules of WebIDL, so all of our optional fields need to be written like:
{ x?: undefined | number }

Enums instead of union types.

First of all, thanks for the very helpful library.

One thing I've noticed is that the union types used for parameter values etc are a bit cumbersome when writing and navigating code. I think it would be easier to use enums. For example, if we take the following type:

type GPUVertexStepMode =
  | "vertex"
  | "instance";

We could also define it like:

enum GPUVertexStepMode {
    VERTEX = "vertex",
    INSTANCE = "instance",
}

At the usage site, we get:

const bufferLayout: GPUVertexBufferLayout = {
    stepMode: 'vertex', // With type unions
    stepMode: GPUVertexStepMode.VERTEX, // With an enum
};

I think there are two benefits of using enums, one is that you can type EnumName. to see the available options. The other benefit is that you see the name of the type at the usage site, if I only see "vertex" I have to look up the struct or function type to see the definition.

Is there any reason not to use enums that I've missed? If not, is it something you think belongs in this library?

Thanks in advance,
Martin

"new GPUInternalError(...)" should return type GPUInternalError

GPUInternalError's new function / constructor is defined without a return type, so it defaults to any. Should this return type be the GPUInternalError interface instead?

interface GPUInternalError
  extends GPUError {
  /**
   * Nominal type branding.
   * https://github.com/microsoft/TypeScript/pull/33038
   * @internal
   */
  readonly __brand: "GPUInternalError";
}

declare var GPUInternalError: {
  prototype: GPUInternalError;
  new (
    message: string
  );
};

Proposed change:

...
declare var GPUInternalError: {
  prototype: GPUInternalError;
  new (
    message: string
  ): GPUInternalError; // <--- This right here.
};

I'd send a PR, but if I understand correctly, this file is generated.

Consider providing ES6 module distribution

Currently, all WebGPU types are added to the global ambients. The option to have them scoped as a module rather than global would be very helpful for me.

Working on large projects, particularly with graphics hardware abstraction layers, types such as GPUBuffer conflict with types already in the engine. For this reason as well as for overall organization and transparency into where the symbols came from in source code, it would be nice to be able to import these types from the package at the top of our ES6 files, as a module.

An additional distribution file that has all the export keywords added could be a solution, since bikeshed-to-ts does seem to have that feature, and typescript would see such a file as a module. Another idea might be to provide a dist file that simply has a declare module wrapper.

For clarity, here's an example of what I'm trying to do:

import type { GPUBuffer } from '@webgpu/types'
// use GPUBuffer

or

import type { GPUBuffer as WebGPUGPUBuffer } from '@webgpu/types'
// use WebGPUGPUBuffer

or

import * as WebGPU from '@webgpu/types'
// use WebGPU.GPUBuffer

Currently, we get
File '.../node_modules/@webgpu/types/dist/index.d.ts' is not a module.

error TS2304: Cannot find name 'PredefinedColorSpace'

After upgrading webgpu/types from 0.1.16 to 0.1.21, I always meet below errors in PR tfjs:6862:

Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": �[96m../node_modules/@webgpu/types/dist/index.d.ts�[0m:�[93m587�[0m:�[93m16�[0m - �[91merror�[0m�[90m TS2304: �[0mCannot find name 'PredefinedColorSpace'.
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": 
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": �[7m587�[0m   colorSpace?: PredefinedColorSpace;
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": �[7m   �[0m �[91m               ~~~~~~~~~~~~~~~~~~~~�[0m
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": 
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": �[96m../node_modules/@webgpu/types/dist/index.d.ts�[0m:�[93m728�[0m:�[93m16�[0m - �[91merror�[0m�[90m TS2304: �[0mCannot find name 'PredefinedColorSpace'.
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": 
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": �[7m728�[0m   colorSpace?: PredefinedColorSpace;
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": �[7m   �[0m �[91m               ~~~~~~~~~~~~~~~~~~~~�[0m
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": 
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": �[96m../node_modules/@webgpu/types/dist/index.d.ts�[0m:�[93m800�[0m:�[93m16�[0m - �[91merror�[0m�[90m TS2304: �[0mCannot find name 'PredefinedColorSpace'.
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": 
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": �[7m800�[0m   colorSpace?: PredefinedColorSpace;
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": �[7m   �[0m �[91m               ~~~~~~~~~~~~~~~~~~~~�[0m
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": 
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": 
Step #2 - "run-cloudbuild": Step #20 - "build-tfjs": Found 3 errors.

Confused by the types of copyBufferToTexture

I read the great proposal for copy by @Kangz . I understood we want to support "copy a portion of the buffer to a region of the texture".

In the specs the last parameter of the copyBufferToTexture is:
typedef (sequence<GPUIntegerCoordinate> or GPUExtent3DDict) GPUExtent3D;

In the types I see:

// (either a point xor dimension).
export type GPUExtent3D = [number, number, number] | GPUExtent3DDict;

A XOR/union sounds inadequate, I think we wanted at least an intersection (both offset and dimensions to define a proper region)?
Or are we expected to change the offset in the buffer object and the texture object directly?

Thank you!

getSwapChainPreferredFormat() is not suitable for the lastest spec.

Passing a GPUDevice to getSwapChainPreferredFormat is deprecated. Pass a GPUAdapter instead, and update the calling code to expect a GPUTextureFormat to be retured instead of a Promise.

it should be:

  // SwapChain / CanvasContext
  export class GPUCanvasContext {
    private __brand: void;
    configureSwapChain(descriptor: GPUSwapChainDescriptor): GPUSwapChain;

    getSwapChainPreferredFormat(adapter: GPUAdapter): GPUTextureFormat;
  }

but now what is in the type definition file :

  // SwapChain / CanvasContext
  export class GPUCanvasContext {
    private __brand: void;
    configureSwapChain(descriptor: GPUSwapChainDescriptor): GPUSwapChain;

    getSwapChainPreferredFormat(device: GPUDevice): Promise<GPUTextureFormat>;
  }

How do I use this?

Your README gives the instruction

npm install --save @webgpu/types

…but explains no further. I run this, then run webpack

ERROR in /Users/mcc/work/h/hello-more/webgpu/src/index.tsx
./src/index.tsx
[tsl] ERROR in /Users/mcc/work/h/hello-more/webgpu/src/index.tsx(58,18)
      TS2339: Property 'gpu' does not exist on type 'Navigator'.

Is there another step?

I remember like five years ago there was some kind of magic ///include "path.d.ts" with a weird syntax that you used in TypeScript to import ambient d.ts files but ever since the @types regime came I've only got types through the normal import statement. I'm not sure how that works since these are ambient definitions.

Firing at random I tried various things like import * as WebGPU from "@types/WebGPU" and got various errors like

ERROR in /Users/mcc/work/h/hello-more/webgpu/src/index.tsx
./src/index.tsx
[tsl] ERROR in /Users/mcc/work/h/hello-more/webgpu/src/index.tsx(3,25)
      TS2307: Cannot find module 'WebGPU' or its corresponding type declarations.

"Expected behavior": There should be a line in the README explaining how to use these types. If I got confused probably so would other people.

Unergonomic type for `size` of GPUTextureDescriptor

Accessing the properties of size in a GPUTextureDescriptor requires first casting it as a GPUExtent3DDictStrict:

const texture: GPUTextureDescriptor = {
  size: { width: 1, height: 2, depthOrArrayLayers: 2 }, // No TS error here
  usage: GPUTextureUsage.COPY_DST,
  format: navigator.gpu.getPreferredCanvasFormat()
};

texture.size.width // Property 'width' does not exist on type 'GPUExtent3DStrict'.
texture.size.depthOrArrayLayers // Property 'depthOrArrayLayers' does not exist on type 'GPUExtent3DStrict'.

const size = texture.size as GPUExtent3DDictStrict;

size.width // OK
size.depthOrArrayLayers // OK

I understand this is probably because size can either be an Iterable or an object, but this isn't very ergonomic.
Perhaps GPUTextureDescriptor could take an optional generic parameter to determine the type of size?

Either way allowing size to be a union type makes dynamically handling GPUTextureDescriptors more complicated than it should be, since it forces you to check the type first.

I realize this is more of a spec issue than a types issue, but ideally size should just have one type. The drawbacks of having to check at runtime if it's an object or Iterable far outweigh the convenience of defining it more concisely as an array.

Remove "src" folder from npm package

I installed this types package, and then added:

"typeRoots": [
        "./node_modules/@webgpu/types",
      ]

to my tsconfig.json, when compiling it throws an error:

Cannot find type definition file for 'src'.

Pretty sure if we just remove the src folder (add an .npmignore) it will go away. I can make a pr if you want?

GPUBuffer#mapAsync does not match spec

 mapAsync(offset?: number, size?: number): Promise<void>;
vs
Promise<void> mapAsync(GPUMapModeFlags mode, optional GPUSize64 offset = 0, optional GPUSize64 size);

Make view property of GPURenderPassColorAttachment optional or accept null/undefined

Currently it seems that there is no way to make the following code from "WebGPU Samples" work. They have disabled the strict setting which is not ideal.

https://webgpu.github.io/webgpu-samples/samples/rotatingCube

`
const renderPassDescriptor: GPURenderPassDescriptor = {
colorAttachments: [
{
view: undefined, // Assigned later

    clearValue: { r: 0.5, g: 0.5, b: 0.5, a: 1.0 },
    loadOp: 'clear',
    storeOp: 'store',
  },
],

//...
};
`

Cannot find name 'VideoFrame' error

I have a WebGPU project that runs fine using @webgpu/types version 0.1.31. However, when updating to 0.1.33, I got the following error when running the same project:

node_modules/@webgpu/types/dist/index.d.ts:83:7 - error TS2304: Cannot find name 'VideoFrame'.

83 | VideoFrame
~~~~~~~~~~

node_modules/@webgpu/types/dist/index.d.ts:807:7 - error TS2304: Cannot find name 'VideoFrame'.

807 | VideoFrame;
~~~~~~~~~~

The error seems nothing to do with my code. How to fix it?

Include documentation in the types

It would be very handy to include /** doc comments */ in this types file.

Ideally, we could extract these doc comments from the spec automatically (perhaps along with autogenerating the entire types file from the IDL in the spec), but I don't know how we would do that.

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.