v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var util = A.util;
-
- var BINARY = ["png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "ico", "svgz", "woff", "woff2", "ttf", "otf", "eot",
- "mp3", "mp4", "webm", "ogg", "wav", "m4a", "mov", "zip", "rar", "7z", "gz", "pdf", "exe", "dll", "psd"];
- var IMAGE = ["png", "jpg", "jpeg", "gif", "webp", "avif", "bmp", "ico", "svg"];
- var MIME = {
- png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", avif: "image/avif",
- bmp: "image/bmp", ico: "image/x-icon", svg: "image/svg+xml", woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf",
- otf: "font/otf", mp3: "audio/mpeg", mp4: "video/mp4", webm: "video/webm", ogg: "audio/ogg", wav: "audio/wav",
- css: "text/css", js: "text/javascript", html: "text/html", json: "application/json", txt: "text/plain"
- };
-
- function exists(path) { return new Error(A.t("fs.exists", { path: path })); }
- function notFound(path) { return new Error(A.t("fs.not_found", { path: path })); }
-
- var collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
- var HIDDEN_DIRS = [".git", "node_modules", ".backups"];
- var HIDDEN_FILES = [".DS_Store", "Thumbs.db"];
-
- function sortEntries(list) {
- return list.sort(function (a, b) {
- if (a.kind !== b.kind) return a.kind === "dir" ? -1 : 1;
- return collator.compare(a.name, b.name);
- });
- }
-
- function splitPath(path) {
- return path ? path.split("/") : [];
- }
-
- function DiskProvider(root) {
- this.root = root;
- this.name = root.name || "Folder";
- this.kind = "disk";
- }
-
- DiskProvider.prototype._dir = async function (path, create) {
- var dir = this.root;
- for (var seg of splitPath(path)) dir = await dir.getDirectoryHandle(seg, { create: !!create });
- return dir;
- };
-
- DiskProvider.prototype._file = async function (path, create) {
- var dir = await this._dir(util.dirname(path), create);
- return dir.getFileHandle(util.basename(path), { create: !!create });
- };
-
- DiskProvider.prototype._handle = async function (path, kind) {
- if (!path) return this.root;
- return kind === "dir" ? this._dir(path) : this._file(path);
- };
-
- DiskProvider.prototype.list = async function (path) {
- var dir = await this._dir(path);
- var out = [];
- for await (var h of dir.values()) out.push({ name: h.name, kind: h.kind === "directory" ? "dir" : "file" });
- return sortEntries(out);
- };
-
- DiskProvider.prototype.readFile = async function (path) {
- try {
- return await (await this._file(path)).getFile();
- } catch (e) {
- if (e.name === "NotFoundError" || e.name === "TypeMismatchError") throw notFound(path);
- throw e;
- }
- };
-
- DiskProvider.prototype.readText = async function (path) {
- return (await this.readFile(path)).text();
- };
-
- DiskProvider.prototype.write = async function (path, data) {
- var fh = await this._file(path, true);
- var w = await fh.createWritable();
- try {
- await w.write(data);
- await w.close();
- } catch (e) {
- try { await w.abort(); } catch (x) { }
- throw e;
- }
- };
-
- DiskProvider.prototype.exists = async function (path) {
- try { await this._file(path); return true; } catch (e) { }
- try { await this._dir(path); return true; } catch (e) { return false; }
- };
-
- DiskProvider.prototype.createFile = async function (path, text) {
- if (await this.exists(path)) throw exists(path);
- await this.write(path, text || "");
- };
-
- DiskProvider.prototype.createDir = async function (path) {
- if (await this.exists(path)) throw exists(path);
- await this._dir(path, true);
- };
-
- DiskProvider.prototype.remove = async function (path) {
- var parent = await this._dir(util.dirname(path));
- await parent.removeEntry(util.basename(path), { recursive: true });
- };
-
- DiskProvider.prototype._copy = async function (from, to, kind) {
- if (kind === "file") return this.write(to, await this.readFile(from));
- await this._dir(to, true);
- for (var e of await this.list(from)) await this._copy(util.join(from, e.name), util.join(to, e.name), e.kind);
- };
-
- DiskProvider.prototype.rename = async function (path, newName, kind) {
- var target = util.join(util.dirname(path), newName);
- if (target === path) return target;
- if (target.toLowerCase() !== path.toLowerCase() && await this.exists(target)) throw exists(target);
- var h = await this._handle(path, kind);
- if (typeof h.move === "function") {
- try { await h.move(newName); return target; } catch (e) { }
- }
- await this._copy(path, target, kind);
- await this.remove(path);
- return target;
- };
-
- DiskProvider.prototype.move = async function (path, destDir, kind) {
- var target = util.join(destDir, util.basename(path));
- if (target === path) return target;
- if (await this.exists(target)) throw exists(target);
- var h = await this._handle(path, kind);
- if (typeof h.move === "function") {
- try {
- await h.move(await this._dir(destDir));
- if (await this.exists(target)) return target;
- } catch (e) { }
- }
- await this._copy(path, target, kind);
- await this.remove(path);
- return target;
- };
-
- function MemoryProvider(name, files) {
- this.name = name;
- this.kind = "memory";
- this.files = new Map();
- this.dirs = new Set();
- var self = this;
- (files || []).forEach(function (f) {
- var rel = (f.webkitRelativePath || f.name).split("/").slice(f.webkitRelativePath ? 1 : 0).join("/");
- self.files.set(rel, { file: f, text: null });
- self._addDirs(util.dirname(rel));
- });
- }
-
- MemoryProvider.prototype._addDirs = function (dir) {
- this._tree = null;
- while (dir) { this.dirs.add(dir); dir = util.dirname(dir); }
- };
-
- MemoryProvider.prototype._buildTree = function () {
- var tree = new Map();
- function add(path, kind) {
- var dir = util.dirname(path);
- if (!tree.has(dir)) tree.set(dir, new Map());
- tree.get(dir).set(util.basename(path), kind);
- }
- this.dirs.forEach(function (d) { add(d, "dir"); });
- this.files.forEach(function (v, p) { add(p, "file"); });
- this._tree = tree;
- return tree;
- };
-
- MemoryProvider.prototype.list = async function (path) {
- var children = (this._tree || this._buildTree()).get(path || "");
- var out = [];
- if (children) children.forEach(function (kind, name) { out.push({ name: name, kind: kind }); });
- return sortEntries(out);
- };
-
- MemoryProvider.prototype.readFile = async function (path) {
- var e = this.files.get(path);
- if (!e) throw notFound(path);
- if (e.text != null) return new File([e.text], util.basename(path), { type: MIME[util.ext(path)] || "text/plain" });
- return e.file;
- };
-
- MemoryProvider.prototype.readText = async function (path) {
- var e = this.files.get(path);
- if (!e) throw notFound(path);
- return e.text != null ? e.text : e.file.text();
- };
-
- MemoryProvider.prototype.write = async function (path, text) {
- this._tree = null;
- this.files.set(path, { file: null, text: text });
- this._addDirs(util.dirname(path));
- };
-
- MemoryProvider.prototype.exists = async function (path) {
- return this.files.has(path) || this.dirs.has(path);
- };
-
- MemoryProvider.prototype.createFile = async function (path, text) {
- if (await this.exists(path)) throw exists(path);
- await this.write(path, text || "");
- };
-
- MemoryProvider.prototype.createDir = async function (path) {
- if (await this.exists(path)) throw exists(path);
- this._addDirs(path);
- };
-
- MemoryProvider.prototype._move = function (path, target) {
- var self = this, prefix = path + "/";
- this._tree = null;
- if (this.files.has(path)) {
- if (target) this.files.set(target, this.files.get(path));
- this.files.delete(path);
- }
- Array.from(this.files.keys()).forEach(function (p) {
- if (p.indexOf(prefix) !== 0) return;
- if (target) self.files.set(target + "/" + p.slice(prefix.length), self.files.get(p));
- self.files.delete(p);
- });
- Array.from(this.dirs).forEach(function (d) {
- if (d !== path && d.indexOf(prefix) !== 0) return;
- self.dirs.delete(d);
- if (target) self.dirs.add(target + d.slice(path.length));
- });
- };
-
- MemoryProvider.prototype.remove = async function (path) {
- this._move(path, null);
- };
-
- MemoryProvider.prototype.rename = async function (path, newName) {
- var target = util.join(util.dirname(path), newName);
- if (target !== path && await this.exists(target)) throw exists(target);
- this._move(path, target);
- return target;
- };
-
- MemoryProvider.prototype.move = async function (path, destDir) {
- var target = util.join(destDir, util.basename(path));
- if (target === path) return target;
- if (await this.exists(target)) throw exists(target);
- this._move(path, target);
- this._addDirs(destDir);
- return target;
- };
-
- var fs = (A.fs = {
- provider: null,
- supported: typeof window.showDirectoryPicker === "function",
- canSaveAs: typeof window.showSaveFilePicker === "function",
- isBinary: function (name) { return BINARY.indexOf(util.ext(name)) >= 0; },
- isImage: function (name) { return IMAGE.indexOf(util.ext(name)) >= 0; },
- mime: function (name) { return MIME[util.ext(name)] || "application/octet-stream"; },
- DiskProvider: DiskProvider,
- MemoryProvider: MemoryProvider
- });
-
- var allFiles = null;
-
- function walkAll(provider, max) {
- return new Promise(function (resolve) {
- var out = [], queue = [""], active = 0, done = false;
- function finish() {
- if (done) return;
- done = true;
- resolve(out.sort(collator.compare));
- }
- function visit(dir) {
- active++;
- provider.list(dir).then(function (entries) {
- entries.forEach(function (e) {
- if (e.kind === "dir") {
- if (!dir && e.name === fs.PRIVATE_DIR && !fs.includePrivate()) return;
- if (HIDDEN_DIRS.indexOf(e.name) < 0) queue.push(util.join(dir, e.name));
- } else if (HIDDEN_FILES.indexOf(e.name) < 0 && out.length < max) {
- out.push(util.join(dir, e.name));
- }
- });
- }, function () { }).then(function () {
- active--;
- pump();
- });
- }
- function pump() {
- while (active < 3 && queue.length && out.length < max) visit(queue.shift());
- if (!active && (!queue.length || out.length >= max)) finish();
- }
- pump();
- });
- }
-
- fs.allFiles = function () {
- var provider = fs.provider;
- if (!provider) return Promise.resolve([]);
- if (!allFiles || allFiles.provider !== provider) {
- var promise = walkAll(provider, 50000);
- allFiles = { provider: provider, promise: promise };
- }
- return allFiles.promise;
- };
-
- fs.invalidateIndex = function () {
- allFiles = null;
- };
-
- fs.HIDDEN_DIRS = HIDDEN_DIRS;
- fs.HIDDEN_FILES = HIDDEN_FILES;
- fs.PRIVATE_DIR = ".private";
- fs.includePrivate = function () { return false; };
-
- A.on("files-changed", fs.invalidateIndex);
-
- fs.setProvider = function (provider) {
- fs.provider = provider;
- allFiles = null;
- if (provider) setTimeout(function () { if (fs.provider === provider) fs.allFiles(); }, 1500);
- if (provider && provider.kind === "disk") A.idb.set("lastRoot", provider.root);
- A.emit("workspace", provider);
- };
-
- fs.pickFolder = async function () {
- if (fs.supported) {
- try {
- return new DiskProvider(await window.showDirectoryPicker({ id: "athera-root", mode: "readwrite" }));
- } catch (e) {
- if (e.name === "AbortError") return null;
- throw e;
- }
- }
- var files = await pickFiles({ directory: true });
- if (!files.length) return null;
- var rootName = (files[0].webkitRelativePath || "").split("/")[0] || "Folder";
- return new MemoryProvider(rootName, files);
- };
-
- fs.lastFolder = async function () {
- if (!fs.supported) return null;
- var h = await A.idb.get("lastRoot");
- return h && h.kind === "directory" ? h : null;
- };
-
- fs.grant = async function (handle) {
- var opts = { mode: "readwrite" };
- if ((await handle.queryPermission(opts)) === "granted") return true;
- return (await handle.requestPermission(opts)) === "granted";
- };
-
- fs.openFiles = async function () {
- if (typeof window.showOpenFilePicker === "function") {
- var handles;
- try {
- handles = await window.showOpenFilePicker({ multiple: true, id: "athera-files" });
- } catch (e) {
- if (e.name === "AbortError") return [];
- throw e;
- }
- return Promise.all(handles.map(async function (h) {
- return { name: h.name, handle: h, file: await h.getFile() };
- }));
- }
- return (await pickFiles({ multiple: true })).map(function (f) { return { name: f.name, handle: null, file: f }; });
- };
-
- fs.writeHandle = async function (handle, text) {
- if (handle.requestPermission && (await handle.requestPermission({ mode: "readwrite" })) !== "granted") {
- throw new Error(A.t("fs.no_permission"));
- }
- var w = await handle.createWritable();
- await w.write(text);
- await w.close();
- };
-
- fs.saveAs = async function (name, text) {
- if (fs.canSaveAs) {
- try {
- var h = await window.showSaveFilePicker({ suggestedName: name, id: "athera-save" });
- await fs.writeHandle(h, text);
- return h;
- } catch (e) {
- if (e.name === "AbortError") return undefined;
- throw e;
- }
- }
- fs.download(name, text);
- return null;
- };
-
- fs.download = function (name, data, type) {
- var blob = data instanceof Blob ? data : new Blob([data], { type: type || "text/plain;charset=utf-8" });
- var url = URL.createObjectURL(blob);
- var a = util.el("a", { href: url, download: name });
- document.body.appendChild(a);
- a.click();
- a.remove();
- setTimeout(function () { URL.revokeObjectURL(url); }, 2000);
- };
-
- fs.pickFiles = pickFiles;
-
- function pickFiles(opts) {
- return new Promise(function (resolve) {
- var input = util.el("input", { type: "file", accept: opts.accept || null, style: "display:none" });
- input.multiple = !!(opts.multiple || opts.directory);
- if (opts.directory) input.webkitdirectory = true;
- var settled = false;
- function finish(list) {
- if (settled) return;
- settled = true;
- input.remove();
- resolve(list);
- }
- input.addEventListener("change", function () { finish(Array.from(input.files || [])); });
- input.addEventListener("cancel", function () { finish([]); });
- document.body.appendChild(input);
- input.click();
- });
- }
- })();
-