function parseContent(contents, filename) {
    var data = stripComments(stripBom(contents));
    if (/^\s*$/.test(data)) {
        return {};
    }
    return parseJson(data, null, filename);
}
async function checkAllTutorials() {
  const files = await walk('js/learn/tutorials');
  const jsonFiles = files.filter((x) => x.endsWith('.json'));
  const promises = [];
  const tutorials = [];
  for (let jsonFilename of jsonFiles) {
    let jsonData = null;
    try {
      jsonData = parseJson(await readFile(jsonFilename));
      tutorials.push(jsonData);
    } catch (e) {
      console.error('Error loading ', jsonFilename, '\n', e);
      continue;
    }
    promises.push(reportAndFix(jsonFilename, jsonData));
  }
  await Promise.all(promises);

  // Used for testing down below
  let defaultTutorials = null;
  try {
    defaultTutorials = require('../js/learn/learnConfig.js').defaultTutorials;
  } catch (e) {
    console.error('Error importing learnConfig.js\n', e);
    return;
  }
  const configuredTutorials = [].concat.apply([], Object.values(defaultTutorials.map((style) => style.tutorials)));
  const missingTutorials = tutorials.filter((fileTut) => !configuredTutorials.find((configTut) => areEqual(configTut, fileTut)));
  for (let tutorial of missingTutorials) {
    console.error('Tutorial not included: ', tutorial.style, tutorial.title);
  }
  console.log('Finished!');
}
Пример #3
0
  getSettings() {
    if (!this.settings) {
      let filePath;
      if (this.settingsPath) {
        filePath = resolvePath(this.settingsPath);
      } else {
        filePath = path.join(this.base, 'settings.json');
      }

      try {
        this.settings = fs.readFileSync(filePath).toString();
      } catch (e) {
        console.log(`Unable to load settings.json at ${filePath}`);
        if (e.code !== 'ENOENT') {
          console.log(e);
        }
        process.exit(1);
      }
      try {
        this.settings = parseJson(this.settings);
      } catch (e) {
        console.log('Error parsing settings file:');
        console.log(e.message);
        process.exit(1);
      }
    }

    return this.settings;
  }
Пример #4
0
module.exports = function (json, filepath) {
  try {
    return parseJson(json);
  } catch (err) {
    err.message = 'JSON Error in ' + filepath + ':\n' + err.message;
    throw err;
  }
};
Пример #5
0
    ], function (err, stdout) {
        if (err) {
            cb(err);
            return;
        }

        cb(null, parseJson(stdout));
    });
Пример #6
0
function loadJson(filepath, content) {
    try {
        return parseJson(stripJsonComments(content));
    } catch (err) {
        err.message = `JSON Error in ${filepath}:\n${err.message}`;
        throw err;
    }
}
Пример #7
0
					request('http://apis.mondorobot.com/beers/' + req.params.id, function(err, beerResp, beerBody){
						beer = parseJson(beerBody).beer;

						res.render('locator', { 
							id: req.params.id,
							beer: beer,
							allbeer: allbeer
						});
					});
Пример #8
0
	return readFileAsync(filePath, 'utf8').then(file => {
		const json = parseJson(file);

		if (options.normalize) {
			require('normalize-package-data')(json);
		}

		return json;
	});
Пример #9
0
      readFile(join(__dirname, file), 'utf8', function (err, contents) {
        var parts = file.replace(/\.json$/i, '').split(sep)
        var source = parts.shift()
        var name = parts.join('/')
        var data

        if (err) {
          return done(err)
        }

        try {
          data = parse(contents)
        } catch (err) {
          return done(err)
        }

        var valid = validate(data)

        if (!valid) {
          return done(new Error('Invalid JSON for "' + name + ' (' + source + ')":\n' + ajv.errorsText(validate.errors)))
        }

        // Push all typings installation tests into a batch executor.
        Object.keys(data.versions).forEach(function (version) {
          arrify(data.versions[version]).forEach(function (info) {
            // Handle plain string locations.
            if (typeof info === 'string') {
              info = { location: info }
            }

            // check if commit sha is specified
            var dependency = typings.parseDependency(info.location)
            if (dependency.type === 'github' || dependency.type === 'bitbucket') {
              if (dependency.meta.sha === 'master') {
                return done(new Error(info.location + ' is mutable and may change, consider specifying a commit hash'))
              }
            }

            typingsBatch.push(function (done) {
              typings.installDependency({
                name: name,
                location: info.location
              }, {
                cwd: __dirname,
                name: name,
                global: globalSources.indexOf(source) > -1
              })
                .then(function () {
                  return done()
                }, done)
            })
          })
        })

        return done()
      })
