WebOrbiton
v1.4.2

AtheraStudio Code

346 lines · 10.6 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var util = A.util;
  6. var t = A.t;
  7. ​
  8. var TIMEOUT = 10000;
  9. var SYNC_TIMEOUT = 180000;
  10. var MAX_SIZE = 4 * 1024 * 1024;
  11. var MAX_DB_SIZE = 50 * 1024 * 1024;
  12. var BATCH_FILES = 300;
  13. var BATCH_BYTES = 16 * 1024 * 1024;
  14. var PHP_EXT = ["php", "phtml", "inc", "html", "htm", "json", "xml", "csv", "txt", "ini", "env", "sql", "md", "yml", "yaml",
  15. "twig", "tpl", "svg", "log", "lock", "htaccess", "sqlite", "sqlite3", "db"];
  16. var DB = ["sqlite", "sqlite3", "db", "sql"];
  17. var SHIM_PATH = "../internal/shared/preload/athera-mysql.php";
  18. var REWRITE_EXT = ["php", "phtml", "inc"];
  19. var REWRITE_TEST = /PDO|mysqli|extension_loaded/i;
  20. ​
  21. var worker = null, workerUrl = null, wasm = null, ready = null, seq = 0;
  22. var pending = {};
  23. var synced = new Map();
  24. var scanned = false;
  25. var needsScan = true;
  26. var dirty = new Set();
  27. var syncing = null;
  28. var cookies = {};
  29. var shimState = null;
  30. var shimNeeded = false;
  31. ​
  32. function loadScript(src) {
  33. return new Promise(function (resolve, reject) {
  34. var s = document.createElement("script");
  35. s.src = src;
  36. s.onload = resolve;
  37. s.onerror = function () { reject(new Error(t("php.load_failed"))); };
  38. document.head.appendChild(s);
  39. });
  40. }
  41. ​
  42. function call(msg, transfer, limit) {
  43. return new Promise(function (resolve, reject) {
  44. var id = ++seq;
  45. var ms = limit || TIMEOUT;
  46. msg.id = id;
  47. var timer = setTimeout(function () {
  48. delete pending[id];
  49. if (worker) reset();
  50. reject(new Error(t(msg.type === "run" ? "php.timeout" : "php.sync_timeout", { s: Math.round(ms / 1000) })));
  51. }, ms);
  52. pending[id] = function (res) {
  53. clearTimeout(timer);
  54. if (res.type === "error") reject(new Error(res.message));
  55. else resolve(res);
  56. };
  57. worker.postMessage(msg, transfer || []);
  58. });
  59. }
  60. ​
  61. function reset() {
  62. if (worker) worker.terminate();
  63. worker = null;
  64. ready = null;
  65. synced.clear();
  66. shimState = null;
  67. shimNeeded = false;
  68. scanned = false;
  69. needsScan = true;
  70. Object.keys(pending).forEach(function (id) {
  71. var cb = pending[id];
  72. delete pending[id];
  73. cb({ type: "error", message: t("php.stopped") });
  74. });
  75. A.emit("php-status", "idle");
  76. }
  77. ​
  78. function start() {
  79. worker = new Worker(workerUrl);
  80. worker.onmessage = function (e) {
  81. var m = e.data, cb = pending[m.id];
  82. if (cb) {
  83. delete pending[m.id];
  84. cb(m);
  85. }
  86. };
  87. worker.onerror = function (e) {
  88. console.error(e);
  89. reset();
  90. };
  91. }
  92. ​
  93. async function boot() {
  94. A.emit("php-status", "loading");
  95. if (!window.AtheraPhpWorker) await loadScript(A.asset("assets/vendor/php/php-worker.js"));
  96. if (!wasm) {
  97. if (!window.AtheraPhpWasm) await loadScript(A.asset("assets/vendor/php/php-8.3.js"));
  98. var b64 = window.AtheraPhpWasm;
  99. var bin = atob(b64);
  100. wasm = new Uint8Array(bin.length);
  101. for (var i = 0; i < bin.length; i++) wasm[i] = bin.charCodeAt(i);
  102. window.AtheraPhpWasm = null;
  103. }
  104. if (!workerUrl) workerUrl = URL.createObjectURL(new Blob([window.AtheraPhpWorker], { type: "text/javascript" }));
  105. start();
  106. var zone = "UTC";
  107. try { zone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; } catch (e) { }
  108. var res = await call({ type: "init", gz: wasm, timezone: zone }, null, 60000);
  109. A.php.version = res.version;
  110. A.emit("php-status", "ready");
  111. return res.version;
  112. }
  113. ​
  114. function wanted(path) {
  115. var name = util.basename(path);
  116. return PHP_EXT.indexOf(util.ext(name)) >= 0 || (name.charAt(0) === "." && name.indexOf(".", 1) < 0);
  117. }
  118. ​
  119. function pool(list, size, fn) {
  120. var i = 0;
  121. function next() {
  122. if (i >= list.length) return Promise.resolve();
  123. var item = list[i++];
  124. return Promise.resolve(fn(item)).then(next, next);
  125. }
  126. var runners = [];
  127. for (var k = 0; k < Math.min(size, list.length); k++) runners.push(next());
  128. return Promise.all(runners);
  129. }
  130. ​
  131. function sync(progress) {
  132. if (!syncing) {
  133. syncing = doSync(progress).then(function (r) { syncing = null; return r; }, function (e) { syncing = null; throw e; });
  134. }
  135. return syncing;
  136. }
  137. ​
  138. async function doSync(progress) {
  139. var provider = A.fs.provider;
  140. var writes = [], deletes = [], bytes = 0, check = [];
  141. var open = new Map();
  142. A.tabs.list.forEach(function (tab) {
  143. if (tab.kind !== "text") return;
  144. if (tab.path != null) {
  145. if (provider && wanted(tab.path)) open.set(tab.path, tab);
  146. } else if (/\.(php|phtml)$/i.test(tab.name)) {
  147. open.set(untitledPath(tab), tab);
  148. }
  149. });
  150. ​
  151. async function flush() {
  152. if (!writes.length && !deletes.length) return;
  153. var w = writes, d = deletes;
  154. writes = [];
  155. deletes = [];
  156. bytes = 0;
  157. var transfer = w.filter(function (x) { return typeof x.data !== "string"; }).map(function (x) { return x.data.buffer; });
  158. await call({ type: "sync", writes: w, deletes: d }, transfer, SYNC_TIMEOUT);
  159. }
  160. ​
  161. function queue(path, data, stamp) {
  162. data = rewrite(path, data);
  163. writes.push({ path: path, data: data });
  164. bytes += typeof data === "string" ? data.length : data.byteLength;
  165. synced.set(path, stamp);
  166. }
  167. ​
  168. if (provider) {
  169. if (!scanned || needsScan) {
  170. needsScan = false;
  171. var paths = (await A.fs.allFiles()).filter(wanted);
  172. var present = new Set(paths);
  173. check = scanned ? paths.filter(function (p) { return !synced.has(p); }) : paths.slice();
  174. synced.forEach(function (v, p) {
  175. if (p.indexOf("__untitled/") !== 0 && !present.has(p)) {
  176. deletes.push(p);
  177. synced.delete(p);
  178. }
  179. });
  180. scanned = true;
  181. }
  182. synced.forEach(function (stamp, p) {
  183. if (stamp.indexOf("live:") === 0 && !open.has(p) && p.indexOf("__untitled/") !== 0) check.push(p);
  184. });
  185. dirty.forEach(function (p) { if (wanted(p)) check.push(p); });
  186. dirty.clear();
  187. var unique = new Set();
  188. check = check.filter(function (p) {
  189. if (open.has(p) || unique.has(p)) return false;
  190. unique.add(p);
  191. return true;
  192. });
  193. ​
  194. var done = 0, total = check.length, lastReport = 0;
  195. if (progress && total > 50) progress(0, total);
  196. await pool(check, 16, async function (p) {
  197. try {
  198. var file = await provider.readFile(p);
  199. var limit = DB.indexOf(util.ext(p)) >= 0 ? MAX_DB_SIZE : MAX_SIZE;
  200. var stamp = file.lastModified + ":" + file.size;
  201. if (file.size <= limit && synced.get(p) !== stamp) {
  202. queue(p, new Uint8Array(await file.arrayBuffer()), stamp);
  203. if (writes.length >= BATCH_FILES || bytes >= BATCH_BYTES) await flush();
  204. }
  205. } catch (e) {
  206. synced.delete(p);
  207. }
  208. done++;
  209. if (progress && total > 50 && Date.now() - lastReport > 120) {
  210. lastReport = Date.now();
  211. progress(done, total);
  212. }
  213. });
  214. }
  215. ​
  216. open.forEach(function (tab, p) {
  217. var text = A.tabs.textOf(tab), stamp = "live:" + text.length + ":" + hash(text);
  218. if (synced.get(p) !== stamp) queue(p, text, stamp);
  219. });
  220. synced.forEach(function (v, p) {
  221. if (p.indexOf("__untitled/") === 0 && !open.has(p)) {
  222. deletes.push(p);
  223. synced.delete(p);
  224. }
  225. });
  226. if (mysqlOn() && shimNeeded && shimState !== true) {
  227. writes.push({ path: SHIM_PATH, data: A.mysqlShim });
  228. shimState = true;
  229. } else if (!mysqlOn() && shimState === true) {
  230. deletes.push(SHIM_PATH);
  231. shimState = false;
  232. }
  233. await flush();
  234. }
  235. ​
  236. function mysqlOn() {
  237. return !!A.mysqlShim && A.settings.get("mysqlEmulation") !== false;
  238. }
  239. ​
  240. function rewrite(path, data) {
  241. if (!mysqlOn() || REWRITE_EXT.indexOf(util.ext(path)) < 0) return data;
  242. var text = typeof data === "string" ? data : new TextDecoder().decode(data);
  243. if (!REWRITE_TEST.test(text)) return data;
  244. shimNeeded = true;
  245. var out = text
  246. .replace(/\bnew\s+\\?PDO\s*\(/gi, "new \\AthPDO(")
  247. .replace(/\\?\bPDO::(MYSQL_ATTR_\w+|getAvailableDrivers)/gi, "\\AthPDO::$1")
  248. .replace(/\bextends\s+\\?PDO\b(?!\w|::)/gi, "extends \\AthPDO")
  249. .replace(/\bextension_loaded\s*\(/g, "ath_extension_loaded(");
  250. return out === text ? data : out;
  251. }
  252. ​
  253. function hash(text) {
  254. var h = 0;
  255. for (var i = 0; i < text.length; i++) h = (h * 31 + text.charCodeAt(i)) | 0;
  256. return h;
  257. }
  258. ​
  259. function untitledPath(tab) {
  260. return "__untitled/" + tab.id + "/" + tab.name;
  261. }
  262. ​
  263. function cookieHeader() {
  264. return Object.keys(cookies).map(function (k) { return k + "=" + cookies[k]; }).join("; ");
  265. }
  266. ​
  267. function storeCookies(headers) {
  268. var list = (headers && (headers["set-cookie"] || headers["Set-Cookie"])) || [];
  269. [].concat(list).forEach(function (line) {
  270. var pair = String(line).split(";")[0];
  271. var i = pair.indexOf("=");
  272. if (i <= 0) return;
  273. var name = pair.slice(0, i).trim(), value = pair.slice(i + 1).trim();
  274. if (/expires=Thu, 01 Jan 1970|max-age=0/i.test(line) || value === "deleted") delete cookies[name];
  275. else cookies[name] = value;
  276. });
  277. }
  278. ​
  279. A.on("workspace", function () {
  280. cookies = {};
  281. shimNeeded = false;
  282. synced.clear();
  283. scanned = false;
  284. needsScan = true;
  285. dirty.clear();
  286. if (worker) reset();
  287. });
  288. A.on("files-changed", function () { needsScan = true; });
  289. A.on("settings", function (keys) {
  290. if (keys.indexOf("mysqlEmulation") < 0) return;
  291. synced.clear();
  292. scanned = false;
  293. needsScan = true;
  294. });
  295. A.on("saved", function (tab) { if (tab && tab.path != null) dirty.add(tab.path); });
  296. ​
  297. A.php = {
  298. version: null,
  299. ​
  300. isReady: function () {
  301. return !!worker && !!ready;
  302. },
  303. ​
  304. ensure: function () {
  305. if (!ready) {
  306. ready = boot().catch(function (e) {
  307. reset();
  308. throw e;
  309. });
  310. }
  311. return ready;
  312. },
  313. ​
  314. scriptPath: function (tab) {
  315. return tab.path != null ? tab.path : untitledPath(tab);
  316. },
  317. ​
  318. rescan: function () {
  319. scanned = false;
  320. needsScan = true;
  321. },
  322. ​
  323. run: async function (tab, route, progress) {
  324. await A.php.ensure();
  325. await sync(progress);
  326. route = route || {};
  327. var res = await call({
  328. type: "run",
  329. path: A.php.scriptPath(tab),
  330. method: route.method || "GET",
  331. query: route.query || "",
  332. body: route.body || "",
  333. contentType: route.body ? "application/x-www-form-urlencoded" : "",
  334. cookie: cookieHeader()
  335. });
  336. storeCookies(res.headers);
  337. return res;
  338. },
  339. ​
  340. restart: function () {
  341. reset();
  342. cookies = {};
  343. }
  344. };
  345. })();
  346. ​