Giter Site home page Giter Site logo

gajus / flow-runtime Goto Github PK

View Code? Open in Web Editor NEW
802.0 13.0 57.0 18.1 MB

A runtime type system for JavaScript with full Flow compatibility.

License: MIT License

JavaScript 99.82% HTML 0.08% CSS 0.08% Shell 0.02%
flow-runtime flowtype babel-plugin type-safety validation

flow-runtime's Introduction

Flow Runtime

Build Status

A runtime type system for JavaScript with full Flow compatibility.

See the website for more information.


Maintenance Status

This project is not very well maintained anymore due to its complexity and maintainers' burnout with Flow in general.

Statement from @jedwards1211

At the moment I need to keep this working in some production projects that use it for API input validation (using the optInOnly option instead of blanket runtime validation everywhere).

However, I would like to eventually migrate those projects to either:

  • a library where I declare validators that I can extract value types from. I created typescript-validators for this purpose in TypeScript
  • a very pared-down version of babel-plugin-flow-runtime that generates validators where requested from Flow type annotations, but only supports certain types and doesn't automatically inject runtime validation everywhere.

If I had the time I would even migrate my production projects to TypeScript though, so I'm not sure I'll continue to use Flow and flow-runtime heavily in the long term.

Contributing

This is a lerna powered mono-repo, composed of the following projects:

Getting started

First clone the repo:

git clone https://github.com/gajus/flow-runtime.git

And bootstrap the project:

cd flow-runtime
yarn
yarn bootstrap
yarn test

flow-runtime's People

Contributors

0rvar avatar abhishiv avatar amilajack avatar aretecode avatar chocolateboy avatar christophehurpeau avatar deecewan avatar dependabot[bot] avatar dkolman-vendavo avatar fabiandev avatar forbeslindesay avatar gajus avatar goodmind avatar jcready avatar jedwards1211 avatar k15a avatar karlhorky avatar niieani avatar phpnode avatar pita avatar skeggse avatar skovhus avatar strml avatar vlsergey avatar vzaidman 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

flow-runtime's Issues

Implement pattern matching

It should be possible to write the following:

const upperFoo = t.match("foo", 
  (input: string) => input.toUpperCase(),
  (input: number) => numberToString(input).toUpperCase(),
  (_) => _ // just return the input if nothing matches
);
console.log(upperFoo); // "FOO"

or something like this:

const maybeUpperCase = t.pattern( 
  (input: string) => input.toUpperCase(),
  (input: number) => numberToString(input).toUpperCase(),
  (_) => _ // just return the input if nothing matches
);

and use it like this:

maybeUpperCase("foo"); // "FOO"
maybeUpperCase(1); // "ONE"
maybeUpperCase(false); // false

If there is no default clause (an unannotated function), a call to t.match() or t.pattern() with a non-matching type should throw.

For performance babel-plugin-flow-runtime could transform the above into something efficient like:

const maybeUpperCase = (_input) => {
  if (t.string().accepts(_input)) {
    return _input.toUpperCase();
  }
  else if (t.number().accepts(_input)) {
    return numberToString(_input).toUpperCase();
  }
  else {
    return _input;
  }
}

And then for known primitives further simplify to:

const maybeUpperCase = (_input) => {
  if (typeof _input === 'string') {
    return _input.toUpperCase();
  }
  else if (typeof _input === 'number') {
    return numberToString(_input).toUpperCase();
  }
  else {
    return _input;
  }
}

Questions:

Should you be able to match against multiple arguments? e.g.

const foobar = t.match("foo", "bar", [
  (a: string, b: string) => a + b,
  (a: string, b: number) => a + String(b),
  (a: number, b: string) => String(a) + b,
  (a: number, b: number) => String(a) + String(b),
]);

This would mean that the clauses would always have to be in an array.

Add support for anonymous params in FunctionTypeAnnotations

This is a:

  • Bug Report

Which concerns:

  • flow-runtime

What is the current behaviour?

When encountering an untyped argument of a function, flow-runtime breaks:

export type Test = {
  test : (untypedArgument) => void,
}

With this unfortunate error:

Cannot read property 'name' of null
    at converters.FunctionTypeParam (babel-plugin-flow-runtime/lib/convert.js:590:29)
    at convert (babel-plugin-flow-runtime/lib/convert.js:38:16)

As soon as we add a type to untypedArgument:

export type Test = {
  test : (typedArgument : string) => void,
}

It compiles properly.


Expected behavior

No Error or a better warning.


Which package versions are you using?

0.2.1 (latest at the time of writing)

Log warnings and continue, but do not throw for unimplemented features

This is a:

  • Bug Report

Which concerns:

  • flow-runtime

What is the current behaviour?

I'm unable to use flow-runtime on my codebase, because it throws errors on unsupported features, in turn breaking the whole application. Example:

Uncaught Error: Not implemented: acceptsType().

What is the expected behaviour?

I think it would be better that instead of throwing it would log that a feature is currently unsupported (log, only optionally), and continue with the supported set of features.

Additionally it could be useful to point to the part of the code which uses the unsupported feature, since at the moment I'm unable to provide you with a specific example of where it breaks.


Which package versions are you using?

flow-runtime 0.21

Add FLOW_RUNTIME=namespace configuration

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validators
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

The current implementation of babel-plugin-flow-runtime allows configuration that either inlines the assertions or skips them at a compile them. This is good enough for developing a library that uses flow-runtime.

const add = (a: number, b: number): number => a + b;

is transformed to:

import t from 'flow-runtime';
const add = (a, b) => {
  let _aType = t.number();
  let _bType = t.number();
  const _returnType = t.return(t.number());
  t.param('a', _aType).assert(a);
  t.param('b', _bType).assert(b);
  return _returnType.assert(a + b);
};

However, it limits library author's ability to distribute code with flow-runtime assertions. I do not want to use dependencies in production that have inlined flow-runtime assertions (for performance reasons).


What is the expected behaviour?

I'd like babel-plugin-flow-runtime to accept a configuration that inlines a conditional runtime assertion, e.g.

{
  "plugins": [["flow-runtime", {
    "assert": "applaudience:showtime-api"
  }]]
}

would produce code:

import t from 'flow-runtime';
const add = (a, b) => {
  if (process.env.FLOW_RUNTIME && process.env.FLOW_RUNTIME.startsWith('applaudience:showtime-api')) {
    let _aType = t.number();
    let _bType = t.number();
    const _returnType = t.return(t.number());
    t.param('a', _aType).assert(a);
    t.param('b', _bType).assert(b);
    return _returnType.assert(a + b);
  } else {
    return a + b;
  }
};

This is a mock implementation. A real-life implementation would follow the debug conventions.

