All files index.js

82.81% Statements 106/128
84.78% Branches 78/92
83.33% Functions 25/30
82.26% Lines 102/124
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271                      13x                       13x 31x 31x 31x     31x     69x   13x 218x 28x 1x   2x         27x 13x 14x 2x       2x   12x 190x 26x 181x 2x 180x         1x 1x         1x 2x   179x 10x   169x     13x   82x 82x     211x   13x         211x 211x 54x   211x 82x   129x     13x 89x 4x     85x 4x     81x 3x     78x       8x   70x       211x 211x         211x             13x 17x 17x     13x     81x 3x   78x 4x   8x 8x 1x   8x   4x     74x 16x   58x     13x   17x 14x 3x 3x   17x       17x   69x       69x     69x     69x     17x     13x 17x 17x 17x     13x               13x 2x   13x                       13x 2x 2x 2x         13x 2x   13x 2x       2x 2x     13x               13x                                    
#! /usr/bin/env node
// @flow
import program from "commander";
import prettier from "prettier";
import yaml from "js-yaml";
import fs from "fs";
import path from "path";
import axios from "axios";
import camelize from "camelize";
 
// Swagger data types are base on types supported by the JSON-Scheme Draft4.
const typeMapping = {
  array: "Array<*>",
  boolean: "boolean",
  integer: "number",
  number: "number",
  null: "null",
  object: "Object",
  Object: "Object",
  string: "string",
  enum: "string"
};
 
const definitionTypeName = (ref): string => {
  const re = /#\/definitions\/(.*)|#\/components\/schemas\/(.*)/;
  const found = ref.match(re);
  Iif (!found) {
    return "";
  }
  return found[1] || found[2];
};
 
