UNPKG

pxt-core

Version:

Microsoft MakeCode provides Blocks / JavaScript / Python tools and editors

89 lines (88 loc) 2.73 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.delAsync = exports.setAsync = exports.getAsync = void 0; const fs = require("fs"); const path = require("path"); const util_1 = require("util"); var U = pxt.Util; const rootPath = path.resolve('.pxt', 'storage'); const mkdirAsync = (0, util_1.promisify)(fs.mkdir); const unlinkAsync = (0, util_1.promisify)(fs.unlink); const readFileAsync = (0, util_1.promisify)(fs.readFile); const writeFileAsync = (0, util_1.promisify)(fs.writeFile); async function initAsync() { try { await mkdirAsync(rootPath, { recursive: true }); } catch (err) { pxt.debug(err); } } async function getAsync(container, key) { await initAsync(); try { const fname = path.resolve(rootPath, sanitize(container), sanitize(key)); pxt.debug(`GET ${fname}`); const srec = (await readFileAsync(fname)).toString("utf8"); const rec = JSON.parse(srec); let val; if (rec.type === "json") val = JSON.parse(rec.val); else val = rec.val; return Promise.resolve(val); } catch (err) { pxt.debug(err); } return undefined; } exports.getAsync = getAsync; async function setAsync(container, key, rec) { await initAsync(); try { const dir = path.resolve(rootPath, sanitize(container)); const fname = path.resolve(dir, sanitize(key)); pxt.debug(`SET ${fname}`); const srec = JSON.stringify(rec); try { await mkdirAsync(path.resolve(rootPath, dir)); } catch (_a) { } await writeFileAsync(fname, srec); } catch (err) { pxt.debug(err); } } exports.setAsync = setAsync; async function delAsync(container, key) { await initAsync(); try { const p = path.resolve(rootPath, sanitize(container), sanitize(key)); pxt.debug(`DEL ${p}`); await unlinkAsync(p); } catch (err) { pxt.debug(err); } } exports.delAsync = delAsync; const whitespaceRe = /[\r\n\s\t]+/g; const illegalRe = /[\/\?<>\\:\*\|"]/g; // eslint-disable-next-line no-control-regex const controlRe = /[\x00-\x1f\x80-\x9f]/g; // https://en.wikipedia.org/wiki/C0_and_C1_control_codes const reservedRe = /^\.+$/; const windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; const windowsTrailingRe = /[\. ]+$/; function sanitize(path) { path = path .replace(whitespaceRe, '-') .replace(illegalRe, '-') .replace(controlRe, '-') .replace(reservedRe, '-') .replace(windowsReservedRe, '-') .replace(windowsTrailingRe, '-'); U.assert(path.length > 0); return path; }