This way, I could distribute all my codes with inlined flow-runtime assertions that users could enable when debugging issues the same way that debug is being used, e.g.

FLOW_RUNTIME=applaudience:* node ./index.js

would enable runtime type assertions for all dependencies under the "applaudience" namespace.


Crashes when React Props type is an intersection

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validatosr
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

Crashes in browser with

flow-runtime.js:5542Uncaught TypeError: Cannot read property 'Symbol(Symbol.iterator)' of undefined
    at makeReactPropTypes (flow-runtime.js:5542)
    at TypeContext.propTypes (flow-runtime.js:7214)
    at Object.<anonymous> (App.js:14)

if I have Props for class defined as an intersection like this

type Props = {
  a?: number
} & {
  b?: string
}
class Z extends React.Component {
  props: Props
  render(){
    return <div/>
  }
}

Here is the create-react-app project that shows an error. Please, remove node_modules/flow-runtime/dist/*.min.js to make it work. Or else it'll crash with regeneratorRuntime is undefined.

issue-flow-runtime-intersection.zip

Which package versions are you using?

"flow-runtime": "0.2.1"

Transformation fails with not meaningful exception: Cannot read property 'id' of null

This is a:

  • Bug Report

Which concerns:

  • babel-plugin-flow-runtime

What is the current behaviour?

UploadProgressReporter.js:

type TaskResult = {
  result: string,
  type: string
};

const BATCH_SIZE = 10;

class UploadProgressReporter {
  server: Hapi$Server;
  Jobs: App$Model$Job;
  job: Model$Job;
  mq: Hapi$Queue;

  constructor(job: Model$Job, req: Hapi$Request) {
    this.server = req.server;
    this.Jobs = req.server.plugins['hapi-mongo-models'].Jobs;
    this.mq = req.server.plugins.queue;
    this.job = job;
  }

  async monitor(tasks: Array<Promise<TaskResult>>): Promise<Array<string>> {
    const _id = this.job._id;
    if(!_id) return ["no job id"];
    let ret = [];

    for(let i=0; i<tasks.length; i+=BATCH_SIZE) {
      const promises = tasks.slice(i, i+BATCH_SIZE);
      try {
        const results = await Promise.all(promises);
        await this.publish(results);
        ret.concat(results.map(({result})=>result));
      } catch(e) {
        this.job.errors.push(e.message);
      }
    }

    try {
      console.log("replace job", await this.Jobs.replaceOne({_id}, this.job));
    } catch(e) {
      this.server.log(['error', 'mongo', 'UploadProgressReporter'], e.message);
    }

    return ret;
  }

  async publish(results: Array<TaskResult>) {
    const ret = results.forEach(({type}) => {
        this.job[type].processed = this.job[type].processed + 1;});
    this.job.updated = new Date();
    await this.mq.publish('events', this.job.userId.toString(), this.job, false);
    return ret;
  }

};

async function task(promise: Promise<string>, type: string): Promise<TaskResult> {
  try {
    const result = await promise;
    return { type, result }
  } catch(err) {
    return { type, result: err.message }
  }
}

export { task };

export default UploadProgressReporter;

Error while processing:

TypeError: server/api/snapshots/UploadProgressReporter.js: Cannot read property 'id' of null
    at ConversionContext.hasForwardTypeDeclaration (/node_modules/babel-plugin-flow-runtime/lib/ConversionContext.js:266:38)
    at ConversionContext.hasTDZIssue (/node_modules/babel-plugin-flow-runtime/lib/ConversionContext.js:238:21)
    at Identifier (node_modules/babel-plugin-flow-runtime/lib/firstPassVisitors.js:56:21)
    at NodePath._call (/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/node_modules/babel-traverse/lib/path/context.js:105:12)
    at TraversalContext.visitQueue (/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitSingle (/node_modules/babel-traverse/lib/context.js:108:19)
    at TraversalContext.visit (/node_modules/babel-traverse/lib/context.js:192:19)
    at Function.traverse.node (/node_modules/babel-traverse/lib/index.js:114:17)

Please note, I load types via libs section of .flowconfig


What is the expected behaviour?

Transformation succeeds or raises meaningful error. Please note, flow checks succeed on the same file.


Which package versions are you using?

flow-runtime an babel-plugin-flow-runtime 0.3.0

Add assertions when implicitly returning from a function

Issuehunt badges

Currently if a function implicitly returns undefined (by leaving the function without an explicit return statement) we won't generate a check for it, e.g:

function foo (): string {
  // no return
}

currently compiles to:

function foo () {
  const _returnType = t.return(t.string()); 
  // no return
}

We should insert a call to _returnType.assert(undefined) at these points.


IssueHunt Summary

Backers (Total: $20.00)

Submitted pull Requests


Become a backer now!

Or submit a pull request to get the deposits!

Tips

Object destructive assignment on arguments is broken

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validatosr
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

Broken code

This code is broken.

/* @flow */

export default function update (
  {id, title, body}: {
    id: number,
    title: string,
    body: string
  }
): number {
  return id
}

Error

   3:
   4: export default function update (
   5:   { id, title, body }: {

  Error: arguments[0].id must be a number

  Expected: number

  Actual: void

  -------------------------------------------------

  arguments[0].title must be a string

  Expected: string

  Actual: void

  -------------------------------------------------

  arguments[0].body must be a string

  Expected: string

  Actual: void

  _callee$ (packages/api/commands/update.js:4:16)
  tryCatch (node_modules/regenerator-runtime/runtime.js:64:40)
  GeneratorFunctionPrototype.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:299:22)
  GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:116:21)
  updateItem (packages/api/commands/updateItem.js:84:17)
  _callee$ (packages/api/commands/updateItem.test.js:14:9)
  tryCatch (node_modules/regenerator-runtime/runtime.js:64:40)
  GeneratorFunctionPrototype.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:299:22)
  GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:116:21)

It looks flow-runtime is going to handle [id, title, body].

Next code passed correctly

/* @flow */
export default function update (
  obj: {
    id: number,
    title: string,
    body: string
  }
): number {
  const {id, title, body} = obj
  return id
}

Which package versions are you using?

v0.5.0

Types not resolving to `.js.flow` files

Issuehunt badges

I'm using an npm package that transpiles its files then uses flow-copy-source to copy its flow annotated files to the package's lib folder. The result is there's an index.js file and an index.js.flow file. index.js.flow contains custom types exported by the application, while index.js has these stripped.

At compile time, the flow-bin binary resolves to index.js.flow instead of index.js, allowing the flow compiler to pick out the custom types. However, the flow-runtime babel plugin doesn't resolve index.js.flowfirst, causing flow-runtime to throw the error Error: Could not reference the given type.

