How to use typescript-json-schema - 10 common examples

To help you get started, we’ve selected a few typescript-json-schema examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jumattos / lsif-util / src / validate.ts View on Github external
});
                    }
                    catch {
                        // Failed to get more details for the error
                    }
                }
                return false;
            }
        }
        console.log(`${outputMessage} done`);
        printPass("Vertices properties are correct");

        /*
         * Check #4: edges properties are correct
         */
        const edgeSchema = TJS.generateSchema(program, "Edge", { required: true, noExtraProps: true });
        count = 1;
        length = Object.keys(edges).length;
        for (let key in edges) {
            outputMessage = `Verifying edge ${count} of ${length}...`;
            process.stdout.write(`${outputMessage}\r`);
            count++;

            const validation = validateSchema(edges[key], edgeSchema);
            if (!validation.valid) {
                console.log(`${outputMessage} error`);
                console.error(`Edge ${key} is not valid:\n${JSON.stringify(edges[key], null, 2)}`);
                
                // Since we checked for inV and outV before, the only possible problem is the label
                if (!edges[key].label || edges[key].label === "") {
                    printError(`requires property "label"`);
                }
github hpcc-systems / Visualization / packages / ddl-shim / util / createSchema.ts View on Github external
function genSchema(src: string, dest: string, type: string) {
    const ddl = TJS.getProgramFromFiles([resolve(`src/${src}.ts`)], {
        skipLibCheck: true
    });
    const ddlSchema = TJS.generateSchema(ddl, type, settings);

    fs.writeFile(`src/${dest}.json`, JSON.stringify(ddlSchema), function (err) {
        if (err) {
            return console.error(err);
        }
    });

    const tpl = `/* tslint:disable */\n` +
        `export const ${dest} =  \n` +
        JSON.stringify(ddlSchema, null, "    ") +
        `;\n`;

    fs.writeFile(`src/${dest}.ts`, tpl, function (err) {
github wavesplatform / waves-transactions / build / schemas.ts View on Github external
excludePrivate: true,
    noExtraProps: false,
  }

  // optionally pass ts compiler options
  const compilerOptions: TJS.CompilerOptions = {
    strictNullChecks: true,
    resolveJsonModule: true,
    allowSyntheticDefaultImports: true,
    downlevelIteration: true,
    lib: [
      'esnext'
    ]
  }

  const program = TJS.getProgramFromFiles([resolve('src/transactions.ts')], compilerOptions)


  TYPES.forEach(type => {
    const id = `https://raw.githubusercontent.com/wavesplatform/waves-transactions/master/src/schemas/${type}.json`
    let schema = TJS.generateSchema(program, type, { ...settings, id })
    //Define generic LONG as string | number in JSON schema. Otherwise ot would be object. Should probably pass param that defines LONG schema;
    schema!.definitions = {...schema!.definitions,  LONG:{type:['string', 'number']}};
    const filePath = `src/schemas/${type}.json`
    const fileContent = JSON.stringify(schema, null, 2)
    writeFile(filePath, fileContent, (err) => {
      if (err) throw err
      console.log(`${type} schema has been written`)
    })
  })

  const manifest = `${TYPES.map(type => `import ${type} from './${type}.json'`).join('\n')}
github intl-wc / intl / packages / utils / src / generate-schemas.ts View on Github external
export default async function generateSchemas() {
    const program = TJS.getProgramFromFiles([resolve('.', 'intl.config.ts')], null);
    const settings: TJS.PartialArgs = {
        ignoreErrors: false,
        required: true
    }
    // const schema = TJS.generateSchema(program, 'Schema');
    const generator = TJS.buildGenerator(program, settings);
    if (generator) {
        // const symbols = generator.getUserSymbols();
        // const symbols = generator.getMainFileSymbols(program);
        const schema = generator.getSchemaForSymbol('Schema', false);
        let generatedSchema = { ...schema };
        let lazyRefs = new Map();
        
        if (schema.properties) {
            // Filter lazy props, get reference to their interfaces
            const lazy = Object.entries(schema.properties).filter(lazyProps())
            for (let [key, value] of lazy) {
                const lazyRef = value.properties.interface['$ref'].split('/').pop();
                lazyRefs.set(key, generator.getSchemaForSymbol(lazyRef, false));
                
                const newValue = { ...value };
                delete newValue.properties.interface;
github transitive-bullshit / functional-typescript / packages / fts / src / parser.ts View on Github external
}

  if (!builder.definition.params.schema) {
    throw new Error(`Error generating params JSON schema for TS file "${file}"`)
  }

  // fix required parameters to only be those which do not have default values
  const { schema } = builder.definition.params
  schema.required = (schema.required || []).filter(
    (k) => schema.properties[k].default === undefined
  )
  if (!schema.required.length) {
    delete schema.required
  }

  builder.definition.returns.schema = TJS.generateSchema(program, FTSReturns, {
    ...jsonSchemaOptions,
    required: false
  })

  if (!builder.definition.returns.schema) {
    throw new Error(
      `Error generating returns JSON schema for TS file "${file}"`
    )
  }
}
github transitive-bullshit / functional-typescript / packages / fts / src / parser.ts View on Github external
const compilerOptions = {
    allowJs: true,
    lib: ['es2018', 'dom'],
    target: 'es5',
    esModuleInterop: true,
    ...jsonCompilerOptions
  }

  const program = TJS.getProgramFromFiles(
    [file],
    compilerOptions,
    process.cwd()
  )

  builder.definition.params.schema = {
    ...TJS.generateSchema(program, FTSParams, jsonSchemaOptions),
    ...(builder.definition.params.schema || {}) // Spread any existing schema params
  }

  if (!builder.definition.params.schema) {
    throw new Error(`Error generating params JSON schema for TS file "${file}"`)
  }

  // fix required parameters to only be those which do not have default values
  const { schema } = builder.definition.params
  schema.required = (schema.required || []).filter(
    (k) => schema.properties[k].default === undefined
  )
  if (!schema.required.length) {
    delete schema.required
  }
github Bearer / bearer-js / packages / cli / src / utils / generators.ts View on Github external
async build() {
    const files = await globby(`${this.srcFunctionsDir}/*.ts`)
    const programGenerator = TJS.getProgramFromFiles(
      files,
      {
        ...config.config.compilerOptions,
        allowUnusedLabels: true,
        // be indulgent
        noUnusedParameters: false,
        noUnusedLocals: false
      },
      './ok'
    )

    const generator = TJS.buildGenerator(programGenerator, {
      required: true
    })

    if (!generator) {
      throw new Error('Please fix above issues before')
    }

    files.forEach(file => {
      const sourceFile = ts.createSourceFile(
        file,
        fs.readFileSync(file, 'utf8'),
        ts.ScriptTarget.Latest,
        false,
        ts.ScriptKind.TSX
      )
      ts.transform(sourceFile, [transformer(generator)])
github eclipse / eclipse.jdt.ls / lang-protocol-generator / Gruntfile.js View on Github external
var TJS = require('typescript-json-schema').TJS;

/*global module:false*/
module.exports = function (grunt) {

  // Project configuration.
  grunt.initConfig({
    // Task configuration.
    shell: {
       gitclone:{
            command: [
               'mkdir ./nodeClient',
               'cd ./nodeClient',
               'git clone git@github.com:Microsoft/vscode-languageserver-node.git',
               'cd vscode-languageserver-node/client',
               'npm install .'
            ].join('&&')
github jumattos / lsif-util / src / validate.ts View on Github external
console.error(`Vertex ${key} is not connected to any other`);
            return false;
        }
    }
    printPass("Vertices are used in at least one edge");

    /*
     * Thorough validation
     */
    if (fs.existsSync(protocolPath)) {
        const program = TJS.getProgramFromFiles([protocolPath]);

        /*
         * Check #3: vertices properties are correct
         */
        const vertexSchema = TJS.generateSchema(program, "Vertex", { required: true });
        let count = 1;
        let length = Object.keys(vertices).length;
        for (let key in vertices) {
            outputMessage = `Verifying vertex ${count} of ${length}...`;
            process.stdout.write(`${outputMessage}\r`);
            count++;

            const validation = validateSchema(vertices[key], vertexSchema);
            if (!validation.valid) {
                console.log(`${outputMessage} error`);
                console.error(`Vertex ${key} is not valid:\n${JSON.stringify(vertices[key], null, 2)}`);

                if (!vertices[key].label || vertices[key].label === "") {
                    printError(`requires property "label"`);
                }
                else {
github contentful / rich-text / packages / rich-text-types / tools / jsonSchemaGen.ts View on Github external
const createJsonSchema = (symbolName: string, nodeType: string): void => {
  const doc = TJS.generateSchema(program, symbolName, settings);

  const schemaString = JSON.stringify(doc, null, 2);

  writeFile(`./src/schemas/generated/${nodeType}.json`, schemaString, (err: Error) => {
    if (err) {
      return console.log(err);
    }
  });
};