const stripBrackets = (name: string) => name.replace(/[[\]']+/g, "");
 
const typeFor = (property: any): string => {
  if (property.type === "array") {
    if ("oneOf" in property.items) {
      return `Array<${property.items.oneOf
        .map(e =>
          e.type === "object"
            ? propertiesTemplate(propertiesList(e.items)).replace(/"/g, "")
            : typeFor(e)
        )
        .join(" | ")}>`;
    } else if ("$ref" in property.items) {
      return `Array<${definitionTypeName(property.items.$ref)}>`;
    } else if (property.items.type === "object") {
      const child = propertiesTemplate(propertiesList(property.items)).replace(
        /"/g,
        ""
      );
      return `Array<${child}>`;
    }
    return `Array<${typeMapping[property.items.type]}>`;
  } else if (property.type === "string" && "enum" in property) {
    return property.enum.map(e => `'${e}'`).join(" | ");
  } else if (Array.isArray(property.type)) {
    return property.type.map(t => typeMapping[t]).join(" | ");
  } else if (
    "allOf" in property ||
    "oneOf" in property ||
    "anyOf" in property
  ) {
    const discriminator = Object.keys(property)[0];
    const discriminatorMap = {
      allOf: "&",
      oneOf: "|",
      anyOf: "|"
    };
    return property[discriminator]
      .map(p => typeFor(p))
      .join(discriminatorMap[discriminator]);
  } else if (property.type === "object") {
    return propertiesTemplate(propertiesList(property)).replace(/"/g, "");
  }
  return typeMapping[property.type] || definitionTypeName(property.$ref);
};
 
const isRequired = (propertyName: string, definition: Object): boolean => {
  const result =
    definition.required && definition.required.indexOf(propertyName) >= 0;
  return result;
};
 
const isNullable = (property: Object): boolean => property.nullable;
 
const propertyKeyForDefinition = (
  propName: string,
  definition: Object
): string => {
  let resolvedPropName =
    propName.indexOf("-") > 0 ? `'${propName}'` : propName;
  if (program.lowerCamelCase) {
    resolvedPropName = camelize(resolvedPropName);
  }
  if (program.checkRequired) {
    return `${resolvedPropName}${isRequired(propName, definition) ? "" : "?"}`;
  }
  return resolvedPropName;
};
 
const propertiesList = (definition: Object) => {
  if ("allOf" in definition) {
    return definition.allOf.map(propertiesList);
  }
 
  if (definition.$ref) {
    return { $ref: definitionTypeName(definition.$ref) };
  }
 
  if ("type" in definition && definition.type !== "object") {
    return typeFor(definition);
  }
 
  if (
    !definition.properties ||
    Object.keys(definition.properties).length === 0
  ) {
    return {};
  }
  return Object.assign.apply(
    null,
    Object.keys(definition.properties).reduce(
      (properties: Array<Object>, propName: string) => {
        const property = definition.properties[propName];
        const arr = properties.concat({
          [propertyKeyForDefinition(propName, definition)]: `${
            isNullable(property) ? "?" : ""
          }${typeFor(property)}`
        });
        return arr;
      },
      [{}]
    )
  );
};
 
const withExact = (property: string): string => {
  const result = property.replace(/{[^|}]/g, "{|").replace(/[^|{]}/g, "|}");
  return result;
};
 
const propertiesTemplate = (
  properties: Object | Array<Object> | string
): string => {
  if (typeof properties === "string") {
    return properties;
  }
  if (Array.isArray(properties)) {
    return properties
      .map(property => {
        let p = property.$ref ? `& ${property.$ref}` : JSON.stringify(property);
        if (!property.$ref && program.exact) {
          p = withExact(p);
        }
        return p;
      })
      .sort(a => (a[0] === "&" ? 1 : -1))
      .join(" ");
  }
  if (program.exact) {
    return withExact(JSON.stringify(properties));
  }
  return JSON.stringify(properties);
};
 
const generate = (swagger: Object): string => {
  let defs;
  if (swagger.definitions) {
    defs = swagger.definitions;
  } else Eif (swagger.components) {
    defs = swagger.components.schemas;
  }
  Iif (!defs) {
    throw new Error("There is no definition");
  }
 
  const g = Object.keys(defs)
    .reduce((acc: Array<Object>, definitionName: string) => {
      const arr = acc.concat({
        title: stripBrackets(definitionName),
        properties: propertiesList(defs[definitionName])
      });
      return arr;
    }, [])
    .map(definition => {
      const s = `export type ${definition.title} = ${propertiesTemplate(
        definition.properties
      ).replace(/"/g, "")};`;
      return s;
    })
    .join(" ");
  return g;
};
 
export const generator = (content: Object, file: string) => {
  const options = prettier.resolveConfig.sync(file) || {};
  const result = `// @flow strict\n${generate(content)}`;
  return prettier.format(result, options);
};
 
export const writeToFile = (dist: string = "./flowtype.js", result: string) => {
  fs.writeFile(dist, result, err => {
    if (err) {
      throw err;
    }
  });
};
 
export const isUrl = (value: string): boolean =>
  value.match(/https?:\/\//) !== null;
 
export const distFile = (p: Object, inputFileName: string): string => {
  if (p.destination) {
    return p.destination;
  }
  if (isUrl(inputFileName)) {
    return "./flowtype.js";
  }
 
  const ext = path.parse(inputFileName).ext;
  return inputFileName.replace(ext, ".js");
};
 
export const getContentFromFile = (file: string): Object => {
  const ext = path.extname(file);
  const readFile = fs.readFileSync(file, "utf8");
  return ext === ".yaml" || ext === ".yml"
    ? yaml.safeLoad(readFile)
    : JSON.parse(readFile);
};
 
export const isObject = (value: any): boolean =>
  typeof value === "object" && value !== null;
 
export const getContentFromUrl = (url: string): Promise<Object> =>
  axios({
    method: "get",
    url
  }).then(response => {
    const { data } = response;
    return isObject(data) ? data : yaml.safeLoad(data);
  });
 
export const getContent = (fileOrUrl: string): Promise<Object> => {
  if (isUrl(fileOrUrl)) {
    return getContentFromUrl(fileOrUrl);
  }
  const content = getContentFromFile(fileOrUrl);
  return Promise.resolve(content);
};
 
program
  .arguments("<file>")
  .option("-d --destination <destination>", "Destination path")
  .option("-cr --check-required", "Add question mark to optional properties")
  .option("-e --exact", "Add exact types")
  .option("-l --lower-camel-case", "Transform property keys to lower camel case")
  .action(async file => {
    try {
      const content = await getContent(file);
      const result = generator(content, file);
      const dist = distFile(program, file);
      writeToFile(dist, result);
      console.log(`Generated flow types to ${dist}`);
    } catch (e) {
      console.log(e);
    }
  })
  .parse(process.argv);