If you could point me in the right direction in the code base I might be able to help submit a PR. If you have another suggestion on how I could fix this though I'd appreciate it!


IssueHunt Summary

Backers (Total: $20.00)

Become a backer now!

Or submit a pull request to get the deposits!

Tips


IssueHunt has been backed by the following sponsors. Become a sponsor

Throw error if import * as React

When I import react in this form:

import * as React from "react"

babel-flow-runtime will throw error:

Module build failed: TypeError: /project/scripts/components/datetime_picker.jsx: Cannot read property 'name' of undefined
  at /Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-plugin-flow-runtime/lib/firstPassVisitors.js:80:47
  at Array.forEach (native)
  at ImportDeclaration (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-plugin-flow-runtime/lib/firstPassVisitors.js:69:30)
  at NodePath._call (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/path/context.js:76:18)
  at NodePath.call (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/path/context.js:48:17)
  at NodePath.visit (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/path/context.js:105:12)
  at TraversalContext.visitQueue (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/context.js:150:16)
  at TraversalContext.visitMultiple (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/context.js:103:17)
  at TraversalContext.visit (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/context.js:190:19)
  at Function.traverse.node (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/index.js:114:17)
  at traverse (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/index.js:79:12)
  at NodePath.traverse (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/path/index.js:144:25)
  at PluginPass.Program (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-plugin-flow-runtime/lib/index.js:14:14)
  at newFn (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/visitors.js:276:21)
  at NodePath._call (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/path/context.js:76:18)
  at NodePath.call (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/path/context.js:48:17)
  at NodePath.visit (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/path/context.js:105:12)
  at TraversalContext.visitQueue (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/context.js:150:16)
  at TraversalContext.visitSingle (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/context.js:108:19)
  at TraversalContext.visit (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/context.js:192:19)
  at Function.traverse.node (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/index.js:114:17)
  at traverse (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/node_modules/babel-traverse/lib/index.js:79:12)
  at File.transform (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/lib/transformation/file/index.js:563:35)
  at /Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/lib/transformation/pipeline.js:50:19
  at File.wrap (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/lib/transformation/file/index.js:579:16)
  at Pipeline.transform (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-core/lib/transformation/pipeline.js:47:17)
  at transpile (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-loader/index.js:38:20)
  at Object.module.exports (/Volumes/HDD/jimu/flux-pomotodo/node_modules/babel-loader/index.js:131:12)

Return values of Promises are not checked in runtime

This is a:

  • Bug Report

Which concerns (not really sure):

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validators

The following code does not raise any errors:

type Person = {
  name: string
}

function untrustedEndpoint(id: string): Promise<{ data: Person }> {
  return Promise.resolve(null) // <= wrong
}

untrustedEndpoint('id')

Currently we will only get the type assertion error once another function receives the return value as an argument, so a workaround is to:

type Person = {
  name: string
}

type Endpoint = { data: Person }

function untrustedEndpoint(id: string): Promise<Endpoint> {
  return Promise.resolve(null) // <= wrong
}

function processPersonNameFromEndpoint(response : Endpoint) {
  return response.data.name
}

untrustedEndpoint('id').then(processPersonNameFromEndpoint)

Raised by @gcanti at gcanti/io-ts#4 (comment)

`regeneratorRuntime` is not defined

This is a:

  • Bug Report

Which concerns:

  • flow-runtime

What is the current behaviour?

flow-runtime.min.js:3 Uncaught (in promise) ReferenceError: regeneratorRuntime is not defined
    at eval (flow-runtime.min.js:3)
    at eval (flow-runtime.min.js:3)

What is the expected behaviour?

Throw error

Please add babel-plugin-transform-runtime is your .babelrc


Which package versions are you using?

0.2.1

babel-plugin-flow-runtime: log to console instead of throwing

We use a modified version of typecheck plugin which uses console.error(message, value) instead of throw. Firstly, it's less of a hindrance in development; secondly, it allows to inspect the actual value, not only it's type signature.

Would you consider adding an option to babel plugin, or point me in a direction where it should be implemented?

Error when using Class<T> type syntax

Hi, thanks for this amazing project. It's really powerful!
However, I'm having the following issue:

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validators
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

I have the following code:

type HasKey = {
  getKey(): string
};

class Klazz {
  getKey() { return 'key'; }
}

const logKey = (C: Class<HasKey>) => {
 const instance = new C;
 console.log(instance.getKey()); 
}

logKey(Klazz);

When I run it in https://codemix.github.io/flow-runtime/#/try I get the following error:

C must be a Class of HasKey

Expected: Class

Actual: Klazz


What is the expected behaviour?

I would expect flow-runtime not to raise any error. Indeed, this "Try Flow" playground does not report anything wrong and to me there is actually nothing wrong with the above code.

Is it a bug in flow-runtime or is it by design ? If it's by design, do you have a suggestion of how to do it differently ?

Thank you :)


Which package versions are you using?

The one currently deployed at https://codemix.github.io/flow-runtime/#/try.

Support React-Native

When install for react-native, it will throws :

transformed 732/776 (94%)(node:12140) UnhandledPromiseRejectionWarning: 
Unhandled promise rejection (rejection id: 1362): 

SyntaxError: TransformError: xxxapp\node_modules\flow-runtime\flow-runtime.js: 
Couldn't find preset "env" relative to directory "xxxapp\\node_modules\\flow-runtime"

Enabling annotations causes our arrow functions to lose their names.

Thanks for creating flow-runtime

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validators
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

When using babel-plugin-flow-runtime with annotations enabled, our stateless functional React components lose their display names. Here is an example that you can run in https://codemix.github.io/flow-runtime/#/try:

type Props = {
  id: string | number;
  name: string;
};

const MyComponent = (props: Props) => {};

console.log(MyComponent.name);

with annotations, this gets transformed to:

const MyComponent = t.annotate(props => {
  let _propsType2 = Props;
  t.param("props", _propsType2).assert(props);
}, t.function(t.param("props", Props)));

If annotations are disabled, the above code logs 'MyComponent'.
If annotations are enabled, the above code logs ''.


What is the expected behaviour?

I would expect that we wouldn't lose the Function.name when annotations are enabled.


I was trying to figure out how this could be accomplished.

Perhaps it could be compiled to something like this:

const MyComponent = t.annotate(function MyComponent(props) {
  let _propsType2 = Props;
  t.param("props", _propsType2).assert(props);
}.bind(this), t.function(t.param("props", Props)), "MyComponent");

I'm not really sure what the right route is to go with this.


Which package versions are you using?

"babel-plugin-flow-runtime": "0.5.0"

Runtime error when generator signature is any

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validators
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