Пример #10
0
module.exports = function parseJsonWrapper(
  json        ,
  filepath        
)         {
  try {
    return parseJson(json);
  } catch (err) {
    err.message = `JSON Error in ${filepath}:\n${err.message}`;
    throw err;
  }
};
Пример #11
0
function readJSONSync(...args) {
  const content = readFileSync(...args);
  let json;
  try {
    json = parseJson(content);
  } catch(e) {
    console.error('error: '.red + args[0].green.underline + ' ' + e.message.green);
    process.exit(0);
  }
  return json;
}
Пример #12
0
 parseFeedContent(feeds) {
     const result = [];
     for (const { fileName, contents } of feeds) {
         try {
             result.push(parseJson(contents));
         } catch (err) {
             throw Boom.boomify(err, {
                 message: `Unable to parse 1 or more feeds as JSON. File ${fileName} was unparseable.`,
             });
         }
     }
     return result;
 }
Пример #13
0
    ], function (err, stdout) {
        if (err) {
            cb(err);
            return;
        }

        var endTimestamp = Date.now();
        var duration = endTimestamp - startTimestamp;

        var result = parseJson(stdout);
        result.junit = junitReporter(url, result.audit, endTimestamp, duration);

        cb(null, result);
    });
Пример #14
0
module.exports.sync = options => {
	options = Object.assign({
		cwd: process.cwd(),
		normalize: true
	}, options);

	const filePath = path.resolve(options.cwd, 'package.json');
	const json = parseJson(fs.readFileSync(filePath, 'utf8'));

	if (options.normalize) {
		require('normalize-package-data')(json);
	}

	return json;
};
 function contextNormalModuleResolve(compiler, resolved, key) {
   if (key.startsWith('__hardSource_parityToken')) {
     parityCache[key] = resolved;
     return;
   }
   if (typeof resolved === 'string') {
     resolved = parseJson(resolved);
   }
   if (resolved.type === 'context') {
     return Object.assign({}, resolved, {
       identifier: contextNormalModuleId(compiler, resolved.identifier),
       resource: contextNormalRequest(compiler, resolved.resource),
     });
   }
   return serialResolveNormal.thaw(resolved, resolved, {
     compiler,
   });
 }
 function contextNormalModuleResolveKey(compiler, key) {
   if (key.startsWith('__hardSource_parityToken')) {
     return key;
   }
   const parsed = parseJson(key);
   if (Array.isArray(parsed)) {
     return JSON.stringify([
       parsed[0],
       contextNormalPath(compiler, parsed[1]),
       parsed[2],
     ]);
   } else {
     return JSON.stringify(
       Object.assign({}, parsed, {
         context: contextNormalPath(compiler, parsed.context),
       }),
     );
   }
 }
Пример #17
0
      readFile(join(__dirname, file), 'utf8', function (err, contents) {
        var parts = file.replace(/\.json$/i, '').split(sep)
        var source = parts.shift()
        var name = parts.join('/')
        var data

        if (err) {
          return done(err)
        }

        try {
          data = parse(contents)
        } catch (err) {
          return done(err)
        }

        var valid = validate(data)

        if (!valid) {
          return done(new Error('Invalid JSON for "' + name + ' (' + source + ')":\n' + ajv.errorsText(validate.errors)))
        }

        // Push all typings installation tests into a batch executor.
        Object.keys(data.versions).forEach(function (version) {
          arrify(data.versions[version]).forEach(function (location) {
            typingsBatch.push(function (done) {
              typings.installDependency({
                name: name,
                location: location
              }, {
                cwd: __dirname,
                name: name,
                ambient: ambientSources.indexOf(source) > -1
              })
                .then(function () {
                  return done()
                }, done)
            })
          })
        })

        return done()
      })
async function checkAllTutorials() {
  const files = (await fs.walk('../js/tutorials/playlists')).map(x => x.path);
  const jsonFiles = files.filter(x => x.endsWith('.json'));
  const promises = [];
  const tutorials = [];
  for (const jsonFilename of jsonFiles) {
    let jsonData = null;
    try {
      jsonData = parseJson(await fs.readFile(jsonFilename));
      tutorials.push(jsonData);
    } catch (e) {
      console.error('Error loading ', jsonFilename, '\n', e);
      continue;
    }
    promises.push(reportAndFix(jsonFilename, jsonData));
  }
  await Promise.all(promises);

  // Used for testing down below
  let defaultTutorials = null;
  try {
    defaultTutorials = require('../js/tutorials/playlistConfig.js').getTutorials(
      ''
    );
  } catch (e) {
    console.error('Error importing learnConfig.js\n', e);
    return;
  }
  const configuredTutorials = [].concat(
    ...defaultTutorials.map(style => style.tutorials)
  );
  const missingTutorials = tutorials.filter(
    fileTut =>
      !configuredTutorials.find(configTut => configTut.id === fileTut.id)
  );
  for (const tutorial of missingTutorials) {
    console.error('Tutorial not included: ', tutorial.style, tutorial.title);
  }
  console.log('Finished!');
}
 function relateNormalModuleResolveKey(compiler, key) {
   const parsed = parseJson(key);
   if (Array.isArray(parsed)) {
     return JSON.stringify([
       parsed[0],
       relateNormalPath(compiler, parsed[1]),
       relateContext.relateAbsoluteRequest(parsed[1], parsed[2]),
     ]);
   } else {
     if (!parsed.request) {
       return JSON.stringify(
         Object.assign({}, parsed, {
           context: relateNormalPath(compiler, parsed.context),
           userRequest: relateContext.relateAbsoluteRequest(
             parsed.context,
             parsed.userRequest,
           ),
           options: Object.assign({}, parsed.options, {
             request: relateContext.relateAbsoluteRequest(
               parsed.context,
               parsed.options.request,
             ),
           }),
         }),
       );
     } else {
       return JSON.stringify(
         Object.assign({}, parsed, {
           context: relateNormalPath(compiler, parsed.context),
           request: relateContext.relateAbsoluteRequest(
             parsed.context,
             parsed.request,
           ),
         }),
       );
     }
   }
 }
