scratch-parser/lib/unpack.js
Karishma Chadha 7f8672dfbc refactor($lib): Add callback wrapper around JSZip promise-based interface. Refactor m
Refactor unpack and main exported function to return optional zip, if originally provided, in
addition to the validated project.

BREAKING CHANGE: Change to main api to return originally provided zip (or null if string was
provided) along with validated project, in a 2-element array.
2018-03-23 09:37:48 -04:00

49 lines
1.5 KiB
JavaScript

var zip = require('./zip');
/**
* If input a buffer, transforms buffer into a UTF-8 string.
* If input is encoded in ZIP format, the input will be extracted and decoded.
* If input is a string, passes that string along to the given callback.
*
* @param {Buffer | string} Input
*
* @return {String}
*/
module.exports = function (input, callback) {
if (typeof input === 'string') {
// Pass string to callback
return callback(null, [input, null]);
}
// Validate input type
var typeError = 'Input must be a Buffer or a string.';
if (!Buffer.isBuffer(input)) {
try {
input = new Buffer(input);
} catch (e) {
return callback(typeError);
}
}
// Determine format
// We don't use the file suffix as this is unreliable and mine-type
// information is unavailable from Scratch's project CDN. Instead, we look
// at the first few bytes from the provided buffer (byte signature).
// https://en.wikipedia.org/wiki/List_of_file_signatures
var signature = input.slice(0, 3).join(' ');
var isLegacy = false;
var isZip = false;
if (signature.indexOf('83 99 114') === 0) isLegacy = true;
if (signature.indexOf('80 75') === 0) isZip = true;
// If not legacy or zip, convert buffer to UTF-8 string and return
if (!isZip && !isLegacy) {
return callback(null, [input.toString('utf-8'), null]);
}
// Return error if legacy encoding detected
if (isLegacy) return callback('Parser only supports Scratch 2.X');
zip(input, callback);
};