The following code fails at runtime:

// Changing this from any to Generator<number, void, void> works
function* someGenerator (): any {
  yield 12;
  yield 42;
}

for (const it of someGenerator()) {
  console.log(it);
}

The error:

Uncaught ReferenceError: _yieldType is not defined
    at someGenerator$ (eval at <anonymous> (http://localhost:3000/bundle.js:3992:1), <anonymous>:46:18)
    at tryCatch (eval at <anonymous> (http://localhost:3000/bundle.js:9008:1), <anonymous>:64:40)
    at Generator.invoke [as _invoke] (eval at <anonymous> (http://localhost:3000/bundle.js:9008:1), <anonymous>:299:22)
    at Generator.prototype.(anonymous function) [as next] (eval at <anonymous> (http://localhost:3000/bundle.js:9008:1), <anonymous>:116:21)
    at eval (eval at <anonymous> (http://localhost:3000/bundle.js:3992:1), <anonymous>:67:116)
    at Object.<anonymous> (http://localhost:3000/bundle.js:3992:1)
    at __webpack_require__ (http://localhost:3000/bundle.js:660:30)
    at fn (http://localhost:3000/bundle.js:84:20)
    at Object.<anonymous> (http://localhost:3000/bundle.js:9081:18)
    at __webpack_require__ (http://localhost:3000/bundle.js:660:30)

What is the expected behaviour?

It should run just fine, as it's valid Flow syntax.


Which package versions are you using?

[email protected]

Question babel-plugin-flow-runtime: overwrite assert: false

According to the documentation assert: true should be turned off during production builds.

For an UMD library with an public API it would be beneficial if assertions could be scoped to specific public methods. That would allow getting the the benefits of run time type checking for the library consumer without getting the overall performance penalty.

Here's an example, where I'd like to get assertions for the public filter method (taken from a tcomb babel-plugin-transform-flow-strip-types implementation).

...
const FilterLogic = enums.of(['or', 'and'], 'FilterLogic')

type FilterExpression = {
  field: string,
  operator: string,
  value: any
}

type FilterGroup = {
  logic: FilterLogic,
  filters: Array<FilterExpression | FilterGroup>
}

export default class Collections {
...

// Would it be possible to turn on assertion for .filter?
// maybe by using a decorator like @guarded?
  filter (options?: FilterGroup) {
    if (!options) {
      return toJS(this.$filter)
    }
    this.$filter = options
    this.data = []

    return this.read()
  }
...
}

False-negative type errors using async functions

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validators
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

It appears flow-runtime gets confused type checking async functions. The following gives me an error in https://codemix.github.io/flow-runtime/#/try (default options):

const bar = async ({
    id
}: {
    id: string;
}) => {
    return await new Promise(resolve => setTimeout(() => resolve(id), 1000));
};

const foo = (id: string) => {
    return bar({
        id
    })
  			.then(id => console.log(id))
        .catch((e: Error) => console.error("foo", e));
};

foo("testId");

results in:

foo TypeError: arguments[0].id must be a string

Expected: string

Actual: void


    at _callee$ (eval at run (https://codemix.github.io/flow-runtime/static/js/main.1ab3461d.js:20454:17), <anonymous>:20:169)
    at tryCatch (https://codemix.github.io/flow-runtime/static/js/main.1ab3461d.js:59153:41)
    at Generator.invoke [as _invoke] (https://codemix.github.io/flow-runtime/static/js/main.1ab3461d.js:59444:23)
    at Generator.prototype.(anonymous function) [as next] (https://codemix.github.io/flow-runtime/static/js/main.1ab3461d.js:59205:22)
    at step (eval at run (https://codemix.github.io/flow-runtime/static/js/main.1ab3461d.js:20454:17), <anonymous>:11:191)
    at eval (eval at run (https://codemix.github.io/flow-runtime/static/js/main.1ab3461d.js:20454:17), <anonymous>:11:437)
    at eval (eval at run (https://codemix.github.io/flow-runtime/static/js/main.1ab3461d.js:20454:17), <anonymous>:11:99)
    at bar (eval at run (https://codemix.github.io/flow-runtime/static/js/main.1ab3461d.js:20454:17), <anonymous>:41:21)
    at foo (eval at run (https://codemix.github.io/flow-runtime/static/js/main.1ab3461d.js:20454:17), <anonymous>:52:12)
    at eval (eval at run (https://codemix.github.io/flow-runtime/static/js/main.1ab3461d.js:20454:17), <anonymous>:65:1)

Whereas non-async functions behave as expected:

const bar = ({
    id
}: {
    id: string;
}) => {
    return new Promise(resolve => setTimeout(() => resolve(id), 1000));
};

const foo = (id: string) => {
    return bar({
        id
    })
  			.then(id => console.log(id))
        .catch((e: Error) => console.error("foo", e));
};

foo("testId");

results in:

testId

What is the expected behaviour?

It should not display false-negative results.


Which package versions are you using?

Node 6.9.1

[email protected]
[email protected]

Crash when returning generator from function with option argument

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validators
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

This snippet:

type Options = {};

export const makeApiCallSaga = (opts: Options) => {
  return function* apiCallWatcherSaga (): Generator<*, void, *> {
  };
};

Causes the following crash:

ERROR in ./src/sagas/api.js
Module build failed: TypeError: /Users/da_petcu21/Work/portal-frontend/src/sagas/api.js: Property id of VariableDeclarator expected node to be of a type ["LVal"] but instead got null
    at Object.validate (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-types/lib/definitions/index.js:109:13)
    at validate (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-types/lib/index.js:505:9)
    at Object.builder (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-types/lib/index.js:466:7)
    at Function (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-plugin-flow-runtime/lib/transformVisitors.js:427:64)
    at NodePath._call (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/path/context.js:76:18)
    at NodePath.call (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/path/context.js:48:17)
    at NodePath.visit (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/path/context.js:105:12)
    at TraversalContext.visitQueue (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitSingle (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/context.js:108:19)
    at TraversalContext.visit (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/context.js:192:19)
    at Function.traverse.node (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/index.js:114:17)
    at NodePath.visit (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/path/context.js:115:19)
    at TraversalContext.visitQueue (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/context.js:150:16)
    at TraversalContext.visitMultiple (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/context.js:103:17)
    at TraversalContext.visit (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/context.js:190:19)
    at Function.traverse.node (/Users/da_petcu21/Work/portal-frontend/node_modules/babel-traverse/lib/index.js:114:17)
 @ ./src/sagas/login.js 12:11-27
 @ ./src/sagas/index.js
 @ ./src/store/configureStore.dev.js
 @ ./src/store/configureStore.js
 @ ./src/index.js
 @ multi ./tools/webpack-public-path webpack-hot-middleware/client?reload=true babel-polyfill ./src

What is the expected behaviour?

It should not crash


Which package versions are you using?

โ”œโ”€ [email protected]
โ”‚  โ””โ”€ flow-config-parser@^0.3.0

Support JSON-Schema

It should be possible to serialize / deserialize types to / from JSON-Schema. That is -

Given a JSON Schema object I should be able to turn it into flow runtime Type instances (which can then be turned into static type definitions via .toString()).

Given some Types, I should be able to generate a JSON Schema document.

I don't know if it will be possible to do this "losslessly" as JSON Schema includes some meta data that we don't e.g. labels and descriptions, but things like validation rules should be transferable as the validators in flow-runtime-validators are based on revalidator which uses JSON Schema.

cc @STRML because I think you were looking into this a while ago?

[babel-plugin-flow-runtime] cannot read .name of null

using default plugin config (flow-runtime), or as object with the defaults explicitly specified ('assert': true, 'decorate': true...)

Cannot read property 'name' of null
   at converters.FunctionTypeParam (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:539:29)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at /project/node_modules/babel-plugin-flow-runtime/lib/convert.js:512:12
   at Array.map (native)
   at converters.FunctionTypeAnnotation (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:511:62)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at converters.ObjectTypeProperty (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:498:15)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at /project/node_modules/babel-plugin-flow-runtime/lib/convert.js:488:12
   at Array.map (native)
   at converters.ObjectTypeAnnotation (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:487:114)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at converters.TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:304:14)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/transformVisitors.js:69:47)
   at NodePath._call (/project/node_modules/babel-traverse/lib/path/context.js:76:18)
   at NodePath.call (/project/node_modules/babel-traverse/lib/path/context.js:48:17)
   at NodePath.visit (/project/node_modules/babel-traverse/lib/path/context.js:105:12)
   at TraversalContext.visitQueue (/project/node_modules/babel-traverse/lib/context.js:150:16)
   at TraversalContext.visitMultiple (/project/node_modules/babel-traverse/lib/context.js:103:17)
   at TraversalContext.visit (/project/node_modules/babel-traverse/lib/context.js:190:19)
   at Function.traverse.node (/project/node_modules/babel-traverse/lib/index.js:114:17)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:40:11)
   at /project/node_modules/babel-plugin-flow-runtime/lib/convert.js:512:12
   at Array.map (native)
   at converters.FunctionTypeAnnotation (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:511:62)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at converters.ObjectTypeProperty (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:498:15)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at /project/node_modules/babel-plugin-flow-runtime/lib/convert.js:488:12
   at Array.map (native)
   at converters.ObjectTypeAnnotation (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:487:114)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at converters.TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:304:14)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/transformVisitors.js:69:47)
   at NodePath._call (/project/node_modules/babel-traverse/lib/path/context.js:76:18)
   at NodePath.call (/project/node_modules/babel-traverse/lib/path/context.js:48:17)
   at NodePath.visit (/project/node_modules/babel-traverse/lib/path/context.js:105:12)
   at TraversalContext.visitQueue (/project/node_modules/babel-traverse/lib/context.js:150:16)
   at TraversalContext.visitMultiple (/project/node_modules/babel-traverse/lib/context.js:103:17)
   at TraversalContext.visit (/project/node_modules/babel-traverse/lib/context.js:190:19)
   at Function.traverse.node (/project/node_modules/babel-traverse/lib/index.js:114:17)
   at traverse (/project/node_modules/babel-traverse/lib/index.js:79:12)
   at NodePath.traverse (/project/node_modules/babel-traverse/lib/path/index.js:144:25)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:40:11)
   at converters.ObjectTypeProperty (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:498:15)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at /project/node_modules/babel-plugin-flow-runtime/lib/convert.js:488:12
   at Array.map (native)
   at converters.ObjectTypeAnnotation (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:487:114)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at converters.TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:304:14)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/transformVisitors.js:69:47)
   at NodePath._call (/project/node_modules/babel-traverse/lib/path/context.js:76:18)
   at NodePath.call (/project/node_modules/babel-traverse/lib/path/context.js:48:17)
   at NodePath.visit (/project/node_modules/babel-traverse/lib/path/context.js:105:12)
   at TraversalContext.visitQueue (/project/node_modules/babel-traverse/lib/context.js:150:16)
   at TraversalContext.visitMultiple (/project/node_modules/babel-traverse/lib/context.js:103:17)
   at TraversalContext.visit (/project/node_modules/babel-traverse/lib/context.js:190:19)
   at Function.traverse.node (/project/node_modules/babel-traverse/lib/index.js:114:17)
   at traverse (/project/node_modules/babel-traverse/lib/index.js:79:12)
   at NodePath.traverse (/project/node_modules/babel-traverse/lib/path/index.js:144:25)
   at PluginPass.Program (/project/node_modules/babel-plugin-flow-runtime/lib/index.js:20:14)
   at newFn (/project/node_modules/babel-traverse/lib/visitors.js:276:21)
   at NodePath._call (/project/node_modules/babel-traverse/lib/path/context.js:76:18)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:40:11)
   at /project/node_modules/babel-plugin-flow-runtime/lib/convert.js:488:12
   at Array.map (native)
   at converters.ObjectTypeAnnotation (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:487:114)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at converters.TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:304:14)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/transformVisitors.js:69:47)
   at NodePath._call (/project/node_modules/babel-traverse/lib/path/context.js:76:18)
   at NodePath.call (/project/node_modules/babel-traverse/lib/path/context.js:48:17)
   at NodePath.visit (/project/node_modules/babel-traverse/lib/path/context.js:105:12)
   at TraversalContext.visitQueue (/project/node_modules/babel-traverse/lib/context.js:150:16)
   at TraversalContext.visitMultiple (/project/node_modules/babel-traverse/lib/context.js:103:17)
   at TraversalContext.visit (/project/node_modules/babel-traverse/lib/context.js:190:19)
   at Function.traverse.node (/project/node_modules/babel-traverse/lib/index.js:114:17)
   at traverse (/project/node_modules/babel-traverse/lib/index.js:79:12)
   at NodePath.traverse (/project/node_modules/babel-traverse/lib/path/index.js:144:25)
   at PluginPass.Program (/project/node_modules/babel-plugin-flow-runtime/lib/index.js:20:14)
   at newFn (/project/node_modules/babel-traverse/lib/visitors.js:276:21)
   at NodePath._call (/project/node_modules/babel-traverse/lib/path/context.js:76:18)
   at NodePath.call (/project/node_modules/babel-traverse/lib/path/context.js:48:17)
   at NodePath.visit (/project/node_modules/babel-traverse/lib/path/context.js:105:12)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:40:11)
   at converters.TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:304:14)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:38:12)
   at TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/transformVisitors.js:69:47)
   at NodePath._call (/project/node_modules/babel-traverse/lib/path/context.js:76:18)
   at NodePath.call (/project/node_modules/babel-traverse/lib/path/context.js:48:17)
   at NodePath.visit (/project/node_modules/babel-traverse/lib/path/context.js:105:12)
   at TraversalContext.visitQueue (/project/node_modules/babel-traverse/lib/context.js:150:16)
   at TraversalContext.visitMultiple (/project/node_modules/babel-traverse/lib/context.js:103:17)
   at TraversalContext.visit (/project/node_modules/babel-traverse/lib/context.js:190:19)
   at Function.traverse.node (/project/node_modules/babel-traverse/lib/index.js:114:17)
   at traverse (/project/node_modules/babel-traverse/lib/index.js:79:12)
   at NodePath.traverse (/project/node_modules/babel-traverse/lib/path/index.js:144:25)
   at PluginPass.Program (/project/node_modules/babel-plugin-flow-runtime/lib/index.js:20:14)
   at newFn (/project/node_modules/babel-traverse/lib/visitors.js:276:21)
   at NodePath._call (/project/node_modules/babel-traverse/lib/path/context.js:76:18)
   at NodePath.call (/project/node_modules/babel-traverse/lib/path/context.js:48:17)
   at NodePath.visit (/project/node_modules/babel-traverse/lib/path/context.js:105:12)
   at TraversalContext.visitQueue (/project/node_modules/babel-traverse/lib/context.js:150:16)
   at TraversalContext.visitSingle (/project/node_modules/babel-traverse/lib/context.js:108:19)
   at TraversalContext.visit (/project/node_modules/babel-traverse/lib/context.js:192:19)
   at Function.traverse.node (/project/node_modules/babel-traverse/lib/index.js:114:17)
   at convert (/project/node_modules/babel-plugin-flow-runtime/lib/convert.js:40:11)
   at TypeAlias (/project/node_modules/babel-plugin-flow-runtime/lib/transformVisitors.js:69:47)
   at NodePath._call (/project/node_modules/babel-traverse/lib/path/context.js:76:18)
   at NodePath.call (/project/node_modules/babel-traverse/lib/path/context.js:48:17)
   at NodePath.visit (/project/node_modules/babel-traverse/lib/path/context.js:105:12)
   at TraversalContext.visitQueue (/project/node_modules/babel-traverse/lib/context.js:150:16)
   at TraversalContext.visitMultiple (/project/node_modules/babel-traverse/lib/context.js:103:17)
   at TraversalContext.visit (/project/node_modules/babel-traverse/lib/context.js:190:19)
   at Function.traverse.node (/project/node_modules/babel-traverse/lib/index.js:114:17)
   at traverse (/project/node_modules/babel-traverse/lib/index.js:79:12)
   at NodePath.traverse (/project/node_modules/babel-traverse/lib/path/index.js:144:25)
   at PluginPass.Program (/project/node_modules/babel-plugin-flow-runtime/lib/index.js:20:14)
   at newFn (/project/node_modules/babel-traverse/lib/visitors.js:276:21)
   at NodePath._call (/project/node_modules/babel-traverse/lib/path/context.js:76:18)
   at NodePath.call (/project/node_modules/babel-traverse/lib/path/context.js:48:17)
   at NodePath.visit (/project/node_modules/babel-traverse/lib/path/context.js:105:12)
   at TraversalContext.visitQueue (/project/node_modules/babel-traverse/lib/context.js:150:16)
   at TraversalContext.visitSingle (/project/node_modules/babel-traverse/lib/context.js:108:19)
   at TraversalContext.visit (/project/node_modules/babel-traverse/lib/context.js:192:19)
   at Function.traverse.node (/project/node_modules/babel-traverse/lib/index.js:114:17)
   at traverse (/project/node_modules/babel-traverse/lib/index.js:79:12)
   at File.transform (/project/node_modules/babel-core/lib/transformation/file/index.js:558:35)

https://github.com/codemix/flow-runtime/blob/master/packages/babel-plugin-flow-runtime/src/firstPassVisitors.js

Failed to reveal type in Temporal Dead Zone.

This is a:

  • Question

Which concerns:

  • flow-runtime

What is the current behaviour?

The message is popping in the console when my app starts. It's probably not an error as app seems to be working, but I am curious if it's normal.

Support $PropertyType<>

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validatosr
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

We don't support annotations like $PropertyType<T, 'propertyName'>


What is the expected behaviour?

type Human = {name: string, age: number}
type HumanAge = $PropertyType<Human, age>
HumanAge.assert(10)

Which package versions are you using?

[email protected]

Document dependencies on other babel plugins

This is a:

  • Question

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime

What is the current behaviour?

I wanted to give this package a shot so I ran:

$ yarn init -y
$ yarn add flow-runtime
$ yarn add --dev babel-cli babel-plugin-flow-runtime
$ echo '{ "plugins": [["flow-runtime", { "assert": true, "annotate": true }]] }' > .babelrc
$ vim index.js
<paste example from https://codemix.github.io/flow-runtime/#/babel-plugin-flow-runtime>
$ babel index.js

SyntaxError: index.js: Unexpected token, expected ; (1:5)
> 1 | type User = {
    |      ^
  2 |     id: number;
  3 |       name: string;
  4 | };

What is the expected behaviour?

I must be doing something wrong, obviously, but since I'm having these difficulties it might indicate that the "getting started" section needs some improvement.


Which package versions are you using?

  • "babel-cli": "6.22.2",
  • "babel-plugin-flow-runtime": "0.2.1"
  • "flow-runtime": "0.2.1"

React$Element support

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validators
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

import React, { Element } from 'react';

class Foo extends React.Component {
  render(): Element {
    return <div>hello world</div>;
  }
}

This code doesn't work correctly at runtime, because there is no "Element" exported in react package.
But for flow itself it's valid construction.

flow-runtime: Cannot resolve type: Buffer

This is a:

Bug Report

Which concerns:

flow-runtime


What is the current behaviour?

code like:

function foo(): Buffer {
  return getData();
}

produces:

flowRuntime.ref('Buffer')

which results in the warning:

flow-runtime: Cannot resolve type: Buffer


What is the expected behaviour?

I would expect it to use Buffer.isBuffer or instanceof Buffer to check that the returned value is a buffer.


Which package versions are you using?

0.5.0

Incorrect return values from functions do not throw.

This is a:

  • [ X ] Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • [ X ] flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validators
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

type StrFunType = () => string;
const strFun: StrFunType = () => 5;
strFun();

strFun() should throw because it did not return a string. Instead, I have to do the following in order to get it to throw:

type StrFunType = () => string;
const strFun: StrFunType = () => {
  const out: string = 5;
  return out;
};
strFun();

What is the expected behaviour?

Incorrect return values from functions should throw.

The above is a contrived example, but I've had to set the return value to a value of the expected type explicitly to get the type checking. My specific use case is that I'm using Ramda and would really like runtime flow checks on it because static flow type checks are not really going to happen for it.


Which package versions are you using?

version 0.7.0

Object key as type without identifier throws TypeError

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validatosr
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

// input.js
type Animal = {};

type AnimalID = string

type AnimalMap = {
  [AnimalID]: Animal,
}

throws...

TypeError: src/types/test.js: Cannot read property 'name' of null
    at converters.ObjectTypeIndexer (/home/seve/workspace/okcollege/libs/okc-js/node_modules/babel-plugin-flow-runtime/lib/convert.js:708:62)
    at convert (/home/seve/workspace/okcollege/libs/okc-js/node_modules/babel-plugin-flow-runtime/lib/convert.js:49:16)
    at /home/seve/workspace/okcollege/libs/okc-js/node_modules/babel-plugin-flow-runtime/lib/convert.js:682:12
    at Array.map (native)
    at converters.ObjectTypeAnnotation (/home/seve/workspace/okcollege/libs/okc-js/node_modules/babel-plugin-flow-runtime/lib/convert.js:681:114)
    at convert (/home/seve/workspace/okcollege/libs/okc-js/node_modules/babel-plugin-flow-runtime/lib/convert.js:49:16)
    at converters.TypeAlias (/home/seve/workspace/okcollege/libs/okc-js/node_modules/babel-plugin-flow-runtime/lib/convert.js:400:14)
    at convert (/home/seve/workspace/okcollege/libs/okc-js/node_modules/babel-plugin-flow-runtime/lib/convert.js:49:16)
    at TypeAlias (/home/seve/workspace/okcollege/libs/okc-js/node_modules/babel-plugin-flow-runtime/lib/transformVisitors.js:133:47)
    at NodePath._call (/usr/local/share/.config/yarn/global/node_modules/babel-traverse/lib/path/context.js:76:18)

What is the expected behaviour?

Successful compilation.


Which package versions are you using?

Approximately,

"dependencies": {
    "babel-cli": "^6.23.0",
    "babel-core": "^6.23.1",
    "babel-plugin-flow-runtime": "^0.5.0",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.23.0",
    "babel-plugin-transform-flow-strip-types": "^6.22.0",
    "babel-preset-stage-1": "^6.22.0"
  },
  "babel": {
    "presets": [
      "stage-1"
    ],
    "plugins": [
      [
        "transform-flow-strip-types"
      ],
      [
        "flow-runtime"
      ],
      [
        "transform-es2015-modules-commonjs"
      ]
    ]
  }

I've used this syntax for some time, but I don't see any official documentation saying it is supported- but it is working with flow right now so it may be worth supporting.

The workaround or "correct" syntax is as follows...

// input.js
type Animal = {};

type AnimalID = string

type AnimalMap = {
  [id: AnimalID]: Animal,
}

Website: try with async functions don't show error

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validators
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

Tested in https://codemix.github.io/flow-runtime/#/try:

const foo = async (): Promise<number> => 'test';
foo().then(x => console.log(x));

with assertions enabled

What is the current behaviour?

nothing is displayed

What is the expected behaviour?

It should display an error ?

Note: it works with warnings and test is displayed if the return type is Promise<string>

Flow's type definitions aren't 100% accurate

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validatosr
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

const err: Error = new Error('hello');

// => flow-runtime will report a type mismatch

What is the expected behaviour?

err should typecheck

Which package versions are you using?

Current version used by the /try web interface

Issue with arrow functions, destructuring, and argument scope - arguments from parent scope used

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validatosr
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

I have the following code:

type Person = {
  name: string
};

let sayHello = ({ name } : Person) => {
  sayHello(name);
}

sayHello({ name: 'Kermit' });

This compiles to:

var _arguments = arguments;
import t from 'flow-runtime';
const Person = t.type('Person', t.object(t.property('name', t.string())));

let sayHello = t.annotate(function ({ name }) {
  t.param('arguments[0]', Person).assert(_arguments[0]);

  sayHello(name);
}, t.function(t.param('_arg', Person)));

sayHello({ name: 'Kermit' });

And gives the error:

 arguments[0].name must be a string

Expected: string

Actual: void

The problem is, since arguments is not defined in the arrow function, it's checking against _arguments, which is arguments from the parent scope. And obviously that doesn't work because the parent scope's arguments don't match what is expected in sayHello


What is the expected behaviour?

There should be no type error, and the function should correctly check the arguments for the current scope.


Which package versions are you using?

no compile time errors

I know it's called flow "runtime" but typecheck has compiletime type checking as well, for example const a: string = 4. Is this planned to be added?

Could not resolve libs in .flowconfig?

This is a:

  • Question

Which concerns:

  • babel-plugin-flow-runtime

What is the current behaviour?

flow-runtime: Cannot resolve type: Card

What is the expected behaviour?

resolve declare types correctly


Which package versions are you using?

0.4.0


My .flowconfig

[ignore]
.*/node_modules/.*
.*/test/.*
.*/build/.*
.*/dist/.*
.*/coverage/.*

[include]
.*/src/.*

[libs]
src/flow

[options]
unsafe.enable_getters_and_setters=true

My src/flow/card.js

declare type Card = {
  cardTypeId: string,
  cardTypeName: void | string,
  cardId: string,
  cardTimes: number,
  cardLimit: string,
  cardDiscount: number,
  isValueCard: boolean,
  cardExpired: string,
  cardStyle: number
}

Annotated function arguments and return value always default to ExistentialType

This is a:

  • Bug Report

Which concerns:

  • flow-runtime

What is the current behaviour?

function foo(one: String, two: String): Number {
}

console.log(require('util').inspect(flow.typeOf(foo), { depth: null }));

Prints:

FunctionType {
  typeName: 'FunctionType',
  context: TypeContext { mode: 'assert' },
  params:
   [ FunctionTypeParam {
       typeName: 'FunctionTypeParam',
       context: TypeContext { mode: 'assert' },
       name: 'a',
       type:
        ExistentialType {
          typeName: 'ExistentialType',
          context: TypeContext { mode: 'assert' } },
       optional: false },
     FunctionTypeParam {
       typeName: 'FunctionTypeParam',
       context: TypeContext { mode: 'assert' },
       name: 'b',
       type:
        ExistentialType {
          typeName: 'ExistentialType',
          context: TypeContext { mode: 'assert' } },
       optional: false } ],
  returnType:
   FunctionTypeReturn {
     typeName: 'FunctionTypeReturn',
     context: TypeContext { mode: 'assert' },
     type:
      ExistentialType {
        typeName: 'ExistentialType',
        context: TypeContext { mode: 'assert' } } } }

What is the expected behaviour?

I was expecting the two arguments and the return type to be of StringType, etc.

Also, the name of each argument is being set as a and b instead of the argument names.

From the documentation, it seems to imply that annotated functions should be well typed.

Is this a bug?


Which package versions are you using?

  • "babel-cli": "6.22.2",
  • "babel-plugin-flow-runtime": "0.2.1"
  • "flow-runtime": "0.2.1"

Implement class property decorators

At the moment babel-plugin-flow-runtime generates decorators for typed class properties, but t.decorate() is not actually implemented yet. Need to implement it in a way that does not confound e.g. mobx

Will this support refinement likes tcomb or flowio?

As homepage said:

It builds on our previous work with babel-plugin-typecheck, but shares a lot of ideas with the work of Giulio Canti and others on tcomb and flow-io.

Will flow-runtime supports refinement?

IE11: Symbol is undefined

Hi, great tool! I get this error when running flow-runtime on IE11:

'Symbol' is undefined
	ReferenceError: 'Symbol' is undefined
	   at Anonymous function (eval code:40:3)
	   at Anonymous function (eval code:34:1)
	   at Anonymous function (eval code:1:31)
	   at eval code (eval code:1:2)
	Evaluating [email protected]/lib/types/Type.js
	Evaluating [email protected]/lib/types/AnyType.js
	Evaluating [email protected]/lib/types/index.js
	Evaluating [email protected]/lib/registerPrimitiveTypes.js
	Evaluating [email protected]/lib/globalContext.js
	Evaluating [email protected]/flow-runtime.js
	Evaluating [email protected]
	Evaluating main.js
	Error loading main.js

Perhaps adding babel-polyfill as a dependency would fix it?

Hoist type aliases

Type aliases should be hoisted just like function declarations are, at the moment this won't work:

type C = A; // A is not defined
type A = string;

Type exports not stripped from imported node modules

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validatosr
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

Importing types from node_modules causes SyntaxError.

See example repository.

yarn install
yarn build
yarn start

Setup

Given a node_module with type exports,

// @flow
export type Animal = {
  name: string,
  hasLegs: bool
};

And a source file...

// @flow
import type { Animal } from 'animals';

const c:any = {
  name: 'Dog',
  hasLegs: 'yes', // this is not the right type (should be bool)
}

console.log((c:Animal).id);

Results in invalid export,

export type Animal = {
^^^^^^
SyntaxError: Unexpected token export
    at Object.exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/home/seve/workspace/flow-runtime-issue/dist/index.js:3:16)
    at Module._compile (module.js:571:32)

What is the expected behaviour?

Remove types from imported node_modules.


Which package versions are you using?

"dependencies": {
    "animals": "file:animals",
    "babel-cli": "^6.23.0",
    "babel-core": "^6.23.1",
    "babel-plugin-flow-runtime": "^0.5.0",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.23.0",
    "babel-plugin-transform-flow-strip-types": "^6.22.0",
    "babel-preset-stage-1": "^6.22.0"
  }

The babel configuration is as follows,

"babel": {
    "presets": [
      "stage-1"
    ],
    "plugins": [
      [ "transform-flow-strip-types" ],
      [ "flow-runtime" ],
      ["transform-es2015-modules-commonjs"]
    ]
}

A workaround is to use the preferred method of type imports with the flow-typed directory. (i didn't personally test this)

Decorate throws `We don't know what to do with this node type.`

When setting decorate to true, the following error is throw:

someFileHere.js: We don't know what to do with this node type. We were previously a Statement but we can't fit in here?

.babelrc

{
  "presets": ["es2015", "stage-0"],
  "plugins": [
    "syntax-flow",
    ["flow-runtime", {
      "assert": true,
      "decorate": true
    }],
    "transform-flow-strip-types",
    "transform-runtime",
    "add-module-exports",
    "transform-es2015-modules-umd"
  ]
}

Setting decorators to false fixes the issue

Strip flow-runtime imports in production mode

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validatosr
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

It's currently not possible to strip developer-added flow-runtime imports in production. This limitation makes it difficult to manually add flow-runtime checks for teams that only type check in development mode, as it makes the flow-runtime package a requirement in production.


What is the expected behaviour?

If possible there should be a user-configurable way to remove user-specified flow-runtime imports / code in environments (prod / stage / test / etc).


Which package versions are you using?

0.2.1

TypeAliasing not working for functions of a Class

This is a:

  • Bug Report

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime

What is the current behaviour?

basically, I think there is an issue with Type Aliasing (please correct me if I am wrong).

// @flow-runtime

type __foo__ = (param: number) => string;

class ParseClass extends {
    constructor() {
        (this.foo: __foo__);
    }
}

class P extends ParseClass {
    foo() {
        // do nothing
    }
}

new P().foo();

What is the expected behaviour?

According to my understanding, the following code should not work, because the TypeAlias of the function foo implemented in the class P is different than __foo__. So ideally, flow should throw an error.


Which package versions are you using?

I am using the "babel-plugin-flow-runtime": "^0.2.1" package installed via npm, and putting it in my .babelrc file as

"plugins": [
    ["flow-runtime", {
        "assert": true,
        "annotate": true
    }]
]

Default for assert not working correctly.

This is a:

  • Bug Report
  • Feature Request
  • Question
  • Other

Which concerns:

  • flow-runtime
  • babel-plugin-flow-runtime
  • flow-runtime-validatosr
  • flow-runtime-mobx
  • flow-config-parser
  • The documentation website

What is the current behaviour?

With config like this:

{
  "presets": [
    "react",
    "stage-2"
  ],
  "plugins": [
    "flow-runtime",
    "syntax-flow",
    "transform-flow-strip-types"
  ]
}

and NODE_ENV=development, assertions are not included in the generated code.


What is the expected behaviour?

Assertions are included as stated by docs


Which package versions are you using?

0.3.0

It works if the config is like this:

    ["flow-runtime", { "assert": "undefined" }],

It seems problem is here https://github.com/codemix/flow-runtime/blob/75630a4e64b5ceeb97be4f26b309f124a5047481/packages/babel-plugin-flow-runtime/src/createConversionContext.js#L18. It is checking whether options.assert === 'undefined' (notice the quotes), instead of options.assert === undefined (without quotes).

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.