v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var util = A.util;
- var t = A.t;
-
- var TIMEOUT = 10000;
- var SYNC_TIMEOUT = 180000;
- var MAX_SIZE = 4 * 1024 * 1024;
- var MAX_DB_SIZE = 50 * 1024 * 1024;
- var BATCH_FILES = 300;
- var BATCH_BYTES = 16 * 1024 * 1024;
- var PHP_EXT = ["php", "phtml", "inc", "html", "htm", "json", "xml", "csv", "txt", "ini", "env", "sql", "md", "yml", "yaml",
- "twig", "tpl", "svg", "log", "lock", "htaccess", "sqlite", "sqlite3", "db"];
- var DB = ["sqlite", "sqlite3", "db", "sql"];
- var SHIM_PATH = "../internal/shared/preload/athera-mysql.php";
- var REWRITE_EXT = ["php", "phtml", "inc"];
- var REWRITE_TEST = /PDO|mysqli|extension_loaded/i;
-
- var worker = null, workerUrl = null, wasm = null, ready = null, seq = 0;
- var pending = {};
- var synced = new Map();
- var scanned = false;
- var needsScan = true;
- var dirty = new Set();
- var syncing = null;
- var cookies = {};
- var shimState = null;
- var shimNeeded = false;
-
- function loadScript(src) {
- return new Promise(function (resolve, reject) {
- var s = document.createElement("script");
- s.src = src;
- s.onload = resolve;
- s.onerror = function () { reject(new Error(t("php.load_failed"))); };
- document.head.appendChild(s);
- });
- }
-
- function call(msg, transfer, limit) {
- return new Promise(function (resolve, reject) {
- var id = ++seq;
- var ms = limit || TIMEOUT;
- msg.id = id;
- var timer = setTimeout(function () {
- delete pending[id];
- if (worker) reset();
- reject(new Error(t(msg.type === "run" ? "php.timeout" : "php.sync_timeout", { s: Math.round(ms / 1000) })));
- }, ms);
- pending[id] = function (res) {
- clearTimeout(timer);
- if (res.type === "error") reject(new Error(res.message));
- else resolve(res);
- };
- worker.postMessage(msg, transfer || []);
- });
- }
-
- function reset() {
- if (worker) worker.terminate();
- worker = null;
- ready = null;
- synced.clear();
- shimState = null;
- shimNeeded = false;
- scanned = false;
- needsScan = true;
- Object.keys(pending).forEach(function (id) {
- var cb = pending[id];
- delete pending[id];
- cb({ type: "error", message: t("php.stopped") });
- });
- A.emit("php-status", "idle");
- }
-
- function start() {
- worker = new Worker(workerUrl);
- worker.onmessage = function (e) {
- var m = e.data, cb = pending[m.id];
- if (cb) {
- delete pending[m.id];
- cb(m);
- }
- };
- worker.onerror = function (e) {
- console.error(e);
- reset();
- };
- }
-
- async function boot() {
- A.emit("php-status", "loading");
- if (!window.AtheraPhpWorker) await loadScript(A.asset("assets/vendor/php/php-worker.js"));
- if (!wasm) {
- if (!window.AtheraPhpWasm) await loadScript(A.asset("assets/vendor/php/php-8.3.js"));
- var b64 = window.AtheraPhpWasm;
- var bin = atob(b64);
- wasm = new Uint8Array(bin.length);
- for (var i = 0; i < bin.length; i++) wasm[i] = bin.charCodeAt(i);
- window.AtheraPhpWasm = null;
- }
- if (!workerUrl) workerUrl = URL.createObjectURL(new Blob([window.AtheraPhpWorker], { type: "text/javascript" }));
- start();
- var zone = "UTC";
- try { zone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; } catch (e) { }
- var res = await call({ type: "init", gz: wasm, timezone: zone }, null, 60000);
- A.php.version = res.version;
- A.emit("php-status", "ready");
- return res.version;
- }
-
- function wanted(path) {
- var name = util.basename(path);
- return PHP_EXT.indexOf(util.ext(name)) >= 0 || (name.charAt(0) === "." && name.indexOf(".", 1) < 0);
- }
-
- function pool(list, size, fn) {
- var i = 0;
- function next() {
- if (i >= list.length) return Promise.resolve();
- var item = list[i++];
- return Promise.resolve(fn(item)).then(next, next);
- }
- var runners = [];
- for (var k = 0; k < Math.min(size, list.length); k++) runners.push(next());
- return Promise.all(runners);
- }
-
- function sync(progress) {
- if (!syncing) {
- syncing = doSync(progress).then(function (r) { syncing = null; return r; }, function (e) { syncing = null; throw e; });
- }
- return syncing;
- }
-
- async function doSync(progress) {
- var provider = A.fs.provider;
- var writes = [], deletes = [], bytes = 0, check = [];
- var open = new Map();
- A.tabs.list.forEach(function (tab) {
- if (tab.kind !== "text") return;
- if (tab.path != null) {
- if (provider && wanted(tab.path)) open.set(tab.path, tab);
- } else if (/\.(php|phtml)$/i.test(tab.name)) {
- open.set(untitledPath(tab), tab);
- }
- });
-
- async function flush() {
- if (!writes.length && !deletes.length) return;
- var w = writes, d = deletes;
- writes = [];
- deletes = [];
- bytes = 0;
- var transfer = w.filter(function (x) { return typeof x.data !== "string"; }).map(function (x) { return x.data.buffer; });
- await call({ type: "sync", writes: w, deletes: d }, transfer, SYNC_TIMEOUT);
- }
-
- function queue(path, data, stamp) {
- data = rewrite(path, data);
- writes.push({ path: path, data: data });
- bytes += typeof data === "string" ? data.length : data.byteLength;
- synced.set(path, stamp);
- }
-
- if (provider) {
- if (!scanned || needsScan) {
- needsScan = false;
- var paths = (await A.fs.allFiles()).filter(wanted);
- var present = new Set(paths);
- check = scanned ? paths.filter(function (p) { return !synced.has(p); }) : paths.slice();
- synced.forEach(function (v, p) {
- if (p.indexOf("__untitled/") !== 0 && !present.has(p)) {
- deletes.push(p);
- synced.delete(p);
- }
- });
- scanned = true;
- }
- synced.forEach(function (stamp, p) {
- if (stamp.indexOf("live:") === 0 && !open.has(p) && p.indexOf("__untitled/") !== 0) check.push(p);
- });
- dirty.forEach(function (p) { if (wanted(p)) check.push(p); });
- dirty.clear();
- var unique = new Set();
- check = check.filter(function (p) {
- if (open.has(p) || unique.has(p)) return false;
- unique.add(p);
- return true;
- });
-
- var done = 0, total = check.length, lastReport = 0;
- if (progress && total > 50) progress(0, total);
- await pool(check, 16, async function (p) {
- try {
- var file = await provider.readFile(p);
- var limit = DB.indexOf(util.ext(p)) >= 0 ? MAX_DB_SIZE : MAX_SIZE;
- var stamp = file.lastModified + ":" + file.size;
- if (file.size <= limit && synced.get(p) !== stamp) {
- queue(p, new Uint8Array(await file.arrayBuffer()), stamp);
- if (writes.length >= BATCH_FILES || bytes >= BATCH_BYTES) await flush();
- }
- } catch (e) {
- synced.delete(p);
- }
- done++;
- if (progress && total > 50 && Date.now() - lastReport > 120) {
- lastReport = Date.now();
- progress(done, total);
- }
- });
- }
-
- open.forEach(function (tab, p) {
- var text = A.tabs.textOf(tab), stamp = "live:" + text.length + ":" + hash(text);
- if (synced.get(p) !== stamp) queue(p, text, stamp);
- });
- synced.forEach(function (v, p) {
- if (p.indexOf("__untitled/") === 0 && !open.has(p)) {
- deletes.push(p);
- synced.delete(p);
- }
- });
- if (mysqlOn() && shimNeeded && shimState !== true) {
- writes.push({ path: SHIM_PATH, data: A.mysqlShim });
- shimState = true;
- } else if (!mysqlOn() && shimState === true) {
- deletes.push(SHIM_PATH);
- shimState = false;
- }
- await flush();
- }
-
- function mysqlOn() {
- return !!A.mysqlShim && A.settings.get("mysqlEmulation") !== false;
- }
-
- function rewrite(path, data) {
- if (!mysqlOn() || REWRITE_EXT.indexOf(util.ext(path)) < 0) return data;
- var text = typeof data === "string" ? data : new TextDecoder().decode(data);
- if (!REWRITE_TEST.test(text)) return data;
- shimNeeded = true;
- var out = text
- .replace(/\bnew\s+\\?PDO\s*\(/gi, "new \\AthPDO(")
- .replace(/\\?\bPDO::(MYSQL_ATTR_\w+|getAvailableDrivers)/gi, "\\AthPDO::$1")
- .replace(/\bextends\s+\\?PDO\b(?!\w|::)/gi, "extends \\AthPDO")
- .replace(/\bextension_loaded\s*\(/g, "ath_extension_loaded(");
- return out === text ? data : out;
- }
-
- function hash(text) {
- var h = 0;
- for (var i = 0; i < text.length; i++) h = (h * 31 + text.charCodeAt(i)) | 0;
- return h;
- }
-
- function untitledPath(tab) {
- return "__untitled/" + tab.id + "/" + tab.name;
- }
-
- function cookieHeader() {
- return Object.keys(cookies).map(function (k) { return k + "=" + cookies[k]; }).join("; ");
- }
-
- function storeCookies(headers) {
- var list = (headers && (headers["set-cookie"] || headers["Set-Cookie"])) || [];
- [].concat(list).forEach(function (line) {
- var pair = String(line).split(";")[0];
- var i = pair.indexOf("=");
- if (i <= 0) return;
- var name = pair.slice(0, i).trim(), value = pair.slice(i + 1).trim();
- if (/expires=Thu, 01 Jan 1970|max-age=0/i.test(line) || value === "deleted") delete cookies[name];
- else cookies[name] = value;
- });
- }
-
- A.on("workspace", function () {
- cookies = {};
- shimNeeded = false;
- synced.clear();
- scanned = false;
- needsScan = true;
- dirty.clear();
- if (worker) reset();
- });
- A.on("files-changed", function () { needsScan = true; });
- A.on("settings", function (keys) {
- if (keys.indexOf("mysqlEmulation") < 0) return;
- synced.clear();
- scanned = false;
- needsScan = true;
- });
- A.on("saved", function (tab) { if (tab && tab.path != null) dirty.add(tab.path); });
-
- A.php = {
- version: null,
-
- isReady: function () {
- return !!worker && !!ready;
- },
-
- ensure: function () {
- if (!ready) {
- ready = boot().catch(function (e) {
- reset();
- throw e;
- });
- }
- return ready;
- },
-
- scriptPath: function (tab) {
- return tab.path != null ? tab.path : untitledPath(tab);
- },
-
- rescan: function () {
- scanned = false;
- needsScan = true;
- },
-
- run: async function (tab, route, progress) {
- await A.php.ensure();
- await sync(progress);
- route = route || {};
- var res = await call({
- type: "run",
- path: A.php.scriptPath(tab),
- method: route.method || "GET",
- query: route.query || "",
- body: route.body || "",
- contentType: route.body ? "application/x-www-form-urlencoded" : "",
- cookie: cookieHeader(),
- userAgent: A.preview && A.preview.userAgent ? A.preview.userAgent() : ""
- });
- storeCookies(res.headers);
- return res;
- },
-
- restart: function () {
- reset();
- cookies = {};
- }
- };
- })();
-