Git Product home page Git Product logo

typson's Introduction

A swisspush project

# Typson

Write your type definitions in TypeScript and Typson will generate json-schemas.

See it in action with its buddy docson

Build Status

Features

  • Available as Node.js module
  • Can also run as-is in the browser.
  • Integrates with Swagger.
  • Supports types in multiple files.
  • Translates required properties, extends, enums, maps, annotation keywords.

Usage

Node.js

  • Install with npm install typson -g
  • Generate definitions from a type script: typson schema example/invoice/line.ts
  • Generate a schema from a type declared in a type script: typson schema example/invoice/line.ts Invoice

Browser

<script src="vendor/require.js"/>
<script>
    require(["lib/typson-schema"], function(typson) {
            typson.schema("example/invoice/line.ts", "Invoice").done(function(schema) {
                console.log(schema);
            });
        });
</script>

Swagger

Static

Generated definitions are compatible with Swagger, you can copy Typson's output to your API files.

Dynamic

You can make Swagger UI read type definitions directly by integrating Typson, you will need a modified version of swagger.js. This version just adds the capability to load the models from another source.

See how it looks like in the Swagger Typson example (Note: this example also illustrate Docson integration in Swagger).

Then, adapt Swagger UI's index.html to

  1. Include Typson integration after the main inline script:
  <script src="/typson/vendor/require.js"></script>
  <script>
      requirejs.config({
          baseUrl: "/typson"
      });
      requirejs(["lib/typson-swagger"]);
  </script>
  1. Initialize Swagger UI only once Typson is ready:
  var typsonReady = $.Deferred();
  typsonReady.done(function () {

instead of jQuery's $(function() { initializer.

Then, just replace the models section of your API file with a tsModels property containing the URL pointing to the type script defining the models.

Similar Projects

Bitdeli Badge

typson's People

Contributors

bartvds avatar bitdeli-chef avatar jon49 avatar lbovet avatar vondacho avatar vorburger avatar

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  avatar  avatar

typson's Issues

Error: util.print: Use console.log instead

I keep getting the error Error: util.print: Use console.log instead. Which makes it more difficult to automate the creation of JSON-schemas, since I catch any stderr's before executing code. It seems to work just find with console.log as suggested.

Generate typescript interfaces from jsonschema

This is probably out of scope for typson, but it would be incredibly useful to have a typeson mode or related project that does the reverse of what typson does - i.e. convert jsonschema into a set of TypeScript interfaces, possibly with some configuration to customize the mapping (since TypeScript -> jsonschema is lossy).

I wouldn't mind if you had to use anonymous structural types in the generated TypeScript declarations, as seems likely.

How to generate string enums

I'm using react-jsonschema-form to generate UI with the schema generated by typson.

Current generated schema for:

export enum CallDirection {
	Inbound,
	Outbound
}

is :

{
	"id": "CallDirection",
	"enum": [
		"Inbound",
		"Outbound"
	]
}

There is no type property in the generated schema. But react-jsonschema-form requires a type property to render the UI.

So I try to define the string enums like this:

type CallDirection = "Inbound" | "Outbound";

But typson will report error:

lib/Config.ts(10,1): error TS1008: Unexpected token; 'module, class, interface, enum, import or statement' expected.
lib/Config.ts(10,13): error TS1005: ';' expected.

/Users/kevin.zeng/.config/yarn/global/node_modules/q/q.js:126
                    throw e;

I also try to add the type property by annotation, but it doesnot work:

/**
 * @type string
 */
export enum CallDirection {
	Inbound,
	Outbound
}

Is there any suggestions for me to generate string enums with default values, like:

{
	"id": "CallDirection",
	"type": "string",
	"enum": [
		"Inbound",
		"Outbound"
	],
	"default": "Outbound"
}

Thanks in advance.

How about a typescript definition for a schema file?

It would be nice to have a definitive typescript interface for json schema.

typson.definitions("example/invoice/line.ts").done(function(tree: JsonSchema) {
    document.getElementById("types").innerHTML = JSON.stringify(tree, undefined, 2);
});

This would facilitate the generation of server classes out of the JSON schema as you mention here

So, one can use the JSON schema to document and validate the JSON data. We can even generate the server classes out of the JSON schema.

This is the GIST of it:

interface IDependencyDescriptor {
    [s: string]: string;
}

interface IPropertyDescriptor {
    [s: string]: {
        '$ref'?: string;
        type?: string;
        format?: string;
        description?: string;
    };
}

export interface IJsonSchema {
    type: string;
    properties: IPropertyDescriptor;
    required?: Array<string>;
    dependencies?: IDependencyDescriptor;
    id?: string;
    '$schema'?: string;
    description?: string;
    title?: string;
    definitions?: any;
}

export interface IJsonSchemaModel {
    [s: string]: IJsonSchema;
}

Would you like a setup for unit tests?

If you want I can setup some easy too maintain tests using grunt, grunt-mocha-test etc. I do those a lot, I think I have a nice pattern to make it easy to update.

Test suite would make it possible to be specific in development or send demos for breakage or new features. Also gets you Travis-CI for PR's (worth it).

I'll trade you this for #9 and/or #10 (I'm too busy on my main project to dive into typson code, but I can grunt in my sleep now :)

I can throw in AMD/PhantomJS (grunt-mocha) later.

Can't extend `interface` in `module`

declare module A {
    interface B {
        a: string
        b: number
    }
}

interface C extends A.B {}

Results in

{
  "A.B": {
    "id": "A.B",
    "type": "object",
    "properties": {
      "a": {
        "type": "string"
      },
      "b": {
        "type": "number"
      }
    },
    "required": [
      "a",
      "b"
    ],
    "additionalProperties": false
  },
  "C": {
    "id": "C",
    "type": "object",
    "properties": {},
    "additionalProperties": false
  }
}

As you can see, C has no properties when it should inherit A.B.

typson can't handle functions?

I'd like to handle the following code using typson.

interface Foo {
foo(): void;
}

But, the typson outputs some error.
Doesn't typson support functions?

parse error of object's array.

when below type file parse on typson, parse error is occurred.

declare module test {
  export interface IHoge {
    items: {}[];โ†ฒ
  }
}

Support modules

I have most code in modules (like a namespace)

module git {
    export interface TreeElem {
        sha:string;
        path:string;
        // ..
    }
}

// other file
var elem:git.TreeElem  = ....

I believe TypeScript does it too.

module TypeScript {
    export class LanguageWidget {
        // ..
    }
}

// other file
var instance = new TypeScript.LanguageWidget();

I would like to export these somehow. They can even be levels deeper nested (like packages in Java or AS3), sometimes they are used with export keyword.

// Export simply as dot seperated name (like in the code)?
{
   "$ref" = "#/definitions/TypeScript.LanguageWidget"
}
// Or maybe forward slashes (unsafe maybe)?
{
   "$ref" = "#/definitions/TypeScript/LanguageWidget"
}

Support rules in array items?

Is there a way to support more detail rules in array items?

I wish to have an array of UUID which the json schema will look like this:

{
    "ids": {
        "type": "array",
        "minItems": 1,
        "items": {
            "type": "string",
            "pattern": "/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i"
        }
    }
}

and an array of string and boolean in an array like this:

{
    "order": {
        "type": "array",
        "minItems": 1,
        "items": {
            "type": "array",
            "minItems": 2,
            "maxItems": 2,
            "items": [{
                "type": "string"
            }, {
                "type": "boolean"
            }]
        }
    }
}

Enable for node.js

For node.js usage some changes would be needed:

  • enable commonJS module export (using a wrapper task seems easiest):
    • grunt-urequire, grunt-microlib, grunt-browserify etc
  • externalise dependencies
  • drop jquery for cross-environment capable utils.
    • Q, bluebird, superagent etc (or use npm's jquery.. never tried it)
  • possibly add grunt (easily run the UMD wrapper, and later easily other stuff like jshint or tests)
  • define a package.json

It is actually a lot of change (but common ones I guess), maybe read up a little on all of this before you commit on it ๐Ÿ˜„

I'm working on some other stuff now but feel free to ask, I can send pointers to where to look for info or get some examples etc.

(as discussed in this thread)

Documentation error in Readme.md

Hi,

in the node.js section it should be:
typson schema example/invoice/line.ts
and
typson schema example/invoice/line.ts Invoice

Otherwise following error comes up:

$ typson example/invoice/line.ts Usage: typson schema <url-or-path-to-type-script-file> [type]

Join Paths Produces Incorrect Result When Passing in Path via Command Line

These two work properly (note that there is a proposed solution at the bottom):

typson schema ./api/users.ts
typson schema api/users.ts

These produce errors:

typson schema .\api\users.ts
typson schema api\users.ts

Errors:

typson : { [Error: ENOENT, open 'C:\Users\1198462\Source\Repos\mobiledlr\mobiledlr\api\users.ts\common\mco-list.ts']
At line:2 char:1
+ typson schema api\users.ts
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: ({ [Error: ENOEN...n\mco-list.ts']:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

  errno: 34,
  code: 'ENOENT',
  path: 'C:\\Users\\1198462\\Source\\Repos\\mobiledlr\\mobiledlr\\api\\users.ts\\common\\mco-list.ts' }
...
...
...
{ [Error: ENOENT, open 'C:\Users\1198462\Source\Repos\mobiledlr\mobiledlr\api\users.ts\common\user.ts']
  errno: 34,
  code: 'ENOENT',
  path: 'C:\\Users\\1198462\\Source\\Repos\\mobiledlr\\mobiledlr\\api\\users.ts\\common\\user.ts' }
api/users.ts: error TS2095: Could not find symbol 'User'.
api/users.ts: error TS2095: Could not find symbol 'McoList'.

I'm guessing that the error comes from the function fullModulePath - but I haven't looked into that deeply. I propose either using node's path (probably not since this is used in the browser also) or do something like the following:

var s = '.\\as\\asf.ts'
s.replace(/\\/g, '/')

Let me know if you would like a pull request.

Invalid input script path logs error but doesn't reject promise

When attempting to create a schema from a file that doesn't exist, an ENOENT: no such file or directory error is logged to the console but isn't thrown. This prevents API consumers from being able to differentiate cases based on whether or not the input file path is valid, and forces consumers to verify all input paths beforehand. If this is the desired behavior, it would be nice to at least have this option configurable so that all errors can be handled by the consumer on a case-by-case basis.

support extends

typson leaves no indication that an interface extends another one. Would it make sense to show this under additionalProperties?

Semicolons required?

I don't use semicolons as line terminators in TS. Typson breaks without them. Probably shouldn't. Current typescript compiler handles this file fine.

Support ECMAScript 5 (Accessors)?

Would be nice if getters/setters would work:

./src/xm/data/PackageJSON.ts(62,3): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.
./src/xm/data/PackageJSON.ts(66,3): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.

feature request: union types

When I have e.g.

export type Response = Info|Success|Failure;

in an interface file :

error TS1008: Unexpected token; 'module, class, interface, enum, import or statement' 

But this could become a anyOf

TypeScript Definition Example for Swagger-UI 2.0

I found this website with an example for Swagger 1.2 http://lbovet.github.io/swagger-ui/dist/index.html but couldn't find the .ts file source.

Is it possible to make an example .ts file that works with Swagger 2.0? Specifically with Swagger-UI? I love being able to do all the docs and typing all in the same language so I don't have to repeat myself, just having a hard time trying to figure our how to get it to all work nicely together. I figured an example would make this happen much faster, till then I'll keep playing with it.

Thanks! Great project!

Possible usecase: validating runtime AJAX responses

Hello all,

I thought of a possible use case of typson and thought it might be great, if it worked out, though, I wanna discuss it with you all.

Let's assume we've got an application written in TypeScript. What TypeScript itself gives us is compile-time typecheck. That is great to find bugs statically, but it can't help us to check anything on runtime. Therefore, what we can do in TS code is to typecast the dynamic response (which we will determine in future) to a static type, but, when transpiled into raw javascript, it will not have any impact nor it will add any behavior.

Now let's say we want to validate contents of a GET request. We know that the expected result should match a given TypeScript type. We use typson to generate JSON schema for that type. And one of the JSON Schema validators (there are many of them in JS only) will be used to typecheck in runtime.

As far as I understand the whole stack of tools (and as long as typson supports typescript well), this would work correctly out of the box. Guess this feature should be somehow optional, so that we can validate all API responses in the development/test environments, but not in the production (due to performance reason).

Please comment on this - what do you think of that feature?

support true numerical enums

I can do the following in TypeScript:

enum HttpStatusCode
{
    OK = 200,
    Unauthorized = 401
    ...
}

It would be nice if typson treated these enumeration as actual enumerations. I was thinking it could look for @type signature above the enum, e.g.,

/**
* @type integer
*/
enum HttpStatusCode
{
    OK = 200,
    Unauthorized = 401
    ...
}

and produce (per http://spacetelescope.github.io/understanding-json-schema/reference/generic.html):

{
type: 'integer'
enum: [200, 401]
}

Otherwise default to string enum

Could not find symbol Date

These errors puzzle me, do you know why they show up? typson still produces a perfectly fine schema output, but ignoring warnings is a sure way to introduce errors, so I would like to resolve this.

assets/ts/models.ts: error TS2095: Could not find symbol 'Date'.
assets/ts/models.ts: error TS2095: Could not find symbol 'Date'.
assets/ts/models.ts: error TS2095: Could not find symbol 'Date'.
assets/ts/models.ts: error TS2095: Could not find symbol 'Date'.
assets/ts/models.ts: error TS2095: Could not find symbol 'Date'.
assets/ts/models.ts: error TS2095: Could not find symbol 'Date'.
assets/ts/models.ts: error TS2095: Could not find symbol 'Date'.
assets/ts/models.ts: error TS2095: Could not find symbol 'Object'.
assets/ts/models.ts: error TS2095: Could not find symbol 'Date'.
assets/ts/models.ts: error TS2095: Could not find symbol 'Date'.

support functions from comments

Would it be possible to create a function in the comments?

e.g.,

/**
* @default [Function Date.now]
*/

The use case, I'm using the json-schema results to convert to mongoose schema and wanted the current date as the default. Currently it outputs the following:

{ default: "[Function" }

Let me know if you want me to take the deep dive into your code and do a pull request.

Unable generate schemas when import is used

When I try to generate schema from this:

import {User} from "users/user";

export interface Post {
    id?: string;
    name: string;
    createdAt: Date;
    updatedAt: Date;
    user: User;
}

I get errors like this:
error TS1008: Unexpected token; 'module, class, interface, enum, import or statement' expected.

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.