Пример #20
0
		readAllStream(res, opts.encoding, function (err, data) {
			var statusCode = res.statusCode;

			if (err) {
				cb(new got.ReadError(err, opts), null, res);
				return;
			}

			if (statusCode < 200 || statusCode > 299) {
				err = new got.HTTPError(statusCode, opts);
			}

			if (opts.json && statusCode !== 204) {
				try {
					data = parseJson(data);
				} catch (e) {
					e.fileName = urlLib.format(opts);
					err = new got.ParseError(e, opts);
				}
			}

			cb(err, data, res);
		});
Пример #21
0
/* Fill a file with a tree. */
function parse(context, file) {
  var message

  if (stats(file).fatal) {
    return
  }

  if (context.treeIn) {
    debug('Not parsing already parsed document')

    try {
      context.tree = json(file.toString())
    } catch (error) {
      message = file.message(
        new Error('Cannot read file as JSON\n' + error.message)
      )
      message.fatal = true
    }

    /* Add the preferred extension to ensure the file, when compiled, is
     * correctly recognized. Only add it if there’s a path — not if the
     * file is for example stdin. */
    if (file.path) {
      file.extname = context.extensions[0]
    }

    file.contents = ''

    return
  }

  debug('Parsing `%s`', file.path)

  context.tree = context.processor.parse(file)

  debug('Parsed document')
}
Пример #22
0
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):e.json=n()}(this,function(){"use strict";var e=require("fast-safe-stringify"),n=require("parse-json");return{stringify:e,parse:function(e,t,i,r){2===arguments.length&&(r=t,t=null);try{var f=n(e,t,i);r(null,f)}catch(e){r(e)}}}});
Пример #23
0
function parseJson(contents, path, allowEmpty) {
    if (contents === '' && allowEmpty) {
        return {};
    }
    return parse(contents, null, path);
}
Пример #24
0
function parse(x, fp) {
    return parseJson(stripBom(x), path.relative(process.cwd(), fp));
}
 Object.keys(moduleResolveCache).forEach(key => {
   const resolveKey = parseJson(key);
   const resolveItem = moduleResolveCache[key];
   let normalId = 'normal';
   if (resolveItem.resolveOptions) {
     normalId = `normal-${new nodeObjectHash({ sort: false }).hash(
       resolveItem.resolveOptions,
     )}`;
   }
   if (resolveItem.type === 'context') {
     const contextMissing =
       missingCache.context[
         JSON.stringify([
           resolveKey.context,
           resolveItem.resource.split('?')[0],
         ])
       ];
     if (!contextMissing || contextMissing.invalid) {
       resolveItem.invalid = true;
       resolveItem.invalidReason = 'resolved context invalid';
     }
   } else {
     const normalMissing =
       missingCache[normalId] &&
       missingCache[normalId][
         JSON.stringify([
           resolveKey[1],
           resolveItem.resource.split('?')[0],
         ])
       ];
     if (!normalMissing || normalMissing.invalid) {
       resolveItem.invalid = true;
       resolveItem.invalidReason = `resolved normal invalid${
         normalMissing
           ? ` ${normalMissing.invalidReason}`
           : ': resolve entry not in cache'
       }`;
     }
     resolveItem.loaders.forEach(loader => {
       if (typeof loader === 'object') {
         if (loader.loader != null) {
           loader = loader.loader;
         } else {
           // Convert { "0": "b", "1": "a", "2": "r" } into "bar"
           loader = Object.assign([], loader).join('');
         }
       }
       // Loaders specified in a dependency are searched for from the
       // context of the module containing that dependency.
       let loaderMissing =
         missingCache.loader[
           JSON.stringify([resolveKey[1], loader.split('?')[0]])
         ];
       if (!loaderMissing) {
         // webpack searches for rule based loaders from the project
         // context.
         loaderMissing =
           missingCache.loader[
             JSON.stringify([
               // compiler may be a Watching instance, which refers to the
               // compiler
               (compiler.options || compiler.compiler.options).context,
               loader.split('?')[0],
             ])
           ];
       }
       if (!loaderMissing || loaderMissing.invalid) {
         resolveItem.invalid = true;
         resolveItem.invalidReason = 'resolved loader invalid';
       }
     });
   }
 });
Пример #26
0
const parseIfString = item => {
  if (typeof item === 'string') {
    return parseJson(item);
  }
  return item;
};
Пример #27
0
const parse = (data, fp) => parseJson(stripBom(data), path.relative('.', fp));