vendor: 4,170 bytes, lines 1-133
1// quarto-ojs-runtime v0.0.15 Copyright 2023 undefined 2var EOL = {}, 3 EOF = {}, 4 QUOTE = 34, 5 NEWLINE = 10, 6 RETURN = 13; 7 8function objectConverter(columns) { 9 return new Function("d", "return {" + columns.map(function(name, i) { 10 return JSON.stringify(name) + ": d[" + i + "] || \"\""; 11 }).join(",") + "}"); 12} 13 14function customConverter(columns, f) { 15 var object = objectConverter(columns); 16 return function(row, i) { 17 return f(object(row), i, columns); 18 }; 19} 20 21// Compute unique columns in order of discovery. 22function inferColumns(rows) { 23 var columnSet = Object.create(null), 24 columns = []; 25 26 rows.forEach(function(row) { 27 for (var column in row) { 28 if (!(column in columnSet)) { 29 columns.push(columnSet[column] = column); 30 } 31 } 32 }); 33 34 return columns; 35} 36 37function pad$1(value, width) { 38 var s = value + "", length = s.length; 39 return length < width ? new Array(width - length + 1).join(0) + s : s; 40} 41 42function formatYear$1(year) { 43 return year < 0 ? "-" + pad$1(-year, 6) 44 : year > 9999 ? "+" + pad$1(year, 6) 45 : pad$1(year, 4); 46} 47 48function formatDate$2(date) { 49 var hours = date.getUTCHours(), 50 minutes = date.getUTCMinutes(), 51 seconds = date.getUTCSeconds(), 52 milliseconds = date.getUTCMilliseconds(); 53 return isNaN(date) ? "Invalid Date" 54 : formatYear$1(date.getUTCFullYear()) + "-" + pad$1(date.getUTCMonth() + 1, 2) + "-" + pad$1(date.getUTCDate(), 2) 55 + (milliseconds ? "T" + pad$1(hours, 2) + ":" + pad$1(minutes, 2) + ":" + pad$1(seconds, 2) + "." + pad$1(milliseconds, 3) + "Z" 56 : seconds ? "T" + pad$1(hours, 2) + ":" + pad$1(minutes, 2) + ":" + pad$1(seconds, 2) + "Z" 57 : minutes || hours ? "T" + pad$1(hours, 2) + ":" + pad$1(minutes, 2) + "Z" 58 : ""); 59} 60 61function dsv$1(delimiter) { 62 var reFormat = new RegExp("[\"" + delimiter + "\n\r]"), 63 DELIMITER = delimiter.charCodeAt(0); 64 65 function parse(text, f) { 66 var convert, columns, rows = parseRows(text, function(row, i) { 67 if (convert) return convert(row, i - 1); 68 columns = row, convert = f ? customConverter(row, f) : objectConverter(row); 69 }); 70 rows.columns = columns || []; 71 return rows; 72 } 73 74 function parseRows(text, f) { 75 var rows = [], // output rows 76 N = text.length, 77 I = 0, // current character index 78 n = 0, // current line number 79 t, // current token 80 eof = N <= 0, // current token followed by EOF? 81 eol = false; // current token followed by EOL? 82 83 // Strip the trailing newline. 84 if (text.charCodeAt(N - 1) === NEWLINE) --N; 85 if (text.charCodeAt(N - 1) === RETURN) --N; 86 87 function token() { 88 if (eof) return EOF; 89 if (eol) return eol = false, EOL; 90 91 // Unescape quotes. 92 var i, j = I, c; 93 if (text.charCodeAt(j) === QUOTE) { 94 while (I++ < N && text.charCodeAt(I) !== QUOTE || text.charCodeAt(++I) === QUOTE); 95 if ((i = I) >= N) eof = true; 96 else if ((c = text.charCodeAt(I++)) === NEWLINE) eol = true; 97 else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; } 98 return text.slice(j + 1, i - 1).replace(/""/g, "\""); 99 } 100 101 // Find next delimiter or newline. 102 while (I < N) { 103 if ((c = text.charCodeAt(i = I++)) === NEWLINE) eol = true; 104 else if (c === RETURN) { eol = true; if (text.charCodeAt(I) === NEWLINE) ++I; } 105 else if (c !== DELIMITER) continue; 106 return text.slice(j, i); 107 } 108 109 // Return last token before EOF. 110 return eof = true, text.slice(j, N); 111 } 112 113 while ((t = token()) !== EOF) { 114 var row = []; 115 while (t !== EOL && t !== EOF) row.push(t), t = token(); 116 if (f && (row = f(row, n++)) == null) continue; 117 rows.push(row); 118 } 119 120 return rows; 121 } 122 123 function preformatBody(rows, columns) { 124 return rows.map(function(row) { 125 return columns.map(function(column) { 126 return formatValue(row[column]); 127 }).join(delimiter); 128 }); 129 } 130 131 function format(rows, columns) { 132 if (columns == null) columns = inferColumns(rows); 133 return [columns.map(formatValue).join(delimiter)].concat(preformatBody(rows, c
133olumns)).join("\n"); 134 } 135 136 function formatBody(rows, columns) { 137 if (columns == null) columns = inferColumns(rows); 138 return preformatBody(rows, columns).join("\n"); 139 } 140 141 function formatRows(rows) { 142 return rows.map(formatRow).join("\n"); 143 } 144 145 function formatRow(row) { 146 return row.map(formatValue).join(delimiter); 147 } 148 149 function formatValue(value) { 150 return value == null ? "" 151 : value instanceof Date ? formatDate$2(value) 152 : reFormat.test(value += "") ? "\"" + value.replace(/"/g, "\"\"") + "\"" 153 : value; 154 } 155 156 return { 157 parse: parse, 158 parseRows: parseRows, 159 format: format, 160 formatBody: formatBody, 161 formatRows: formatRows, 162 formatRow: formatRow, 163 formatValue: formatValue 164 }; 165} 166 167var csv = dsv$1(","); 168 169var csvParse = csv.parse; 170var csvParseRows = csv.parseRows; 171 172var tsv = dsv$1("\t"); 173 174var tsvParse = tsv.parse; 175var tsvParseRows = tsv.parseRows; 176 177function autoType(object) { 178 for (var key in object) { 179 var value = object[key].trim(), number, m; 180 if (!value) value = null; 181 else if (value === "true") value = true; 182 else if (value === "false") value = false; 183 else if (value === "NaN") value = NaN; 184 else if (!isNaN(number = +value)) value = number; 185 else if (m = value.match(/^([-+]\d{2})?\d{4}(-\d{2}(-\d{2})?)?(T\d{2}:\d{2}(:\d{2}(\.\d{3})?)?(Z|[-+]\d{2}:\d{2})?)?$/)) { 186 if (fixtz && !!m[4] && !m[7]) value = value.replace(/-/g, "/").replace(/T/, " "); 187 value = new Date(value); 188 } 189 else continue; 190 object[key] = value; 191 } 192 return object; 193} 194 195// https://github.com/d3/d3-dsv/issues/45 196const fixtz = new Date("2019-01-01T00:00").getHours() || new Date("2019-07-01T00:00").getHours(); 197 198function dependency(name, version, main) { 199 return { 200 resolve(path = main) { 201 return `${name}@${version}/${path}`; 202 } 203 }; 204} 205 206const d3 = dependency("d3", "7.6.1", "dist/d3.min.js"); 207const inputs = dependency("@observablehq/inputs", "0.10.4", "dist/inputs.min.js"); 208const plot = dependency("@observablehq/plot", "0.6.0", "dist/plot.umd.min.js"); 209const graphviz = dependency("@observablehq/graphviz", "0.2.1", "dist/graphviz.min.js"); 210const highlight = dependency("@observablehq/highlight.js", "2.0.0", "highlight.min.js"); 211const katex = dependency("@observablehq/katex", "0.11.1", "dist/katex.min.js"); 212const lodash = dependency("lodash", "4.17.21", "lodash.min.js"); 213const htl = dependency("htl", "0.3.1", "dist/htl.min.js"); 214const jszip = dependency("jszip", "3.10.0", "dist/jszip.min.js"); 215const marked = dependency("marked", "0.3.12", "marked.min.js"); 216const sql = dependency("sql.js", "1.7.0", "dist/sql-wasm.js"); 217const vega = dependency("vega", "5.22.1", "build/vega.min.js"); 218const vegalite = dependency("vega-lite", "5.5.0", "build/vega-lite.min.js"); 219const vegaliteApi = dependency("vega-lite-api", "5.0.0", "build/vega-lite-api.min.js"); 220const arrow4 = dependency("apache-arrow", "4.0.1", "Arrow.es2015.min.js"); 221const arrow9 = dependency("apache-arrow", "9.0.0", "+esm"); 222const arquero = dependency("arquero", "4.8.8", "dist/arquero.min.js"); 223const topojson = dependency("topojson-client", "3.1.0", "dist/topojson-client.min.js"); 224const exceljs = dependency("exceljs", "4.3.0", "dist/exceljs.min.js"); 225const mermaid$1 = dependency("mermaid", "9.1.6", "dist/mermaid.min.js"); 226const leaflet$1 = dependency("leaflet", "1.8.0", "dist/leaflet.js"); 227const duckdb = dependency("@duckdb/duckdb-wasm", "1.17.0", "+esm"); 228 229const metas = new Map; 230const queue$1 = []; 231const map$2 = queue$1.map; 232const some = queue$1.some; 233const hasOwnProperty$2 = queue$1.hasOwnProperty; 234const identifierRe = /^((?:@[^/@]+\/)?[^/@]+)(?:@([^/]+))?(?:\/(.*))?$/; 235const versionRe = /^\d+\.\d+\.\d+(-[\w-.+]+)?$/; 236const extensionRe = /(?:\.[^/]*|\/)$/; 237 238class RequireError extends Error { 239 constructor(message) { 240 super(message); 241 } 242} 243 244RequireError.prototype.name = RequireError.name; 245 246function parseIdentifier(identifier) { 247 const match = identifierRe.exec(identifier); 248 return match && { 249 name: match[1], 250 version: match[2], 251 path: match[3] 252 }; 253} 254 255function resolveFrom(origin = "https://cdn.jsdelivr.net/npm/", mains = ["unpkg", "jsdelivr", "browser", "main"]) { 256 if (!/\/$/.test(origin)) throw new Error("origin lacks trailing slash"); 257 258 function main(meta) { 259 for (const key of mains) { 260 let value = meta[key]; 261 if (typeof value === "string") { 262 if (value.startsWith("./")) value = value.slice(2); 263 return extensionRe.test(value) ? value : `${value}.js`; 264 } 265 } 266 } 267 268 function resolveMeta(target) { 269 const url = `${origin}${target.name}${target.version ? `@${target.version}` : ""}/package.json`; 270 let meta = metas.get(url); 271 if (!meta) metas.set(url, meta = fetch(url).then(response => { 272 if (!response.ok) throw new RequireError("unable to load package.json"); 273 if (response.redirected && !metas.has(response.url)) metas.set(response.url, meta); 274 return response.json(); 275 })); 276 return meta; 277 } 278 279 return async function resolve(name, base) { 280 if (name.startsWith(origin)) name = name.substring(origin.length); 281 if (/^(\w+:)|\/\//i.test(name)) return name; 282 if (/^[.]{0,2}\//i.test(name)) return new URL(name, base == null ? location : base).href; 283 if (!name.length || /^[\s._]/.test(name) || /\s$/.test(name)) throw new RequireError("illegal name"); 284 const target = parseIdentifier(name); 285 if (!target) return `${origin}${name}`; 286 if (!target.version && base != null && base.startsWith(origin)) { 287 const meta = await resolveMeta(parseIdentifier(base.substring(origin.length))); 288 target.version = meta.dependencies && meta.dependencies[target.name] || meta.peerDepen
288dencies && meta.peerDependencies[target.name]; 289 } 290 if (target.path && !extensionRe.test(target.path)) target.path += ".js"; 291 if (target.path && target.version && versionRe.test(target.version)) return `${origin}${target.name}@${target.version}/${target.path}`; 292 const meta = await resolveMeta(target); 293 return `${origin}${meta.name}@${meta.version}/${target.path || main(meta) || "index.js"}`; 294 }; 295} 296 297var require = requireFrom(resolveFrom()); 298let requestsInFlight = 0; 299let prevDefine = undefined; 300 301function requireFrom(resolver) { 302 const cache = new Map; 303 const requireBase = requireRelative(null); 304 305 function requireAbsolute(url) { 306 if (typeof url !== "string") return url; 307 let module = cache.get(url); 308 if (!module) cache.set(url, module = new Promise((resolve, reject) => { 309 const script = document.createElement("script"); 310 script.onload = () => { 311 try { resolve(queue$1.pop()(requireRelative(url))); } 312 catch (error) { reject(new RequireError("invalid module")); } 313 script.remove(); 314 requestsInFlight--; 315 if (requestsInFlight === 0) { 316 window.define = prevDefine; 317 } 318 }; 319 script.onerror = () => { 320 reject(new RequireError("unable to load module")); 321 script.remove(); 322 requestsInFlight--; 323 if (requestsInFlight === 0) { 324 window.define = prevDefine; 325 } 326 }; 327 script.async = true; 328 script.src = url; 329 if (requestsInFlight === 0) { 330 prevDefine = window.define; 331 window.define = define; 332 } 333 requestsInFlight++; 334 335 document.head.appendChild(script); 336 })); 337 return module; 338 } 339 340 function requireRelative(base) { 341 return name => Promise.resolve(resolver(name, base)).then(requireAbsolute); 342 } 343 344 function requireAlias(aliases) { 345 return requireFrom((name, base) => { 346 if (name in aliases) { 347 name = aliases[name], base = null; 348 if (typeof name !== "string") return name; 349 } 350 return resolver(name, base); 351 }); 352 } 353 354 function require(name) { 355 return arguments.length > 1 356 ? Promise.all(map$2.call(arguments, requireBase)).then(merge) 357 : requireBase(name); 358 } 359 360 require.alias = requireAlias; 361 require.resolve = resolver; 362 363 return require; 364} 365 366function merge(modules) { 367 const o = {}; 368 for (const m of modules) { 369 for (const k in m) { 370 if (hasOwnProperty$2.call(m, k)) { 371 if (m[k] == null) Object.defineProperty(o, k, {get: getter(m, k)}); 372 else o[k] = m[k]; 373 } 374 } 375 } 376 return o; 377} 378 379function getter(object, name) { 380 return () => object[name]; 381} 382 383function isbuiltin(name) { 384 name = name + ""; 385 return name === "exports" || name === "module"; 386} 387 388function define(name, dependencies, factory) { 389 const n = arguments.length; 390 if (n < 2) factory = name, dependencies = []; 391 else if (n < 3) factory = dependencies, dependencies = typeof name === "string" ? [] : name; 392 queue$1.push(some.call(dependencies, isbuiltin) ? require => { 393 const exports = {}; 394 const module = {exports}; 395 return Promise.all(map$2.call(dependencies, name => { 396 name = name + ""; 397 return name === "exports" ? exports : name === "module" ? module : require(name); 398 })).then(dependencies => { 399 factory.apply(null, dependencies); 400 return module.exports; 401 }); 402 } : require => { 403 return Promise.all(map$2.call(dependencies, require)).then(dependencies => { 404 return typeof factory === "function" ? factory.apply(null, dependencies) : factory; 405 }); 406 }); 407} 408 409define.amd = {}; 410 411// TODO Allow this to be overridden using the Libraryâs resolver. 412const cdn = "https://cdn.observableusercontent.com/npm/"; 413 414let requireDefault = require; 415 416function setDefaultRequire(require) { 417 requireDefault = require; 418} 419 420function requirer(resolver) { 421 return resolver == null ? requireDefault : requireFrom(resolver); 422} 423 424function fromEntries(obj) { 425 const result = {}; 426 for (const [key, value] of obj) { 427 result[key] = value; 428 } 429 return result; 430} 431 432async function SQLite(require) { 433 const [init, dist] = await Promise.all([require(sql.resolve()), require.resolve(sql.resolve("dist/"))]); 434 return init({locateFile: file => `${dist}${file}`}); 435} 436 437class SQLiteDatabaseClient { 438 constructor(db) { 439 Object.defineProperties(this, { 440 _db: {value: db} 441 }); 442 } 443 static async open(source) { 444 const [SQL, buffer] = await Promise.all([SQLite(requireDefault), Promise.resolve(source).then(load$1)]); 445 return new SQLiteDatabaseClient(new SQL.Database(buffer)); 446 } 447 async query(query, params) { 448 return await exec(this._db, query, params); 449 } 450 async queryRow(query, params) { 451 return (await this.query(query, params))[0] || null; 452 } 453 async explain(query, params) { 454 const rows = await this.query(`EXPLAIN QUERY PLAN ${query}`, params); 455 return element$1("pre", {className: "observablehq--inspect"}, [ 456 text$2(rows.map(row => row.detail).join("\n")) 457 ]); 458 }
459 async describeTables({schema} = {}) { 460 return this.query(`SELECT NULLIF(schema, 'main') AS schema, name FROM pragma_table_list() WHERE type = 'table'${schema == null ? "" : ` AND schema = ?`} AND name NOT LIKE 'sqlite_%'`, schema == null ? [] : [schema]); 461 } 462 async describeColumns({schema, table} = {}) { 463 if (table == null) throw new Error(`missing table`); 464 const rows = await this.query(`SELECT name, type, "notnull" FROM pragma_table_info(?${schema == null ? "" : `, ?`}) ORDER BY cid`, schema == null ? [table] : [table, schema]); 465 if (!rows.length) throw new Error(`table not found: ${table}`); 466 return rows.map(({name, type, notnull}) => ({name, type: sqliteType(type), databaseType: type, nullable: !notnull})); 467 } 468 async describe(object) { 469 const rows = await (object === undefined 470 ? this.query(`SELECT name FROM sqlite_master WHERE type = 'table'`) 471 : this.query(`SELECT * FROM pragma_table_info(?)`, [object])); 472 if (!rows.length) throw new Error("Not found"); 473 const {columns} = rows; 474 return element$1("table", {value: rows}, [ 475 element$1("thead", [element$1("tr", columns.map(c => element$1("th", [text$2(c)])))]), 476 element$1("tbody", rows.map(r => element$1("tr", columns.map(c => element$1("td", [text$2(r[c])]))))) 477 ]); 478 } 479 async sql() { 480 return this.query(...this.queryTag.apply(this, arguments)); 481 } 482 queryTag(strings, ...params) { 483 return [strings.join("?"), params]; 484 } 485} 486 487Object.defineProperty(SQLiteDatabaseClient.prototype, "dialect", { 488 value: "sqlite" 489}); 490 491// https://www.sqlite.org/datatype3.html 492function sqliteType(type) { 493 switch (type) { 494 case "NULL": 495 return "null"; 496 case "INT": 497 case "INTEGER": 498 case "TINYINT": 499 case "SMALLINT": 500 case "MEDIUMINT": 501 case "BIGINT": 502 case "UNSIGNED BIG INT": 503 case "INT2": 504 case "INT8": 505 return "integer"; 506 case "TEXT": 507 case "CLOB": 508 return "string"; 509 case "REAL": 510 case "DOUBLE": 511 case "DOUBLE PRECISION": 512 case "FLOAT": 513 case "NUMERIC": 514 return "number"; 515 case "BLOB": 516 return "buffer"; 517 case "DATE": 518 case "DATETIME": 519 return "string"; // TODO convert strings to Date instances in sql.js 520 default: 521 return /^(?:(?:(?:VARYING|NATIVE) )?CHARACTER|(?:N|VAR|NVAR)CHAR)\(/.test(type) ? "string" 522 : /^(?:DECIMAL|NUMERIC)\(/.test(type) ? "number" 523 : "other"; 524 } 525} 526 527function load$1(source) { 528 return typeof source === "string" ? fetch(source).then(load$1) 529 : source instanceof Response || source instanceof Blob ? source.arrayBuffer().then(load$1) 530 : source instanceof ArrayBuffer ? new Uint8Array(source) 531 : source; 532} 533 534async function exec(db, query, params) { 535 const [result] = await db.exec(query, params); 536 if (!result) return []; 537 const {columns, values} = result; 538 const rows = values.map(row => fromEntries(row.map((value, i) => [columns[i], value]))); 539 rows.columns = columns; 540 return rows; 541} 542 543function element$1(name, props, children) { 544 if (arguments.length === 2) children = props, props = undefined; 545 const element = document.createElement(name); 546 if (props !== undefined) for (const p in props) element[p] = props[p]; 547 if (children !== undefined) for (const c of children) element.appendChild(c); 548 return element; 549} 550 551function text$2(value) { 552 return document.createTextNode(value); 553} 554 555class Workbook { 556 constructor(workbook) { 557 Object.defineProperties(this, { 558 _: {value: workbook}, 559 sheetNames: { 560 value: workbook.worksheets.map((s) => s.name), 561 enumerable: true 562 } 563 }); 564 } 565 sheet(name, options) { 566 const sname = 567 typeof name === "number" 568 ? this.sheetNames[name] 569 : this.sheetNames.includes((name += "")) 570 ? name 571 : null; 572 if (sname == null) throw new Error(`Sheet not found: ${name}`); 573 const sheet = this._.getWorksheet(sname); 574 return extract(sheet, options); 575 } 576} 577 578function extract(sheet, {range, headers} = {}) { 579 let [[c0, r0], [c1, r1]] = parseRange(range, sheet); 580 const headerRow = headers ? sheet._rows[r0++] : null; 581 let names = new Set(["#"]); 582 for (let n = c0; n <= c1; n++) { 583 const value = headerRow ? valueOf(headerRow.findCell(n + 1)) : null; 584 let name = (value && value + "") || toColumn(n); 585 while (names.has(name)) name += "_"; 586 names.add(name); 587 }
588 names = new Array(c0).concat(Array.from(names)); 589 590 const output = new Array(r1 - r0 + 1); 591 for (let r = r0; r <= r1; r++) { 592 const row = (output[r - r0] = Object.create(null, {"#": {value: r + 1}})); 593 const _row = sheet.getRow(r + 1); 594 if (_row.hasValues) 595 for (let c = c0; c <= c1; c++) { 596 const value = valueOf(_row.findCell(c + 1)); 597 if (value != null) row[names[c + 1]] = value; 598 } 599 } 600 601 output.columns = names.filter(() => true); // Filter sparse columns 602 return output; 603} 604 605function valueOf(cell) { 606 if (!cell) return; 607 const {value} = cell; 608 if (value && typeof value === "object" && !(value instanceof Date)) { 609 if (value.formula || value.sharedFormula) { 610 return value.result && value.result.error ? NaN : value.result; 611 } 612 if (value.richText) { 613 return richText(value); 614 } 615 if (value.text) { 616 let {text} = value; 617 if (text.richText) text = richText(text); 618 return value.hyperlink && value.hyperlink !== text 619 ? `${value.hyperlink} ${text}` 620 : text; 621 } 622 return value; 623 } 624 return value; 625} 626 627function richText(value) { 628 return value.richText.map((d) => d.text).join(""); 629} 630 631function parseRange(specifier = ":", {columnCount, rowCount}) { 632 specifier += ""; 633 if (!specifier.match(/^[A-Z]*\d*:[A-Z]*\d*$/)) 634 throw new Error("Malformed range specifier"); 635 const [[c0 = 0, r0 = 0], [c1 = columnCount - 1, r1 = rowCount - 1]] = 636 specifier.split(":").map(fromCellReference); 637 return [ 638 [c0, r0], 639 [c1, r1] 640 ]; 641} 642 643// Returns the default column name for a zero-based column index. 644// For example: 0 -> "A", 1 -> "B", 25 -> "Z", 26 -> "AA", 27 -> "AB". 645function toColumn(c) { 646 let sc = ""; 647 c++; 648 do { 649 sc = String.fromCharCode(64 + (c % 26 || 26)) + sc; 650 } while ((c = Math.floor((c - 1) / 26))); 651 return sc; 652} 653 654// Returns the zero-based indexes from a cell reference. 655// For example: "A1" -> [0, 0], "B2" -> [1, 1], "AA10" -> [26, 9]. 656function fromCellReference(s) {
657 const [, sc, sr] = s.match(/^([A-Z]*)(\d*)$/); 658 let c = 0; 659 if (sc) 660 for (let i = 0; i < sc.length; i++) 661 c += Math.pow(26, sc.length - i - 1) * (sc.charCodeAt(i) - 64); 662 return [c ? c - 1 : undefined, sr ? +sr - 1 : undefined]; 663} 664 665async function remote_fetch(file) { 666 const response = await fetch(await file.url()); 667 if (!response.ok) throw new Error(`Unable to load file: ${file.name}`); 668 return response; 669} 670 671async function dsv(file, delimiter, {array = false, typed = false} = {}) { 672 const text = await file.text(); 673 return (delimiter === "\t" 674 ? (array ? tsvParseRows : tsvParse) 675 : (array ? csvParseRows : csvParse))(text, typed && autoType); 676} 677 678class AbstractFile { 679 constructor(name, mimeType) { 680 Object.defineProperty(this, "name", {value: name, enumerable: true}); 681 if (mimeType !== undefined) Object.defineProperty(this, "mimeType", {value: mimeType + "", enumerable: true}); 682 } 683 async blob() { 684 return (await remote_fetch(this)).blob(); 685 } 686 async arrayBuffer() { 687 return (await remote_fetch(this)).arrayBuffer(); 688 } 689 async text() { 690 return (await remote_fetch(this)).text(); 691 } 692 async json() { 693 return (await remote_fetch(this)).json(); 694 } 695 async stream() { 696 return (await remote_fetch(this)).body; 697 } 698 async csv(options) { 699 return dsv(this, ",", options); 700 } 701 async tsv(options) { 702 return dsv(this, "\t", options); 703 } 704 async image(props) { 705 const url = await this.url(); 706 return new Promise((resolve, reject) => { 707 const i = new Image(); 708 if (new URL(url, document.baseURI).origin !== new URL(location).origin) { 709 i.crossOrigin = "anonymous"; 710 } 711 Object.assign(i, props); 712 i.onload = () => resolve(i); 713 i.onerror = () => reject(new Error(`Unable to load file: ${this.name}`)); 714 i.src = url; 715 }); 716 } 717 async arrow({version = 4} = {}) { 718 switch (version) { 719 case 4: { 720 const [Arrow, response] = await Promise.all([requireDefault(arrow4.resolve()), remote_fetch(this)]); 721 return Arrow.Table.from(response); 722 } 723 case 9: { 724 const [Arrow, response] = await Promise.all([import(`${cdn}${arrow9.resolve()}`), remote_fetch(this)]); 725 return Arrow.tableFromIPC(response); 726 } 727 default: throw new Error(`unsupported arrow version: ${version}`); 728 } 729 } 730 async sqlite() { 731 return SQLiteDatabaseClient.open(remote_fetch(this)); 732 } 733 async zip() { 734 const [JSZip, buffer] = await Promise.all([requireDefault(jszip.resolve()), this.arrayBuffer()]); 735 return new ZipArchive(await JSZip.loadAsync(buffer)); 736 } 737 async xml(mimeType = "application/xml") { 738 return (new DOMParser).parseFromString(await this.text(), mimeType); 739 } 740 async html() { 741 return this.xml("text/html"); 742 } 743 async xlsx() { 744 const [ExcelJS, buffer] = await Promise.all([requireDefault(exceljs.resolve()), this.arrayBuffer()]); 745 return new Workbook(await new ExcelJS.Workbook().xlsx.load(buffer)); 746 } 747} 748 749class FileAttachment extends AbstractFile { 750 constructor(url, name, mimeType) { 751 super(name, mimeType); 752 Object.defineProperty(this, "_url", {value: url}); 753 } 754 async url() { 755 return (await this._url) + ""; 756 } 757} 758 759function NoFileAttachments(name) { 760 throw new Error(`File not found: ${name}`); 761} 762 763function FileAttachments(resolve) { 764 return Object.assign( 765 name => { 766 const result = resolve(name += ""); 767 if (result == null) throw new Error(`File not found: ${name}`); 768 if (typeof result === "object" && "url" in result) { 769 const {url, mimeType} = result; 770 return new FileAttachment(url, name, mimeType); 771 } 772 return new FileAttachment(result, name); 773 }, 774 {prototype: FileAttachment.prototype} // instanceof 775 ); 776} 777 778class ZipArchive { 779 constructor(archive) { 780 Object.defineProperty(this, "_", {value: archive}); 781 this.filenames = Object.keys(archive.files).filter(name => !archive.files[name].dir); 782 } 783 file(path) { 784 const object = this._.file(path += ""); 785 if (!object || object.dir) throw new Error(`file not found: ${path}`); 786 return new ZipArchiveEntry(object); 787 } 788} 789 790class ZipArchiveEntry extends AbstractFile { 791 constructor(object) { 792 super(object.name);
793 Object.defineProperty(this, "_", {value: object}); 794 Object.defineProperty(this, "_url", {writable: true}); 795 } 796 async url() { 797 return this._url || (this._url = this.blob().then(URL.createObjectURL)); 798 } 799 async blob() { 800 return this._.async("blob"); 801 } 802 async arrayBuffer() { 803 return this._.async("arraybuffer"); 804 } 805 async text() { 806 return this._.async("text"); 807 } 808 async json() { 809 return JSON.parse(await this.text()); 810 } 811} 812 813function canvas(width, height) { 814 var canvas = document.createElement("canvas"); 815 canvas.width = width; 816 canvas.height = height; 817 return canvas; 818} 819 820function context2d(width, height, dpi) { 821 if (dpi == null) dpi = devicePixelRatio; 822 var canvas = document.createElement("canvas"); 823 canvas.width = width * dpi; 824 canvas.height = height * dpi; 825 canvas.style.width = width + "px"; 826 var context = canvas.getContext("2d"); 827 context.scale(dpi, dpi); 828 return context; 829} 830 831function download(value, name = "untitled", label = "Save") { 832 const a = document.createElement("a"); 833 const b = a.appendChild(document.createElement("button")); 834 b.textContent = label;
835 a.download = name; 836 837 async function reset() { 838 await new Promise(requestAnimationFrame); 839 URL.revokeObjectURL(a.href); 840 a.removeAttribute("href"); 841 b.textContent = label; 842 b.disabled = false; 843 } 844 845 a.onclick = async event => { 846 b.disabled = true; 847 if (a.href) return reset(); // Already saved. 848 b.textContent = "Savingâ¦"; 849 try { 850 const object = await (typeof value === "function" ? value() : value); 851 b.textContent = "Download"; 852 a.href = URL.createObjectURL(object); // eslint-disable-line require-atomic-updates 853 } catch (ignore) { 854 b.textContent = label; 855 } 856 if (event.eventPhase) return reset(); // Already downloaded. 857 b.disabled = false; 858 }; 859 860 return a; 861} 862 863var namespaces = { 864 math: "http://www.w3.org/1998/Math/MathML", 865 svg: "http://www.w3.org/2000/svg", 866 xhtml: "http://www.w3.org/1999/xhtml", 867 xlink: "http://www.w3.org/1999/xlink", 868 xml: "http://www.w3.org/XML/1998/namespace", 869 xmlns: "http://www.w3.org/2000/xmlns/" 870}; 871 872function element(name, attributes) { 873 var prefix = name += "", i = prefix.indexOf(":"), value; 874 if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1); 875 var element = namespaces.hasOwnProperty(prefix) // eslint-disable-line no-prototype-builtins 876 ? document.createElementNS(namespaces[prefix], name) 877 : document.createElement(name); 878 if (attributes) for (var key in attributes) { 879 prefix = key, i = prefix.indexOf(":"), value = attributes[key]; 880 if (i >= 0 && (prefix = key.slice(0, i)) !== "xmlns") key = key.slice(i + 1); 881 if (namespaces.hasOwnProperty(prefix)) element.setAttributeNS(namespaces[prefix], key, value); // eslint-disable-line no-prototype-builtins 882 else element.setAttribute(key, value); 883 } 884 return element; 885} 886 887function input$1(type) { 888 var input = document.createElement("input"); 889 if (type != null) input.type = type; 890 return input; 891} 892 893function range$1(min, max, step) { 894 if (arguments.length === 1) max = min, min = null; 895 var input = document.createElement("input"); 896 input.min = min = min == null ? 0 : +min; 897 input.max = max = max == null ? 1 : +max; 898 input.step = step == null ? "any" : step = +step; 899 input.type = "range"; 900 return input; 901} 902 903function select(values) { 904 var select = document.createElement("select"); 905 Array.prototype.forEach.call(values, function(value) { 906 var option = document.createElement("option"); 907 option.value = option.textContent = value; 908 select.appendChild(option); 909 }); 910 return select; 911} 912 913function svg$1(width, height) { 914 var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); 915 svg.setAttribute("viewBox", [0, 0, width, height]); 916 svg.setAttribute("width", width); 917 svg.setAttribute("height", height); 918 return svg; 919} 920 921function text$1(value) { 922 return document.createTextNode(value); 923} 924 925var count$1 = 0; 926 927function uid(name) { 928 return new Id("O-" + (name == null ? "" : name + "-") + ++count$1); 929} 930 931function Id(id) { 932 this.id = id; 933 this.href = new URL(`#${id}`, location) + ""; 934} 935 936Id.prototype.toString = function() { 937 return "url(" + this.href + ")"; 938}; 939 940var DOM = /*#__PURE__*/Object.freeze({ 941__proto__: null, 942canvas: canvas, 943context2d: context2d, 944download: download, 945element: element, 946input: input$1, 947range: range$1, 948select: select, 949svg: svg$1, 950text: text$1, 951uid: uid 952}); 953 954function buffer(file) { 955 return new Promise(function(resolve, reject) { 956 var reader = new FileReader; 957 reader.onload = function() { resolve(reader.result); }; 958 reader.onerror = reject; 959 reader.readAsArrayBuffer(file); 960 }); 961} 962 963function text(file) { 964 return new Promise(function(resolve, reject) { 965 var reader = new FileReader; 966 reader.onload = function() { resolve(reader.result); }; 967 reader.onerror = reject; 968 reader.readAsText(file); 969 }); 970} 971 972function url(file) { 973 return new Promise(function(resolve, reject) { 974 var reader = new FileReader; 975 reader.onload = function() { resolve(reader.result); }; 976 reader.onerror = reject; 977 reader.readAsDataURL(file); 978 }); 979} 980 981var Files = /*#__PURE__*/Object.freeze({ 982__proto__: null, 983buffer: buffer, 984text: text, 985url: url 986}); 987 988function that() { 989 return this; 990} 991 992function disposable(value, dispose) { 993 let done = false;
994 if (typeof dispose !== "function") { 995 throw new Error("dispose is not a function"); 996 } 997 return { 998 [Symbol.iterator]: that, 999 next: () => done ? {done: true} : (done = true, {done: false, value}), 1000 return: () => (done = true, dispose(value), {done: true}), 1001 throw: () => ({done: done = true}) 1002 }; 1003} 1004 1005function* filter(iterator, test) { 1006 var result, index = -1; 1007 while (!(result = iterator.next()).done) { 1008 if (test(result.value, ++index)) { 1009 yield result.value; 1010 } 1011 } 1012} 1013 1014function observe(initialize) { 1015 let stale = false; 1016 let value; 1017 let resolve; 1018 const dispose = initialize(change); 1019 1020 if (dispose != null && typeof dispose !== "function") { 1021 throw new Error(typeof dispose.then === "function" 1022 ? "async initializers are not supported" 1023 : "initializer returned something, but not a dispose function"); 1024 } 1025 1026 function change(x) { 1027 if (resolve) resolve(x), resolve = null; 1028 else stale = true; 1029 return value = x; 1030 } 1031 1032 function next() { 1033 return {done: false, value: stale 1034 ? (stale = false, Promise.resolve(value)) 1035 : new Promise(_ => (resolve = _))}; 1036 } 1037 1038 return { 1039 [Symbol.iterator]: that, 1040 throw: () => ({done: true}), 1041 return: () => (dispose != null && dispose(), {done: true}), 1042 next 1043 }; 1044} 1045 1046function input(input) { 1047 return observe(function(change) { 1048 var event = eventof(input), value = valueof$1(input); 1049 function inputted() { change(valueof$1(input)); } 1050 input.addEventListener(event, inputted); 1051 if (value !== undefined) change(value); 1052 return function() { input.removeEventListener(event, inputted); }; 1053 }); 1054} 1055 1056function valueof$1(input) { 1057 switch (input.type) { 1058 case "range": 1059 case "number": return input.valueAsNumber; 1060 case "date": return input.valueAsDate; 1061 case "checkbox": return input.checked; 1062 case "file": return input.multiple ? input.files : input.files[0]; 1063 case "select-multiple": return Array.from(input.selectedOptions, o => o.value); 1064 default: return input.value; 1065 } 1066} 1067 1068function eventof(input) { 1069 switch (input.type) { 1070 case "button": 1071 case "submit": 1072 case "checkbox": return "click"; 1073 case "file": return "change"; 1074 default: return "input"; 1075 } 1076} 1077 1078function* map$1(iterator, transform) { 1079 var result, index = -1; 1080 while (!(result = iterator.next()).done) { 1081 yield transform(result.value, ++index); 1082 } 1083} 1084 1085function queue(initialize) { 1086 let resolve; 1087 const queue = []; 1088 const dispose = initialize(push); 1089 1090 if (dispose != null && typeof dispose !== "function") { 1091 throw new Error(typeof dispose.then === "function" 1092 ? "async initializers are not supported" 1093 : "initializer returned something, but not a dispose function"); 1094 } 1095 1096 function push(x) { 1097 queue.push(x); 1098 if (resolve) resolve(queue.shift()), resolve = null; 1099 return x; 1100 } 1101 1102 function next() { 1103 return {done: false, value: queue.length 1104 ? Promise.resolve(queue.shift()) 1105 : new Promise(_ => (resolve = _))}; 1106 } 1107 1108 return { 1109 [Symbol.iterator]: that, 1110 throw: () => ({done: true}), 1111 return: () => (dispose != null && dispose(), {done: true}), 1112 next 1113 }; 1114} 1115 1116function* range(start, stop, step) { 1117 start = +start; 1118 stop = +stop; 1119 step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step; 1120 var i = -1, n = Math.max(0, Math.ceil((stop - start) / step)) | 0; 1121 while (++i < n) { 1122 yield start + i * step; 1123 } 1124} 1125 1126function valueAt(iterator, i) { 1127 if (!isFinite(i = +i) || i < 0 || i !== i | 0) return; 1128 var result, index = -1; 1129 while (!(result = iterator.next()).done) { 1130 if (++index === i) { 1131 return result.value; 1132 } 1133 } 1134} 1135 1136function worker(source) { 1137 const url = URL.createObjectURL(new Blob([source], {type: "text/javascript"})); 1138 const worker = new Worker(url);
1139 return disposable(worker, () => { 1140 worker.terminate(); 1141 URL.revokeObjectURL(url); 1142 }); 1143} 1144 1145var Generators$1 = /*#__PURE__*/Object.freeze({ 1146__proto__: null, 1147disposable: disposable, 1148filter: filter, 1149input: input, 1150map: map$1, 1151observe: observe, 1152queue: queue, 1153range: range, 1154valueAt: valueAt, 1155worker: worker 1156}); 1157 1158// Returns true if the vaue is an Apache Arrow table. This uses a âduckâ test 1159// (instead of strict instanceof) because we want it to work with a range of 1160// Apache Arrow versions at least 7.0.0 or above. 1161// https://arrow.apache.org/docs/7.0/js/classes/Arrow_dom.Table.html 1162function isArrowTable(value) { 1163 return ( 1164 value && 1165 typeof value.getChild === "function" && 1166 typeof value.toArray === "function" && 1167 value.schema && 1168 Array.isArray(value.schema.fields) 1169 ); 1170} 1171 1172function getArrowTableSchema(table) { 1173 return table.schema.fields.map(getArrowFieldSchema); 1174} 1175 1176function getArrowFieldSchema(field) { 1177 return { 1178 name: field.name, 1179 type: getArrowType(field.type), 1180 nullable: field.nullable, 1181 databaseType: String(field.type) 1182 }; 1183} 1184 1185// https://github.com/apache/arrow/blob/89f9a0948961f6e94f1ef5e4f310b707d22a3c11/js/src/enum.ts#L140-L141 1186function getArrowType(type) { 1187 switch (type.typeId) { 1188 case 2: // Int 1189 return "integer"; 1190 case 3: // Float 1191 case 7: // Decimal 1192 return "number"; 1193 case 4: // Binary 1194 case 15: // FixedSizeBinary 1195 return "buffer"; 1196 case 5: // Utf8 1197 return "string"; 1198 case 6: // Bool 1199 return "boolean"; 1200 case 8: // Date 1201 case 9: // Time 1202 case 10: // Timestamp 1203 return "date"; 1204 case 12: // List 1205 case 16: // FixedSizeList 1206 return "array"; 1207 case 13: // Struct 1208 case 14: // Union 1209 return "object"; 1210 case 11: // Interval 1211 case 17: // Map 1212 default: 1213 return "other"; 1214 } 1215} 1216 1217// Adapted from https://observablehq.com/@cmudig/duckdb-client 1218// Copyright 2021 CMU Data Interaction Group 1219// 1220// Redistribution and use in source and binary forms, with or without 1221// modification, are permitted provided that the following conditions are met: 1222// 1223// 1. Redistributions of source code must retain the above copyright notice, 1224// this list of conditions and the following disclaimer. 1225// 1226// 2. Redistributions in binary form must reproduce the above copyright notice, 1227// this list of conditions and the following disclaimer in the documentation 1228// and/or other materials provided with the distribution. 1229// 1230// 3. Neither the name of the copyright holder nor the names of its contributors 1231// may be used to endorse or promote products derived from this software 1232// without specific prior written permission. 1233// 1234// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 1235// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 1236// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 1237// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 1238// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 1239// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 1240// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 1241// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 1242// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 1243// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 1244// POSSIBILITY OF SUCH DAMAGE. 1245 1246class DuckDBClient { 1247 constructor(db) { 1248 Object.defineProperties(this, { 1249 _db: {value: db} 1250 }); 1251 } 1252 1253 async queryStream(query, params) { 1254 const connection = await this._db.connect(); 1255 let reader, batch; 1256 try { 1257 if (params?.length > 0) { 1258 const statement = await connection.prepare(query); 1259 reader = await statement.send(...params); 1260 } else { 1261 reader = await connection.send(query); 1262 } 1263 batch = await reader.next(); 1264 if (batch.done) throw new Error("missing first batch"); 1265 } catch (error) { 1266 await connection.close(); 1267 throw error; 1268 } 1269 return { 1270 schema: getArrowTableSchema(batch.value), 1271 async *readRows() { 1272 try { 1273 while (!batch.done) { 1274 yield batch.value.toArray(); 1275 batch = await reader.next(); 1276 } 1277 } finally { 1278 await connection.close(); 1279 } 1280 } 1281 }; 1282 } 1283 1284 async query(query, params) { 1285 const result = await this.queryStream(query, params); 1286 const results = []; 1287 for await (const rows of result.readRows()) { 1288 for (const row of rows) { 1289 results.push(row); 1290 } 1291 } 1292 results.schema = result.schema; 1293 return results; 1294 } 1295 1296 async queryRow(query, params) { 1297 const result = await this.queryStream(query, params); 1298 const reader = result.readRows(); 1299 try { 1300 const {done, value} = await reader.next(); 1301 return done || !value.length ? null : value[0]; 1302 } finally { 1303 await reader.return(); 1304 } 1305 } 1306 1307 async sql(strings, ...args) { 1308 return await this.query(strings.join("?"), args); 1309 } 1310 1311 queryTag(strings, ...params) { 1312 return [strings.join("?"), params]; 1313 } 1314 1315 escape(name) { 1316 return `"${name}"`; 1317 } 1318 1319 async describeTables() { 1320 const tables = await this.query(`SHOW TABLES`); 1321 return tables.map(({name}) => ({name})); 1322 } 1323 1324 async describeColumns({table} = {}) { 1325 const columns = await this.query(`DESCRIBE ${table}`); 1326 return columns.map(({column_name, column_type, null: nullable}) => ({ 1327 name: column_name, 1328 type: getDuckDBType(column_type), 1329 nullable: nullable !== "NO", 1330 databaseType: column_type 1331 })); 1332 } 1333 1334 static async of(sources = {}, config = {}) { 1335 const db = await createDuckDB(); 1336 if (config.query?.castTimestampToDate === undefined) { 1337 config = {...config, query: {...config.query, castTimestampToDate: true}}; 1338 } 1339 await db.open(config); 1340 await Promise.all( 1341 Object.entries(sources).map(async ([name, source]) => { 1342 if (source instanceof FileAttachment) { // bare file 1343 await insertFile(db, name, source); 1344 } else if (isArrowTable(source)) { // bare arrow table 1345 await insertArrowTable(db, name, source); 1346 } else if (Array.isArray(source)) { // bare array of objects 1347 await insertArray(db, name, source); 1348 } else if ("data" in source) { // data + options 1349 const {data, ...options} = source; 1350 if (isArrowTable(data)) { 1351 await insertArrowTable(db, name, data, options); 1352 } else { 1353 await insertArray(db, name, data, options); 1354 } 1355 } else if ("file" in source) { // file + options 1356 const {file, ...options} = source; 1357 await insertFile(db, name, file, options); 1358 } else { 1359 throw new Error(`invalid source: ${source}`); 1360 } 1361 }) 1362 ); 1363 return new DuckDBClient(db); 1364 } 1365} 1366 1367Object.defineProperty(DuckDBClient.prototype, "dialect", { 1368 value: "duckdb" 1369}); 1370 1371async function insertFile(database, name, file, options) { 1372 const url = await file.url(); 1373 if (url.startsWith("blob:")) { 1374 const buffer = await file.arrayBuffer(); 1375 await database.registerFileBuffer(file.name, new Uint8Array(buffer)); 1376 } else { 1377 await database.registerFileURL(file.name, url); 1378 } 1379 const connection = await database.connect(); 1380 try { 1381 switch (file.mimeType) { 1382 case "text/csv": 1383 return await connection.insertCSVFromPath(file.name, { 1384 name, 1385 schema: "main", 1386 ...options 1387 }); 1388 case "application/json": 1389 return await connection.insertJSONFromPath(file.name, { 1390 name, 1391 schema: "main", 1392 ...options 1393 }); 1394 default: 1395 if (/\.arrow$/i.test(file.name)) { 1396 const buffer = new Uint8Array(await file.arrayBuffer()); 1397 return await connection.insertArrowFromIPCStream(buffer, { 1398 name, 1399 schema: "main", 1400 ...options 1401 }); 1402 } 1403 if (/\.parquet$/i.test(file.name)) { 1404 return await connection.query( 1405 `CREATE VIEW '${name}' AS SELECT * FROM parquet_scan('${file.name}')` 1406 ); 1407 } 1408 throw new Error(`unknown file type: ${file.mimeType}`); 1409 } 1410 } finally { 1411 await connection.close(); 1412 } 1413} 1414 1415async function insertArrowTable(database, name, table, options) { 1416 const arrow = await loadArrow(); 1417 const buffer = arrow.tableToIPC(table); 1418 const connection = await database.connect(); 1419 try { 1420 await connection.insertArrowFromIPCStream(buffer, { 1421 name, 1422 schema: "main", 1423 ...options 1424 }); 1425 } finally { 1426 await connection.close(); 1427 } 1428} 1429 1430async function insertArray(database, name, array, options) { 1431 const arrow = await loadArrow(); 1432 const table = arrow.tableFromJSON(array); 1433 return await insertArrowTable(database, name, table, options); 1434} 1435 1436async function createDuckDB() { 1437 const duck = await import(`${cdn}
1437${duckdb.resolve()}`); 1438 const bundle = await duck.selectBundle({ 1439 mvp: { 1440 mainModule: `${cdn}${duckdb.resolve("dist/duckdb-mvp.wasm")}`, 1441 mainWorker: `${cdn}${duckdb.resolve("dist/duckdb-browser-mvp.worker.js")}` 1442 }, 1443 eh: { 1444 mainModule: `${cdn}${duckdb.resolve("dist/duckdb-eh.wasm")}`, 1445 mainWorker: `${cdn}${duckdb.resolve("dist/duckdb-browser-eh.worker.js")}` 1446 } 1447 }); 1448 const logger = new duck.ConsoleLogger(); 1449 const worker = await duck.createWorker(bundle.mainWorker); 1450 const db = new duck.AsyncDuckDB(logger, worker); 1451 await db.instantiate(bundle.mainModule); 1452 return db; 1453} 1454 1455async function loadArrow() { 1456 return await import(`${cdn}${arrow9.resolve()}`); 1457} 1458 1459// https://duckdb.org/docs/sql/data_types/overview 1460function getDuckDBType(type) { 1461 switch (type) { 1462 case "BIGINT": 1463 case "HUGEINT": 1464 case "UBIGINT": 1465 return "bigint"; 1466 case "DOUBLE": 1467 case "REAL": 1468 return "number"; 1469 case "INTEGER": 1470 case "SMALLINT": 1471 case "TINYINT": 1472 case "USMALLINT": 1473 case "UINTEGER": 1474 case "UTINYINT": 1475 return "integer"; 1476 case "BOOLEAN": 1477 return "boolean"; 1478 case "DATE": 1479 case "TIMESTAMP": 1480 case "TIMESTAMP WITH TIME ZONE": 1481 return "date"; 1482 case "VARCHAR": 1483 case "UUID": 1484 return "string"; 1485 // case "BLOB": 1486 // case "INTERVAL": 1487 // case "TIME": 1488 default: 1489 if (/^DECIMAL\(/.test(type)) return "integer"; 1490 return "other"; 1491 } 1492} 1493 1494function template(render, wrapper) { 1495 return function(strings) { 1496 var string = strings[0], 1497 parts = [], part, 1498 root = null, 1499 node, nodes, 1500 walker, 1501 i, n, j, m, k = -1; 1502 1503 // Concatenate the text using comments as placeholders. 1504 for (i = 1, n = arguments.length; i < n; ++i) { 1505 part = arguments[i]; 1506 if (part instanceof Node) { 1507 parts[++k] = part; 1508 string += "<!--o:" + k + "-->"; 1509 } else if (Array.isArray(part)) { 1510 for (j = 0, m = part.length; j < m; ++j) { 1511 node = part[j]; 1512 if (node instanceof Node) { 1513 if (root === null) { 1514 parts[++k] = root = document.createDocumentFragment(); 1515 string += "<!--o:" + k + "-->"; 1516 } 1517 root.appendChild(node); 1518 } else { 1519 root = null; 1520 string += node; 1521 } 1522 } 1523 root = null; 1524 } else { 1525 string += part; 1526 } 1527 string += strings[i]; 1528 } 1529 1530 // Render the text. 1531 root = render(string); 1532 1533 // Walk the rendered content to replace comment placeholders. 1534 if (++k > 0) { 1535 nodes = new Array(k); 1536 walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT, null, false); 1537 while (walker.nextNode()) { 1538 node = walker.currentNode; 1539 if (/^o:/.test(node.nodeValue)) { 1540 nodes[+node.nodeValue.slice(2)] = node; 1541 } 1542 } 1543 for (i = 0; i < k; ++i) { 1544 if (node = nodes[i]) { 1545 node.parentNode.replaceChild(parts[i], node); 1546 } 1547 } 1548 } 1549 1550 // Is the rendered content 1551 // ⦠a parent of a single child? Detach and return the child. 1552 // ⦠a document fragment? Replace the fragment with an element. 1553 // ⦠some other node? Return it. 1554 return root.childNodes.length === 1 ? root.removeChild(root.firstChild) 1555 : root.nodeType === 11 ? ((node = wrapper()).appendChild(root), node) 1556 : root; 1557 }; 1558} 1559 1560const html$1 = template(function(string) { 1561 var template = document.createElement("template"); 1562 template.innerHTML = string.trim(); 1563 return document.importNode(template.content, true); 1564}, function() { 1565 return document.createElement("span"); 1566}); 1567 1568async function leaflet(require) { 1569 const L = await require(leaflet$1.resolve()); 1570 if (!L._style) { 1571 const link = document.createElement("link"); 1572 link.rel = "stylesheet"; 1573 link.href = await require.resolve(leaflet$1.resolve("dist/leaflet.css")); 1574 L._style = document.head.appendChild(link); 1575 } 1576 return L; 1577} 1578 1579function md(require) { 1580 return require(marked.resolve()).then(function(marked) { 1581 return template( 1582 function(string) { 1583 var root = document.createElement("div"); 1584 root.innerHTML = marked(string, {langPrefix: ""}).trim(); 1585 var code = root.querySelectorAll("pre code[class]"); 1586 if (code.length > 0) { 1587 require(highlight.resolve()).then(function(hl) { 1588 code.forEach(function(block) { 1589 function done() { 1590 hl.highlightBlock(block); 1591 block.parentNode.classList.add("observablehq--md-pre"); 1592 } 1593 if (hl.getLanguage(block.className)) { 1594 done(); 1595 } else { 1596 require(highlight.resolve("async-languages/index.js")) 1597 .then(index => { 1598 if (index.has(block.className)) { 1599 return require(highlight.resolve("async-languages/" + index.get(block.className))).then(language => { 1600 hl.registerLanguage(block.className, language); 1601 }); 1602 } 1603 }) 1604 .then(done, done); 1605 } 1606 }); 1607 }); 1608 } 1609 return root; 1610 }, 1611 function() { 1612 return document.createElement("div"); 1613 } 1614 ); 1615 }); 1616} 1617 1618async function mermaid(require) { 1619 const mer = await require(mermaid$1.resolve()); 1620 mer.initialize({securityLevel: "loose", theme: "neutral"}); 1621 return function mermaid() { 1622 const root = document.createElement("div"); 1623 root.innerHTML = mer.render(uid().id, String.raw.apply(String, arguments)); 1624 return root.removeChild(root.firstChild); 1625 }; 1626} 1627 1628function Mutable(value) { 1629 let change; 1630 Object.defineProperties(this, { 1631 generator: {value: observe(_ => void (change = _))}, 1632 value: {get: () => value, set: x => change(value = x)} // eslint-disable-line no-setter-return 1633 }); 1634 if (value !== undefined) change(value); 1635} 1636 1637function* now() { 1638 while (true) { 1639 yield Date.now(); 1640 } 1641} 1642 1643function delay(duration, value) { 1644 return new Promise(function(resolve) { 1645 setTimeout(function() { 1646 resolve(value); 1647 }, duration); 1648 }); 1649} 1650 1651var timeouts = new Map; 1652 1653function timeout(now, time) { 1654 var t = new Promise(function(resolve) { 1655 timeouts.delete(time);
1656 var delay = time - now; 1657 if (!(delay > 0)) throw new Error("invalid time"); 1658 if (delay > 0x7fffffff) throw new Error("too long to wait"); 1659 setTimeout(resolve, delay); 1660 }); 1661 timeouts.set(time, t); 1662 return t; 1663} 1664 1665function when(time, value) { 1666 var now; 1667 return (now = timeouts.get(time = +time)) ? now.then(() => value) 1668 : (now = Date.now()) >= time ? Promise.resolve(value) 1669 : timeout(now, time).then(() => value); 1670} 1671 1672function tick(duration, value) { 1673 return when(Math.ceil((Date.now() + 1) / duration) * duration, value); 1674} 1675 1676var Promises = /*#__PURE__*/Object.freeze({ 1677__proto__: null, 1678delay: delay, 1679tick: tick, 1680when: when 1681}); 1682 1683function resolve(name, base) { 1684 if (/^(\w+:)|\/\//i.test(name)) return name; 1685 if (/^[.]{0,2}\//i.test(name)) return new URL(name, base == null ? location : base).href; 1686 if (!name.length || /^[\s._]/.test(name) || /\s$/.test(name)) throw new Error("illegal name"); 1687 return "https://unpkg.com/" + name; 1688} 1689 1690const svg = template(function(string) { 1691 var root = document.createElementNS("http://www.w3.org/2000/svg", "g"); 1692 root.innerHTML = string.trim(); 1693 return root; 1694}, function() { 1695 return document.createElementNS("http://www.w3.org/2000/svg", "g"); 1696}); 1697 1698var raw = String.raw; 1699 1700function style(href) { 1701 return new Promise(function(resolve, reject) { 1702 var link = document.createElement("link"); 1703 link.rel = "stylesheet"; 1704 link.href = href; 1705 link.onerror = reject; 1706 link.onload = resolve; 1707 document.head.appendChild(link); 1708 }); 1709} 1710 1711function tex(require) { 1712 return Promise.all([ 1713 require(katex.resolve()), 1714 require.resolve(katex.resolve("dist/katex.min.css")).then(style) 1715 ]).then(function(values) { 1716 var katex = values[0], tex = renderer(); 1717 1718 function renderer(options) { 1719 return function() { 1720 var root = document.createElement("div"); 1721 katex.render(raw.apply(String, arguments), root, options); 1722 return root.removeChild(root.firstChild); 1723 }; 1724 } 1725 1726 tex.options = renderer; 1727 tex.block = renderer({displayMode: true}); 1728 return tex; 1729 }); 1730} 1731 1732async function vl(require) { 1733 const [v, vl, api] = await Promise.all([vega, vegalite, vegaliteApi].map(d => require(d.resolve()))); 1734 return api.register(v, vl); 1735} 1736 1737function width() { 1738 return observe(function(change) { 1739 var width = change(document.body.clientWidth); 1740 function resized() { 1741 var w = document.body.clientWidth; 1742 if (w !== width) change(width = w); 1743 } 1744 window.addEventListener("resize", resized); 1745 return function() { 1746 window.removeEventListener("resize", resized); 1747 }; 1748 }); 1749} 1750 1751function ascending(a, b) { 1752 return a == null || b == null ? NaN : a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; 1753} 1754 1755function descending(a, b) { 1756 return a == null || b == null ? NaN 1757 : b < a ? -1 1758 : b > a ? 1 1759 : b >= a ? 0 1760 : NaN; 1761} 1762 1763function bisector(f) { 1764 let compare1, compare2, delta; 1765 1766 // If an accessor is specified, promote it to a comparator. In this case we 1767 // can test whether the search value is (self-) comparable. We canât do this 1768 // for a comparator (except for specific, known comparators) because we canât 1769 // tell if the comparator is symmetric, and an asymmetric comparator canât be 1770 // used to test whether a single value is comparable. 1771 if (f.length !== 2) { 1772 compare1 = ascending; 1773 compare2 = (d, x) => ascending(f(d), x); 1774 delta = (d, x) => f(d) - x; 1775 } else { 1776 compare1 = f === ascending || f === descending ? f : zero; 1777 compare2 = f; 1778 delta = f; 1779 } 1780 1781 function left(a, x, lo = 0, hi = a.length) { 1782 if (lo < hi) { 1783 if (compare1(x, x) !== 0) return hi; 1784 do { 1785 const mid = (lo + hi) >>> 1; 1786 if (compare2(a[mid], x) < 0) lo = mid + 1; 1787 else hi = mid; 1788 } while (lo < hi); 1789 } 1790 return lo; 1791 } 1792 1793 function right(a, x, lo = 0, hi = a.length) { 1794 if (lo < hi) { 1795 if (compare1(x, x) !== 0) return hi; 1796 do { 1797 const mid = (lo + hi) >>> 1; 1798 if (compare2(a[mid], x) <= 0) lo = mid + 1; 1799 else hi = mid; 1800 } while (lo < hi); 1801 } 1802 return lo; 1803 } 1804 1805 function center(a, x, lo = 0, hi = a.length) { 1806 const i = left(a, x, lo, hi - 1); 1807 return i > lo && delta(a[i - 1], x) > -delta(a[i], x) ? i - 1 : i; 1808 } 1809 1810 return {left, center, right}; 1811} 1812 1813function zero() { 1814 return 0; 1815} 1816 1817function number(x) { 1818 return x === null ? NaN : +x; 1819} 1820 1821bisector(ascending); 1822bisector(number).center; 1823 1824function reverse(values) { 1825 if (typeof values[Symbol.iterator] !== "function") throw new TypeError("values is not iterable"); 1826 return Array.from(values).reverse(); 1827} 1828 1829const nChecks = 20; // number of values to check in each array 1830 1831// We support two levels of DatabaseClient. The simplest DatabaseClient 1832// implements only the client.sql tagged template literal. More advanced 1833// DatabaseClients implement client.query and client.queryStream, which support 1834// streaming and abort, and the client.queryTag tagged template literal is used 1835// to translate the contents of a SQL cell or Table cell into the appropriate 1836// arguments for calling client.query or client.queryStream. For table cells, we
1837// additionally require client.describeColumns. The client.describeTables method 1838// is optional. 1839function isDatabaseClient(value, mode) { 1840 return ( 1841 value && 1842 (typeof value.sql === "function" || 1843 (typeof value.queryTag === "function" && 1844 (typeof value.query === "function" || 1845 typeof value.queryStream === "function"))) && 1846 (mode !== "table" || typeof value.describeColumns === "function") && 1847 value !== __query // donât match our internal helper 1848 ); 1849} 1850 1851// Returns true if the value is a typed array (for a single-column table), or if 1852// itâs an array. In the latter case, the elements of the array must be 1853// consistently typed: either plain objects or primitives or dates. 1854function isDataArray(value) { 1855 return ( 1856 (Array.isArray(value) && 1857 (isQueryResultSetSchema(value.schema) || 1858 isQueryResultSetColumns(value.columns) || 1859 arrayContainsObjects(value) || 1860 arrayContainsPrimitives(value) || 1861 arrayContainsDates(value))) || 1862 isTypedArray(value) 1863 ); 1864} 1865 1866// Given an array, checks that the given value is an array that does not contain 1867// any primitive values (at least for the first few values that we check), and 1868// that the first object contains enumerable keys (see computeSchema for how we 1869// infer the columns). We assume that the contents of the table are homogenous, 1870// but we donât currently enforce this. 1871// https://observablehq.com/@observablehq/database-client-specification#§1 1872function arrayContainsObjects(value) { 1873 const n = Math.min(nChecks, value.length); 1874 for (let i = 0; i < n; ++i) { 1875 const v = value[i]; 1876 if (v === null || typeof v !== "object") return false; 1877 } 1878 return n > 0 && objectHasEnumerableKeys(value[0]); 1879} 1880 1881// Using a for-in loop here means that we can abort after finding at least one 1882// enumerable key (whereas Object.keys would require materializing the array of 1883// all keys, which would be considerably slower if the value has many keys!). 1884// This function assumes that value is an object; see arrayContainsObjects. 1885function objectHasEnumerableKeys(value) { 1886 for (const _ in value) return true; 1887 return false; 1888} 1889 1890function isQueryResultSetSchema(schemas) { 1891 return (Array.isArray(schemas) && schemas.every((s) => s && typeof s.name === "string")); 1892} 1893 1894function isQueryResultSetColumns(columns) { 1895 return (Array.isArray(columns) && columns.every((name) => typeof name === "string")); 1896} 1897 1898// Returns true if the value represents an array of primitives (i.e., a 1899// single-column table). This should only be passed values for which 1900// isDataArray returns true. 1901function arrayIsPrimitive(value) { 1902 return ( 1903 isTypedArray(value) || 1904 arrayContainsPrimitives(value) || 1905 arrayContainsDates(value) 1906 ); 1907} 1908 1909// Given an array, checks that the first n elements are primitives (number, 1910// string, boolean, bigint) of a consistent type. 1911function arrayContainsPrimitives(value) { 1912 const n = Math.min(nChecks, value.length); 1913 if (!(n > 0)) return false; 1914 let type; 1915 let hasPrimitive = false; // ensure we encounter 1+ primitives 1916 for (let i = 0; i < n; ++i) { 1917 const v = value[i]; 1918 if (v == null) continue; // ignore null and undefined 1919 const t = typeof v; 1920 if (type === undefined) { 1921 switch (t) { 1922 case "number": 1923 case "boolean": 1924 case "string": 1925 case "bigint": 1926 type = t; 1927 break; 1928 default: 1929 return false; 1930 } 1931 } else if (t !== type) { 1932 return false; 1933 } 1934 hasPrimitive = true; 1935 } 1936 return hasPrimitive; 1937} 1938 1939// Given an array, checks that the first n elements are dates. 1940function arrayContainsDates(value) { 1941 const n = Math.min(nChecks, value.length); 1942 if (!(n > 0)) return false; 1943 let hasDate = false; // ensure we encounter 1+ dates 1944 for (let i = 0; i < n; ++i) { 1945 const v = value[i]; 1946 if (v == null) continue; // ignore null and undefined 1947 if (!(v instanceof Date)) return false; 1948 hasDate = true; 1949 } 1950 return hasDate; 1951} 1952 1953function isTypedArray(value) { 1954 return ( 1955 value instanceof Int8Array || 1956 value instanceof Int16Array || 1957 value instanceof Int32Array || 1958 value instanceof Uint8Array || 1959 value instanceof Uint8ClampedArray || 1960 value instanceof Uint16Array || 1961 value instanceof Uint32Array || 1962 value instanceof Float32Array || 1963 value instanceof Float64Array 1964 ); 1965} 1966 1967// __query is used by table cells; __query.sql is used by SQL cells. 1968const __query = Object.assign( 1969 async (source, operations, invalidation) => {
1970 source = await loadDataSource(await source, "table"); 1971 if (isDatabaseClient(source)) return evaluateQuery(source, makeQueryTemplate(operations, source), invalidation); 1972 if (isDataArray(source)) return __table(source, operations); 1973 if (!source) throw new Error("missing data source"); 1974 throw new Error("invalid data source"); 1975 }, 1976 { 1977 sql(source, invalidation) { 1978 return async function () { 1979 return evaluateQuery(await loadDataSource(await source, "sql"), arguments, invalidation); 1980 }; 1981 } 1982 } 1983); 1984 1985async function loadDataSource(source, mode) { 1986 if (source instanceof FileAttachment) { 1987 if (mode === "table") { 1988 switch (source.mimeType) { 1989 case "text/csv": return source.csv({typed: true}); 1990 case "text/tab-separated-values": return source.tsv({typed: true}); 1991 case "application/json": return source.json(); 1992 } 1993 } 1994 if (mode === "table" || mode === "sql") { 1995 switch (source.mimeType) { 1996 case "application/x-sqlite3": return source.sqlite(); 1997 } 1998 if (/\.arrow$/i.test(source.name)) return DuckDBClient.of({__table: await source.arrow({version: 9})}); 1999 } 2000 throw new Error(`unsupported file type: ${source.mimeType}`); 2001 } 2002 if ((mode === "table" || mode === "sql") && isArrowTable(source)) { 2003 return DuckDBClient.of({__table: source}); 2004 } 2005 return source; 2006} 2007 2008async function evaluateQuery(source, args, invalidation) { 2009 if (!source) throw new Error("missing data source"); 2010 2011 // If this DatabaseClient supports abort and streaming, use that. 2012 if (typeof source.queryTag === "function") { 2013 const abortController = new AbortController(); 2014 const options = {signal: abortController.signal}; 2015 invalidation.then(() => abortController.abort("invalidated")); 2016 if (typeof source.queryStream === "function") { 2017 return accumulateQuery( 2018 source.queryStream(...source.queryTag.apply(source, args), options) 2019 ); 2020 } 2021 if (typeof source.query === "function") { 2022 return source.query(...source.queryTag.apply(source, args), options); 2023 } 2024 } 2025 2026 // Otherwise, fallback to the basic sql tagged template literal. 2027 if (typeof source.sql === "function") { 2028 return source.sql.apply(source, args); 2029 } 2030 2031 // TODO: test if source is a file attachment, and support CSV etc. 2032 throw new Error("source does not implement query, queryStream, or sql"); 2033} 2034 2035// Generator function that yields accumulated query results client.queryStream 2036async function* accumulateQuery(queryRequest) { 2037 let then = performance.now(); 2038 const queryResponse = await queryRequest; 2039 const values = []; 2040 values.done = false; 2041 values.error = null; 2042 values.schema = queryResponse.schema; 2043 try { 2044 for await (const rows of queryResponse.readRows()) { 2045 if (performance.now() - then > 10 && values.length > 0) { 2046 yield values; 2047 then = performance.now(); 2048 } 2049 for (const value of rows) { 2050 values.push(value); 2051 } 2052 } 2053 values.done = true; 2054 yield values; 2055 } catch (error) { 2056 values.error = error; 2057 yield values; 2058 } 2059} 2060 2061/** 2062 * Returns a SQL query in the form [[parts], ...params] where parts is an array 2063 * of sub-strings and params are the parameter values to be inserted between each 2064 * sub-string. 2065 */ 2066function makeQueryTemplate(operations, source) { 2067 const escaper = 2068 typeof source.escape === "function" ? source.escape : (i) => i; 2069 const {select, from, filter, sort, slice} = operations; 2070 if (!from.table) 2071 throw new Error("missing from table"); 2072 if (select.columns && select.columns.length === 0) 2073 throw new Error("at least one column must be selected"); 2074 const columns = select.columns ? select.columns.map((c) => `t.${escaper(c)}`) : "*"; 2075 const args = [ 2076 [`SELECT ${columns} FROM ${formatTable(from.table, escaper)} t`] 2077 ]; 2078 for (let i = 0; i < filter.length; ++i) { 2079 appendSql(i ? `\nAND ` : `\nWHERE `, args); 2080 appendWhereEntry(filter[i], args, escaper); 2081 } 2082 for (let i = 0; i < sort.length; ++i) { 2083 appendSql(i ? `, ` : `\nORDER BY `, args); 2084 appendOrderBy(sort[i], args, escaper); 2085 } 2086 if (source.dialect === "mssql") { 2087 if (slice.to !== null || slice.from !== null) { 2088 if (!sort.length) { 2089 if (!select.columns) 2090 throw new Error( 2091 "at least one column must be explicitly specified. Received '*'." 2092 );
2093 appendSql(`\nORDER BY `, args); 2094 appendOrderBy( 2095 {column: select.columns[0], direction: "ASC"}, 2096 args, 2097 escaper 2098 ); 2099 } 2100 appendSql(`\nOFFSET ${slice.from || 0} ROWS`, args); 2101 appendSql( 2102 `\nFETCH NEXT ${ 2103 slice.to !== null ? slice.to - (slice.from || 0) : 1e9 2104 } ROWS ONLY`, 2105 args 2106 ); 2107 } 2108 } else { 2109 if (slice.to !== null || slice.from !== null) { 2110 appendSql( 2111 `\nLIMIT ${slice.to !== null ? slice.to - (slice.from || 0) : 1e9}`, 2112 args 2113 ); 2114 } 2115 if (slice.from !== null) { 2116 appendSql(` OFFSET ${slice.from}`, args); 2117 } 2118 } 2119 return args; 2120} 2121 2122function formatTable(table, escaper) { 2123 if (typeof table === "object") { // i.e., not a bare string specifier 2124 let from = ""; 2125 if (table.database != null) from += escaper(table.database) + "."; 2126 if (table.schema != null) from += escaper(table.schema) + "."; 2127 from += escaper(table.table); 2128 return from; 2129 } 2130 return table; 2131} 2132 2133function appendSql(sql, args) { 2134 const strings = args[0]; 2135 strings[strings.length - 1] += sql; 2136} 2137 2138function appendOrderBy({column, direction}, args, escaper) { 2139 appendSql(`t.${escaper(column)} ${direction.toUpperCase()}`, args); 2140} 2141 2142function appendWhereEntry({type, operands}, args, escaper) { 2143 if (operands.length < 1) throw new Error("Invalid operand length"); 2144 2145 // Unary operations 2146 if (operands.length === 1) { 2147 appendOperand(operands[0], args, escaper); 2148 switch (type) { 2149 case "n": 2150 appendSql(` IS NULL`, args); 2151 return; 2152 case "nn": 2153 appendSql(` IS NOT NULL`, args); 2154 return; 2155 default: 2156 throw new Error("Invalid filter operation"); 2157 } 2158 } 2159 2160 // Binary operations 2161 if (operands.length === 2) { 2162 if (["in", "nin"].includes(type)) ; else if (["c", "nc"].includes(type)) { 2163 // TODO: Case (in)sensitive? 2164 appendOperand(operands[0], args, escaper); 2165 switch (type) { 2166 case "c": 2167 appendSql(` LIKE `, args); 2168 break; 2169 case "nc": 2170 appendSql(` NOT LIKE `, args); 2171 break; 2172 } 2173 appendOperand(likeOperand(operands[1]), args, escaper); 2174 return; 2175 } else { 2176 appendOperand(operands[0], args, escaper); 2177 switch (type) { 2178 case "eq": 2179 appendSql(` = `, args); 2180 break; 2181 case "ne": 2182 appendSql(` <> `, args); 2183 break; 2184 case "gt": 2185 appendSql(` > `, args); 2186 break; 2187 case "lt": 2188 appendSql(` < `, args); 2189 break; 2190 case "gte": 2191 appendSql(` >= `, args); 2192 break; 2193 case "lte": 2194 appendSql(` <= `, args); 2195 break; 2196 default: 2197 throw new Error("Invalid filter operation"); 2198 } 2199 appendOperand(operands[1], args, escaper); 2200 return; 2201 } 2202 } 2203 2204 // List operations 2205 appendOperand(operands[0], args, escaper); 2206 switch (type) { 2207 case "in": 2208 appendSql(` IN (`, args); 2209 break; 2210 case "nin": 2211 appendSql(` NOT IN (`, args); 2212 break; 2213 default: 2214 throw new Error("Invalid filter operation"); 2215 } 2216 appendListOperands(operands.slice(1), args); 2217 appendSql(")", args); 2218} 2219 2220function appendOperand(o, args, escaper) { 2221 if (o.type === "column") { 2222 appendSql(`t.${escaper(o.value)}`, args); 2223 } else { 2224 args.push(o.value); 2225 args[0].push(""); 2226 } 2227} 2228 2229// TODO: Support column operands here? 2230function appendListOperands(ops, args) { 2231 let first = true; 2232 for (const op of ops) { 2233 if (first) first = false; 2234 else appendSql(",", args); 2235 args.push(op.value); 2236 args[0].push(""); 2237 } 2238} 2239 2240function likeOperand(operand) { 2241 return {...operand, value: `%${operand.value}%`}; 2242} 2243 2244// This function applies table cell operations to an in-memory table (array of 2245// objects); it should be equivalent to the corresponding SQL query. 2246function __table(source, operations) { 2247 const input = source; 2248 let {schema, columns} = source; 2249 let primitive = arrayIsPrimitive(source); 2250 if (primitive) source = Array.from(source, (value) => ({value})); 2251 for (const {type, operands} of operations.filter) { 2252 const [{value: column}] = operands; 2253 const values = operands.slice(1).map(({value}) => value); 2254 switch (type) { 2255 case "eq": { 2256 const [value] = values; 2257 if (value instanceof Date) { 2258 const time = +value; // compare as primitive 2259 source = source.filter((d) => +d[column] === time); 2260 } else { 2261 source = source.filter((d) => d[column] === value); 2262 } 2263 break; 2264 } 2265 case "ne": { 2266 const [value] = values; 2267 source = source.filter((d) => d[column] !== value); 2268 break; 2269 } 2270 case "c": { 2271 const [value] = values; 2272 source = source.filter( 2273 (d) => typeof d[column] === "string" && d[column].includes(value) 2274 ); 2275 break; 2276 } 2277 case "nc": { 2278 const [value] = values; 2279 source = source.filter( 2280 (d) => typeof d[column] === "string" && !d[column].includes(value) 2281 ); 2282 break; 2283 } 2284 case "in": { 2285 const set = new Set(values); // TODO support dates? 2286 source = source.filter((d) => set.has(d[column])); 2287 break; 2288 } 2289 case "nin": { 2290 const set = new Set(values); // TODO support dates? 2291 source = source.filter((d) => !set.has(d[column])); 2292 break; 2293 } 2294 case "n": { 2295 source = source.filter((d) => d[column] == null); 2296 break; 2297 } 2298 case "nn": { 2299 source = source.filter((d) => d[column] != null); 2300 break; 2301 } 2302 case "lt": { 2303 const [value] = values; 2304 source = source.filter((d) => d[column] < value); 2305 break; 2306 } 2307 case "lte": { 2308 const [value] = values; 2309 source = source.filter((d) => d[column] <= value); 2310 break; 2311 } 2312 case "gt": { 2313 const [value] = values; 2314 source = source.filter((d) => d[column] > value); 2315 break; 2316 } 2317 case "gte": { 2318 const [value] = values; 2319 source = source.filter((d) => d[column] >= value); 2320 break; 2321 } 2322 default: 2323 throw new Error(`unknown filter type: ${type}`); 2324 } 2325 } 2326 for (const {column, direction} of reverse(operations.sort)) { 2327 const compare = direction === "desc" ? descending : ascending; 2328 if (source === input) source = source.slice(); // defensive copy 2329 source.sort((a, b) => compare(a[column], b[column])); 2330 } 2331 let {from, to} = operations.slice; 2332 from = from == null ? 0 : Math.max(0, from);
2333 to = to == null ? Infinity : Math.max(0, to); 2334 if (from > 0 || to < Infinity) { 2335 source = source.slice(Math.max(0, from), Math.max(0, to)); 2336 } 2337 if (operations.select.columns) { 2338 if (schema) { 2339 const schemaByName = new Map(schema.map((s) => [s.name, s])); 2340 schema = operations.select.columns.map((c) => schemaByName.get(c)); 2341 } 2342 if (columns) { 2343 columns = operations.select.columns; 2344 } 2345 source = source.map((d) => 2346 Object.fromEntries(operations.select.columns.map((c) => [c, d[c]])) 2347 ); 2348 } 2349 if (primitive) source = source.map((d) => d.value); 2350 if (source !== input) { 2351 if (schema) source.schema = schema; 2352 if (columns) source.columns = columns; 2353 } 2354 return source; 2355} 2356 2357const Library = Object.assign(Object.defineProperties(function Library(resolver) { 2358 const require = requirer(resolver); 2359 Object.defineProperties(this, properties({ 2360 FileAttachment: () => NoFileAttachments, 2361 Mutable: () => Mutable, 2362 now, 2363 width, 2364 2365 // Tagged template literals 2366 dot: () => require(graphviz.resolve()), 2367 htl: () => require(htl.resolve()), 2368 html: () => html$1, 2369 md: () => md(require), 2370 svg: () => svg, 2371 tex: () => tex(require), 2372 2373 // Recommended libraries 2374 // https://observablehq.com/@observablehq/recommended-libraries 2375 _: () => require(lodash.resolve()), 2376 aq: () => require.alias({"apache-arrow": arrow4.resolve()})(arquero.resolve()), // TODO upgrade to apache-arrow@9 2377 Arrow: () => require(arrow4.resolve()), // TODO upgrade to apache-arrow@9 2378 d3: () => require(d3.resolve()), 2379 DuckDBClient: () => DuckDBClient, 2380 Inputs: () => require(inputs.resolve()).then(Inputs => ({...Inputs, file: Inputs.fileOf(AbstractFile)})), 2381 L: () => leaflet(require), 2382 mermaid: () => mermaid(require), 2383 Plot: () => require(plot.resolve()), 2384 __query: () => __query, 2385 require: () => require, 2386 resolve: () => resolve, // deprecated; use async require.resolve instead 2387 SQLite: () => SQLite(require), 2388 SQLiteDatabaseClient: () => SQLiteDatabaseClient, 2389 topojson: () => require(topojson.resolve()), 2390 vl: () => vl(require), 2391 2392 // Sample datasets 2393 // https://observablehq.com/@observablehq/datasets 2394 aapl: () => new FileAttachment("https://static.observableusercontent.com/files/3ccff97fd2d93da734e76829b2b066eafdaac6a1fafdec0faf6ebc443271cfc109d29e80dd217468fcb2aff1e6bffdc73f356cc48feb657f35378e6abbbb63b9").csv({typed: true}), 2395 alphabet: () => new FileAttachment("https://static.observableusercontent.com/files/75d52e6c3130b1cae83cda89305e17b50f33e7420ef205587a135e8562bcfd22e483cf4fa2fb5df6dff66f9c5d19740be1cfaf47406286e2eb6574b49ffc685d").csv({typed: true}), 2396 cars: () => new FileAttachment("https://static.observableusercontent.com/files/048ec3dfd528110c0665dfa363dd28bc516ffb7247231f3ab25005036717f5c4c232a5efc7bb74bc03037155cb72b1abe85a33d86eb9f1a336196030443be4f6").csv({typed: true}), 2397 citywages: () => new FileAttachment("https://static.observableusercontent.com/files/39837ec5121fcc163131dbc2fe8c1a2e0b3423a5d1e96b5ce371e2ac2e20a290d78b71a4fb08b9fa6a0107776e17fb78af313b8ea70f4cc6648fad68ddf06f7a").csv({typed: true}), 2398 diamonds: () => new FileAttachment("https://static.observableusercontent.com/files/87942b1f5d061a21fa4bb8f2162db44e3ef0f7391301f867ab5ba718b225a63091af20675f0bfe7f922db097b217b377135203a7eab34651e21a8d09f4e37252").csv({typed: true}), 2399 flare: () => new FileAttachment("https://static.observableusercontent.com/files/a6b0d94a7f5828fd133765a934f4c9746d2010e2f342d335923991f31b14120de96b5cb4f160d509d8dc627f0107d7f5b5070d2516f01e4c862b5b4867533000").csv({typed: true}), 2400 industries: () => new FileAttachment("https://static.observableusercontent.com/files/76f13741128340cc88798c0a0b7fa5a2df8370f57554000774ab8ee9ae785ffa2903010cad670d4939af3e9c17e5e18e7e05ed2b38b848ac2fc1a0066aa0005f").csv({typed: true}), 2401 miserables: () => new FileAttachment("https://static.observableusercontent.com/files/31d904f6e21d42d4963ece9c8cc4fbd75efcbdc404bf511bc79906f0a1be68b5a01e935f65123670ed04e35ca8cae3c2b943f82bf8db49c5a67c85cbb58db052").json(), 2402 olympians: () => new FileAttachment("https://static.observableusercontent.com/files/31ca24545a0603dce099d10ee89ee5ae72d29fa55e8fc7c9ffb5ded87ac83060d80f1d9e21f4ae8eb04c1e8940b7287d179fe8060d887fb1f055f430e210007c").csv({typed: true}), 2403 penguins: () => new FileAttachment("https://static.observableusercontent.com/files/715db1223e067f00500780077febc6cebbdd90c151d3d78317c802732252052ab0e367039872ab9c77d6ef99e5f55a0724b35ddc898a1c99cb14c31a379af80a").csv({typed: true}), 2404 weather: () => new FileAttachment("https://static.observableusercontent.com/files/693a46b22b33db0f042728700e0c73e836fa13d55446df89120682d55339c6db7cc9e574d3d73f24ecc9bc7eb9ac9a1e7e104a1ee52c00aab1e77eb102913c1f").csv({typed: true}), 2405 2406 // Note: these are namespace objects, and thus exposed directly rather than 2407 // being wrapped in a function. This allows library.Generators to resolve, 2408 // rather than needing module.value. 2409 DOM, 2410 Files, 2411 Generators: Generators$1, 2412 Promises 2413 })); 2414}, { 2415 resolve: { 2416 get: () => requireDefault.resolve, 2417 enumerable: true, 2418 configurable: true 2419 }, 2420 require: { 2421 get: () => requireDefault, 2422 set: setDefaultRequire, 2423 enumerable: true, 2424 configurable: true 2425 } 2426}), { 2427 resolveFrom, 2428 requireFrom 2429}); 2430 2431function properties(values) { 2432 return Object.fromEntries(Object.entries(values).map(property)); 2433} 2434 2435function property([key, value]) { 2436 return [key, ({value, writable: true, enumerable: true})]; 2437} 2438 2439// src/main.js 2440class PandocCodeDecorator { 2441 constructor(node) { 2442 this._node = node; 2443 this._spans = []; 2444 this.normalizeCodeRange(); 2445 this.initializeEntryPoints(); 2446 } 2447 normalizeCodeRange() { 2448 const n = this._node; 2449 const lines = n.querySelectorAll("code > span"); 2450 for (const line of lines) { 2451 Array.from(line.childNodes).filter((n2) =>
2451 n2.nodeType === n2.TEXT_NODE).forEach((n2) => { 2452 const newSpan = document.createElement("span"); 2453 newSpan.textContent = n2.wholeText; 2454 n2.replaceWith(newSpan); 2455 }); 2456 } 2457 } 2458 initializeEntryPoints() { 2459 const lines = this._node.querySelectorAll("code > span"); 2460 let result = []; 2461 let offset = this._node.parentElement.dataset.sourceOffset && -Number(this._node.parentElement.dataset.sourceOffset) || 0; 2462 for (const line of lines) { 2463 let lineNumber = Number(line.id.split("-").pop()); 2464 let column = 1; 2465 Array.from(line.childNodes).filter((n) => n.nodeType === n.ELEMENT_NODE && n.nodeName === "SPAN").forEach((n) => { 2466 result.push({ 2467 offset, 2468 line: lineNumber, 2469 column, 2470 node: n 2471 }); 2472 offset += n.textContent.length; 2473 column += n.textContent.length; 2474 }); 2475 offset += 1; 2476 } 2477 this._elementEntryPoints = result; 2478 } 2479 locateEntry(offset) { 2480 let candidate; 2481 if (offset === Infinity) 2482 return void 0; 2483 for (let i = 0; i < this._elementEntryPoints.length; ++i) { 2484 const entry = this._elementEntryPoints[i]; 2485 if (entry.offset > offset) { 2486 return { entry: candidate, index: i - 1 }; 2487 } 2488 candidate = entry; 2489 } 2490 if (offset < candidate.offset + candidate.node.textContent.length) { 2491 return { entry: candidate, index: this._elementEntryPoints.length - 1 }; 2492 } else { 2493 return void 0; 2494 } 2495 } 2496 offsetToLineColumn(offset) { 2497 let entry = this.locateEntry(offset); 2498 if (entry === void 0) { 2499 const entries = this._elementEntryPoints; 2500 const last = entries[entries.length - 1]; 2501 return { 2502 line: last.line, 2503 column: last.column + Math.min(last.node.textContent.length, offset - last.offset) 2504 }; 2505 } 2506 return { 2507 line: entry.entry.line, 2508 column: entry.entry.column + offset - entry.entry.offset 2509 }; 2510 } 2511 *spanSelection(start, end) { 2512 this.ensureExactSpan(start, end); 2513 const startEntry = this.locateEntry(start); 2514 const endEntry = this.locateEntry(end); 2515 if (startEntry === void 0) { 2516 return; 2517 } 2518 const startIndex = startEntry.index; 2519 const endIndex = endEntry && endEntry.index || this._elementEntryPoints.length; 2520 for (let i = startIndex; i < endIndex; ++i) { 2521 if (this._elementEntryPoints[i] !== void 0) { 2522 yield this._elementEntryPoints[i]; 2523 } 2524 } 2525 } 2526 decorateSpan(start, end, classes) { 2527 for (const entryPoint of this.spanSelection(start, end)) { 2528 for (const cssClass of classes) { 2529 entryPoint.node.classList.add(cssClass); 2530 } 2531 } 2532 } 2533 clearSpan(start, end, classes) { 2534 for (const entryPoint of this.spanSelection(start, end)) { 2535 for (const cssClass of classes) { 2536 entryPoint.node.classList.remove(cssClass); 2537 } 2538 } 2539 } 2540 ensureExactSpan(start, end) { 2541 const splitEntry = (entry, offset) => { 2542 const newSpan = document.createElement("span"); 2543 for (const cssClass of entry.node.classList) { 2544 newSpan.classList.add(cssClass); 2545 } 2546 const beforeText = entry.node.textContent.slice(0, offset - entry.offset); 2547 const afterText = entry.node.textContent.slice(offset - entry.offset); 2548 entry.node.textContent = beforeText; 2549 newSpan.textContent = afterText; 2550 entry.node.after(newSpan); 2551 this._elementEntryPoints.push({ 2552 column: entry.column + offset - entry.offset, 2553 line: entry.line, 2554 node: newSpan, 2555 offset 2556 }); 2557 this._elementEntryPoints.sort((a, b) => a.offset - b.offset); 2558 }; 2559 const startEntry = this.locateEntry(start); 2560 if (startEntry !== void 0 && startEntry.entry !== void 0 && startEntry.entry.offset != start) { 2561 splitEntry(startEntry.entry, start); 2562 } 2563 const endEntry = this.locateEntry(end); 2564 if (endEntry !== void 0 && startEntry.entry !== void 0 && endEntry.entry.offset !== end) { 2565 splitEntry(endEntry.entry, end); 2566 } 2567 } 2568 clearSpan(start, end, classes) { 2569 this.ensureExactSpan(start, end); 2570 const startEntry = this.locateEntry(start); 2571 const endEntry = this.locateEntry(end); 2572 if (startEntry === void 0) { 2573 return; 2574 } 2575 const startIndex = startEntry.index; 2576 const endIndex = endEntry && endEntry.index || this._elementEntryPoints.length; 2577 for (let i = startIndex; i < endIndex; ++i) { 2578 for (const cssClass of classes) { 2579 this._elementEntryPoints[i].node.classList.remove(cssClass); 2580 } 2581 } 2582 } 2583} 2584 2585function dispatch(node, type, detail) { 2586 detail = detail || {}; 2587 var document = node.ownerDocument, event = document.defaultView.CustomEvent; 2588 if (typeof event === "function") { 2589 event = new event(type, {detail: detail}); 2590 } else { 2591 event = document.createEvent("Event"); 2592 event.initEvent(type, false, false); 2593 event.detail = detail; 2594 } 2595 node.dispatchEvent(event); 2596} 2597 2598// TODO https://twitter.com/mbostock/status/702737065121742848 2599function isarray(value) { 2600 return Array.isArray(value) 2601 || value instanceof Int8Array 2602 || value instanceof Int16Array 2603 || value instanceof Int32Array 2604 || value instanceof Uint8Array 2605 || value instanceof Uint8ClampedArray 2606 || value instanceof Uint16Array 2607 || value instanceof Uint32Array 2608 || value instanceof Float32Array 2609 || value instanceof Float64Array; 2610} 2611 2612// Non-integer keys in arrays, e.g. [1, 2, 0.5: "value"]. 2613function isindex(key) { 2614 return key === (key | 0) + ""; 2615} 2616 2617function inspectName(name) { 2618 const n = document.createElement("span"); 2619 n.className = "observablehq--cellname"; 2620 n.textContent = `${name} = `; 2621 return n; 2622} 2623 2624const symbolToString = Symbol.prototype.toString; 2625 2626// Symbols do not coerce to strings; they must be explicitly converted. 2627function formatSymbol(symbol) { 2628 return symbolToString.call(symbol); 2629} 2630 2631const {getOwnPropertySymbols, prototype: {hasOwnProperty: hasOwnProperty$1}} = Object; 2632const {toStringTag} = Symbol; 2633 2634const FORBIDDEN = {}; 2635 2636const symbolsof = getOwnPropertySymbols; 2637 2638function isown(object, key) { 2639 return hasOwnProperty$1.call(object, key); 2640} 2641 2642function tagof(object) { 2643 return object[toStringTag] 2644 || (object.constructor && object.constructor.name) 2645 || "Object"; 2646} 2647 2648function valueof(object, key) { 2649 try { 2650 const value = object[key]; 2651 if (value) value.constructor; // Test for SecurityError. 2652 return value; 2653 } catch (ignore) { 2654 return FORBIDDEN; 2655 } 2656} 2657 2658const SYMBOLS = [ 2659 { symbol: "@@__IMMUTABLE_INDEXED__@@", name: "Indexed", modifier: true }, 2660 { symbol: "@@__IMMUTABLE_KEYED__@@", name: "Keyed", modifier: true },
2661 { symbol: "@@__IMMUTABLE_LIST__@@", name: "List", arrayish: true }, 2662 { symbol: "@@__IMMUTABLE_MAP__@@", name: "Map" }, 2663 { 2664 symbol: "@@__IMMUTABLE_ORDERED__@@", 2665 name: "Ordered", 2666 modifier: true, 2667 prefix: true 2668 }, 2669 { symbol: "@@__IMMUTABLE_RECORD__@@", name: "Record" }, 2670 { 2671 symbol: "@@__IMMUTABLE_SET__@@", 2672 name: "Set", 2673 arrayish: true, 2674 setish: true 2675 }, 2676 { symbol: "@@__IMMUTABLE_STACK__@@", name: "Stack", arrayish: true } 2677]; 2678 2679function immutableName(obj) { 2680 try { 2681 let symbols = SYMBOLS.filter(({ symbol }) => obj[symbol] === true); 2682 if (!symbols.length) return; 2683 2684 const name = symbols.find(s => !s.modifier); 2685 const prefix = 2686 name.name === "Map" && symbols.find(s => s.modifier && s.prefix); 2687 2688 const arrayish = symbols.some(s => s.arrayish); 2689 const setish = symbols.some(s => s.setish); 2690 2691 return { 2692 name: `${prefix ? prefix.name : ""}${name.name}`, 2693 symbols, 2694 arrayish: arrayish && !setish, 2695 setish 2696 }; 2697 } catch (e) { 2698 return null; 2699 } 2700} 2701 2702const {getPrototypeOf, getOwnPropertyDescriptors} = Object; 2703const objectPrototype = getPrototypeOf({}); 2704 2705function inspectExpanded(object, _, name, proto) { 2706 let arrayish = isarray(object); 2707 let tag, fields, next, n; 2708 2709 if (object instanceof Map) { 2710 if (object instanceof object.constructor) { 2711 tag = `Map(${object.size})`; 2712 fields = iterateMap$1; 2713 } else { // avoid incompatible receiver error for prototype 2714 tag = "Map()"; 2715 fields = iterateObject$1; 2716 } 2717 } else if (object instanceof Set) { 2718 if (object instanceof object.constructor) { 2719 tag = `Set(${object.size})`; 2720 fields = iterateSet$1; 2721 } else { // avoid incompatible receiver error for prototype 2722 tag = "Set()"; 2723 fields = iterateObject$1; 2724 } 2725 } else if (arrayish) { 2726 tag = `${object.constructor.name}(${object.length})`; 2727 fields = iterateArray$1; 2728 } else if ((n = immutableName(object))) { 2729 tag = `Immutable.${n.name}${n.name === "Record" ? "" : `(${object.size})`}`; 2730 arrayish = n.arrayish; 2731 fields = n.arrayish 2732 ? iterateImArray$1 2733 : n.setish 2734 ? iterateImSet$1 2735 : iterateImObject$1; 2736 } else if (proto) { 2737 tag = tagof(object); 2738 fields = iterateProto; 2739 } else { 2740 tag = tagof(object); 2741 fields = iterateObject$1; 2742 } 2743 2744 const span = document.createElement("span"); 2745 span.className = "observablehq--expanded"; 2746 if (name) { 2747 span.appendChild(inspectName(name)); 2748 } 2749 const a = span.appendChild(document.createElement("a")); 2750 a.innerHTML = `<svg width=8 height=8 class='observablehq--caret'> 2751 <path d='M4 7L0 1h8z' fill='currentColor' /> 2752 </svg>`; 2753 a.appendChild(document.createTextNode(`${tag}${arrayish ? " [" : " {"}`)); 2754 a.addEventListener("mouseup", function(event) { 2755 event.stopPropagation(); 2756 replace(span, inspectCollapsed(object, null, name, proto)); 2757 }); 2758 2759 fields = fields(object); 2760 for (let i = 0; !(next = fields.next()).done && i < 20; ++i) { 2761 span.appendChild(next.value); 2762 } 2763 2764 if (!next.done) { 2765 const a = span.appendChild(document.createElement("a")); 2766 a.className = "observablehq--field"; 2767 a.style.display = "block"; 2768 a.appendChild(document.createTextNode(` ⦠more`)); 2769 a.addEventListener("mouseup", function(event) { 2770 event.stopPropagation(); 2771 span.insertBefore(next.value, span.lastChild.previousSibling); 2772 for (let i = 0; !(next = fields.next()).done && i < 19; ++i) { 2773 span.insertBefore(next.value, span.lastChild.previousSibling); 2774 } 2775 if (next.done) span.removeChild(span.lastChild.previousSibling); 2776 dispatch(span, "load"); 2777 }); 2778 } 2779 2780 span.appendChild(document.createTextNode(arrayish ? "]" : "}")); 2781 2782 return span; 2783} 2784 2785function* iterateMap$1(map) { 2786 for (const [key, value] of map) { 2787 yield formatMapField$1(key, value); 2788 } 2789 yield* iterateObject$1(map); 2790} 2791 2792function* iterateSet$1(set) { 2793 for (const value of set) { 2794 yield formatSetField(value); 2795 } 2796 yield* iterateObject$1(set); 2797} 2798 2799function* iterateImSet$1(set) { 2800 for (const value of set) { 2801 yield formatSetField(value); 2802 } 2803} 2804 2805function* iterateArray$1(array) { 2806 for (let i = 0, n = array.length; i < n; ++i) { 2807 if (i in array) { 2808 yield formatField$1(i, valueof(array, i), "observablehq--index"); 2809 } 2810 } 2811 for (const key in array) { 2812 if (!isindex(key) && isown(array, key)) { 2813 yield formatField$1(key, valueof(array, key), "observablehq--key"); 2814 } 2815 } 2816 for (const symbol of symbolsof(array)) { 2817 yield formatField$1( 2818 formatSymbol(symbol), 2819 valueof(array, symbol), 2820 "observablehq--symbol" 2821 ); 2822 } 2823} 2824 2825function* iterateImArray$1(array) { 2826 let i1 = 0; 2827 for (const n = array.size; i1 < n; ++i1) { 2828 yield formatField$1(i1, array.get(i1), true); 2829 } 2830} 2831 2832function* iterateProto(object) { 2833 for (const key in getOwnPropertyDescriptors(object)) { 2834 yield formatField$1(key, valueof(object, key), "observablehq--key"); 2835 } 2836 for (const symbol of symbolsof(object)) { 2837 yield formatField$1( 2838 formatSymbol(symbol), 2839 valueof(object, symbol), 2840 "observablehq--symbol" 2841 ); 2842 } 2843 2844 const proto = getPrototypeOf(object); 2845 if (proto && proto !== objectPrototype) { 2846 yield formatPrototype(proto); 2847 } 2848} 2849
2850function* iterateObject$1(object) { 2851 for (const key in object) { 2852 if (isown(object, key)) { 2853 yield formatField$1(key, valueof(object, key), "observablehq--key"); 2854 } 2855 } 2856 for (const symbol of symbolsof(object)) { 2857 yield formatField$1( 2858 formatSymbol(symbol), 2859 valueof(object, symbol), 2860 "observablehq--symbol" 2861 ); 2862 } 2863 2864 const proto = getPrototypeOf(object); 2865 if (proto && proto !== objectPrototype) { 2866 yield formatPrototype(proto); 2867 } 2868} 2869 2870function* iterateImObject$1(object) { 2871 for (const [key, value] of object) { 2872 yield formatField$1(key, value, "observablehq--key"); 2873 } 2874} 2875 2876function formatPrototype(value) { 2877 const item = document.createElement("div"); 2878 const span = item.appendChild(document.createElement("span")); 2879 item.className = "observablehq--field"; 2880 span.className = "observablehq--prototype-key"; 2881 span.textContent = ` <prototype>`; 2882 item.appendChild(document.createTextNode(": ")); 2883 item.appendChild(inspect(value, undefined, undefined, undefined, true)); 2884 return item; 2885} 2886 2887function formatField$1(key, value, className) { 2888 const item = document.createElement("div"); 2889 const span = item.appendChild(document.createElement("span")); 2890 item.className = "observablehq--field"; 2891 span.className = className; 2892 span.textContent = ` ${key}`; 2893 item.appendChild(document.createTextNode(": ")); 2894 item.appendChild(inspect(value)); 2895 return item; 2896} 2897 2898function formatMapField$1(key, value) { 2899 const item = document.createElement("div"); 2900 item.className = "observablehq--field"; 2901 item.appendChild(document.createTextNode(" ")); 2902 item.appendChild(inspect(key)); 2903 item.appendChild(document.createTextNode(" => ")); 2904 item.appendChild(inspect(value)); 2905 return item; 2906} 2907 2908function formatSetField(value) { 2909 const item = document.createElement("div"); 2910 item.className = "observablehq--field"; 2911 item.appendChild(document.createTextNode(" ")); 2912 item.appendChild(inspect(value)); 2913 return item; 2914} 2915 2916function hasSelection(elem) { 2917 const sel = window.getSelection(); 2918 return ( 2919 sel.type === "Range" && 2920 (sel.containsNode(elem, true) || 2921 sel.anchorNode.isSelfOrDescendant(elem) || 2922 sel.focusNode.isSelfOrDescendant(elem)) 2923 ); 2924} 2925 2926function inspectCollapsed(object, shallow, name, proto) { 2927 let arrayish = isarray(object); 2928 let tag, fields, next, n; 2929 2930 if (object instanceof Map) { 2931 if (object instanceof object.constructor) { 2932 tag = `Map(${object.size})`; 2933 fields = iterateMap; 2934 } else { // avoid incompatible receiver error for prototype 2935 tag = "Map()"; 2936 fields = iterateObject; 2937 } 2938 } else if (object instanceof Set) { 2939 if (object instanceof object.constructor) { 2940 tag = `Set(${object.size})`; 2941 fields = iterateSet; 2942 } else { // avoid incompatible receiver error for prototype 2943 tag = "Set()"; 2944 fields = iterateObject; 2945 } 2946 } else if (arrayish) { 2947 tag = `${object.constructor.name}(${object.length})`; 2948 fields = iterateArray; 2949 } else if ((n = immutableName(object))) { 2950 tag = `Immutable.${n.name}${n.name === 'Record' ? '' : `(${object.size})`}`; 2951 arrayish = n.arrayish; 2952 fields = n.arrayish ? iterateImArray : n.setish ? iterateImSet : iterateImObject; 2953 } else { 2954 tag = tagof(object); 2955 fields = iterateObject; 2956 } 2957 2958 if (shallow) { 2959 const span = document.createElement("span"); 2960 span.className = "observablehq--shallow"; 2961 if (name) { 2962 span.appendChild(inspectName(name)); 2963 } 2964 span.appendChild(document.createTextNode(tag)); 2965 span.addEventListener("mouseup", function(event) { 2966 if (hasSelection(span)) return; 2967 event.stopPropagation(); 2968 replace(span, inspectCollapsed(object)); 2969 }); 2970 return span; 2971 } 2972 2973 const span = document.createElement("span"); 2974 span.className = "observablehq--collapsed"; 2975 if (name) { 2976 span.appendChild(inspectName(name)); 2977 } 2978 const a = span.appendChild(document.createElement("a")); 2979 a.innerHTML = `<svg width=8 height=8 class='observablehq--caret'> 2980 <path d='M7 4L1 8V0z' fill='currentColor' /> 2981 </svg>`; 2982 a.appendChild(document.createTextNode(`${tag}${arrayish ? " [" : " {"}`)); 2983 span.addEventListener("mouseup", function(event) { 2984 if (hasSelection(span)) return; 2985 event.stopPropagation(); 2986 replace(span, inspectExpanded(object, null, name, proto)); 2987 }, true); 2988 2989 fields = fields(object); 2990 for (let i = 0; !(next = fields.next()).done && i < 20; ++i) { 2991 if (i > 0) span.appendChild(document.createTextNode(", ")); 2992 span.appendChild(next.value); 2993 } 2994 2995 if (!next.done) span.appendChild(document.createTextNode(", â¦")); 2996 span.appendChild(document.createTextNode(arrayish ? "]" : "}")); 2997 2998 return span; 2999} 3000 3001function* iterateMap(map) { 3002 for (const [key, value] of map) { 3003 yield formatMapField(key, value); 3004 }
3005 yield* iterateObject(map); 3006} 3007 3008function* iterateSet(set) { 3009 for (const value of set) { 3010 yield inspect(value, true); 3011 } 3012 yield* iterateObject(set); 3013} 3014 3015function* iterateImSet(set) { 3016 for (const value of set) { 3017 yield inspect(value, true); 3018 } 3019} 3020 3021function* iterateImArray(array) { 3022 let i0 = -1, i1 = 0; 3023 for (const n = array.size; i1 < n; ++i1) { 3024 if (i1 > i0 + 1) yield formatEmpty(i1 - i0 - 1); 3025 yield inspect(array.get(i1), true); 3026 i0 = i1; 3027 } 3028 if (i1 > i0 + 1) yield formatEmpty(i1 - i0 - 1); 3029} 3030 3031function* iterateArray(array) { 3032 let i0 = -1, i1 = 0; 3033 for (const n = array.length; i1 < n; ++i1) { 3034 if (i1 in array) { 3035 if (i1 > i0 + 1) yield formatEmpty(i1 - i0 - 1); 3036 yield inspect(valueof(array, i1), true); 3037 i0 = i1; 3038 } 3039 } 3040 if (i1 > i0 + 1) yield formatEmpty(i1 - i0 - 1); 3041 for (const key in array) { 3042 if (!isindex(key) && isown(array, key)) { 3043 yield formatField(key, valueof(array, key), "observablehq--key"); 3044 } 3045 } 3046 for (const symbol of symbolsof(array)) { 3047 yield formatField(formatSymbol(symbol), valueof(array, symbol), "observablehq--symbol"); 3048 } 3049} 3050 3051function* iterateObject(object) { 3052 for (const key in object) { 3053 if (isown(object, key)) { 3054 yield formatField(key, valueof(object, key), "observablehq--key"); 3055 } 3056 } 3057 for (const symbol of symbolsof(object)) { 3058 yield formatField(formatSymbol(symbol), valueof(object, symbol), "observablehq--symbol"); 3059 } 3060} 3061 3062function* iterateImObject(object) { 3063 for (const [key, value] of object) { 3064 yield formatField(key, value, "observablehq--key"); 3065 } 3066} 3067 3068function formatEmpty(e) { 3069 const span = document.createElement("span"); 3070 span.className = "observablehq--empty"; 3071 span.textContent = e === 1 ? "empty" : `empty à ${e}`; 3072 return span; 3073} 3074 3075function formatField(key, value, className) { 3076 const fragment = document.createDocumentFragment(); 3077 const span = fragment.appendChild(document.createElement("span")); 3078 span.className = className; 3079 span.textContent = key; 3080 fragment.appendChild(document.createTextNode(": ")); 3081 fragment.appendChild(inspect(value, true)); 3082 return fragment; 3083} 3084 3085function formatMapField(key, value) { 3086 const fragment = document.createDocumentFragment(); 3087 fragment.appendChild(inspect(key, true)); 3088 fragment.appendChild(document.createTextNode(" => ")); 3089 fragment.appendChild(inspect(value, true)); 3090 return fragment; 3091} 3092 3093function format(date, fallback) { 3094 if (!(date instanceof Date)) date = new Date(+date); 3095 if (isNaN(date)) return typeof fallback === "function" ? fallback(date) : fallback; 3096 const hours = date.getUTCHours(); 3097 const minutes = date.getUTCMinutes(); 3098 const seconds = date.getUTCSeconds(); 3099 const milliseconds = date.getUTCMilliseconds(); 3100 return `${formatYear(date.getUTCFullYear())}-${pad(date.getUTCMonth() + 1, 2)}-${pad(date.getUTCDate(), 2)}${ 3101 hours || minutes || seconds || milliseconds ? `T${pad(hours, 2)}:${pad(minutes, 2)}${ 3102 seconds || milliseconds ? `:${pad(seconds, 2)}${ 3103 milliseconds ? `.${pad(milliseconds, 3)}` : `` 3104 }` : `` 3105 }Z` : `` 3106 }`; 3107} 3108 3109function formatYear(year) { 3110 return year < 0 ? `-${pad(-year, 6)}` 3111 : year > 9999 ? `+${pad(year, 6)}` 3112 : pad(year, 4); 3113} 3114 3115function pad(value, width) { 3116 return `${value}`.padStart(width, "0"); 3117} 3118 3119function formatDate$1(date) { 3120 return format(date, "Invalid Date"); 3121} 3122 3123var errorToString = Error.prototype.toString; 3124 3125function formatError(value) { 3126 return value.stack || errorToString.call(value); 3127} 3128 3129var regExpToString = RegExp.prototype.toString; 3130 3131function formatRegExp(value) { 3132 return regExpToString.call(value); 3133} 3134 3135/* eslint-disable no-control-regex */ 3136const NEWLINE_LIMIT = 20; 3137 3138function formatString(string, shallow, expanded, name) { 3139 if (shallow === false) { 3140 // String has fewer escapes displayed with double quotes 3141 if (count(string, /["\n]/g) <= count(string, /`|\${/g)) { 3142 const span = document.createElement("span"); 3143 if (name) span.appendChild(inspectName(name)); 3144 const textValue = span.appendChild(document.createElement("span")); 3145 textValue.className = "observablehq--string"; 3146 textValue.textContent = JSON.stringify(string); 3147 return span; 3148 } 3149 const lines = string.split("\n"); 3150 if (lines.length > NEWLINE_LIMIT && !expanded) { 3151 const div = document.createElement("div"); 3152 if (name) div.appendChild(inspectName(name)); 3153 const textValue = div.appendChild(document.createElement("span")); 3154 textValue.className = "observablehq--string"; 3155 textValue.textContent = "`" + templatify(lines.slice(0, NEWLINE_LIMIT).join("\n")); 3156 const splitter = div.appendChild(document.createElement("span")); 3157 const truncatedCount = lines.length - NEWLINE_LIMIT; 3158 splitter.textContent = `Show ${truncatedCount} truncated line${truncatedCount > 1 ? "s": ""}`; splitter.className = "observablehq--string-expand"; 3159 splitter.addEventListener("mouseup", function (event) { 3160 event.stopPropagation(); 3161 replace(div, inspect(string, shallow, true, name)); 3162 }); 3163 return div; 3164 } 3165 const span = document.createElement("span"); 3166 if (name) span.appendChild(inspectName(name)); 3167 const textValue = span.appendChild(document.createElement("span")); 3168 textValue.className = `observablehq--string${expanded ? " observablehq--expanded" : ""}`; 3169 textValue.textContent = "`" + templatify(string) + "`"; 3170 return span; 3171 } 3172 3173 const span = document.createElement("span"); 3174 if (name) span.appendChild(inspectName(name)); 3175 const textValue = span.appendChild(document.createElement("span")); 3176 textValue.className = "observablehq--string"; 3177 textValue.textContent = JSON.stringify(string.length > 100 ? 3178 `${string.slice(0, 50)}â¦${string.slice(-49)}` : string); 3179 return span; 3180} 3181 3182function templatify(string) { 3183 return string.replace(/[\\`\x00-\x09\x0b-\x19]|\${/g, templatifyChar); 3184} 3185 3186function templatifyChar(char) { 3187 var code = char.charCodeAt(0); 3188 switch (code) { 3189 case 0x8: return "\\b"; 3190 case 0x9: return "\\t"; 3191 case 0xb: return "\\v"; 3192 case 0xc: return "\\f"; 3193 case 0xd: return "\\r"; 3194 } 3195 return code < 0x10 ? "\\x0" + code.toString(16) 3196 : code < 0x20 ? "\\x" + code.toString(16) 3197 : "\\" + char; 3198} 3199 3200function count(string, re) { 3201 var n = 0; 3202 while (re.exec(string)) ++n; 3203 return n; 3204} 3205 3206var toString$2 = Function.prototype.toString, 3207 TYPE_ASYNC = {prefix: "async Æ"},
3208 TYPE_ASYNC_GENERATOR = {prefix: "async Æ*"}, 3209 TYPE_CLASS = {prefix: "class"}, 3210 TYPE_FUNCTION = {prefix: "Æ"}, 3211 TYPE_GENERATOR = {prefix: "Æ*"}; 3212 3213function inspectFunction(f, name) { 3214 var type, m, t = toString$2.call(f); 3215 3216 switch (f.constructor && f.constructor.name) { 3217 case "AsyncFunction": type = TYPE_ASYNC; break; 3218 case "AsyncGeneratorFunction": type = TYPE_ASYNC_GENERATOR; break; 3219 case "GeneratorFunction": type = TYPE_GENERATOR; break; 3220 default: type = /^class\b/.test(t) ? TYPE_CLASS : TYPE_FUNCTION; break; 3221 } 3222 3223 // A class, possibly named. 3224 // class Name 3225 if (type === TYPE_CLASS) { 3226 return formatFunction(type, "", name); 3227 } 3228 3229 // An arrow function with a single argument. 3230 // foo => 3231 // async foo => 3232 if ((m = /^(?:async\s*)?(\w+)\s*=>/.exec(t))) { 3233 return formatFunction(type, "(" + m[1] + ")", name); 3234 } 3235 3236 // An arrow function with parenthesized arguments. 3237 // (â¦) 3238 // async (â¦) 3239 if ((m = /^(?:async\s*)?\(\s*(\w+(?:\s*,\s*\w+)*)?\s*\)/.exec(t))) { 3240 return formatFunction(type, m[1] ? "(" + m[1].replace(/\s*,\s*/g, ", ") + ")" : "()", name); 3241 } 3242 3243 // A function, possibly: async, generator, anonymous, simply arguments. 3244 // function name(â¦) 3245 // function* name(â¦) 3246 // async function name(â¦) 3247 // async function* name(â¦) 3248 if ((m = /^(?:async\s*)?function(?:\s*\*)?(?:\s*\w+)?\s*\(\s*(\w+(?:\s*,\s*\w+)*)?\s*\)/.exec(t))) { 3249 return formatFunction(type, m[1] ? "(" + m[1].replace(/\s*,\s*/g, ", ") + ")" : "()", name); 3250 } 3251 3252 // Something else, like destructuring, comments or default values. 3253 return formatFunction(type, "(â¦)", name); 3254} 3255 3256function formatFunction(type, args, cellname) { 3257 var span = document.createElement("span"); 3258 span.className = "observablehq--function"; 3259 if (cellname) { 3260 span.appendChild(inspectName(cellname)); 3261 } 3262 var spanType = span.appendChild(document.createElement("span")); 3263 spanType.className = "observablehq--keyword"; 3264 spanType.textContent = type.prefix; 3265 span.appendChild(document.createTextNode(args)); 3266 return span; 3267} 3268 3269const {prototype: {toString: toString$1}} = Object; 3270 3271function inspect(value, shallow, expand, name, proto) { 3272 let type = typeof value; 3273 switch (type) { 3274 case "boolean": 3275 case "undefined": { value += ""; break; } 3276 case "number": { value = value === 0 && 1 / value < 0 ? "-0" : value + ""; break; } 3277 case "bigint": { value = value + "n"; break; } 3278 case "symbol": { value = formatSymbol(value); break; } 3279 case "function": { return inspectFunction(value, name); } 3280 case "string": { return formatString(value, shallow, expand, name); } 3281 default: { 3282 if (value === null) { type = null, value = "null"; break; } 3283 if (value instanceof Date) { type = "date", value = formatDate$1(value); break; } 3284 if (value === FORBIDDEN) { type = "forbidden", value = "[forbidden]"; break; } 3285 switch (toString$1.call(value)) { 3286 case "[object RegExp]": { type = "regexp", value = formatRegExp(value); break; } 3287 case "[object Error]": // https://github.com/lodash/lodash/blob/master/isError.js#L26 3288 case "[object DOMException]": { type = "error", value = formatError(value); break; } 3289 default: return (expand ? inspectExpanded : inspectCollapsed)(value, shallow, name, proto); 3290 } 3291 break; 3292 } 3293 } 3294 const span = document.createElement("span"); 3295 if (name) span.appendChild(inspectName(name)); 3296 const n = span.appendChild(document.createElement("span")); 3297 n.className = `observablehq--${type}`; 3298 n.textContent = value; 3299 return span; 3300} 3301 3302function replace(spanOld, spanNew) { 3303 if (spanOld.classList.contains("observablehq--inspect")) spanNew.classList.add("observablehq--inspect"); 3304 spanOld.parentNode.replaceChild(spanNew, spanOld); 3305 dispatch(spanNew, "load"); 3306} 3307 3308const LOCATION_MATCH = /\s+\(\d+:\d+\)$/m; 3309 3310class Inspector { 3311 constructor(node) { 3312 if (!node) throw new Error("invalid node"); 3313 this._node = node; 3314 node.classList.add("observablehq"); 3315 } 3316 pending() { 3317 const {_node} = this; 3318 _node.classList.remove("observablehq--error"); 3319 _node.classList.add("observablehq--running"); 3320 } 3321 fulfilled(value, name) { 3322 const {_node} = this; 3323 if (!isnode(value) || (value.parentNode && value.parentNode !== _node)) { 3324 value = inspect(value, false, _node.firstChild // TODO Do this better. 3325 && _node.firstChild.classList 3326 && _node.firstChild.classList.contains("observablehq--expanded"), name); 3327 value.classList.add("observablehq--inspect"); 3328 } 3329 _node.classList.remove("observablehq--running", "observablehq--error"); 3330 if (_node.firstChild !== value) { 3331 if (_node.firstChild) { 3332 while (_node.lastChild !== _node.firstChild) _node.removeChild(_node.lastChild); 3333 _node.replaceChild(value, _node.firstChild); 3334 } else { 3335 _node.appendChild(value); 3336 } 3337 } 3338 dispatch(_node, "update"); 3339 } 3340 rejected(error, name) { 3341 const {_node} = this; 3342 _node.classList.remove("observablehq--running"); 3343 _node.classList.add("observablehq--error"); 3344 while (_node.lastChild) _node.removeChild(_node.lastChild); 3345 var div = document.createElement("div"); 3346 div.className = "observablehq--inspect"; 3347 if (name) div.appendChild(inspectName(name)); 3348 div.appendChild(document.createTextNode((error + "").replace(LOCATION_MATCH, ""))); 3349 _node.appendChild(div); 3350 dispatch(_node, "error", {error: error}); 3351 } 3352} 3353 3354Inspector.into = function(container) { 3355 if (typeof container === "string") { 3356 container = document.querySelector(container); 3357 if (container == null) throw new Error("container not found"); 3358 } 3359 return function() { 3360 return new Inspector(container.appendChild(document.createElement("div"))); 3361 }; 3362}; 3363 3364// Returns true if the given value is something that should be added to the DOM 3365// by the inspector, rather than being inspected. This deliberately excludes 3366// DocumentFragment since appending a fragment âdissolvesâ (mutates) the 3367// fragment, and we wish for the inspector to not have side-effects. Also, 3368// HTMLElement.prototype is an instanceof Element, but not an element! 3369function isnode(value) { 3370 return (value instanceof Element || value instanceof Text) 3371 && (value instanceof value.constructor); 3372} 3373
3374class RuntimeError extends Error { 3375 constructor(message, input) { 3376 super(message); 3377 this.input = input; 3378 } 3379} 3380 3381RuntimeError.prototype.name = "RuntimeError"; 3382 3383function generatorish(value) { 3384 return value 3385 && typeof value.next === "function" 3386 && typeof value.return === "function"; 3387} 3388 3389function load(notebook, library, observer) { 3390 if (typeof library == "function") observer = library, library = null; 3391 if (typeof observer !== "function") throw new Error("invalid observer"); 3392 if (library == null) library = new Library(); 3393 3394 const {modules, id} = notebook; 3395 const map = new Map; 3396 const runtime = new Runtime(library); 3397 const main = runtime_module(id); 3398 3399 function runtime_module(id) { 3400 let module = map.get(id); 3401 if (!module) map.set(id, module = runtime.module()); 3402 return module; 3403 } 3404 3405 for (const m of modules) { 3406 const module = runtime_module(m.id); 3407 let i = 0; 3408 for (const v of m.variables) { 3409 if (v.from) module.import(v.remote, v.name, runtime_module(v.from)); 3410 else if (module === main) module.variable(observer(v, i, m.variables)).define(v.name, v.inputs, v.value); 3411 else module.define(v.name, v.inputs, v.value); 3412 ++i; 3413 } 3414 } 3415 3416 return runtime; 3417} 3418 3419function constant(x) { 3420 return () => x; 3421} 3422 3423function identity$1(x) { 3424 return x; 3425} 3426 3427function rethrow(error) { 3428 return () => { 3429 throw error; 3430 }; 3431} 3432 3433const prototype = Array.prototype; 3434const map = prototype.map; 3435 3436function noop() {} 3437 3438const TYPE_NORMAL = 1; // a normal variable 3439const TYPE_IMPLICIT = 2; // created on reference 3440const TYPE_DUPLICATE = 3; // created on duplicate definition 3441 3442const no_observer = Symbol("no-observer"); 3443 3444function Variable(type, module, observer) { 3445 if (!observer) observer = no_observer; 3446 Object.defineProperties(this, { 3447 _observer: {value: observer, writable: true}, 3448 _definition: {value: variable_undefined, writable: true}, 3449 _duplicate: {value: undefined, writable: true}, 3450 _duplicates: {value: undefined, writable: true}, 3451 _indegree: {value: NaN, writable: true}, // The number of computing inputs. 3452 _inputs: {value: [], writable: true}, 3453 _invalidate: {value: noop, writable: true}, 3454 _module: {value: module}, 3455 _name: {value: null, writable: true}, 3456 _outputs: {value: new Set, writable: true}, 3457 _promise: {value: Promise.resolve(undefined), writable: true}, 3458 _reachable: {value: observer !== no_observer, writable: true}, // Is this variable transitively visible? 3459 _rejector: {value: variable_rejector(this)}, 3460 _type: {value: type}, 3461 _value: {value: undefined, writable: true}, 3462 _version: {value: 0, writable: true} 3463 }); 3464} 3465 3466Object.defineProperties(Variable.prototype, { 3467 _pending: {value: variable_pending, writable: true, configurable: true}, 3468 _fulfilled: {value: variable_fulfilled, writable: true, configurable: true}, 3469 _rejected: {value: variable_rejected, writable: true, configurable: true}, 3470 define: {value: variable_define, writable: true, configurable: true}, 3471 delete: {value: variable_delete, writable: true, configurable: true}, 3472 import: {value: variable_import, writable: true, configurable: true} 3473}); 3474 3475function variable_attach(variable) { 3476 variable._module._runtime._dirty.add(variable); 3477 variable._outputs.add(this); 3478} 3479 3480function variable_detach(variable) { 3481 variable._module._runtime._dirty.add(variable); 3482 variable._outputs.delete(this); 3483} 3484 3485function variable_undefined() { 3486 throw variable_undefined; 3487} 3488 3489function variable_stale() { 3490 throw variable_stale; 3491} 3492 3493function variable_rejector(variable) { 3494 return (error) => { 3495 if (error === variable_stale) throw error; 3496 if (error === variable_undefined) throw new RuntimeError(`${variable._name} is not defined`, variable._name); 3497 if (error instanceof Error && error.message) throw new RuntimeError(error.message, variable._name); 3498 throw new RuntimeError(`${variable._name} could not be resolved`, variable._name); 3499 }; 3500} 3501 3502function variable_duplicate(name) { 3503 return () => { 3504 throw new RuntimeError(`${name} is defined more than once`); 3505 }; 3506} 3507 3508function variable_define(name, inputs, definition) { 3509 switch (arguments.length) { 3510 case 1: { 3511 definition = name, name = inputs = null; 3512 break; 3513 } 3514 case 2: {
3515 definition = inputs; 3516 if (typeof name === "string") inputs = null; 3517 else inputs = name, name = null; 3518 break; 3519 } 3520 } 3521 return variable_defineImpl.call(this, 3522 name == null ? null : String(name), 3523 inputs == null ? [] : map.call(inputs, this._module._resolve, this._module), 3524 typeof definition === "function" ? definition : constant(definition) 3525 ); 3526} 3527 3528function variable_defineImpl(name, inputs, definition) { 3529 const scope = this._module._scope, runtime = this._module._runtime; 3530 3531 this._inputs.forEach(variable_detach, this); 3532 inputs.forEach(variable_attach, this); 3533 this._inputs = inputs; 3534 this._definition = definition; 3535 this._value = undefined; 3536 3537 // Is this an active variable (that may require disposal)? 3538 if (definition === noop) runtime._variables.delete(this); 3539 else runtime._variables.add(this); 3540 3541 // Did the variableâs name change? Time to patch references! 3542 if (name !== this._name || scope.get(name) !== this) { 3543 let error, found; 3544 3545 if (this._name) { // Did this variable previously have a name? 3546 if (this._outputs.size) { // And did other variables reference this variable? 3547 scope.delete(this._name); 3548 found = this._module._resolve(this._name); 3549 found._outputs = this._outputs, this._outputs = new Set; 3550 found._outputs.forEach(function(output) { output._inputs[output._inputs.indexOf(this)] = found; }, this); 3551 found._outputs.forEach(runtime._updates.add, runtime._updates); 3552 runtime._dirty.add(found).add(this); 3553 scope.set(this._name, found); 3554 } else if ((found = scope.get(this._name)) === this) { // Do no other variables reference this variable? 3555 scope.delete(this._name); // Itâs safe to delete! 3556 } else if (found._type === TYPE_DUPLICATE) { // Do other variables assign this name? 3557 found._duplicates.delete(this); // This variable no longer assigns this name. 3558 this._duplicate = undefined; 3559 if (found._duplicates.size === 1) { // Is there now only one variable assigning this name? 3560 found = found._duplicates.keys().next().value; // Any references are now fixed! 3561 error = scope.get(this._name); 3562 found._outputs = error._outputs, error._outputs = new Set; 3563 found._outputs.forEach(function(output) { output._inputs[output._inputs.indexOf(error)] = found; }); 3564 found._definition = found._duplicate, found._duplicate = undefined; 3565 runtime._dirty.add(error).add(found); 3566 runtime._updates.add(found); 3567 scope.set(this._name, found); 3568 } 3569 } else { 3570 throw new Error; 3571 } 3572 } 3573 3574 if (this._outputs.size) throw new Error; 3575 3576 if (name) { // Does this variable have a new name? 3577 if (found = scope.get(name)) { // Do other variables reference or assign this name? 3578 if (found._type === TYPE_DUPLICATE) { // Do multiple other variables already define this name? 3579 this._definition = variable_duplicate(name), this._duplicate = definition; 3580 found._duplicates.add(this); 3581 } else if (found._type === TYPE_IMPLICIT) { // Are the variable references broken? 3582 this._outputs = found._outputs, found._outputs = new Set; // Now theyâre fixed! 3583 this._outputs.forEach(function(output) { output._inputs[output._inputs.indexOf(found)] = this; }, this); 3584 runtime._dirty.add(found).add(this); 3585 scope.set(name, this); 3586 } else { // Does another variable define this name? 3587 found._duplicate = found._definition, this._duplicate = definition; // Now theyâre duplicates. 3588 error = new Variable(TYPE_DUPLICATE, this._module); 3589 error._name = name; 3590 error._definition = this._definition = found._definition = variable_duplicate(name); 3591 error._outputs = found._outputs, found._outputs = new Set; 3592 error._outputs.forEach(function(output) { output._inputs[output._inputs.indexOf(found)] = error; }); 3593 error._duplicates = new Set([this, found]); 3594 runtime._dirty.add(found).add(error); 3595 runtime._updates.add(found).add(error); 3596 scope.set(name, error); 3597 } 3598 } else { 3599 scope.set(name, this); 3600 } 3601 } 3602 3603 this._name = name; 3604 } 3605 3606 // If this redefined variable was previously evaluated, invalidate it. (If the 3607 // variable was never evaluated, then the invalidated value could never have 3608 // been exposed and we can avoid this extra work.) 3609 if (this._version > 0) ++this._version; 3610 3611 runtime._updates.add(this); 3612 runtime._compute(); 3613 return this; 3614} 3615 3616function variable_import(remote, name, module) { 3617 if (arguments.length < 3) module = name, name = remote; 3618 return variable_defineImpl.call(this, String(name), [module._resolve(String(remote))], identity$1); 3619} 3620 3621function variable_delete() { 3622 return variable_defineImpl.call(this, null, [], noop); 3623} 3624 3625function variable_pending() { 3626 if (this._observer.pending) this._observer.pending(); 3627} 3628 3629function variable_fulfilled(value) { 3630 if (this._observer.fulfilled) this._observer.fulfilled(value, this._name); 3631} 3632 3633function variable_rejected(error) { 3634 if (this._observer.rejected) this._observer.rejected(error, this._name); 3635} 3636 3637const variable_variable = Symbol("variable"); 3638const variable_invalidation = Symbol("invalidation"); 3639const variable_visibility = Symbol("visibility"); 3640 3641function Module(runtime, builtins = []) { 3642 Object.defineProperties(this, { 3643 _runtime: {value: runtime}, 3644 _scope: {value: new Map}, 3645 _builtins: {value: new Map([ 3646 ["@variable", variable_variable],
3647 ["invalidation", variable_invalidation], 3648 ["visibility", variable_visibility], 3649 ...builtins 3650 ])}, 3651 _source: {value: null, writable: true} 3652 }); 3653} 3654 3655Object.defineProperties(Module.prototype, { 3656 _resolve: {value: module_resolve, writable: true, configurable: true}, 3657 redefine: {value: module_redefine, writable: true, configurable: true}, 3658 define: {value: module_define, writable: true, configurable: true}, 3659 derive: {value: module_derive, writable: true, configurable: true}, 3660 import: {value: module_import, writable: true, configurable: true}, 3661 value: {value: module_value, writable: true, configurable: true}, 3662 variable: {value: module_variable, writable: true, configurable: true}, 3663 builtin: {value: module_builtin, writable: true, configurable: true} 3664}); 3665 3666function module_redefine(name) { 3667 const v = this._scope.get(name); 3668 if (!v) throw new RuntimeError(`${name} is not defined`); 3669 if (v._type === TYPE_DUPLICATE) throw new RuntimeError(`${name} is defined more than once`); 3670 return v.define.apply(v, arguments); 3671} 3672 3673function module_define() { 3674 const v = new Variable(TYPE_NORMAL, this); 3675 return v.define.apply(v, arguments); 3676} 3677 3678function module_import() { 3679 const v = new Variable(TYPE_NORMAL, this); 3680 return v.import.apply(v, arguments); 3681} 3682 3683function module_variable(observer) { 3684 return new Variable(TYPE_NORMAL, this, observer); 3685} 3686 3687async function module_value(name) { 3688 let v = this._scope.get(name); 3689 if (!v) throw new RuntimeError(`${name} is not defined`); 3690 if (v._observer === no_observer) { 3691 v = this.variable(true).define([name], identity$1); 3692 try { 3693 return await module_revalue(this._runtime, v); 3694 } finally { 3695 v.delete(); 3696 } 3697 } else { 3698 return module_revalue(this._runtime, v); 3699 } 3700} 3701 3702// If the variable is redefined before its value resolves, try again. 3703async function module_revalue(runtime, variable) { 3704 await runtime._compute(); 3705 try { 3706 return await variable._promise; 3707 } catch (error) { 3708 if (error === variable_stale) return module_revalue(runtime, variable); 3709 throw error; 3710 } 3711} 3712 3713function module_derive(injects, injectModule) { 3714 const map = new Map(); 3715 const modules = new Set(); 3716 const copies = []; 3717 3718 // Given a module, derives an alias of that module with an initially-empty 3719 // definition. The variables will be copied later in a second pass below. 3720 function alias(source) { 3721 let target = map.get(source); 3722 if (target) return target; 3723 target = new Module(source._runtime, source._builtins); 3724 target._source = source; 3725 map.set(source, target); 3726 copies.push([target, source]); 3727 modules.add(source); 3728 return target; 3729 } 3730 3731 // Inject the given variables as reverse imports into the derived module. 3732 const derive = alias(this); 3733 for (const inject of injects) { 3734 const {alias, name} = typeof inject === "object" ? inject : {name: inject}; 3735 derive.import(name, alias == null ? name : alias, injectModule); 3736 } 3737 3738 // Iterate over all the variables (currently) in this module. If any 3739 // represents an import-with (i.e., an import of a module with a _source), the 3740 // transitive import-with must be copied, too, as direct injections may affect 3741 // transitive injections. Note that an import-with can only be created with 3742 // module.derive and hence itâs not possible for an import-with to be added 3743 // later; therefore we only need to apply this check once, now. 3744 for (const module of modules) { 3745 for (const [name, variable] of module._scope) { 3746 if (variable._definition === identity$1) { // import 3747 if (module === this && derive._scope.has(name)) continue; // overridden by injection 3748 const importedModule = variable._inputs[0]._module; 3749 if (importedModule._source) alias(importedModule); 3750 } 3751 } 3752 } 3753 3754 // Finally, with the modules resolved, copy the variable definitions. 3755 for (const [target, source] of copies) { 3756 for (const [name, sourceVariable] of source._scope) { 3757 const targetVariable = target._scope.get(name); 3758 if (targetVariable && targetVariable._type !== TYPE_IMPLICIT) continue; // preserve injection 3759 if (sourceVariable._definition === identity$1) { // import
3760 const sourceInput = sourceVariable._inputs[0]; 3761 const sourceModule = sourceInput._module; 3762 target.import(sourceInput._name, name, map.get(sourceModule) || sourceModule); 3763 } else { // non-import 3764 target.define(name, sourceVariable._inputs.map(variable_name), sourceVariable._definition); 3765 } 3766 } 3767 } 3768 3769 return derive; 3770} 3771 3772function module_resolve(name) { 3773 let variable = this._scope.get(name), value; 3774 if (!variable) { 3775 variable = new Variable(TYPE_IMPLICIT, this); 3776 if (this._builtins.has(name)) { 3777 variable.define(name, constant(this._builtins.get(name))); 3778 } else if (this._runtime._builtin._scope.has(name)) { 3779 variable.import(name, this._runtime._builtin); 3780 } else { 3781 try { 3782 value = this._runtime._global(name); 3783 } catch (error) { 3784 return variable.define(name, rethrow(error)); 3785 } 3786 if (value === undefined) { 3787 this._scope.set(variable._name = name, variable); 3788 } else { 3789 variable.define(name, constant(value)); 3790 } 3791 } 3792 } 3793 return variable; 3794} 3795 3796function module_builtin(name, value) { 3797 this._builtins.set(name, value); 3798} 3799 3800function variable_name(variable) { 3801 return variable._name; 3802} 3803 3804const frame = typeof requestAnimationFrame === "function" ? requestAnimationFrame 3805 : typeof setImmediate === "function" ? setImmediate 3806 : f => setTimeout(f, 0); 3807 3808function Runtime(builtins = new Library, global = window_global) { 3809 const builtin = this.module(); 3810 Object.defineProperties(this, { 3811 _dirty: {value: new Set}, 3812 _updates: {value: new Set}, 3813 _precomputes: {value: [], writable: true}, 3814 _computing: {value: null, writable: true}, 3815 _init: {value: null, writable: true}, 3816 _modules: {value: new Map}, 3817 _variables: {value: new Set}, 3818 _disposed: {value: false, writable: true}, 3819 _builtin: {value: builtin}, 3820 _global: {value: global} 3821 }); 3822 if (builtins) for (const name in builtins) { 3823 (new Variable(TYPE_IMPLICIT, builtin)).define(name, [], builtins[name]); 3824 } 3825} 3826 3827Object.defineProperties(Runtime.prototype, { 3828 _precompute: {value: runtime_precompute, writable: true, configurable: true}, 3829 _compute: {value: runtime_compute, writable: true, configurable: true}, 3830 _computeSoon: {value: runtime_computeSoon, writable: true, configurable: true}, 3831 _computeNow: {value: runtime_computeNow, writable: true, configurable: true}, 3832 dispose: {value: runtime_dispose, writable: true, configurable: true}, 3833 module: {value: runtime_module, writable: true, configurable: true}, 3834 fileAttachments: {value: FileAttachments, writable: true, configurable: true}, 3835 load: {value: load, writable: true, configurable: true} 3836}); 3837 3838function runtime_dispose() { 3839 this._computing = Promise.resolve(); 3840 this._disposed = true;
3841 this._variables.forEach(v => { 3842 v._invalidate(); 3843 v._version = NaN; 3844 }); 3845} 3846 3847function runtime_module(define, observer = noop) { 3848 let module; 3849 if (define === undefined) { 3850 if (module = this._init) { 3851 this._init = null; 3852 return module; 3853 } 3854 return new Module(this); 3855 } 3856 module = this._modules.get(define); 3857 if (module) return module; 3858 this._init = module = new Module(this); 3859 this._modules.set(define, module); 3860 try { 3861 define(this, observer); 3862 } finally { 3863 this._init = null; 3864 } 3865 return module; 3866} 3867 3868function runtime_precompute(callback) { 3869 this._precomputes.push(callback); 3870 this._compute(); 3871} 3872 3873function runtime_compute() { 3874 return this._computing || (this._computing = this._computeSoon()); 3875} 3876 3877function runtime_computeSoon() { 3878 return new Promise(frame).then(() => this._disposed ? undefined : this._computeNow()); 3879} 3880 3881async function runtime_computeNow() { 3882 let queue = [], 3883 variables, 3884 variable, 3885 precomputes = this._precomputes; 3886 3887 // If there are any paused generators, resume them before computing so they 3888 // can update (if synchronous) before computing downstream variables. 3889 if (precomputes.length) { 3890 this._precomputes = []; 3891 for (const callback of precomputes) callback(); 3892 await runtime_defer(3); 3893 } 3894 3895 // Compute the reachability of the transitive closure of dirty variables. 3896 // Any newly-reachable variable must also be recomputed. 3897 // Any no-longer-reachable variable must be terminated. 3898 variables = new Set(this._dirty);
3899 variables.forEach(function(variable) { 3900 variable._inputs.forEach(variables.add, variables); 3901 const reachable = variable_reachable(variable); 3902 if (reachable > variable._reachable) { 3903 this._updates.add(variable); 3904 } else if (reachable < variable._reachable) { 3905 variable._invalidate(); 3906 } 3907 variable._reachable = reachable; 3908 }, this); 3909 3910 // Compute the transitive closure of updating, reachable variables. 3911 variables = new Set(this._updates); 3912 variables.forEach(function(variable) { 3913 if (variable._reachable) { 3914 variable._indegree = 0; 3915 variable._outputs.forEach(variables.add, variables); 3916 } else { 3917 variable._indegree = NaN; 3918 variables.delete(variable); 3919 } 3920 }); 3921 3922 this._computing = null; 3923 this._updates.clear(); 3924 this._dirty.clear(); 3925 3926 // Compute the indegree of updating variables. 3927 variables.forEach(function(variable) { 3928 variable._outputs.forEach(variable_increment); 3929 }); 3930 3931 do { 3932 // Identify the root variables (those with no updating inputs). 3933 variables.forEac
3933h(function(variable) { 3934 if (variable._indegree === 0) { 3935 queue.push(variable); 3936 } 3937 }); 3938 3939 // Compute the variables in topological order. 3940 while (variable = queue.pop()) { 3941 variable_compute(variable); 3942 variable._outputs.forEach(postqueue); 3943 variables.delete(variable); 3944 } 3945 3946 // Any remaining variables are circular, or depend on them. 3947 variables.forEach(function(variable) { 3948 if (variable_circular(variable)) { 3949 variable_error(variable, new RuntimeError("circular definition")); 3950 variable._outputs.forEach(variable_decrement); 3951 variables.delete(variable); 3952 } 3953 }); 3954 } while (variables.size); 3955 3956 function postqueue(variable) { 3957 if (--variable._indegree === 0) { 3958 queue.push(variable); 3959 } 3960 } 3961} 3962 3963// We want to give generators, if theyâre defined synchronously, a chance to 3964// update before computing downstream variables. This creates a synchronous 3965// promise chain of the given depth that weâll await before recomputing 3966// downstream variables. 3967function runtime_defer(depth = 0) { 3968 let p = Promise.resolve(); 3969 for (let i = 0; i < depth; ++i) p = p.then(() => {}); 3970 return p; 3971} 3972 3973function variable_circular(variable) { 3974 const inputs = new Set(variable._inputs); 3975 for (const i of inputs) { 3976 if (i === variable) return true; 3977 i._inputs.forEach(inputs.add, inputs); 3978 } 3979 return false; 3980} 3981 3982function variable_increment(variable) { 3983 ++variable._indegree; 3984} 3985 3986function variable_decrement(variable) { 3987 --variable._indegree; 3988} 3989 3990function variable_value(variable) { 3991 return variable._promise.catch(variable._rejector); 3992} 3993 3994function variable_invalidator(variable) { 3995 return new Promise(function(resolve) { 3996 variable._invalidate = resolve; 3997 }); 3998} 3999 4000function variable_intersector(invalidation, variable) { 4001 let node = typeof IntersectionObserver === "function" && variable._observer && variable._observer._node; 4002 let visible = !node, resolve = noop, reject = noop, promise, observer; 4003 if (node) { 4004 observer = new IntersectionObserver(([entry]) => (visible = entry.isIntersecting) && (promise = null, resolve())); 4005 observer.observe(node); 4006 invalidation.then(() => (observer.disconnect(), observer = null, reject())); 4007 } 4008 return function(value) { 4009 if (visible) return Promise.resolve(value); 4010 if (!observer) return Promise.reject(); 4011 if (!promise) promise = new Promise((y, n) => (resolve = y, reject = n)); 4012 return promise.then(() => value); 4013 }; 4014} 4015 4016function variable_compute(variable) { 4017 variable._invalidate(); 4018 variable._invalidate = noop; 4019 variable._pending(); 4020 4021 const value0 = variable._value; 4022 const version = ++variable._version; 4023 4024 // Lazily-constructed invalidation variable; only constructed if referenced as an input. 4025 let invalidation = null; 4026 4027 // If the variable doesnât have any inputs, we can optimize slightly. 4028 const promise = variable._promise = (variable._inputs.length 4029 ? Promise.all(variable._inputs.map(variable_value)).then(define) 4030 : new Promise(resolve => resolve(variable._definition.call(value0)))) 4031 .then(generate); 4032 4033 // Compute the initial value of the variable. 4034 function define(inputs) { 4035 if (variable._version !== version) throw variable_stale; 4036 4037 // Replace any reference to invalidation with the promise, lazily. 4038 for (let i = 0, n = inputs.length; i < n; ++i) { 4039 switch (inputs[i]) { 4040 case variable_invalidation: { 4041 inputs[i] = invalidation = variable_invalidator(variable); 4042 break; 4043 } 4044 case variable_visibility: { 4045 if (!invalidation) invalidation = variable_invalidator(variable); 4046 inputs[i] = variable_intersector(invalidation, variable); 4047 break; 4048 } 4049 case variable_variable: { 4050 inputs[i] = variable; 4051 break; 4052 } 4053 } 4054 } 4055 4056 return variable._definition.apply(value0, inputs); 4057 } 4058 4059 // If the value is a generator, then retrieve its first value, and dispose of 4060 // the generator if the variable is invalidated. Note that the cell may 4061 // already have been invalidated here, in which case we need to terminate the 4062 // generator immediately! 4063 function generate(value) { 4064 if (variable._version !== version) throw variable_stale; 4065 if (generatorish(value)) { 4066 (invalidation || variable_invalidator(variable)).then(variable_return(value)); 4067 return variable_generate(variable, version, value); 4068 } 4069 return value; 4070 } 4071 4072 promise.then((value) => { 4073 variable._value = value; 4074 variable._fulfilled(value); 4075 }, (error) => { 4076 if (error === variable_stale) return; 4077 variable._value = undefined; 4078 variable._rejected(error); 4079 }); 4080} 4081 4082function variable_generate(variable, version, generator) { 4083 const runtime = variable._module._runtime; 4084 let currentValue; // so that yield resolves to the yielded value 4085 4086 // Retrieve the next value from the generator; if successful, invoke the 4087 // specified callback. The returned promise resolves to the yielded value, or 4088 // to undefined if the generator is done. 4089 function compute(onfulfilled) { 4090 return new Promise(resolve => resolve(generator.next(currentValue))).then(({done, value}) => { 4091 return done ? undefined : Promise.resolve(value).then(onfulfilled); 4092 }); 4093 } 4094 4095 // Retrieve the next value from the generator; if successful, fulfill the 4096 // variable, compute downstream variables, and schedule the next value to be 4097 // pulled from the generator at the start of the next animation frame. If not 4098 // successful, reject the variable, compute downstream variables, and return. 4099 function recompute() { 4100 const promise = compute((value) => { 4101 if (variable._version !== version) throw variable_stale; 4102 currentValue = value; 4103 postcompute(value, promise).then(() => runtime._precompute(recompute)); 4104 variable._fulfilled(value); 4105 return value; 4106 }); 4107 promise.catch((error) => { 4108 if (error === variable_stale || variable._version !== version) return; 4109 postcompute(undefined, promise); 4110 variable._rejected(error); 4111 }); 4112 } 4113 4114 // After the generator fulfills or rejects, set its current value, promise, 4115 // and schedule any downstream variables for update. 4116 function postcompute(value, promise) { 4117 variable._value = value; 4118 variable._promise = promise;
4119 variable._outputs.forEach(runtime._updates.add, runtime._updates); 4120 return runtime._compute(); 4121 } 4122 4123 // When retrieving the first value from the generator, the promise graph is 4124 // already established, so we only need to queue the next pull. 4125 return compute((value) => { 4126 if (variable._version !== version) throw variable_stale; 4127 currentValue = value; 4128 runtime._precompute(recompute); 4129 return value; 4130 }); 4131} 4132 4133function variable_error(variable, error) { 4134 variable._invalidate(); 4135 variable._invalidate = noop; 4136 variable._pending(); 4137 ++variable._version; 4138 variable._indegree = NaN; 4139 (variable._promise = Promise.reject(error)).catch(noop); 4140 variable._value = undefined; 4141 variable._rejected(error); 4142} 4143 4144function variable_return(generator) { 4145 return function() { 4146 generator.return(); 4147 }; 4148} 4149 4150function variable_reachable(variable) { 4151 if (variable._observer !== no_observer) return true; // Directly reachable. 4152 const outputs = new Set(variable._outputs); 4153 for (const output of outputs) { 4154 if (output._observer !== no_observer) return true; 4155 output._outputs.forEach(outputs.add, outputs); 4156 } 4157 return false; 4158} 4159 4160function window_global(name) { 4161 return globalThis[name]; 4162} 4163 4164function renderHtml(string) { 4165 const template = document.createElement("template"); 4166 template.innerHTML = string; 4167 return document.importNode(template.content, true); 4168} 4169
4170function renderSvg(string) { 4171 const g = document.createElementNS("http://www.w3.org/2000/svg", "g"); 4172 g.innerHTML = string; 4173 return g; 4174} 4175 4176const html = Object.assign(hypertext(renderHtml, fragment => { 4177 if (fragment.firstChild === null) return null; 4178 if (fragment.firstChild === fragment.lastChild) return fragment.removeChild(fragment.firstChild); 4179 const span = document.createElement("span"); 4180 span.appendChild(fragment); 4181 return span; 4182}), {fragment: hypertext(renderHtml, fragment => fragment)}); 4183 4184Object.assign(hypertext(renderSvg, g => { 4185 if (g.firstChild === null) return null; 4186 if (g.firstChild === g.lastChild) return g.removeChild(g.firstChild); 4187 return g; 4188}), {fragment: hypertext(renderSvg, g => { 4189 const fragment = document.createDocumentFragment(); 4190 while (g.firstChild) fragment.appendChild(g.firstChild); 4191 return fragment; 4192})}); 4193 4194const 4195CODE_TAB = 9, 4196CODE_LF = 10, 4197CODE_FF = 12, 4198CODE_CR = 13, 4199CODE_SPACE = 32, 4200CODE_UPPER_A = 65, 4201CODE_UPPER_Z = 90, 4202CODE_LOWER_A = 97, 4203CODE_LOWER_Z = 122, 4204CODE_LT = 60, 4205CODE_GT = 62, 4206CODE_SLASH = 47, 4207CODE_DASH = 45, 4208CODE_BANG = 33, 4209CODE_EQ = 61, 4210CODE_DQUOTE = 34, 4211CODE_SQUOTE = 39, 4212CODE_QUESTION = 63, 4213STATE_DATA = 1, 4214STATE_TAG_OPEN = 2, 4215STATE_END_TAG_OPEN = 3, 4216STATE_TAG_NAME = 4, 4217STATE_BOGUS_COMMENT = 5, 4218STATE_BEFORE_ATTRIBUTE_NAME = 6, 4219STATE_AFTER_ATTRIBUTE_NAME = 7, 4220STATE_ATTRIBUTE_NAME = 8, 4221STATE_BEFORE_ATTRIBUTE_VALUE = 9, 4222STATE_ATTRIBUTE_VALUE_DOUBLE_QUOTED = 10, 4223STATE_ATTRIBUTE_VALUE_SINGLE_QUOTED = 11, 4224STATE_ATTRIBUTE_VALUE_UNQUOTED = 12, 4225STATE_AFTER_ATTRIBUTE_VALUE_QUOTED = 13, 4226STATE_SELF_CLOSING_START_TAG = 14, 4227STATE_COMMENT_START = 15, 4228STATE_COMMENT_START_DASH = 16, 4229STATE_COMMENT = 17, 4230STATE_COMMENT_LESS_THAN_SIGN = 18, 4231STATE_COMMENT_LESS_THAN_SIGN_BANG = 19, 4232STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH = 20, 4233STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH = 21, 4234STATE_COMMENT_END_DASH = 22, 4235STATE_COMMENT_END = 23, 4236STATE_COMMENT_END_BANG = 24, 4237STATE_MARKUP_DECLARATION_OPEN = 25, 4238STATE_RAWTEXT = 26, 4239STATE_RAWTEXT_LESS_THAN_SIGN = 27, 4240STATE_RAWTEXT_END_TAG_OPEN = 28, 4241STATE_RAWTEXT_END_TAG_NAME = 29, 4242SHOW_COMMENT = 128, 4243SHOW_ELEMENT = 1, 4244TYPE_COMMENT = 8, 4245TYPE_ELEMENT = 1, 4246NS_SVG = "http://www.w3.org/2000/svg", 4247NS_XLINK = "http://www.w3.org/1999/xlink", 4248NS_XML = "http://www.w3.org/XML/1998/namespace", 4249NS_XMLNS = "http://www.w3.org/2000/xmlns/"; 4250 4251const svgAdjustAttributes = new Map([ 4252 "attributeName", 4253 "attributeType", 4254 "baseFrequency", 4255 "baseProfile", 4256 "calcMode", 4257 "clipPathUnits", 4258 "diffuseConstant", 4259 "edgeMode", 4260 "filterUnits", 4261 "glyphRef", 4262 "gradientTransform", 4263 "gradientUnits", 4264 "kernelMatrix", 4265 "kernelUnitLength", 4266 "keyPoints", 4267 "keySplines", 4268 "keyTimes", 4269 "lengthAdjust", 4270 "limitingConeAngle", 4271 "markerHeight", 4272 "markerUnits", 4273 "markerWidth", 4274 "maskContentUnits", 4275 "maskUnits", 4276 "numOctaves", 4277 "pathLength", 4278 "patternContentUnits", 4279 "patternTransform", 4280 "patternUnits", 4281 "pointsAtX", 4282 "pointsAtY", 4283 "pointsAtZ", 4284 "preserveAlpha", 4285 "preserveAspectRatio", 4286 "primitiveUnits", 4287 "refX", 4288 "refY", 4289 "repeatCount", 4290 "repeatDur", 4291 "requiredExtensions", 4292 "requiredFeatures", 4293 "specularConstant", 4294 "specularExponent", 4295 "spreadMethod", 4296 "startOffset", 4297 "stdDeviation", 4298 "stitchTiles", 4299 "surfaceScale", 4300 "systemLanguage", 4301 "tableValues", 4302 "targetX", 4303 "targetY", 4304 "textLength", 4305 "viewBox", 4306 "viewTarget", 4307 "xChannelSelector", 4308 "yChannelSelector", 4309 "zoomAndPan" 4310].map(name => [name.toLowerCase(), name])); 4311 4312const svgForeignAttributes = new Map([ 4313 ["xlink:actuate", NS_XLINK], 4314 ["xlink:arcrole", NS_XLINK], 4315 ["xlink:href", NS_XLINK], 4316 ["xlink:role", NS_XLINK], 4317 ["xlink:show", NS_XLINK], 4318 ["xlink:title", NS_XLINK], 4319 ["xlink:type", NS_XLINK], 4320 ["xml:lang", NS_XML], 4321 ["xml:space", NS_XML], 4322 ["xmlns", NS_XMLNS], 4323 ["xmlns:xlink", NS_XMLNS] 4324]); 4325 4326function hypertext(render, postprocess) { 4327 return function({raw: strings}) { 4328 let state = STATE_DATA; 4329 let string = ""; 4330 let tagNameStart; // either an open tag or an end tag 4331 let tagName; // only open; beware nesting! used only for rawtext 4332 let attributeNameStart; 4333 let attributeNameEnd; 4334 let nodeFilter = 0; 4335 4336 for (let j = 0, m = arguments.length; j < m; ++j) { 4337 const input = strings[j]; 4338 4339 if (j > 0) { 4340 const value = arguments[j]; 4341 switch (state) { 4342 case STATE_RAWTEXT: { 4343 if (value != null) { 4344 const text = `${value}`; 4345 if (isEscapableRawText(tagName)) {
vendor: 12,226 bytes, lines 4346-4688
4346 string += text.replace(/[<]/g, entity); 4347 } else if (new RegExp(`</${tagName}[\\s>/]`, "i").test(string.slice(-tagName.length - 2) + text)) { 4348 throw new Error("unsafe raw text"); // appropriate end tag 4349 } else { 4350 string += text; 4351 } 4352 } 4353 break; 4354 } 4355 case STATE_DATA: { 4356 if (value == null) ; else if (value instanceof Node 4357 || (typeof value !== "string" && value[Symbol.iterator]) 4358 || (/(?:^|>)$/.test(strings[j - 1]) && /^(?:<|$)/.test(input))) { 4359 string += "<!--::" + j + "-->"; 4360 nodeFilter |= SHOW_COMMENT; 4361 } else { 4362 string += `${value}`.replace(/[<&]/g, entity); 4363 } 4364 break; 4365 } 4366 case STATE_BEFORE_ATTRIBUTE_VALUE: { 4367 state = STATE_ATTRIBUTE_VALUE_UNQUOTED; 4368 let text; 4369 if (/^[\s>]/.test(input)) { 4370 if (value == null || value === false) { 4371 string = string.slice(0, attributeNameStart - strings[j - 1].length); 4372 break; 4373 } 4374 if (value === true || (text = `${value}`) === "") { 4375 string += "''"; 4376 break; 4377 } 4378 const name = strings[j - 1].slice(attributeNameStart, attributeNameEnd); 4379 if ((name === "style" && isObjectLiteral(value)) || typeof value === "function") { 4380 string += "::" + j; 4381 nodeFilter |= SHOW_ELEMENT; 4382 break; 4383 } 4384 } 4385 if (text === undefined) text = `${value}`; 4386 if (text === "") throw new Error("unsafe unquoted empty string"); 4387 string += text.replace(/^['"]|[\s>&]/g, entity); 4388 break; 4389 } 4390 case STATE_ATTRIBUTE_VALUE_UNQUOTED: { 4391 string += `${value}`.replace(/[\s>&]/g, entity); 4392 break; 4393 } 4394 case STATE_ATTRIBUTE_VALUE_SINGLE_QUOTED: { 4395 string += `${value}`.replace(/['&]/g, entity); 4396 break; 4397 } 4398 case STATE_ATTRIBUTE_VALUE_DOUBLE_QUOTED: { 4399 string += `${value}`.replace(/["&]/g, entity); 4400 break; 4401 } 4402 case STATE_BEFORE_ATTRIBUTE_NAME: { 4403 if (isObjectLiteral(value)) { 4404 string += "::" + j + "=''"; 4405 nodeFilter |= SHOW_ELEMENT; 4406 break; 4407 } 4408 throw new Error("invalid binding"); 4409 } 4410 case STATE_COMMENT: break; 4411 default: throw new Error("invalid binding"); 4412 } 4413 } 4414 4415 for (let i = 0, n = input.length; i < n; ++i) { 4416 const code = input.charCodeAt(i); 4417 4418 switch (state) { 4419 case STATE_DATA: { 4420 if (code === CODE_LT) { 4421 state = STATE_TAG_OPEN; 4422 } 4423 break; 4424 } 4425 case STATE_TAG_OPEN: { 4426 if (code === CODE_BANG) { 4427 state = STATE_MARKUP_DECLARATION_OPEN; 4428 } else if (code === CODE_SLASH) { 4429 state = STATE_END_TAG_OPEN; 4430 } else if (isAsciiAlphaCode(code)) { 4431 tagNameStart = i, tagName = undefined; 4432 state = STATE_TAG_NAME, --i; 4433 } else if (code === CODE_QUESTION) { 4434 state = STATE_BOGUS_COMMENT, --i; 4435 } else { 4436 state = STATE_DATA, --i; 4437 } 4438 break; 4439 } 4440 case STATE_END_TAG_OPEN: { 4441 if (isAsciiAlphaCode(code)) { 4442 state = STATE_TAG_NAME, --i; 4443 } else if (code === CODE_GT) { 4444 state = STATE_DATA; 4445 } else { 4446 state = STATE_BOGUS_COMMENT, --i; 4447 } 4448 break; 4449 } 4450 case STATE_TAG_NAME: { 4451 if (isSpaceCode(code)) { 4452 state = STATE_BEFORE_ATTRIBUTE_NAME; 4453 tagName = lower(input, tagNameStart, i); 4454 } else if (code === CODE_SLASH) { 4455 state = STATE_SELF_CLOSING_START_TAG; 4456 } else if (code === CODE_GT) { 4457 tagName = lower(input, tagNameStart, i); 4458 state = isRawText(tagName) ? STATE_RAWTEXT : STATE_DATA; 4459 } 4460 break; 4461 } 4462 case STATE_BEFORE_ATTRIBUTE_NAME: { 4463 if (isSpaceCode(code)) ; else if (code === CODE_SLASH || code === CODE_GT) { 4464 state = STATE_AFTER_ATTRIBUTE_NAME, --i; 4465 } else if (code === CODE_EQ) { 4466 state = STATE_ATTRIBUTE_NAME; 4467 attributeNameStart = i + 1, attributeNameEnd = undefined; 4468 } else { 4469 state = STATE_ATTRIBUTE_NAME, --i; 4470 attributeNameStart = i + 1, attributeNameEnd = undefined; 4471 } 4472 break; 4473 } 4474 case STATE_ATTRIBUTE_NAME: { 4475 if (isSpaceCode(code) || code === CODE_SLASH || code === CODE_GT) { 4476 state = STATE_AFTER_ATTRIBUTE_NAME, --i; 4477 attributeNameEnd = i; 4478 } else if (code === CODE_EQ) { 4479 state = STATE_BEFORE_ATTRIBUTE_VALUE; 4480 attributeNameEnd = i; 4481 } 4482 break; 4483 } 4484 case STATE_AFTER_ATTRIBUTE_NAME: { 4485 if (isSpaceCode(code)) ; else if (code === CODE_SLASH) { 4486 state = STATE_SELF_CLOSING_START_TAG; 4487 } else if (code === CODE_EQ) { 4488 state = STATE_BEFORE_ATTRIBUTE_VALUE; 4489 } else if (code === CODE_GT) { 4490 state = isRawText(tagName) ? STATE_RAWTEXT : STATE_DATA; 4491 } else { 4492 state = STATE_ATTRIBUTE_NAME, --i; 4493 attributeNameStart = i + 1, attributeNameEnd = undefined; 4494 } 4495 break; 4496 } 4497 case STATE_BEFORE_ATTRIBUTE_VALUE: { 4498 if (isSpaceCode(code)) ; else if (code === CODE_DQUOTE) { 4499 state = STATE_ATTRIBUTE_VALUE_DOUBLE_QUOTED; 4500 } else if (code === CODE_SQUOTE) { 4501 state = STATE_ATTRIBUTE_VALUE_SINGLE_QUOTED; 4502 } else if (code === CODE_GT) { 4503 state = isRawText(tagName) ? STATE_RAWTEXT : STATE_DATA; 4504 } else { 4505 state = STATE_ATTRIBUTE_VALUE_UNQUOTED, --i; 4506 } 4507 break; 4508 } 4509 case STATE_ATTRIBUTE_VALUE_DOUBLE_QUOTED: { 4510 if (code === CODE_DQUOTE) { 4511 state = STATE_AFTER_ATTRIBUTE_VALUE_QUOTED; 4512 } 4513 break; 4514 } 4515 case STATE_ATTRIBUTE_VALUE_SINGLE_QUOTED: { 4516 if (code === CODE_SQUOTE) { 4517 state = STATE_AFTER_ATTRIBUTE_VALUE_QUOTED; 4518 } 4519 break; 4520 } 4521 case STATE_ATTRIBUTE_VALUE_UNQUOTED: { 4522 if (isSpaceCode(code)) { 4523 state = STATE_BEFORE_ATTRIBUTE_NAME; 4524 } else if (code === CODE_GT) { 4525 state = isRawText(tagName) ? STATE_RAWTEXT : STATE_DATA; 4526 } 4527 break; 4528 } 4529 case STATE_AFTER_ATTRIBUTE_VALUE_QUOTED: { 4530 if (isSpaceCode(code)) { 4531 state = STATE_BEFORE_ATTRIBUTE_NAME; 4532 } else if (code === CODE_SLASH) { 4533 state = STATE_SELF_CLOSING_START_TAG; 4534 } else if (code === CODE_GT) { 4535 state = isRawText(tagName) ? STATE_RAWTEXT : STATE_DATA; 4536 } else { 4537 state = STATE_BEFORE_ATTRIBUTE_NAME, --i; 4538 } 4539 break; 4540 } 4541 case STATE_SELF_CLOSING_START_TAG: { 4542 if (code === CODE_GT) { 4543 state = STATE_DATA; 4544 } else { 4545 state = STATE_BEFORE_ATTRIBUTE_NAME, --i; 4546 } 4547 break; 4548 } 4549 case STATE_BOGUS_COMMENT: { 4550 if (code === CODE_GT) { 4551 state = STATE_DATA; 4552 } 4553 break; 4554 } 4555 case STATE_COMMENT_START: { 4556 if (code === CODE_DASH) { 4557 state = STATE_COMMENT_START_DASH; 4558 } else if (code === CODE_GT) { 4559 state = STATE_DATA; 4560 } else { 4561 state = STATE_COMMENT, --i; 4562 } 4563 break; 4564 } 4565 case STATE_COMMENT_START_DASH: { 4566 if (code === CODE_DASH) { 4567 state = STATE_COMMENT_END; 4568 } else if (code === CODE_GT) { 4569 state = STATE_DATA; 4570 } else { 4571 state = STATE_COMMENT, --i; 4572 } 4573 break; 4574 } 4575 case STATE_COMMENT: { 4576 if (code === CODE_LT) { 4577 state = STATE_COMMENT_LESS_THAN_SIGN; 4578 } else if (code === CODE_DASH) { 4579 state = STATE_COMMENT_END_DASH; 4580 } 4581 break; 4582 } 4583 case STATE_COMMENT_LESS_THAN_SIGN: { 4584 if (code === CODE_BANG) { 4585 state = STATE_COMMENT_LESS_THAN_SIGN_BANG; 4586 } else if (code !== CODE_LT) { 4587 state = STATE_COMMENT, --i; 4588 } 4589 break; 4590 } 4591 case STATE_COMMENT_LESS_THAN_SIGN_BANG: { 4592 if (code === CODE_DASH) { 4593 state = STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH; 4594 } else { 4595 state = STATE_COMMENT, --i; 4596 } 4597 break; 4598 } 4599 case STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH: { 4600 if (code === CODE_DASH) { 4601 state = STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH; 4602 } else { 4603 state = STATE_COMMENT_END, --i; 4604 } 4605 break; 4606 } 4607 case STATE_COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH: { 4608 state = STATE_COMMENT_END, --i; 4609 break; 4610 } 4611 case STATE_COMMENT_END_DASH: { 4612 if (code === CODE_DASH) { 4613 state = STATE_COMMENT_END; 4614 } else { 4615 state = STATE_COMMENT, --i; 4616 } 4617 break; 4618 } 4619 case STATE_COMMENT_END: { 4620 if (code === CODE_GT) { 4621 state = STATE_DATA; 4622 } else if (code === CODE_BANG) { 4623 state = STATE_COMMENT_END_BANG; 4624 } else if (code !== CODE_DASH) { 4625 state = STATE_COMMENT, --i; 4626 } 4627 break; 4628 } 4629 case STATE_COMMENT_END_BANG: { 4630 if (code === CODE_DASH) { 4631 state = STATE_COMMENT_END_DASH; 4632 } else if (code === CODE_GT) { 4633 state = STATE_DATA; 4634 } else { 4635 state = STATE_COMMENT, --i; 4636 } 4637 break; 4638 } 4639 case STATE_MARKUP_DECLARATION_OPEN: { 4640 if (code === CODE_DASH && input.charCodeAt(i + 1) === CODE_DASH) { 4641 state = STATE_COMMENT_START, ++i; 4642 } else { // Note: CDATA and DOCTYPE unsupported! 4643 state = STATE_BOGUS_COMMENT, --i; 4644 } 4645 break; 4646 } 4647 case STATE_RAWTEXT: { 4648 if (code === CODE_LT) { 4649 state = STATE_RAWTEXT_LESS_THAN_SIGN; 4650 } 4651 break; 4652 } 4653 case STATE_RAWTEXT_LESS_THAN_SIGN: { 4654 if (code === CODE_SLASH) { 4655 state = STATE_RAWTEXT_END_TAG_OPEN; 4656 } else { 4657 state = STATE_RAWTEXT, --i; 4658 } 4659 break; 4660 } 4661 case STATE_RAWTEXT_END_TAG_OPEN: { 4662 if (isAsciiAlphaCode(code)) { 4663 tagNameStart = i; 4664 state = STATE_RAWTEXT_END_TAG_NAME, --i; 4665 } else { 4666 state = STATE_RAWTEXT, --i; 4667 } 4668 break; 4669 } 4670 case STATE_RAWTEXT_END_TAG_NAME: { 4671 if (isSpaceCode(code) && tagName === lower(input, tagNameStart, i)) { 4672 state = STATE_BEFORE_ATTRIBUTE_NAME; 4673 } else if (code === CODE_SLASH && tagName === lower(input, tagNameStart, i)) { 4674 state = STATE_SELF_CLOSING_START_TAG; 4675 } else if (code === CODE_GT && tagName === lower(input, tagNameStart, i)) { 4676 state = STATE_DATA; 4677 } else if (!isAsciiAlphaCode(code)) { 4678 state = STATE_RAWTEXT, --i; 4679 } 4680 break; 4681 } 4682 default: { 4683 state = undefined; 4684 break; 4685 } 4686 } 4687 } 4688
4689 string += input; 4690 } 4691 4692 const root = render(string); 4693 4694 const walker = document.createTreeWalker(root, nodeFilter, null, false); 4695 const removeNodes = []; 4696 while (walker.nextNode()) { 4697 const node = walker.currentNode; 4698 switch (node.nodeType) { 4699 case TYPE_ELEMENT: { 4700 const attributes = node.attributes; 4701 for (let i = 0, n = attributes.length; i < n; ++i) { 4702 const {name, value: currentValue} = attributes[i]; 4703 if (/^::/.test(name)) { 4704 const value = arguments[+name.slice(2)]; 4705 removeAttribute(node, name), --i, --n; 4706 for (const key in value) { 4707 const subvalue = value[key]; 4708 if (subvalue == null || subvalue === false) ; else if (typeof subvalue === "function") { 4709 node[key] = subvalue; 4710 } else if (key === "style" && isObjectLiteral(subvalue)) { 4711 setStyles(node[key], subvalue); 4712 } else { 4713 setAttribute(node, key, subvalue === true ? "" : subvalue); 4714 } 4715 } 4716 } else if (/^::/.test(currentValue)) { 4717 const value = arguments[+currentValue.slice(2)]; 4718 removeAttribute(node, name), --i, --n; 4719 if (typeof value === "function") { 4720 node[name] = value; 4721 } else { // style 4722 setStyles(node[name], value); 4723 } 4724 } 4725 } 4726 break; 4727 } 4728 case TYPE_COMMENT: { 4729 if (/^::/.test(node.data)) { 4730 const parent = node.parentNode; 4731 const value = arguments[+node.data.slice(2)]; 4732 if (value instanceof Node) { 4733 parent.insertBefore(value, node); 4734 } else if (typeof value !== "string" && value[Symbol.iterator]) { 4735 if (value instanceof NodeList || value instanceof HTMLCollection) { 4736 for (let i = value.length - 1, r = node; i >= 0; --i) { 4737 r = parent.insertBefore(value[i], r); 4738 } 4739 } else { 4740 for (const subvalue of value) { 4741 if (subvalue == null) continue; 4742 parent.insertBefore(subvalue instanceof Node ? subvalue : document.createTextNode(subvalue), node); 4743 } 4744 } 4745 } else { 4746 parent.insertBefore(document.createTextNode(value), node); 4747 } 4748 removeNodes.push(node); 4749 } 4750 break; 4751 } 4752 } 4753 } 4754 4755 for (const node of removeNodes) { 4756 node.parentNode.removeChild(node); 4757 } 4758 4759 return postprocess(root); 4760 }; 4761} 4762 4763function entity(character) { 4764 return `&#${character.charCodeAt(0).toString()};`; 4765} 4766 4767function isAsciiAlphaCode(code) { 4768 return (CODE_UPPER_A <= code && code <= CODE_UPPER_Z) 4769 || (CODE_LOWER_A <= code && code <= CODE_LOWER_Z); 4770} 4771 4772function isSpaceCode(code) { 4773 return code === CODE_TAB 4774 || code === CODE_LF 4775 || code === CODE_FF 4776 || code === CODE_SPACE 4777 || code === CODE_CR; // normalize newlines 4778} 4779 4780function isObjectLiteral(value) { 4781 return value && value.toString === Object.prototype.toString; 4782} 4783 4784function isRawText(tagName) { 4785 return tagName === "script" || tagName === "style" || isEscapableRawText(tagName); 4786} 4787 4788function isEscapableRawText(tagName) { 4789 return tagName === "textarea" || tagName === "title"; 4790} 4791 4792function lower(input, start, end) { 4793 return input.slice(start, end).toLowerCase(); 4794} 4795 4796function setAttribute(node, name, value) { 4797 if (node.namespaceURI === NS_SVG) { 4798 name = name.toLowerCase(); 4799 name = svgAdjustAttributes.get(name) || name; 4800 if (svgForeignAttributes.has(name)) { 4801 node.setAttributeNS(svgForeignAttributes.get(name), name, value); 4802 return; 4803 } 4804 } 4805 node.setAttribute(name, value); 4806} 4807 4808function removeAttribute(node, name) { 4809 if (node.namespaceURI === NS_SVG) { 4810 name = name.toLowerCase(); 4811 name = svgAdjustAttributes.get(name) || name; 4812 if (svgForeignAttributes.has(name)) { 4813 node.removeAttributeNS(svgForeignAttributes.get(name), name); 4814 return; 4815 } 4816 } 4817 node.removeAttribute(name); 4818} 4819 4820// We canât use Object.assign because custom properties⦠4821function setStyles(style, values) { 4822 for (const name in values) { 4823 const value = values[name]; 4824 if (name.startsWith("--")) style.setProperty(name, value); 4825 else style[name] = value; 4826 } 4827} 4828 4829function length(x) { 4830 return x == null ? null : typeof x === "number" ? `${x}px` : `${x}`; 4831} 4832 4833const bubbles = {bubbles: true}; 4834 4835function preventDefault(event) { 4836 event.preventDefault(); 4837} 4838 4839function dispatchInput({currentTarget}) { 4840 (currentTarget.form || currentTarget).dispatchEvent(new Event("input", bubbles)); 4841} 4842 4843function identity(x) { 4844 return x; 4845} 4846 4847let nextId = 0; 4848 4849function newId() { 4850 return `__ns__-${++nextId}`; 4851} 4852 4853function maybeLabel(label, input) { 4854 if (!label) return; 4855 label = html`<label>${label}`; 4856 if (input !== undefined) label.htmlFor = input.id = newId(); 4857 return label; 4858} 4859 4860function button(content = "â¡", { 4861 label = "", 4862 value, 4863 reduce, 4864 disabled, 4865 required = false, 4866 width 4867} = {}) { 4868 const solitary = typeof content === "string" || content instanceof Node; 4869 if (solitary) { 4870 if (!required && value === undefined) value = 0; 4871 if (reduce === undefined) reduce = (value = 0) => value + 1; 4872 disabled = new Set(disabled ? [content] : []); 4873 content = [[content, reduce]]; 4874 } else { 4875 if (!required && value === undefined) value = null; 4876 disabled = new Set(disabled === true ? Array.from(content, ([content]) => content) : disabled || undefined); 4877 } 4878 const form = html`<form class=__ns__ onsubmit=${preventDefault}>`; 4879 const style = {width: length(width)}; 4880 const buttons = Array.from(content, ([content, reduce = identity]) => { 4881 if (typeof reduce !== "function") throw new TypeError("reduce is not a function"); 4882 return html`<button disabled=${disabled.has(content)} style=${style} onclick=${event => { 4883 form.value = reduce(form.value); 4884 dispatchInput(event); 4885 }}>${content}`; 4886 }); 4887 if (label = maybeLabel(label, solitary ? buttons[0] : undefined)) form.append(label); 4888 form.append(...buttons); 4889 form.value = value; 4890 return form; 4891} 4892 4893const formatLocaleAuto = localize(locale => { 4894 const formatNumber = formatLocaleNumber(locale); 4895 return value => value == null ? "" 4896 : typeof value === "number" ? formatNumber(value) 4897 : value instanceof Date ? formatDate(value) 4898 : `${value}`; 4899}); 4900 4901const formatLocaleNumber = localize(locale => { 4902 return value =>
4902 value === 0 ? "0" : value.toLocaleString(locale); // handle negative zero 4903}); 4904 4905formatLocaleAuto(); 4906 4907formatLocaleNumber(); 4908 4909function formatDate(date) { 4910 return format(date, "Invalid Date"); 4911} 4912 4913// Memoize the last-returned locale. 4914function localize(f) { 4915 let key = localize, value; 4916 return (locale = "en") => locale === key ? value : (value = f(key = locale)); 4917} 4918 4919/* 4920* quarto-inspector.js 4921* 4922* Copyright (C) 2022 RStudio, PBC 4923* 4924*/ 4925 4926class QuartoInspector extends Inspector { 4927 constructor(node, cellAst) { 4928 super(node); 4929 this._cellAst = cellAst; 4930 } 4931 rejected(error) { 4932 return super.rejected(error); 4933 } 4934} 4935 4936/*global Shiny, $ 4937* 4938* quarto-observable-shiny.js 4939* 4940* Copyright (C) 2022 RStudio, PBC 4941*/ 4942 4943const shinyInputVars = new Set(); 4944let shinyInitialValue = {}; 4945 4946function extendObservableStdlib(lib) { 4947 class NamedVariableOutputBinding extends Shiny.OutputBinding { 4948 constructor(name, change) { 4949 super(); 4950 this._name = name; 4951 this._change = change; 4952 } 4953 find(scope) { 4954 return $(scope).find("#" + this._name); 4955 } 4956 getId(el) { 4957 return el.id; 4958 } 4959 renderValue(_el, data) { 4960 this._change(data); 4961 } 4962 onValueError(el, err) { 4963 const group = `Shiny error in ${el.id}`; 4964 console.groupCollapsed(`%c${group}`, "color:red"); 4965 console.log(`${err.message}`); 4966 console.log(`call: ${err.call}`); 4967 console.groupEnd(group); 4968 } 4969 } 4970 4971 $(document).on("shiny:connected", function (_event) { 4972 Object.entries(shinyInitialValue).map(([k, v]) => { 4973 window.Shiny.setInputValue(k, v); 4974 }); 4975 shinyInitialValue = {}; 4976 }); 4977 4978 lib.shinyInput = function () { 4979 return (name) => { 4980 shinyInputVars.add(name); 4981 window._ojs.ojsConnector.mainModule.value(name) 4982 .then((val) => { 4983 if (window.Shiny && window.Shiny.setInputValue) { 4984 window.Shiny.setInputValue(name, val); 4985 } else { 4986 shinyInitialValue[name] = val; 4987 } 4988 }); 4989 }; 4990 }; 4991 4992 lib.shinyOutput = function () { 4993 return function (name) { 4994 const dummySpan = document.createElement("div"); 4995 dummySpan.id = name; 4996 dummySpan.classList.add("ojs-variable-writer"); 4997 window._ojs.shinyElementRoot.appendChild(dummySpan); 4998 return lib.Generators.observe((change) => { 4999 Shiny.outputBindings.register( 5000 new NamedVariableOutputBinding(name, change), 5001 ); 5002 }); 5003 }; 5004 }; 5005} 5006 5007class ShinyInspector extends QuartoInspector { 5008 constructor(node) { 5009 super(node); 5010 } 5011 fulfilled(value, name) { 5012 if (shinyInputVars.has(name) && window.Shiny) { 5013 if (window.Shiny.setInputValue === undefined) { 5014 shinyInitialValue[name] = value; 5015 } else { 5016 window.Shiny.setInputValue(name, value); 5017 } 5018 } 5019 return super.fulfilled(value, name); 5020 } 5021} 5022 5023const { Generators } = new Library(); 5024 5025class OjsButtonInput /*extends ShinyInput*/ { 5026 find(_scope) { 5027 return document.querySelectorAll(".ojs-inputs-button"); 5028 } 5029 5030 init(el, change) { 5031 const btn = button(el.textContent); 5032 el.innerHTML = ""; 5033 el.appendChild(btn); 5034 5035 const obs = Generators.input(el.firstChild); 5036 (async function () { 5037 // throw away the first value, it doesn't count for buttons 5038 await obs.next().value; 5039 for (const x of obs) { 5040 change(await x); 5041 } 5042 })(); 5043 // TODO: error handling 5044 5045 return { 5046 onSetValue: (_value) => { 5047 }, 5048 dispose: () => { 5049 obs.return(); 5050 }, 5051 }; 5052 } 5053} 5054 5055function initOjsShinyRuntime() { 5056 const valueSym = Symbol("value"); 5057 const callbackSym = Symbol("callback"); 5058 const instanceSym = Symbol("instance"); 5059 // const values = new WeakMap(); // unused? 5060 5061 class BindingAdapter extends Shiny.InputBinding { 5062 constructor(x) { 5063 super(); 5064 this.x = x; 5065 } 5066 5067 find(scope) { 5068 const matches = this.x.find(scope); 5069 return $(matches); 5070 } 5071 getId(el) { 5072 if (this.x.getId) { 5073 return this.x.getId(el); 5074 } else { 5075 return super.getId(el); 5076 } 5077 } 5078 initialize(el) { 5079 const changeHandler = (value) => { 5080 el[valueSym] = value; 5081 el[callbackSym](); 5082 }; 5083 const instance = this.x.init(el, changeHandler); 5084 el[instanceSym] = instance; 5085 } 5086 getValue(el) { 5087 return el[valueSym]; 5088 } 5089 setValue(el, value) { 5090 el[valueSym] = value; 5091 el[instanceSym].onSetValue(value); 5092 } 5093 subscribe(el, callback) { 5094 el[callbackSym] = callback; 5095 } 5096 unsubscribe(el) { 5097 el[instanceSym].dispose(); 5098 } 5099 } 5100 5101 class InspectorOutputBinding extends Shiny.OutputBinding { 5102 find(scope) { 5103 return $(scope).find(".observablehq-inspector"); 5104 } 5105 getId(el) { 5106 return el.id; 5107 } 5108 renderValue(el, data) { 5109 (new Inspector(el)).fulfilled(data); 5110 } 5111 } 5112 5113 if (window.Shiny === undefined) { 5114 console.warn("Shiny runtime not found; Shiny features won't work."); 5115 return false;
5116 } 5117 5118 Shiny.inputBindings.register(new BindingAdapter(new OjsButtonInput())); 5119 Shiny.outputBindings.register(new InspectorOutputBinding()); 5120 5121 // Handle requests from the server to export Shiny outputs to ojs. 5122 Shiny.addCustomMessageHandler("ojs-export", ({ name }) => { 5123 window._ojs.ojsConnector.mainModule.redefine( 5124 name, 5125 window._ojs.ojsConnector.library.shinyOutput()(name), 5126 ); 5127 // shinyOutput() creates an output DOM element, but we have to cause it to 5128 // be actually bound. I don't love this code being here, I'd prefer if we 5129 // could receive Shiny outputs without using output bindings at all (for 5130 // this case, not for things that truly are DOM-oriented outputs). 5131 Shiny.bindAll(document.body); 5132 }); 5133 5134 return true; 5135} 5136 5137var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; 5138 5139var dist = {exports: {}}; 5140 5141(function (module, exports) { 5142 (function(g,f){f(exports);}(commonjsGlobal,(function(exports){ 5143 var reservedWords = { 5144 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", 5145 5: "class enum extends super const export import", 5146 6: "enum", 5147 strict: "implements interface let package private protected public static yield", 5148 strictBind: "eval arguments" 5149 }; 5150 5151 // And the keywords 5152 5153 var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; 5154 5155 var keywords = { 5156 5: ecma5AndLessKeywords, 5157 "5module": ecma5AndLessKeywords + " export import", 5158 6: ecma5AndLessKeywords + " const class extends export import super" 5159 }; 5160 5161 var keywordRelationalOperator = /^in(stanceof)?$/; 5162 5163 // ## Character categories 5164 5165 // Big ugly regular expressions that match characters in the 5166 // whitespace, identifier, and identifier-start categories. These 5167 // are only applied when a character is found to actually have a 5168 // code point above 128. 5169 // Generated by `bin/generate-identifier-regex.js`. 5170 var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u
517019b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; 5171 var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; 5172 5173 var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); 5174 var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); 5175 5176 nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; 5177 5178 // These are a run-length and offset encoded representation of the 5179 // >0xffff code points that are a valid part of identifiers. The 5180 // offset starts at 0x10000, and each pair of numbers represents an 5181 // offset to the next range, and then a size of the range. They were 5182 // generated by bin/generate-identifier-regex.js 5183 5184 // eslint-disable-next-line comma-spacing 5185 var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,
vendor: 2,553 bytes, lines 5185-5238
518515,7472,3104,541,1507,4938]; 5186 5187 // eslint-disable-next-line comma-spacing 5188 var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239]; 5189 5190 // This has a complexity linear to the value of the code. The 5191 // assumption is that looking up astral identifier characters is 5192 // rare. 5193 function isInAstralSet(code, set) { 5194 var pos = 0x10000; 5195 for (var i = 0; i < set.length; i += 2) { 5196 pos += set[i]; 5197 if (pos > code) { return false } 5198 pos += set[i + 1]; 5199 if (pos >= code) { return true } 5200 } 5201 } 5202 5203 // Test whether a given character code starts an identifier. 5204 5205 function isIdentifierStart(code, astral) { 5206 if (code < 65) { return code === 36 } 5207 if (code < 91) { return true } 5208 if (code < 97) { return code === 95 } 5209 if (code < 123) { return true } 5210 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } 5211 if (astral === false) { return false } 5212 return isInAstralSet(code, astralIdentifierStartCodes) 5213 } 5214 5215 // Test whether a given character is part of an identifier. 5216 5217 function isIdentifierChar(code, astral) { 5218 if (code < 48) { return code === 36 } 5219 if (code < 58) { return true } 5220 if (code < 65) { return false } 5221 if (code < 91) { return true } 5222 if (code < 97) { return code === 95 } 5223 if (code < 123) { return true } 5224 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } 5225 if (astral === false) { return false } 5226 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) 5227 } 5228 5229 // ## Token types 5230 5231 // The assignment of fine-grained, information-carrying type objects 5232 // allows the tokenizer to store the information it has about a 5233 // token in a way that is very cheap for the parser to look up. 5234 5235 // All token type variables start with an underscore, to make them 5236 // easy to recognize. 5237 5238 // The `beforeExpr` property is used to disambiguate between regular
vendor: 2,028 bytes, lines 5239-5297
5239 // expressions and divisions. It is set on all token types that can 5240 // be followed by an expression (thus, a slash after them would be a 5241 // regular expression). 5242 // 5243 // The `startsExpr` property is used to check if the token ends a 5244 // `yield` expression. It is set on all token types that either can 5245 // directly start an expression (like a quotation mark) or can 5246 // continue an expression (like the body of a string). 5247 // 5248 // `isLoop` marks a keyword as starting a loop, which is important 5249 // to know when parsing a label, in order to allow or disallow 5250 // continue jumps to that label. 5251 5252 var TokenType = function TokenType(label, conf) { 5253 if ( conf === void 0 ) conf = {}; 5254 5255 this.label = label; 5256 this.keyword = conf.keyword; 5257 this.beforeExpr = !!conf.beforeExpr; 5258 this.startsExpr = !!conf.startsExpr; 5259 this.isLoop = !!conf.isLoop; 5260 this.isAssign = !!conf.isAssign; 5261 this.prefix = !!conf.prefix; 5262 this.postfix = !!conf.postfix; 5263 this.binop = conf.binop || null; 5264 this.updateContext = null; 5265 }; 5266 5267 function binop(name, prec) { 5268 return new TokenType(name, {beforeExpr: true, binop: prec}) 5269 } 5270 var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; 5271 5272 // Map keyword names to token types. 5273 5274 var keywords$1 = {}; 5275 5276 // Succinct definitions of keyword token types 5277 function kw(name, options) { 5278 if ( options === void 0 ) options = {}; 5279 5280 options.keyword = name; 5281 return keywords$1[name] = new TokenType(name, options) 5282 } 5283 5284 var types = { 5285 num: new TokenType("num", startsExpr), 5286 regexp: new TokenType("regexp", startsExpr), 5287 string: new TokenType("string", startsExpr), 5288 name: new TokenType("name", startsExpr), 5289 eof: new TokenType("eof"), 5290 5291 // Punctuation token types. 5292 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), 5293 bracketR: new TokenType("]"), 5294 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), 5295 braceR: new TokenType("}"), 5296 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), 5297 parenR: new TokenType(")"),
5298 comma: new TokenType(",", beforeExpr), 5299 semi: new TokenType(";", beforeExpr), 5300 colon: new TokenType(":", beforeExpr), 5301 dot: new TokenType("."), 5302 question: new TokenType("?", beforeExpr), 5303 questionDot: new TokenType("?."), 5304 arrow: new TokenType("=>", beforeExpr), 5305 template: new TokenType("template"), 5306 invalidTemplate: new TokenType("invalidTemplate"), 5307 ellipsis: new TokenType("...", beforeExpr), 5308 backQuote: new TokenType("`", startsExpr), 5309 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), 5310 5311 // Operators. These carry several kinds of properties to help the 5312 // parser use them properly (the presence of these properties is 5313 // what categorizes them as operators). 5314 // 5315 // `binop`, when present, specifies that this operator is a binary 5316 // operator, and will refer to its precedence. 5317 // 5318 // `prefix` and `postfix` mark the operator as a prefix or postfix 5319 // unary operator. 5320 // 5321 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as 5322 // binary operators with a very low precedence, that should result 5323 // in AssignmentExpression nodes. 5324 5325 eq: new TokenType("=", {beforeExpr: true, isAssign: true}), 5326 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), 5327 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), 5328 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), 5329 logicalOR: binop("||", 1), 5330 logicalAND: binop("&&", 2), 5331 bitwiseOR: binop("|", 3), 5332 bitwiseXOR: binop("^", 4), 5333 bitwiseAND: binop("&", 5), 5334 equality: binop("==/!=/===/!==", 6), 5335 relational: binop("</>/<=/>=", 7), 5336 bitShift: binop("<</>>/>>>", 8), 5337 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), 5338 modulo: binop("%", 10), 5339 star: binop("*", 10), 5340 slash: binop("/", 10), 5341 starstar: new TokenType("**", {beforeExpr: true}), 5342 coalesce: binop("??", 1), 5343 5344 // Keyword token types. 5345 _break: kw("break"),
vendor: 125,239 bytes, lines 5346-8624
5346 _case: kw("case", beforeExpr), 5347 _catch: kw("catch"), 5348 _continue: kw("continue"), 5349 _debugger: kw("debugger"), 5350 _default: kw("default", beforeExpr), 5351 _do: kw("do", {isLoop: true, beforeExpr: true}), 5352 _else: kw("else", beforeExpr), 5353 _finally: kw("finally"), 5354 _for: kw("for", {isLoop: true}), 5355 _function: kw("function", startsExpr), 5356 _if: kw("if"), 5357 _return: kw("return", beforeExpr), 5358 _switch: kw("switch"), 5359 _throw: kw("throw", beforeExpr), 5360 _try: kw("try"), 5361 _var: kw("var"), 5362 _const: kw("const"), 5363 _while: kw("while", {isLoop: true}), 5364 _with: kw("with"), 5365 _new: kw("new", {beforeExpr: true, startsExpr: true}), 5366 _this: kw("this", startsExpr), 5367 _super: kw("super", startsExpr), 5368 _class: kw("class", startsExpr), 5369 _extends: kw("extends", beforeExpr), 5370 _export: kw("export"), 5371 _import: kw("import", startsExpr), 5372 _null: kw("null", startsExpr), 5373 _true: kw("true", startsExpr), 5374 _false: kw("false", startsExpr), 5375 _in: kw("in", {beforeExpr: true, binop: 7}), 5376 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), 5377 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), 5378 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), 5379 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) 5380 }; 5381 5382 // Matches a whole line break (where CRLF is considered a single 5383 // line break). Used to count lines. 5384 5385 var lineBreak = /\r\n?|\n|\u2028|\u2029/; 5386 var lineBreakG = new RegExp(lineBreak.source, "g"); 5387 5388 function isNewLine(code, ecma2019String) { 5389 return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029)) 5390 } 5391 5392 var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; 5393 5394 var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; 5395 5396 var ref = Object.prototype; 5397 var hasOwnProperty = ref.hasOwnProperty; 5398 var toString = ref.toString; 5399 5400 // Checks if an object has a property. 5401 5402 function has(obj, propName) { 5403 return hasOwnProperty.call(obj, propName) 5404 } 5405 5406 var isArray = Array.isArray || (function (obj) { return ( 5407 toString.call(obj) === "[object Array]" 5408 ); }); 5409 5410 function wordsRegexp(words) { 5411 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") 5412 } 5413 5414 // These are used when `options.locations` is on, for the 5415 // `startLoc` and `endLoc` properties. 5416 5417 var Position = function Position(line, col) { 5418 this.line = line; 5419 this.column = col; 5420 }; 5421 5422 Position.prototype.offset = function offset (n) { 5423 return new Position(this.line, this.column + n) 5424 }; 5425 5426 var SourceLocation = function SourceLocation(p, start, end) { 5427 this.start = start; 5428 this.end = end; 5429 if (p.sourceFile !== null) { this.source = p.sourceFile; } 5430 }; 5431 5432 // The `getLineInfo` function is mostly useful when the 5433 // `locations` option is off (for performance reasons) and you 5434 // want to find the line/column position for a given character 5435 // offset. `input` should be the code string that the offset refers 5436 // into. 5437 5438 function getLineInfo(input, offset) { 5439 for (var line = 1, cur = 0;;) { 5440 lineBreakG.lastIndex = cur; 5441 var match = lineBreakG.exec(input); 5442 if (match && match.index < offset) { 5443 ++line; 5444 cur = match.index + match[0].length; 5445 } else { 5446 return new Position(line, offset - cur) 5447 } 5448 } 5449 } 5450 5451 // A second optional argument can be given to further configure 5452 // the parser process. These options are recognized: 5453 5454 var defaultOptions = { 5455 // `ecmaVersion` indicates the ECMAScript version to parse. Must be 5456 // either 3, 5, 6 (2015), 7 (2016), 8 (2017), 9 (2018), or 10 5457 // (2019). This influences support for strict mode, the set of 5458 // reserved words, and support for new syntax features. The default 5459 // is 10. 5460 ecmaVersion: 10, 5461 // `sourceType` indicates the mode the code should be parsed in. 5462 // Can be either `"script"` or `"module"`. This influences global 5463 // strict mode and parsing of `import` and `export` declarations. 5464 sourceType: "script", 5465 // `onInsertedSemicolon` can be a callback that will be called 5466 // when a semicolon is automatically inserted. It will be passed 5467 // the position of the comma as an offset, and if `locations` is 5468 // enabled, it is given the location as a `{line, column}` object 5469 // as second argument. 5470 onInsertedSemicolon: null, 5471 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for 5472 // trailing commas. 5473 onTrailingComma: null, 5474 // By default, reserved words are only enforced if ecmaVersion >= 5. 5475 // Set `allowReserved` to a boolean value to explicitly turn this on 5476 // an off. When this option has the value "never", reserved words 5477 // and keywords can also not be used as property names. 5478 allowReserved: null, 5479 // When enabled, a return at the top level is not considered an 5480 // error. 5481 allowReturnOutsideFunction: false, 5482 // When enabled, import/export statements are not constrained to 5483 // appearing at the top of the program. 5484 allowImportExportEverywhere: false, 5485 // When enabled, await identifiers are allowed to appear at the top-level scope, 5486 // but they are still not allowed in non-async functions. 5487 allowAwaitOutsideFunction: false, 5488 // When enabled, hashbang directive in the beginning of file 5489 // is allowed and treated as a line comment. 5490 allowHashBang: false, 5491 // When `locations` is on, `loc` properties holding objects with 5492 // `start` and `end` properties in `{line, column}` form (with 5493 // line being 1-based and column 0-based) will be attached to the 5494 // nodes. 5495 locations: false, 5496 // A function can be passed as `onToken` option, which will 5497 // cause Acorn to call that function with object in the same 5498 // format as tokens returned from `tokenizer().getToken()`. Note 5499 // that you are not allowed to call the parser from the 5500 // callbackâthat will corrupt its internal state. 5501 onToken: null, 5502 // A function can be passed as `onComment` option, which will 5503 // cause Acorn to call that function with `(block, text, start, 5504 // end)` parameters whenever a comment is skipped. `block` is a 5505 // boolean indicating whether this is a block (`/* */`) comment, 5506 // `text` is the content of the comment, and `start` and `end` are 5507 // character offsets that denote the start and end of the comment. 5508 // When the `locations` option is on, two more parameters are 5509 // passed, the full `{line, column}` locations of the start and 5510 // end of the comments. Note that you are not allowed to call the 5511 // parser from the callbackâthat will corrupt its internal state. 5512 onComment: null, 5513 // Nodes have their start and end characters offsets recorded in 5514 // `start` and `end` properties (directly on the node, rather than 5515 // the `loc` object, which holds line/column data. To also add a 5516 // [semi-standardized][range] `range` property holding a `[start, 5517 // end]` array with the same numbers, set the `ranges` option to 5518 // `true`. 5519 // 5520 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 5521 ranges: false, 5522 // It is possible to parse multiple files into a single AST by 5523 // passing the tree produced by parsing the first file as 5524 // `program` option in subsequent parses. This will add the 5525 // toplevel forms of the parsed file to the `Program` (top) node 5526 // of an existing parse tree. 5527 program: null, 5528 // When `locations` is on, you can pass this to record the source 5529 // file in every node's `loc` object. 5530 sourceFile: null, 5531 // This value, if given, is stored in every node, whether 5532 // `locations` is on or off. 5533 directSourceFile: null, 5534 // When enabled, parenthesized expressions are represented by 5535 // (non-standard) ParenthesizedExpression nodes 5536 preserveParens: false 5537 }; 5538 5539 // Interpret and default an options object 5540 5541 function getOptions(opts) { 5542 var options = {}; 5543 5544 for (var opt in defaultOptions) 5545 { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; } 5546 5547 if (options.ecmaVersion >= 2015) 5548 { options.ecmaVersion -= 2009; } 5549 5550 if (options.allowReserved == null) 5551 { options.allowReserved = options.ecmaVersion < 5; } 5552 5553 if (isArray(options.onToken)) { 5554 var tokens = options.onToken; 5555 options.onToken = function (token) { return tokens.push(token); }; 5556 } 5557 if (isArray(options.onComment)) 5558 { options.onComment = pushComment(options, options.onComment); } 5559 5560 return options 5561 } 5562 5563 function pushComment(options, array) { 5564 return function(block, text, start, end, startLoc, endLoc) { 5565 var comment = { 5566 type: block ? "Block" : "Line", 5567 value: text, 5568 start: start, 5569 end: end 5570 }; 5571 if (options.locations) 5572 { comment.loc = new SourceLocation(this, startLoc, endLoc); } 5573 if (options.ranges) 5574 { comment.range = [start, end]; } 5575 array.push(comment); 5576 } 5577 } 5578 5579 // Each scope gets a bitset that may contain these flags 5580 var 5581 SCOPE_TOP = 1, 5582 SCOPE_FUNCTION = 2, 5583 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION, 5584 SCOPE_ASYNC = 4, 5585 SCOPE_GENERATOR = 8, 5586 SCOPE_ARROW = 16, 5587 SCOPE_SIMPLE_CATCH = 32, 5588 SCOPE_SUPER = 64, 5589 SCOPE_DIRECT_SUPER = 128; 5590 5591 function functionFlags(async, generator) { 5592 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) 5593 } 5594 5595 // Used in checkLVal and declareName to determine the type of a binding 5596 var 5597 BIND_NONE = 0, // Not a binding 5598 BIND_VAR = 1, // Var-style binding 5599 BIND_LEXICAL = 2, // Let- or const-style binding 5600 BIND_FUNCTION = 3, // Function declaration 5601 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding 5602 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function 5603 5604 var Parser = function Parser(options, input, startPos) { 5605 this.options = options = getOptions(options); 5606 this.sourceFile = options.sourceFile; 5607 this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); 5608 var reserved = ""; 5609 if (options.allowReserved !== true) { 5610 for (var v = options.ecmaVersion;; v--) 5611 { if (reserved = reservedWords[v]) { break } } 5612 if (options.sourceType === "module") { reserved += " await"; } 5613 } 5614 this.reservedWords = wordsRegexp(reserved); 5615 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; 5616 this.reservedWordsStrict = wordsRegexp(reservedStrict); 5617 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); 5618 this.input = String(input); 5619 5620 // Used to signal to callers of `readWord1` whether the word 5621 // contained any escape sequences. This is needed because words with 5622 // escape sequences must not be interpreted as keywords. 5623 this.containsEsc = false; 5624 5625 // Set up token state 5626 5627 // The current position of the tokenizer in the input. 5628 if (startPos) { 5629 this.pos = startPos; 5630 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; 5631 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; 5632 } else { 5633 this.pos = this.lineStart = 0; 5634 this.curLine = 1; 5635 } 5636 5637 // Properties of the current token: 5638 // Its type 5639 this.type = types.eof; 5640 // For tokens that include more information than their type, the value 5641 this.value = null; 5642 // Its start and end offset 5643 this.start = this.end = this.pos; 5644 // And, if locations are used, the {line, column} object 5645 // corresponding to those offsets 5646 this.startLoc = this.endLoc = this.curPosition(); 5647 5648 // Position information for the previous token 5649 this.lastTokEndLoc = this.lastTokStartLoc = null; 5650 this.lastTokStart = this.lastTokEnd = this.pos; 5651 5652 // The context stack is used to superficially track syntactic 5653 // context to predict whether a regular expression is allowed in a 5654 // given position. 5655 this.context = this.initialContext(); 5656 this.exprAllowed = true; 5657 5658 // Figure out if it's a module code. 5659 this.inModule = options.sourceType === "module"; 5660 this.strict = this.inModule || this.strictDirective(this.pos); 5661 5662 // Used to signify the start of a potential arrow function 5663 this.potentialArrowAt = -1; 5664 5665 // Positions to delayed-check that yield/await does not exist in default parameters. 5666 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; 5667 // Labels in scope. 5668 this.labels = []; 5669 // Thus-far undefined exports. 5670 this.undefinedExports = {}; 5671 5672 // If enabled, skip leading hashbang line. 5673 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") 5674 { this.skipLineComment(2); } 5675 5676 // Scope tracking for duplicate variable names (see scope.js) 5677 this.scopeStack = []; 5678 this.enterScope(SCOPE_TOP); 5679 5680 // For RegExp validation 5681 this.regexpState = null; 5682 }; 5683 5684 var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true } }; 5685 5686 Parser.prototype.parse = function parse () { 5687 var node = this.options.program || this.startNode(); 5688 this.nextToken(); 5689 return this.parseTopLevel(node) 5690 }; 5691 5692 prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 }; 5693 prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 }; 5694 prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 }; 5695 prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 }; 5696 prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; 5697 prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; 5698 5699 // Switch to a getter for 7.0.0. 5700 Parser.prototype.inNonArrowFunction = function inNonArrowFunction () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 }; 5701 5702 Parser.extend = function extend () { 5703 var plugins = [], len = arguments.length; 5704 while ( len-- ) plugins[ len ] = arguments[ len ]; 5705 5706 var cls = this; 5707 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } 5708 return cls 5709 }; 5710 5711 Parser.parse = function parse (input, options) { 5712 return new this(options, input).parse() 5713 }; 5714 5715 Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { 5716 var parser = new this(options, input, pos); 5717 parser.nextToken(); 5718 return parser.parseExpression() 5719 }; 5720 5721 Parser.tokenizer = function tokenizer (input, options) { 5722 return new this(options, input) 5723 }; 5724 5725 Object.defineProperties( Parser.prototype, prototypeAccessors ); 5726 5727 var pp = Parser.prototype; 5728 5729 // ## Parser utilities 5730 5731 var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; 5732 pp.strictDirective = function(start) { 5733 for (;;) { 5734 // Try to find string literal. 5735 skipWhiteSpace.lastIndex = start; 5736 start += skipWhiteSpace.exec(this.input)[0].length; 5737 var match = literal.exec(this.input.slice(start)); 5738 if (!match) { return false } 5739 if ((match[1] || match[2]) === "use strict") { 5740 skipWhiteSpace.lastIndex = start + match[0].length; 5741 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; 5742 var next = this.input.charAt(end); 5743 return next === ";" || next === "}" || 5744 (lineBreak.test(spaceAfter[0]) && 5745 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) 5746 } 5747 start += match[0].length; 5748 5749 // Skip semicolon, if any. 5750 skipWhiteSpace.lastIndex = start; 5751 start += skipWhiteSpace.exec(this.input)[0].length; 5752 if (this.input[start] === ";") 5753 { start++; } 5754 } 5755 }; 5756 5757 // Predicate that tests whether the next token is of the given 5758 // type, and if yes, consumes it as a side effect. 5759 5760 pp.eat = function(type) { 5761 if (this.type === type) { 5762 this.next(); 5763 return true 5764 } else { 5765 return false 5766 } 5767 }; 5768 5769 // Tests whether parsed token is a contextual keyword. 5770 5771 pp.isContextual = function(name) { 5772 return this.type === types.name && this.value === name && !this.containsEsc 5773 }; 5774 5775 // Consumes contextual keyword if possible. 5776 5777 pp.eatContextual = function(name) { 5778 if (!this.isContextual(name)) { return false } 5779 this.next(); 5780 return true 5781 }; 5782 5783 // Asserts that following token is given contextual keyword. 5784 5785 pp.expectContextual = function(name) { 5786 if (!this.eatContextual(name)) { this.unexpected(); } 5787 }; 5788 5789 // Test whether a semicolon can be inserted at the current position. 5790 5791 pp.canInsertSemicolon = function() { 5792 return this.type === types.eof || 5793 this.type === types.braceR || 5794 lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) 5795 }; 5796 5797 pp.insertSemicolon = function() { 5798 if (this.canInsertSemicolon()) { 5799 if (this.options.onInsertedSemicolon) 5800 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } 5801 return true 5802 } 5803 }; 5804 5805 // Consume a semicolon, or, failing that, see if we are allowed to 5806 // pretend that there is a semicolon at this position. 5807 5808 pp.semicolon = function() { 5809 if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); } 5810 }; 5811 5812 pp.afterTrailingComma = function(tokType, notNext) { 5813 if (this.type === tokType) { 5814 if (this.options.onTrailingComma) 5815 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } 5816 if (!notNext) 5817 { this.next(); } 5818 return true 5819 } 5820 }; 5821 5822 // Expect a token of a given type. If found, consume it, otherwise, 5823 // raise an unexpected token error. 5824 5825 pp.expect = function(type) { 5826 this.eat(type) || this.unexpected(); 5827 }; 5828 5829 // Raise an unexpected token error. 5830 5831 pp.unexpected = function(pos) { 5832 this.raise(pos != null ? pos : this.start, "Unexpected token"); 5833 }; 5834 5835 function DestructuringErrors() { 5836 this.shorthandAssign = 5837 this.trailingComma = 5838 this.parenthesizedAssign = 5839 this.parenthesizedBind = 5840 this.doubleProto = 5841 -1; 5842 } 5843 5844 pp.checkPatternErrors = function(refDestructuringErrors, isAssign) { 5845 if (!refDestructuringErrors) { return } 5846 if (refDestructuringErrors.trailingComma > -1) 5847 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } 5848 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; 5849 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); } 5850 }; 5851 5852 pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) { 5853 if (!refDestructuringErrors) { return false } 5854 var shorthandAssign = refDestructuringErrors.shorthandAssign; 5855 var doubleProto = refDestructuringErrors.doubleProto; 5856 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } 5857 if (shorthandAssign >= 0) 5858 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } 5859 if (doubleProto >= 0) 5860 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } 5861 }; 5862 5863 pp.checkYieldAwaitInDefaultParams = function() { 5864 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) 5865 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } 5866 if (this.awaitPos) 5867 { this.raise(this.awaitPos, "Await expression cannot be a default value"); } 5868 }; 5869 5870 pp.isSimpleAssignTarget = function(expr) { 5871 if (expr.type === "ParenthesizedExpression") 5872 { return this.isSimpleAssignTarget(expr.expression) } 5873 return expr.type === "Identifier" || expr.type === "MemberExpression" 5874 }; 5875 5876 var pp$1 = Parser.prototype; 5877 5878 // ### Statement parsing 5879 5880 // Parse a program. Initializes the parser, reads any number of 5881 // statements, and wraps them in a Program node. Optionally takes a 5882 // `program` argument. If present, the statements will be appended 5883 // to its body instead of creating a new node. 5884 5885 pp$1.parseTopLevel = function(node) { 5886 var exports = {}; 5887 if (!node.body) { node.body = []; } 5888 while (this.type !== types.eof) { 5889 var stmt = this.parseStatement(null, true, exports); 5890 node.body.push(stmt); 5891 } 5892 if (this.inModule) 5893 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) 5894 { 5895 var name = list[i]; 5896 5897 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); 5898 } } 5899 this.adaptDirectivePrologue(node.body); 5900 this.next(); 5901 node.sourceType = this.options.sourceType; 5902 return this.finishNode(node, "Program") 5903 }; 5904 5905 var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; 5906 5907 pp$1.isLet = function(context) { 5908 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } 5909 skipWhiteSpace.lastIndex = this.pos; 5910 var skip = skipWhiteSpace.exec(this.input); 5911 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); 5912 // For ambiguous cases, determine if a LexicalDeclaration (or only a 5913 // Statement) is allowed here. If context is not empty then only a Statement 5914 // is allowed. However, `let [` is an explicit negative lookahead for 5915 // ExpressionStatement, so special-case it first. 5916 if (nextCh === 91) { return true } // '[' 5917 if (context) { return false } 5918 5919 if (nextCh === 123) { return true } // '{' 5920 if (isIdentifierStart(nextCh, true)) { 5921 var pos = next + 1; 5922 while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; } 5923 var ident = this.input.slice(next, pos); 5924 if (!keywordRelationalOperator.test(ident)) { return true } 5925 } 5926 return false 5927 }; 5928 5929 // check 'async [no LineTerminator here] function' 5930 // - 'async /*foo*/ function' is OK. 5931 // - 'async /*\n*/ function' is invalid. 5932 pp$1.isAsyncFunction = function() { 5933 if (this.options.ecmaVersion < 8 || !this.isContextual("async")) 5934 { return false } 5935 5936 skipWhiteSpace.lastIndex = this.pos; 5937 var skip = skipWhiteSpace.exec(this.input); 5938 var next = this.pos + skip[0].length; 5939 return !lineBreak.test(this.input.slice(this.pos, next)) && 5940 this.input.slice(next, next + 8) === "function" && 5941 (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8))) 5942 }; 5943 5944 // Parse a single statement. 5945 // 5946 // If expecting a statement and finding a slash operator, parse a 5947 // regular expression literal. This is to handle cases like 5948 // `if (foo) /blah/.exec(foo)`, where looking at the previous token 5949 // does not help. 5950 5951 pp$1.parseStatement = function(context, topLevel, exports) { 5952 var starttype = this.type, node = this.startNode(), kind; 5953 5954 if (this.isLet(context)) { 5955 starttype = types._var; 5956 kind = "let"; 5957 } 5958 5959 // Most types of statements are recognized by the keyword they 5960 // start with. Many are trivial to parse, some require a bit of 5961 // complexity. 5962 5963 switch (starttype) { 5964 case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword) 5965 case types._debugger: return this.parseDebuggerStatement(node) 5966 case types._do: return this.parseDoStatement(node) 5967 case types._for: return this.parseForStatement(node) 5968 case types._function: 5969 // Function as sole body of either an if statement or a labeled statement 5970 // works, but not when it is part of a labeled statement that is the sole 5971 // body of an if statement. 5972 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } 5973 return this.parseFunctionStatement(node, false, !context) 5974 case types._class: 5975 if (context) { this.unexpected(); } 5976 return this.parseClass(node, true) 5977 case types._if: return this.parseIfStatement(node) 5978 case types._return: return this.parseReturnStatement(node) 5979 case types._switch: return this.parseSwitchStatement(node) 5980 case types._throw: return this.parseThrowStatement(node) 5981 case types._try: return this.parseTryStatement(node) 5982 case types._const: case types._var: 5983 kind = kind || this.value; 5984 if (context && kind !== "var") { this.unexpected(); } 5985 return this.parseVarStatement(node, kind) 5986 case types._while: return this.parseWhileStatement(node) 5987 case types._with: return this.parseWithStatement(node) 5988 case types.braceL: return this.parseBlock(true, node) 5989 case types.semi: return this.parseEmptyStatement(node) 5990 case types._export: 5991 case types._import: 5992 if (this.options.ecmaVersion > 10 && starttype === types._import) { 5993 skipWhiteSpace.lastIndex = this.pos; 5994 var skip = skipWhiteSpace.exec(this.input); 5995 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); 5996 if (nextCh === 40 || nextCh === 46) // '(' or '.' 5997 { return this.parseExpressionStatement(node, this.parseExpression()) } 5998 } 5999 6000 if (!this.options.allowImportExportEverywhere) { 6001 if (!topLevel) 6002 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } 6003 if (!this.inModule) 6004 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } 6005 } 6006 return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports) 6007 6008 // If the statement does not start with a statement keyword or a 6009 // brace, it's an ExpressionStatement or LabeledStatement. We 6010 // simply start parsing an expression, and afterwards, if the 6011 // next token is a colon and the expression was a simple 6012 // Identifier node, we switch to interpreting it as a label. 6013 default: 6014 if (this.isAsyncFunction()) { 6015 if (context) { this.unexpected(); } 6016 this.next(); 6017 return this.parseFunctionStatement(node, true, !context) 6018 } 6019 6020 var maybeName = this.value, expr = this.parseExpression(); 6021 if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon)) 6022 { return this.parseLabeledStatement(node, maybeName, expr, context) } 6023 else { return this.parseExpressionStatement(node, expr) } 6024 } 6025 }; 6026 6027 pp$1.parseBreakContinueStatement = function(node, keyword) { 6028 var isBreak = keyword === "break"; 6029 this.next(); 6030 if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; } 6031 else if (this.type !== types.name) { this.unexpected(); } 6032 else { 6033 node.label = this.parseIdent(); 6034 this.semicolon(); 6035 } 6036 6037 // Verify that there is an actual destination to break or 6038 // continue to. 6039 var i = 0; 6040 for (; i < this.labels.length; ++i) { 6041 var lab = this.labels[i]; 6042 if (node.label == null || lab.name === node.label.name) { 6043 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } 6044 if (node.label && isBreak) { break } 6045 } 6046 } 6047 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } 6048 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") 6049 }; 6050 6051 pp$1.parseDebuggerStatement = function(node) { 6052 this.next(); 6053 this.semicolon(); 6054 return this.finishNode(node, "DebuggerStatement") 6055 }; 6056 6057 pp$1.parseDoStatement = function(node) { 6058 this.next(); 6059 this.labels.push(loopLabel); 6060 node.body = this.parseStatement("do"); 6061 this.labels.pop(); 6062 this.expect(types._while); 6063 node.test = this.parseParenExpression(); 6064 if (this.options.ecmaVersion >= 6) 6065 { this.eat(types.semi); } 6066 else 6067 { this.semicolon(); } 6068 return this.finishNode(node, "DoWhileStatement") 6069 }; 6070 6071 // Disambiguating between a `for` and a `for`/`in` or `for`/`of` 6072 // loop is non-trivial. Basically, we have to parse the init `var` 6073 // statement or expression, disallowing the `in` operator (see 6074 // the second parameter to `parseExpression`), and then check 6075 // whether the next token is `in` or `of`. When there is no init 6076 // part (semicolon immediately after the opening parenthesis), it 6077 // is a regular `for` loop. 6078 6079 pp$1.parseForStatement = function(node) { 6080 this.next(); 6081 var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1; 6082 this.labels.push(loopLabel); 6083 this.enterScope(0); 6084 this.expect(types.parenL); 6085 if (this.type === types.semi) { 6086 if (awaitAt > -1) { this.unexpected(awaitAt); } 6087 return this.parseFor(node, null) 6088 } 6089 var isLet = this.isLet(); 6090 if (this.type === types._var || this.type === types._const || isLet) { 6091 var init$1 = this.startNode(), kind = isLet ? "let" : this.value; 6092 this.next(); 6093 this.parseVar(init$1, true, kind); 6094 this.finishNode(init$1, "VariableDeclaration"); 6095 if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { 6096 if (this.options.ecmaVersion >= 9) { 6097 if (this.type === types._in) { 6098 if (awaitAt > -1) { this.unexpected(awaitAt); } 6099 } else { node.await = awaitAt > -1; } 6100 } 6101 return this.parseForIn(node, init$1) 6102 } 6103 if (awaitAt > -1) { this.unexpected(awaitAt); } 6104 return this.parseFor(node, init$1) 6105 } 6106 var refDestructuringErrors = new DestructuringErrors; 6107 var init = this.parseExpression(true, refDestructuringErrors); 6108 if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) { 6109 if (this.options.ecmaVersion >= 9) { 6110 if (this.type === types._in) { 6111 if (awaitAt > -1) { this.unexpected(awaitAt); } 6112 } else { node.await = awaitAt > -1; } 6113 } 6114 this.toAssignable(init, false, refDestructuringErrors); 6115 this.checkLVal(init); 6116 return this.parseForIn(node, init) 6117 } else { 6118 this.checkExpressionErrors(refDestructuringErrors, true); 6119 } 6120 if (awaitAt > -1) { this.unexpected(awaitAt); } 6121 return this.parseFor(node, init) 6122 }; 6123 6124 pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) { 6125 this.next(); 6126 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) 6127 }; 6128 6129 pp$1.parseIfStatement = function(node) { 6130 this.next(); 6131 node.test = this.parseParenExpression(); 6132 // allow function declarations in branches, but only in non-strict mode 6133 node.consequent = this.parseStatement("if"); 6134 node.alternate = this.eat(types._else) ? this.parseStatement("if") : null; 6135 return this.finishNode(node, "IfStatement") 6136 }; 6137 6138 pp$1.parseReturnStatement = function(node) { 6139 if (!this.inFunction && !this.options.allowReturnOutsideFunction) 6140 { this.raise(this.start, "'return' outside of function"); } 6141 this.next(); 6142 6143 // In `return` (and `break`/`continue`), the keywords with 6144 // optional arguments, we eagerly look for a semicolon or the 6145 // possibility to insert one. 6146 6147 if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; } 6148 else { node.argument = this.parseExpression(); this.semicolon(); } 6149 return this.finishNode(node, "ReturnStatement") 6150 }; 6151 6152 pp$1.parseSwitchStatement = function(node) { 6153 this.next(); 6154 node.discriminant = this.parseParenExpression(); 6155 node.cases = []; 6156 this.expect(types.braceL); 6157 this.labels.push(switchLabel); 6158 this.enterScope(0); 6159 6160 // Statements under must be grouped (by label) in SwitchCase 6161 // nodes. `cur` is used to keep the node that we are currently 6162 // adding statements to. 6163 6164 var cur; 6165 for (var sawDefault = false; this.type !== types.braceR;) { 6166 if (this.type === types._case || this.type === types._default) { 6167 var isCase = this.type === types._case; 6168 if (cur) { this.finishNode(cur, "SwitchCase"); } 6169 node.cases.push(cur = this.startNode()); 6170 cur.consequent = []; 6171 this.next(); 6172 if (isCase) { 6173 cur.test = this.parseExpression(); 6174 } else { 6175 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } 6176 sawDefault = true; 6177 cur.test = null; 6178 } 6179 this.expect(types.colon); 6180 } else { 6181 if (!cur) { this.unexpected(); } 6182 cur.consequent.push(this.parseStatement(null)); 6183 } 6184 } 6185 this.exitScope(); 6186 if (cur) { this.finishNode(cur, "SwitchCase"); } 6187 this.next(); // Closing brace 6188 this.labels.pop(); 6189 return this.finishNode(node, "SwitchStatement") 6190 }; 6191 6192 pp$1.parseThrowStatement = function(node) { 6193 this.next(); 6194 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) 6195 { this.raise(this.lastTokEnd, "Illegal newline after throw"); } 6196 node.argument = this.parseExpression(); 6197 this.semicolon(); 6198 return this.finishNode(node, "ThrowStatement") 6199 }; 6200 6201 // Reused empty array added for node fields that are always empty. 6202 6203 var empty = []; 6204 6205 pp$1.parseTryStatement = function(node) { 6206 this.next(); 6207 node.block = this.parseBlock(); 6208 node.handler = null; 6209 if (this.type === types._catch) { 6210 var clause = this.startNode(); 6211 this.next(); 6212 if (this.eat(types.parenL)) { 6213 clause.param = this.parseBindingAtom(); 6214 var simple = clause.param.type === "Identifier"; 6215 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); 6216 this.checkLVal(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); 6217 this.expect(types.parenR); 6218 } else { 6219 if (this.options.ecmaVersion < 10) { this.unexpected(); } 6220 clause.param = null; 6221 this.enterScope(0); 6222 } 6223 clause.body = this.parseBlock(false); 6224 this.exitScope(); 6225 node.handler = this.finishNode(clause, "CatchClause"); 6226 } 6227 node.finalizer = this.eat(types._finally) ? this.parseBlock() : null; 6228 if (!node.handler && !node.finalizer) 6229 { this.raise(node.start, "Missing catch or finally clause"); } 6230 return this.finishNode(node, "TryStatement") 6231 }; 6232 6233 pp$1.parseVarStatement = function(node, kind) { 6234 this.next(); 6235 this.parseVar(node, false, kind); 6236 this.semicolon(); 6237 return this.finishNode(node, "VariableDeclaration") 6238 }; 6239 6240 pp$1.parseWhileStatement = function(node) { 6241 this.next(); 6242 node.test = this.parseParenExpression(); 6243 this.labels.push(loopLabel); 6244 node.body = this.parseStatement("while"); 6245 this.labels.pop(); 6246 return this.finishNode(node, "WhileStatement") 6247 }; 6248 6249 pp$1.parseWithStatement = function(node) { 6250 if (this.strict) { this.raise(this.start, "'with' in strict mode"); } 6251 this.next(); 6252 node.object = this.parseParenExpression(); 6253 node.body = this.parseStatement("with"); 6254 return this.finishNode(node, "WithStatement") 6255 }; 6256 6257 pp$1.parseEmptyStatement = function(node) { 6258 this.next(); 6259 return this.finishNode(node, "EmptyStatement") 6260 }; 6261 6262 pp$1.parseLabeledStatement = function(node, maybeName, expr, context) { 6263 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) 6264 { 6265 var label = list[i$1]; 6266 6267 if (label.name === maybeName) 6268 { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); 6269 } } 6270 var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null; 6271 for (var i = this.labels.length - 1; i >= 0; i--) { 6272 var label$1 = this.labels[i]; 6273 if (label$1.statementStart === node.start) { 6274 // Update information about previous labels on this node 6275 label$1.statementStart = this.start; 6276 label$1.kind = kind; 6277 } else { break } 6278 } 6279 this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); 6280 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); 6281 this.labels.pop(); 6282 node.label = expr; 6283 return this.finishNode(node, "LabeledStatement") 6284 }; 6285 6286 pp$1.parseExpressionStatement = function(node, expr) { 6287 node.expression = expr; 6288 this.semicolon(); 6289 return this.finishNode(node, "ExpressionStatement") 6290 }; 6291 6292 // Parse a semicolon-enclosed block of statements, handling `"use 6293 // strict"` declarations when `allowStrict` is true (used for 6294 // function bodies). 6295 6296 pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) { 6297 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; 6298 if ( node === void 0 ) node = this.startNode(); 6299 6300 node.body = []; 6301 this.expect(types.braceL); 6302 if (createNewLexicalScope) { this.enterScope(0); } 6303 while (this.type !== types.braceR) { 6304 var stmt = this.parseStatement(null); 6305 node.body.push(stmt); 6306 } 6307 if (exitStrict) { this.strict = false; } 6308 this.next(); 6309 if (createNewLexicalScope) { this.exitScope(); } 6310 return this.finishNode(node, "BlockStatement") 6311 }; 6312 6313 // Parse a regular `for` loop. The disambiguation code in 6314 // `parseStatement` will already have parsed the init statement or 6315 // expression. 6316 6317 pp$1.parseFor = function(node, init) { 6318 node.init = init; 6319 this.expect(types.semi); 6320 node.test = this.type === types.semi ? null : this.parseExpression(); 6321 this.expect(types.semi); 6322 node.update = this.type === types.parenR ? null : this.parseExpression(); 6323 this.expect(types.parenR); 6324 node.body = this.parseStatement("for"); 6325 this.exitScope(); 6326 this.labels.pop(); 6327 return this.finishNode(node, "ForStatement") 6328 }; 6329 6330 // Parse a `for`/`in` and `for`/`of` loop, which are almost 6331 // same from parser's perspective. 6332 6333 pp$1.parseForIn = function(node, init) { 6334 var isForIn = this.type === types._in; 6335 this.next(); 6336 6337 if ( 6338 init.type === "VariableDeclaration" && 6339 init.declarations[0].init != null && 6340 ( 6341 !isForIn || 6342 this.options.ecmaVersion < 8 || 6343 this.strict || 6344 init.kind !== "var" || 6345 init.declarations[0].id.type !== "Identifier" 6346 ) 6347 ) { 6348 this.raise( 6349 init.start, 6350 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") 6351 ); 6352 } else if (init.type === "AssignmentPattern") { 6353 this.raise(init.start, "Invalid left-hand side in for-loop"); 6354 } 6355 node.left = init; 6356 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); 6357 this.expect(types.parenR); 6358 node.body = this.parseStatement("for"); 6359 this.exitScope(); 6360 this.labels.pop(); 6361 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") 6362 }; 6363 6364 // Parse a list of variable declarations. 6365 6366 pp$1.parseVar = function(node, isFor, kind) { 6367 node.declarations = []; 6368 node.kind = kind; 6369 for (;;) { 6370 var decl = this.startNode(); 6371 this.parseVarId(decl, kind); 6372 if (this.eat(types.eq)) { 6373 decl.init = this.parseMaybeAssign(isFor); 6374 } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { 6375 this.unexpected(); 6376 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) { 6377 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); 6378 } else { 6379 decl.init = null; 6380 } 6381 node.declarations.push(this.finishNode(decl, "VariableDeclarator")); 6382 if (!this.eat(types.comma)) { break } 6383 } 6384 return node 6385 }; 6386 6387 pp$1.parseVarId = function(decl, kind) { 6388 decl.id = this.parseBindingAtom(); 6389 this.checkLVal(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); 6390 }; 6391 6392 var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; 6393 6394 // Parse a function declaration or literal (depending on the 6395 // `statement & FUNC_STATEMENT`). 6396 6397 // Remove `allowExpressionBody` for 7.0.0, as it is only called with false 6398 pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) { 6399 this.initFunction(node); 6400 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { 6401 if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT)) 6402 { this.unexpected(); } 6403 node.generator = this.eat(types.star); 6404 } 6405 if (this.options.ecmaVersion >= 8) 6406 { node.async = !!isAsync; } 6407 6408 if (statement & FUNC_STATEMENT) { 6409 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent(); 6410 if (node.id && !(statement & FUNC_HANGING_STATEMENT)) 6411 // If it is a regular function declaration in sloppy mode, then it is 6412 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding 6413 // mode depends on properties of the current scope (see 6414 // treatFunctionsAsVar). 6415 { this.checkLVal(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } 6416 } 6417 6418 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; 6419 this.yieldPos = 0; 6420 this.awaitPos = 0; 6421 this.awaitIdentPos = 0; 6422 this.enterScope(functionFlags(node.async, node.generator)); 6423 6424 if (!(statement & FUNC_STATEMENT)) 6425 { node.id = this.type === types.name ? this.parseIdent() : null; } 6426 6427 this.parseFunctionParams(node); 6428 this.parseFunctionBody(node, allowExpressionBody, false); 6429 6430 this.yieldPos = oldYieldPos; 6431 this.awaitPos = oldAwaitPos; 6432 this.awaitIdentPos = oldAwaitIdentPos; 6433 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") 6434 }; 6435 6436 pp$1.parseFunctionParams = function(node) { 6437 this.expect(types.parenL); 6438 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); 6439 this.checkYieldAwaitInDefaultParams(); 6440 }; 6441 6442 // Parse a class declaration or literal (depending on the 6443 // `isStatement` parameter). 6444 6445 pp$1.parseClass = function(node, isStatement) { 6446 this.next(); 6447 6448 // ecma-262 14.6 Class Definitions 6449 // A class definition is always strict mode code. 6450 var oldStrict = this.strict; 6451 this.strict = true; 6452 6453 this.parseClassId(node, isStatement); 6454 this.parseClassSuper(node); 6455 var classBody = this.startNode(); 6456 var hadConstructor = false; 6457 classBody.body = []; 6458 this.expect(types.braceL); 6459 while (this.type !== types.braceR) { 6460 var element = this.parseClassElement(node.superClass !== null); 6461 if (element) { 6462 classBody.body.push(element); 6463 if (element.type === "MethodDefinition" && element.kind === "constructor") { 6464 if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); } 6465 hadConstructor = true; 6466 } 6467 } 6468 } 6469 this.strict = oldStrict; 6470 this.next(); 6471 node.body = this.finishNode(classBody, "ClassBody"); 6472 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") 6473 }; 6474 6475 pp$1.parseClassElement = function(constructorAllowsSuper) { 6476 var this$1$1 = this; 6477 6478 if (this.eat(types.semi)) { return null } 6479 6480 var method = this.startNode(); 6481 var tryContextual = function (k, noLineBreak) { 6482 if ( noLineBreak === void 0 ) noLineBreak = false; 6483 6484 var start = this$1$1.start, startLoc = this$1$1.startLoc; 6485 if (!this$1$1.eatContextual(k)) { return false } 6486 if (this$1$1.type !== types.parenL && (!noLineBreak || !this$1$1.canInsertSemicolon())) { return true } 6487 if (method.key) { this$1$1.unexpected(); } 6488 method.computed = false; 6489 method.key = this$1$1.startNodeAt(start, startLoc); 6490 method.key.name = k; 6491 this$1$1.finishNode(method.key, "Identifier"); 6492 return false 6493 }; 6494 6495 method.kind = "method"; 6496 method.static = tryContextual("static"); 6497 var isGenerator = this.eat(types.star); 6498 var isAsync = false; 6499 if (!isGenerator) { 6500 if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) { 6501 isAsync = true; 6502 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); 6503 } else if (tryContextual("get")) { 6504 method.kind = "get"; 6505 } else if (tryContextual("set")) { 6506 method.kind = "set"; 6507 } 6508 } 6509 if (!method.key) { this.parsePropertyName(method); } 6510 var key = method.key; 6511 var allowsDirectSuper = false; 6512 if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" || 6513 key.type === "Literal" && key.value === "constructor")) { 6514 if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); } 6515 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } 6516 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } 6517 method.kind = "constructor"; 6518 allowsDirectSuper = constructorAllowsSuper; 6519 } else if (method.static && key.type === "Identifier" && key.name === "prototype") { 6520 this.raise(key.start, "Classes may not have a static property named prototype"); 6521 } 6522 this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper); 6523 if (method.kind === "get" && method.value.params.length !== 0) 6524 { this.raiseRecoverable(method.value.start, "getter should have no params"); } 6525 if (method.kind === "set" && method.value.params.length !== 1) 6526 { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); } 6527 if (method.kind === "set" && method.value.params[0].type === "RestElement") 6528 { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); } 6529 return method 6530 }; 6531 6532 pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { 6533 method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); 6534 return this.finishNode(method, "MethodDefinition") 6535 }; 6536 6537 pp$1.parseClassId = function(node, isStatement) { 6538 if (this.type === types.name) { 6539 node.id = this.parseIdent(); 6540 if (isStatement) 6541 { this.checkLVal(node.id, BIND_LEXICAL, false); } 6542 } else { 6543 if (isStatement === true) 6544 { this.unexpected(); } 6545 node.id = null; 6546 } 6547 }; 6548 6549 pp$1.parseClassSuper = function(node) { 6550 node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null; 6551 }; 6552 6553 // Parses module export declaration. 6554 6555 pp$1.parseExport = function(node, exports) { 6556 this.next(); 6557 // export * from '...' 6558 if (this.eat(types.star)) { 6559 if (this.options.ecmaVersion >= 11) { 6560 if (this.eatContextual("as")) { 6561 node.exported = this.parseIdent(true); 6562 this.checkExport(exports, node.exported.name, this.lastTokStart); 6563 } else { 6564 node.exported = null; 6565 } 6566 } 6567 this.expectContextual("from"); 6568 if (this.type !== types.string) { this.unexpected(); } 6569 node.source = this.parseExprAtom(); 6570 this.semicolon(); 6571 return this.finishNode(node, "ExportAllDeclaration") 6572 } 6573 if (this.eat(types._default)) { // export default ... 6574 this.checkExport(exports, "default", this.lastTokStart); 6575 var isAsync; 6576 if (this.type === types._function || (isAsync = this.isAsyncFunction())) { 6577 var fNode = this.startNode(); 6578 this.next(); 6579 if (isAsync) { this.next(); } 6580 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); 6581 } else if (this.type === types._class) { 6582 var cNode = this.startNode(); 6583 node.declaration = this.parseClass(cNode, "nullableID"); 6584 } else { 6585 node.declaration = this.parseMaybeAssign(); 6586 this.semicolon(); 6587 } 6588 return this.finishNode(node, "ExportDefaultDeclaration") 6589 } 6590 // export var|const|let|function|class ... 6591 if (this.shouldParseExportStatement()) { 6592 node.declaration = this.parseStatement(null); 6593 if (node.declaration.type === "VariableDeclaration") 6594 { this.checkVariableExport(exports, node.declaration.declarations); } 6595 else 6596 { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); } 6597 node.specifiers = []; 6598 node.source = null; 6599 } else { // export { x, y as z } [from '...'] 6600 node.declaration = null; 6601 node.specifiers = this.parseExportSpecifiers(exports); 6602 if (this.eatContextual("from")) { 6603 if (this.type !== types.string) { this.unexpected(); } 6604 node.source = this.parseExprAtom(); 6605 } else { 6606 for (var i = 0, list = node.specifiers; i < list.length; i += 1) { 6607 // check for keywords used as local names 6608 var spec = list[i]; 6609 6610 this.checkUnreserved(spec.local); 6611 // check if export is defined 6612 this.checkLocalExport(spec.local); 6613 } 6614 6615 node.source = null; 6616 } 6617 this.semicolon(); 6618 } 6619 return this.finishNode(node, "ExportNamedDeclaration") 6620 }; 6621 6622 pp$1.checkExport = function(exports, name, pos) { 6623 if (!exports) { return } 6624 if (has(exports, name)) 6625 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } 6626 exports[name] = true; 6627 }; 6628 6629 pp$1.checkPatternExport = function(exports, pat) { 6630 var type = pat.type; 6631 if (type === "Identifier") 6632 { this.checkExport(exports, pat.name, pat.start); } 6633 else if (type === "ObjectPattern") 6634 { for (var i = 0, list = pat.properties; i < list.length; i += 1) 6635 { 6636 var prop = list[i]; 6637 6638 this.checkPatternExport(exports, prop); 6639 } } 6640 else if (type === "ArrayPattern") 6641 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { 6642 var elt = list$1[i$1]; 6643 6644 if (elt) { this.checkPatternExport(exports, elt); } 6645 } } 6646 else if (type === "Property") 6647 { this.checkPatternExport(exports, pat.value); } 6648 else if (type === "AssignmentPattern") 6649 { this.checkPatternExport(exports, pat.left); } 6650 else if (type === "RestElement") 6651 { this.checkPatternExport(exports, pat.argument); } 6652 else if (type === "ParenthesizedExpression") 6653 { this.checkPatternExport(exports, pat.expression); } 6654 }; 6655 6656 pp$1.checkVariableExport = function(exports, decls) { 6657 if (!exports) { return } 6658 for (var i = 0, list = decls; i < list.length; i += 1) 6659 { 6660 var decl = list[i]; 6661 6662 this.checkPatternExport(exports, decl.id); 6663 } 6664 }; 6665 6666 pp$1.shouldParseExportStatement = function() { 6667 return this.type.keyword === "var" || 6668 this.type.keyword === "const" || 6669 this.type.keyword === "class" || 6670 this.type.keyword === "function" || 6671 this.isLet() || 6672 this.isAsyncFunction() 6673 }; 6674 6675 // Parses a comma-separated list of module exports. 6676 6677 pp$1.parseExportSpecifiers = function(exports) { 6678 var nodes = [], first = true; 6679 // export { x, y as z } [from '...'] 6680 this.expect(types.braceL); 6681 while (!this.eat(types.braceR)) { 6682 if (!first) { 6683 this.expect(types.comma); 6684 if (this.afterTrailingComma(types.braceR)) { break } 6685 } else { first = false; } 6686 6687 var node = this.startNode(); 6688 node.local = this.parseIdent(true); 6689 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local; 6690 this.checkExport(exports, node.exported.name, node.exported.start); 6691 nodes.push(this.finishNode(node, "ExportSpecifier")); 6692 } 6693 return nodes 6694 }; 6695 6696 // Parses import declaration. 6697 6698 pp$1.parseImport = function(node) { 6699 this.next(); 6700 // import '...' 6701 if (this.type === types.string) { 6702 node.specifiers = empty; 6703 node.source = this.parseExprAtom(); 6704 } else { 6705 node.specifiers = this.parseImportSpecifiers(); 6706 this.expectContextual("from"); 6707 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); 6708 } 6709 this.semicolon(); 6710 return this.finishNode(node, "ImportDeclaration") 6711 }; 6712 6713 // Parses a comma-separated list of module imports. 6714 6715 pp$1.parseImportSpecifiers = function() { 6716 var nodes = [], first = true; 6717 if (this.type === types.name) { 6718 // import defaultObj, { x, y as z } from '...' 6719 var node = this.startNode(); 6720 node.local = this.parseIdent(); 6721 this.checkLVal(node.local, BIND_LEXICAL); 6722 nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); 6723 if (!this.eat(types.comma)) { return nodes } 6724 } 6725 if (this.type === types.star) { 6726 var node$1 = this.startNode(); 6727 this.next(); 6728 this.expectContextual("as"); 6729 node$1.local = this.parseIdent(); 6730 this.checkLVal(node$1.local, BIND_LEXICAL); 6731 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); 6732 return nodes 6733 } 6734 this.expect(types.braceL); 6735 while (!this.eat(types.braceR)) { 6736 if (!first) { 6737 this.expect(types.comma); 6738 if (this.afterTrailingComma(types.braceR)) { break } 6739 } else { first = false; } 6740 6741 var node$2 = this.startNode(); 6742 node$2.imported = this.parseIdent(true); 6743 if (this.eatContextual("as")) { 6744 node$2.local = this.parseIdent(); 6745 } else { 6746 this.checkUnreserved(node$2.imported); 6747 node$2.local = node$2.imported; 6748 } 6749 this.checkLVal(node$2.local, BIND_LEXICAL); 6750 nodes.push(this.finishNode(node$2, "ImportSpecifier")); 6751 } 6752 return nodes 6753 }; 6754 6755 // Set `ExpressionStatement#directive` property for directive prologues. 6756 pp$1.adaptDirectivePrologue = function(statements) { 6757 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { 6758 statements[i].directive = statements[i].expression.raw.slice(1, -1); 6759 } 6760 }; 6761 pp$1.isDirectiveCandidate = function(statement) { 6762 return ( 6763 statement.type === "ExpressionStatement" && 6764 statement.expression.type === "Literal" && 6765 typeof statement.expression.value === "string" && 6766 // Reject parenthesized strings. 6767 (this.input[statement.start] === "\"" || this.input[statement.start] === "'") 6768 ) 6769 }; 6770 6771 var pp$2 = Parser.prototype; 6772 6773 // Convert existing expression atom to assignable pattern 6774 // if possible. 6775 6776 pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) { 6777 if (this.options.ecmaVersion >= 6 && node) { 6778 switch (node.type) { 6779 case "Identifier": 6780 if (this.inAsync && node.name === "await") 6781 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } 6782 break 6783 6784 case "ObjectPattern": 6785 case "ArrayPattern": 6786 case "RestElement": 6787 break 6788 6789 case "ObjectExpression": 6790 node.type = "ObjectPattern"; 6791 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } 6792 for (var i = 0, list = node.properties; i < list.length; i += 1) { 6793 var prop = list[i]; 6794 6795 this.toAssignable(prop, isBinding); 6796 // Early error: 6797 // AssignmentRestProperty[Yield, Await] : 6798 // `...` DestructuringAssignmentTarget[Yield, Await] 6799 // 6800 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. 6801 if ( 6802 prop.type === "RestElement" && 6803 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") 6804 ) { 6805 this.raise(prop.argument.start, "Unexpected token"); 6806 } 6807 } 6808 break 6809 6810 case "Property": 6811 // AssignmentProperty has type === "Property" 6812 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } 6813 this.toAssignable(node.value, isBinding); 6814 break 6815 6816 case "ArrayExpression": 6817 node.type = "ArrayPattern"; 6818 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } 6819 this.toAssignableList(node.elements, isBinding); 6820 break 6821 6822 case "SpreadElement": 6823 node.type = "RestElement"; 6824 this.toAssignable(node.argument, isBinding); 6825 if (node.argument.type === "AssignmentPattern") 6826 { this.raise(node.argument.start, "Rest elements cannot have a default value"); } 6827 break 6828 6829 case "AssignmentExpression": 6830 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } 6831 node.type = "AssignmentPattern"; 6832 delete node.operator; 6833 this.toAssignable(node.left, isBinding); 6834 // falls through to AssignmentPattern 6835 6836 case "AssignmentPattern": 6837 break 6838 6839 case "ParenthesizedExpression": 6840 this.toAssignable(node.expression, isBinding, refDestructuringErrors); 6841 break 6842 6843 case "ChainExpression": 6844 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); 6845 break 6846 6847 case "MemberExpression": 6848 if (!isBinding) { break } 6849 6850 default: 6851 this.raise(node.start, "Assigning to rvalue"); 6852 } 6853 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } 6854 return node 6855 }; 6856 6857 // Convert list of expression atoms to binding list. 6858 6859 pp$2.toAssignableList = function(exprList, isBinding) { 6860 var end = exprList.length; 6861 for (var i = 0; i < end; i++) { 6862 var elt = exprList[i]; 6863 if (elt) { this.toAssignable(elt, isBinding); } 6864 } 6865 if (end) { 6866 var last = exprList[end - 1]; 6867 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") 6868 { this.unexpected(last.argument.start); } 6869 } 6870 return exprList 6871 }; 6872 6873 // Parses spread element. 6874 6875 pp$2.parseSpread = function(refDestructuringErrors) { 6876 var node = this.startNode(); 6877 this.next(); 6878 node.argument = this.parseMaybeAssign(false, refDestructuringErrors); 6879 return this.finishNode(node, "SpreadElement") 6880 }; 6881 6882 pp$2.parseRestBinding = function() { 6883 var node = this.startNode(); 6884 this.next(); 6885 6886 // RestElement inside of a function parameter must be an identifier 6887 if (this.options.ecmaVersion === 6 && this.type !== types.name) 6888 { this.unexpected(); } 6889 6890 node.argument = this.parseBindingAtom(); 6891 6892 return this.finishNode(node, "RestElement") 6893 }; 6894 6895 // Parses lvalue (assignable) atom. 6896 6897 pp$2.parseBindingAtom = function() { 6898 if (this.options.ecmaVersion >= 6) { 6899 switch (this.type) { 6900 case types.bracketL: 6901 var node = this.startNode(); 6902 this.next(); 6903 node.elements = this.parseBindingList(types.bracketR, true, true); 6904 return this.finishNode(node, "ArrayPattern") 6905 6906 case types.braceL: 6907 return this.parseObj(true) 6908 } 6909 } 6910 return this.parseIdent() 6911 }; 6912 6913 pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) { 6914 var elts = [], first = true; 6915 while (!this.eat(close)) { 6916 if (first) { first = false; } 6917 else { this.expect(types.comma); } 6918 if (allowEmpty && this.type === types.comma) { 6919 elts.push(null); 6920 } else if (allowTrailingComma && this.afterTrailingComma(close)) { 6921 break 6922 } else if (this.type === types.ellipsis) { 6923 var rest = this.parseRestBinding(); 6924 this.parseBindingListItem(rest); 6925 elts.push(rest); 6926 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } 6927 this.expect(close); 6928 break 6929 } else { 6930 var elem = this.parseMaybeDefault(this.start, this.startLoc); 6931 this.parseBindingListItem(elem); 6932 elts.push(elem); 6933 } 6934 } 6935 return elts 6936 }; 6937 6938 pp$2.parseBindingListItem = function(param) { 6939 return param 6940 }; 6941 6942 // Parses assignment pattern around given atom if possible. 6943 6944 pp$2.parseMaybeDefault = function(startPos, startLoc, left) { 6945 left = left || this.parseBindingAtom(); 6946 if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left } 6947 var node = this.startNodeAt(startPos, startLoc); 6948 node.left = left; 6949 node.right = this.parseMaybeAssign(); 6950 return this.finishNode(node, "AssignmentPattern") 6951 }; 6952 6953 // Verify that a node is an lval â something that can be assigned 6954 // to. 6955 // bindingType can be either: 6956 // 'var' indicating that the lval creates a 'var' binding 6957 // 'let' indicating that the lval creates a lexical ('let' or 'const') binding 6958 // 'none' indicating that the binding should be checked for illegal identifiers, but not for duplicate references 6959 6960 pp$2.checkLVal = function(expr, bindingType, checkClashes) { 6961 if ( bindingType === void 0 ) bindingType = BIND_NONE; 6962 6963 switch (expr.type) { 6964 case "Identifier": 6965 if (bindingType === BIND_LEXICAL && expr.name === "let") 6966 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } 6967 if (this.strict && this.reservedWordsStrictBind.test(expr.name)) 6968 { this.raiseRecoverable(expr.start, (bindingType ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } 6969 if (checkClashes) { 6970 if (has(checkClashes, expr.name)) 6971 { this.raiseRecoverable(expr.start, "Argument name clash"); } 6972 checkClashes[expr.name] = true; 6973 } 6974 if (bindingType !== BIND_NONE && bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } 6975 break 6976 6977 case "ChainExpression": 6978 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); 6979 break 6980 6981 case "MemberExpression": 6982 if (bindingType) { this.raiseRecoverable(expr.start, "Binding member expression"); } 6983 break 6984 6985 case "ObjectPattern": 6986 for (var i = 0, list = expr.properties; i < list.length; i += 1) 6987 { 6988 var prop = list[i]; 6989 6990 this.checkLVal(prop, bindingType, checkClashes); 6991 } 6992 break 6993 6994 case "Property": 6995 // AssignmentProperty has type === "Property" 6996 this.checkLVal(expr.value, bindingType, checkClashes); 6997 break 6998 6999 case "ArrayPattern": 7000 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { 7001 var elem = list$1[i$1]; 7002 7003 if (elem) { this.checkLVal(elem, bindingType, checkClashes); } 7004 } 7005 break 7006 7007 case "AssignmentPattern": 7008 this.checkLVal(expr.left, bindingType, checkClashes); 7009 break 7010 7011 case "RestElement": 7012 this.checkLVal(expr.argument, bindingType, checkClashes); 7013 break 7014 7015 case "ParenthesizedExpression": 7016 this.checkLVal(expr.expression, bindingType, checkClashes); 7017 break 7018 7019 default: 7020 this.raise(expr.start, (bindingType ? "Binding" : "Assigning to") + " rvalue"); 7021 } 7022 }; 7023 7024 // A recursive descent parser operates by defining functions for all 7025 7026 var pp$3 = Parser.prototype; 7027 7028 // Check if property name clashes with already added. 7029 // Object/class getters and setters are not allowed to clash â 7030 // either with each other or with an init property â and in 7031 // strict mode, init properties are also not allowed to be repeated. 7032 7033 pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) { 7034 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") 7035 { return } 7036 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) 7037 { return } 7038 var key = prop.key; 7039 var name; 7040 switch (key.type) { 7041 case "Identifier": name = key.name; break 7042 case "Literal": name = String(key.value); break 7043 default: return 7044 } 7045 var kind = prop.kind; 7046 if (this.options.ecmaVersion >= 6) { 7047 if (name === "__proto__" && kind === "init") { 7048 if (propHash.proto) { 7049 if (refDestructuringErrors) { 7050 if (refDestructuringErrors.doubleProto < 0) 7051 { refDestructuringErrors.doubleProto = key.start; } 7052 // Backwards-compat kludge. Can be removed in version 6.0 7053 } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); } 7054 } 7055 propHash.proto = true; 7056 } 7057 return 7058 } 7059 name = "$" + name; 7060 var other = propHash[name]; 7061 if (other) { 7062 var redefinition; 7063 if (kind === "init") { 7064 redefinition = this.strict && other.init || other.get || other.set; 7065 } else { 7066 redefinition = other.init || other[kind]; 7067 } 7068 if (redefinition) 7069 { this.raiseRecoverable(key.start, "Redefinition of property"); } 7070 } else { 7071 other = propHash[name] = { 7072 init: false, 7073 get: false, 7074 set: false 7075 }; 7076 } 7077 other[kind] = true; 7078 }; 7079 7080 // ### Expression parsing 7081 7082 // These nest, from the most general expression type at the top to 7083 // 'atomic', nondivisible expression types at the bottom. Most of 7084 // the functions will simply let the function(s) below them parse, 7085 // and, *if* the syntactic construct they handle is present, wrap 7086 // the AST node that the inner parser gave them in another node. 7087 7088 // Parse a full expression. The optional arguments are used to 7089 // forbid the `in` operator (in for loops initalization expressions) 7090 // and provide reference for storing '=' operator inside shorthand 7091 // property assignment in contexts where both object expression 7092 // and object pattern might appear (so it's possible to raise 7093 // delayed syntax error at correct position). 7094 7095 pp$3.parseExpression = function(noIn, refDestructuringErrors) { 7096 var startPos = this.start, startLoc = this.startLoc; 7097 var expr = this.parseMaybeAssign(noIn, refDestructuringErrors); 7098 if (this.type === types.comma) { 7099 var node = this.startNodeAt(startPos, startLoc); 7100 node.expressions = [expr]; 7101 while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); } 7102 return this.finishNode(node, "SequenceExpression") 7103 } 7104 return expr 7105 }; 7106 7107 // Parse an assignment expression. This includes applications of 7108 // operators like `+=`. 7109 7110 pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) { 7111 if (this.isContextual("yield")) { 7112 if (this.inGenerator) { return this.parseYield(noIn) } 7113 // The tokenizer will assume an expression is allowed after 7114 // `yield`, but this isn't that kind of yield 7115 else { this.exprAllowed = false; } 7116 } 7117 7118 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1; 7119 if (refDestructuringErrors) { 7120 oldParenAssign = refDestructuringErrors.parenthesizedAssign; 7121 oldTrailingComma = refDestructuringErrors.trailingComma; 7122 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; 7123 } else { 7124 refDestructuringErrors = new DestructuringErrors; 7125 ownDestructuringErrors = true; 7126 } 7127 7128 var startPos = this.start, startLoc = this.startLoc; 7129 if (this.type === types.parenL || this.type === types.name) 7130 { this.potentialArrowAt = this.start; } 7131 var left = this.parseMaybeConditional(noIn, refDestructuringErrors); 7132 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } 7133 if (this.type.isAssign) { 7134 var node = this.startNodeAt(startPos, startLoc); 7135 node.operator = this.value; 7136 node.left = this.type === types.eq ? this.toAssignable(left, false, refDestructuringErrors) : left; 7137 if (!ownDestructuringErrors) { 7138 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; 7139 } 7140 if (refDestructuringErrors.shorthandAssign >= node.left.start) 7141 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly 7142 this.checkLVal(left); 7143 this.next(); 7144 node.right = this.parseMaybeAssign(noIn); 7145 return this.finishNode(node, "AssignmentExpression") 7146 } else { 7147 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } 7148 } 7149 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } 7150 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } 7151 return left 7152 }; 7153 7154 // Parse a ternary conditional (`?:`) operator. 7155 7156 pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) { 7157 var startPos = this.start, startLoc = this.startLoc; 7158 var expr = this.parseExprOps(noIn, refDestructuringErrors); 7159 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } 7160 if (this.eat(types.question)) { 7161 var node = this.startNodeAt(startPos, startLoc); 7162 node.test = expr; 7163 node.consequent = this.parseMaybeAssign(); 7164 this.expect(types.colon); 7165 node.alternate = this.parseMaybeAssign(noIn); 7166 return this.finishNode(node, "ConditionalExpression") 7167 } 7168 return expr 7169 }; 7170 7171 // Start the precedence parser. 7172 7173 pp$3.parseExprOps = function(noIn, refDestructuringErrors) { 7174 var startPos = this.start, startLoc = this.startLoc; 7175 var expr = this.parseMaybeUnary(refDestructuringErrors, false); 7176 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } 7177 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn) 7178 }; 7179 7180 // Parse binary operators with the operator precedence parsing 7181 // algorithm. `left` is the left-hand side of the operator. 7182 // `minPrec` provides context that allows the function to stop and 7183 // defer further parser to one of its callers when it encounters an 7184 // operator that has a lower precedence than the set it is parsing. 7185 7186 pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) { 7187 var prec = this.type.binop; 7188 if (prec != null && (!noIn || this.type !== types._in)) { 7189 if (prec > minPrec) { 7190 var logical = this.type === types.logicalOR || this.type === types.logicalAND; 7191 var coalesce = this.type === types.coalesce; 7192 if (coalesce) { 7193 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. 7194 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. 7195 prec = types.logicalAND.binop; 7196 } 7197 var op = this.value; 7198 this.next(); 7199 var startPos = this.start, startLoc = this.startLoc; 7200 var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn); 7201 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); 7202 if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) { 7203 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); 7204 } 7205 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn) 7206 } 7207 } 7208 return left 7209 }; 7210 7211 pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) { 7212 var node = this.startNodeAt(startPos, startLoc); 7213 node.left = left; 7214 node.operator = op; 7215 node.right = right; 7216 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") 7217 }; 7218 7219 // Parse unary operators, both prefix and postfix. 7220 7221 pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) { 7222 var startPos = this.start, startLoc = this.startLoc, expr; 7223 if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) { 7224 expr = this.parseAwait(); 7225 sawUnary = true; 7226 } else if (this.type.prefix) { 7227 var node = this.startNode(), update = this.type === types.incDec; 7228 node.operator = this.value; 7229 node.prefix = true; 7230 this.next(); 7231 node.argument = this.parseMaybeUnary(null, true); 7232 this.checkExpressionErrors(refDestructuringErrors, true); 7233 if (update) { this.checkLVal(node.argument); } 7234 else if (this.strict && node.operator === "delete" && 7235 node.argument.type === "Identifier") 7236 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } 7237 else { sawUnary = true; } 7238 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); 7239 } else { 7240 expr = this.parseExprSubscripts(refDestructuringErrors); 7241 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } 7242 while (this.type.postfix && !this.canInsertSemicolon()) { 7243 var node$1 = this.startNodeAt(startPos, startLoc); 7244 node$1.operator = this.value; 7245 node$1.prefix = false; 7246 node$1.argument = expr; 7247 this.checkLVal(expr); 7248 this.next(); 7249 expr = this.finishNode(node$1, "UpdateExpression"); 7250 } 7251 } 7252 7253 if (!sawUnary && this.eat(types.starstar)) 7254 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) } 7255 else 7256 { return expr } 7257 }; 7258 7259 // Parse call, dot, and `[]`-subscript expressions. 7260 7261 pp$3.parseExprSubscripts = function(refDestructuringErrors) { 7262 var startPos = this.start, startLoc = this.startLoc; 7263 var expr = this.parseExprAtom(refDestructuringErrors); 7264 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") 7265 { return expr } 7266 var result = this.parseSubscripts(expr, startPos, startLoc); 7267 if (refDestructuringErrors && result.type === "MemberExpression") { 7268 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } 7269 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } 7270 } 7271 return result 7272 }; 7273 7274 pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) { 7275 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && 7276 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && 7277 this.potentialArrowAt === base.start; 7278 var optionalChained = false; 7279 7280 while (true) { 7281 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained); 7282 7283 if (element.optional) { optionalChained = true; } 7284 if (element === base || element.type === "ArrowFunctionExpression") { 7285 if (optionalChained) { 7286 var chainNode = this.startNodeAt(startPos, startLoc); 7287 chainNode.expression = element; 7288 element = this.finishNode(chainNode, "ChainExpression"); 7289 } 7290 return element 7291 } 7292 7293 base = element; 7294 } 7295 }; 7296 7297 pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) { 7298 var optionalSupported = this.options.ecmaVersion >= 11; 7299 var optional = optionalSupported && this.eat(types.questionDot); 7300 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } 7301 7302 var computed = this.eat(types.bracketL); 7303 if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) { 7304 var node = this.startNodeAt(startPos, startLoc); 7305 node.object = base; 7306 node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never"); 7307 node.computed = !!computed; 7308 if (computed) { this.expect(types.bracketR); } 7309 if (optionalSupported) { 7310 node.optional = optional; 7311 } 7312 base = this.finishNode(node, "MemberExpression"); 7313 } else if (!noCalls && this.eat(types.parenL)) { 7314 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; 7315 this.yieldPos = 0; 7316 this.awaitPos = 0; 7317 this.awaitIdentPos = 0; 7318 var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); 7319 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) { 7320 this.checkPatternErrors(refDestructuringErrors, false); 7321 this.checkYieldAwaitInDefaultParams(); 7322 if (this.awaitIdentPos > 0) 7323 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } 7324 this.yieldPos = oldYieldPos; 7325 this.awaitPos = oldAwaitPos; 7326 this.awaitIdentPos = oldAwaitIdentPos; 7327 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true) 7328 } 7329 this.checkExpressionErrors(refDestructuringErrors, true); 7330 this.yieldPos = oldYieldPos || this.yieldPos; 7331 this.awaitPos = oldAwaitPos || this.awaitPos; 7332 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; 7333 var node$1 = this.startNodeAt(startPos, startLoc); 7334 node$1.callee = base; 7335 node$1.arguments = exprList; 7336 if (optionalSupported) { 7337 node$1.optional = optional; 7338 } 7339 base = this.finishNode(node$1, "CallExpression"); 7340 } else if (this.type === types.backQuote) { 7341 if (optional || optionalChained) { 7342 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); 7343 } 7344 var node$2 = this.startNodeAt(startPos, startLoc); 7345 node$2.tag = base; 7346 node$2.quasi = this.parseTemplate({isTagged: true}); 7347 base = this.finishNode(node$2, "TaggedTemplateExpression"); 7348 } 7349 return base 7350 }; 7351 7352 // Parse an atomic expression â either a single token that is an 7353 // expression, an expression started by a keyword like `function` or 7354 // `new`, or an expression wrapped in punctuation like `()`, `[]`, 7355 // or `{}`. 7356 7357 pp$3.parseExprAtom = function(refDestructuringErrors) { 7358 // If a division operator appears in an expression position, the 7359 // tokenizer got confused, and we force it to read a regexp instead. 7360 if (this.type === types.slash) { this.readRegexp(); } 7361 7362 var node, canBeArrow = this.potentialArrowAt === this.start; 7363 switch (this.type) { 7364 case types._super: 7365 if (!this.allowSuper) 7366 { this.raise(this.start, "'super' keyword outside a method"); } 7367 node = this.startNode(); 7368 this.next(); 7369 if (this.type === types.parenL && !this.allowDirectSuper) 7370 { this.raise(node.start, "super() call outside constructor of a subclass"); } 7371 // The `super` keyword can appear at below: 7372 // SuperProperty: 7373 // super [ Expression ] 7374 // super . IdentifierName 7375 // SuperCall: 7376 // super ( Arguments ) 7377 if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL) 7378 { this.unexpected(); } 7379 return this.finishNode(node, "Super") 7380 7381 case types._this: 7382 node = this.startNode(); 7383 this.next(); 7384 return this.finishNode(node, "ThisExpression") 7385 7386 case types.name: 7387 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; 7388 var id = this.parseIdent(false); 7389 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function)) 7390 { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) } 7391 if (canBeArrow && !this.canInsertSemicolon()) { 7392 if (this.eat(types.arrow)) 7393 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) } 7394 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) { 7395 id = this.parseIdent(false); 7396 if (this.canInsertSemicolon() || !this.eat(types.arrow)) 7397 { this.unexpected(); } 7398 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true) 7399 } 7400 } 7401 return id 7402 7403 case types.regexp: 7404 var value = this.value; 7405 node = this.parseLiteral(value.value); 7406 node.regex = {pattern: value.pattern, flags: value.flags}; 7407 return node 7408 7409 case types.num: case types.string: 7410 return this.parseLiteral(this.value) 7411 7412 case types._null: case types._true: case types._false: 7413 node = this.startNode(); 7414 node.value = this.type === types._null ? null : this.type === types._true; 7415 node.raw = this.type.keyword; 7416 this.next(); 7417 return this.finishNode(node, "Literal") 7418 7419 case types.parenL: 7420 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow); 7421 if (refDestructuringErrors) { 7422 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) 7423 { refDestructuringErrors.parenthesizedAssign = start; } 7424 if (refDestructuringErrors.parenthesizedBind < 0) 7425 { refDestructuringErrors.parenthesizedBind = start; } 7426 } 7427 return expr 7428 7429 case types.bracketL: 7430 node = this.startNode(); 7431 this.next(); 7432 node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors); 7433 return this.finishNode(node, "ArrayExpression") 7434 7435 case types.braceL: 7436 return this.parseObj(false, refDestructuringErrors) 7437 7438 case types._function: 7439 node = this.startNode(); 7440 this.next(); 7441 return this.parseFunction(node, 0) 7442 7443 case types._class: 7444 return this.parseClass(this.startNode(), false) 7445 7446 case types._new: 7447 return this.parseNew() 7448 7449 case types.backQuote: 7450 return this.parseTemplate() 7451 7452 case types._import: 7453 if (this.options.ecmaVersion >= 11) { 7454 return this.parseExprImport() 7455 } else { 7456 return this.unexpected() 7457 } 7458 7459 default: 7460 this.unexpected(); 7461 } 7462 }; 7463 7464 pp$3.parseExprImport = function() { 7465 var node = this.startNode(); 7466 7467 // Consume `import` as an identifier for `import.meta`. 7468 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. 7469 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } 7470 var meta = this.parseIdent(true); 7471 7472 switch (this.type) { 7473 case types.parenL: 7474 return this.parseDynamicImport(node) 7475 case types.dot: 7476 node.meta = meta; 7477 return this.parseImportMeta(node) 7478 default: 7479 this.unexpected(); 7480 } 7481 }; 7482 7483 pp$3.parseDynamicImport = function(node) { 7484 this.next(); // skip `(` 7485 7486 // Parse node.source. 7487 node.source = this.parseMaybeAssign(); 7488 7489 // Verify ending. 7490 if (!this.eat(types.parenR)) { 7491 var errorPos = this.start; 7492 if (this.eat(types.comma) && this.eat(types.parenR)) { 7493 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); 7494 } else { 7495 this.unexpected(errorPos); 7496 } 7497 } 7498 7499 return this.finishNode(node, "ImportExpression") 7500 }; 7501 7502 pp$3.parseImportMeta = function(node) { 7503 this.next(); // skip `.` 7504 7505 var containsEsc = this.containsEsc; 7506 node.property = this.parseIdent(true); 7507 7508 if (node.property.name !== "meta") 7509 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } 7510 if (containsEsc) 7511 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } 7512 if (this.options.sourceType !== "module") 7513 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } 7514 7515 return this.finishNode(node, "MetaProperty") 7516 }; 7517 7518 pp$3.parseLiteral = function(value) { 7519 var node = this.startNode(); 7520 node.value = value; 7521 node.raw = this.input.slice(this.start, this.end); 7522 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } 7523 this.next(); 7524 return this.finishNode(node, "Literal") 7525 }; 7526 7527 pp$3.parseParenExpression = function() { 7528 this.expect(types.parenL); 7529 var val = this.parseExpression(); 7530 this.expect(types.parenR); 7531 return val 7532 }; 7533 7534 pp$3.parseParenAndDistinguishExpression = function(canBeArrow) { 7535 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; 7536 if (this.options.ecmaVersion >= 6) { 7537 this.next(); 7538 7539 var innerStartPos = this.start, innerStartLoc = this.startLoc; 7540 var exprList = [], first = true, lastIsComma = false; 7541 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; 7542 this.yieldPos = 0; 7543 this.awaitPos = 0; 7544 // Do not save awaitIdentPos to allow checking awaits nested in parameters 7545 while (this.type !== types.parenR) { 7546 first ? first = false : this.expect(types.comma); 7547 if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) { 7548 lastIsComma = true; 7549 break 7550 } else if (this.type === types.ellipsis) { 7551 spreadStart = this.start; 7552 exprList.push(this.parseParenItem(this.parseRestBinding())); 7553 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } 7554 break 7555 } else { 7556 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); 7557 } 7558 } 7559 var innerEndPos = this.start, innerEndLoc = this.startLoc; 7560 this.expect(types.parenR); 7561 7562 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) { 7563 this.checkPatternErrors(refDestructuringErrors, false); 7564 this.checkYieldAwaitInDefaultParams(); 7565 this.yieldPos = oldYieldPos; 7566 this.awaitPos = oldAwaitPos; 7567 return this.parseParenArrowList(startPos, startLoc, exprList) 7568 } 7569 7570 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } 7571 if (spreadStart) { this.unexpected(spreadStart); } 7572 this.checkExpressionErrors(refDestructuringErrors, true); 7573 this.yieldPos = oldYieldPos || this.yieldPos; 7574 this.awaitPos = oldAwaitPos || this.awaitPos; 7575 7576 if (exprList.length > 1) { 7577 val = this.startNodeAt(innerStartPos, innerStartLoc); 7578 val.expressions = exprList; 7579 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); 7580 } else { 7581 val = exprList[0]; 7582 } 7583 } else { 7584 val = this.parseParenExpression(); 7585 } 7586 7587 if (this.options.preserveParens) { 7588 var par = this.startNodeAt(startPos, startLoc); 7589 par.expression = val; 7590 return this.finishNode(par, "ParenthesizedExpression") 7591 } else { 7592 return val 7593 } 7594 }; 7595 7596 pp$3.parseParenItem = function(item) { 7597 return item 7598 }; 7599 7600 pp$3.parseParenArrowList = function(startPos, startLoc, exprList) { 7601 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList) 7602 }; 7603 7604 // New's precedence is slightly tricky. It must allow its argument to 7605 // be a `[]` or dot subscript expression, but not a call â at least, 7606 // not without wrapping it in parentheses. Thus, it uses the noCalls 7607 // argument to parseSubscripts to prevent it from consuming the 7608 // argument list. 7609 7610 var empty$1 = []; 7611 7612 pp$3.parseNew = function() { 7613 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } 7614 var node = this.startNode(); 7615 var meta = this.parseIdent(true); 7616 if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) { 7617 node.meta = meta; 7618 var containsEsc = this.containsEsc; 7619 node.property = this.parseIdent(true); 7620 if (node.property.name !== "target") 7621 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } 7622 if (containsEsc) 7623 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } 7624 if (!this.inNonArrowFunction()) 7625 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); } 7626 return this.finishNode(node, "MetaProperty") 7627 } 7628 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import; 7629 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true); 7630 if (isImport && node.callee.type === "ImportExpression") { 7631 this.raise(startPos, "Cannot use new with import()"); 7632 } 7633 if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); } 7634 else { node.arguments = empty$1; } 7635 return this.finishNode(node, "NewExpression") 7636 }; 7637 7638 // Parse template expression. 7639 7640 pp$3.parseTemplateElement = function(ref) { 7641 var isTagged = ref.isTagged; 7642 7643 var elem = this.startNode(); 7644 if (this.type === types.invalidTemplate) { 7645 if (!isTagged) { 7646 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); 7647 } 7648 elem.value = { 7649 raw: this.value, 7650 cooked: null 7651 }; 7652 } else { 7653 elem.value = { 7654 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), 7655 cooked: this.value 7656 }; 7657 } 7658 this.next(); 7659 elem.tail = this.type === types.backQuote; 7660 return this.finishNode(elem, "TemplateElement") 7661 }; 7662 7663 pp$3.parseTemplate = function(ref) { 7664 if ( ref === void 0 ) ref = {}; 7665 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; 7666 7667 var node = this.startNode(); 7668 this.next(); 7669 node.expressions = []; 7670 var curElt = this.parseTemplateElement({isTagged: isTagged}); 7671 node.quasis = [curElt]; 7672 while (!curElt.tail) { 7673 if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); } 7674 this.expect(types.dollarBraceL); 7675 node.expressions.push(this.parseExpression()); 7676 this.expect(types.braceR); 7677 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); 7678 } 7679 this.next(); 7680 return this.finishNode(node, "TemplateLiteral") 7681 }; 7682 7683 pp$3.isAsyncProp = function(prop) { 7684 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && 7685 (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) && 7686 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) 7687 }; 7688 7689 // Parse an object literal or binding pattern. 7690 7691 pp$3.parseObj = function(isPattern, refDestructuringErrors) { 7692 var node = this.startNode(), first = true, propHash = {}; 7693 node.properties = []; 7694 this.next(); 7695 while (!this.eat(types.braceR)) { 7696 if (!first) { 7697 this.expect(types.comma); 7698 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break } 7699 } else { first = false; } 7700 7701 var prop = this.parseProperty(isPattern, refDestructuringErrors); 7702 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } 7703 node.properties.push(prop); 7704 } 7705 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") 7706 }; 7707 7708 pp$3.parseProperty = function(isPattern, refDestructuringErrors) { 7709 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; 7710 if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) { 7711 if (isPattern) { 7712 prop.argument = this.parseIdent(false); 7713 if (this.type === types.comma) { 7714 this.raise(this.start, "Comma is not permitted after the rest element"); 7715 } 7716 return this.finishNode(prop, "RestElement") 7717 } 7718 // To disallow parenthesized identifier via `this.toAssignable()`. 7719 if (this.type === types.parenL && refDestructuringErrors) { 7720 if (refDestructuringErrors.parenthesizedAssign < 0) { 7721 refDestructuringErrors.parenthesizedAssign = this.start; 7722 } 7723 if (refDestructuringErrors.parenthesizedBind < 0) { 7724 refDestructuringErrors.parenthesizedBind = this.start; 7725 } 7726 } 7727 // Parse argument. 7728 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); 7729 // To disallow trailing comma via `this.toAssignable()`. 7730 if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { 7731 refDestructuringErrors.trailingComma = this.start; 7732 } 7733 // Finish 7734 return this.finishNode(prop, "SpreadElement") 7735 } 7736 if (this.options.ecmaVersion >= 6) { 7737 prop.method = false; 7738 prop.shorthand = false; 7739 if (isPattern || refDestructuringErrors) { 7740 startPos = this.start; 7741 startLoc = this.startLoc; 7742 } 7743 if (!isPattern) 7744 { isGenerator = this.eat(types.star); } 7745 } 7746 var containsEsc = this.containsEsc; 7747 this.parsePropertyName(prop); 7748 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { 7749 isAsync = true; 7750 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star); 7751 this.parsePropertyName(prop, refDestructuringErrors); 7752 } else { 7753 isAsync = false; 7754 } 7755 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); 7756 return this.finishNode(prop, "Property") 7757 }; 7758 7759 pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { 7760 if ((isGenerator || isAsync) && this.type === types.colon) 7761 { this.unexpected(); } 7762 7763 if (this.eat(types.colon)) { 7764 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); 7765 prop.kind = "init"; 7766 } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) { 7767 if (isPattern) { this.unexpected(); } 7768 prop.kind = "init"; 7769 prop.method = true; 7770 prop.value = this.parseMethod(isGenerator, isAsync); 7771 } else if (!isPattern && !containsEsc && 7772 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && 7773 (prop.key.name === "get" || prop.key.name === "set") && 7774 (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) { 7775 if (isGenerator || isAsync) { this.unexpected(); } 7776 prop.kind = prop.key.name; 7777 this.parsePropertyName(prop); 7778 prop.value = this.parseMethod(false); 7779 var paramCount = prop.kind === "get" ? 0 : 1; 7780 if (prop.value.params.length !== paramCount) { 7781 var start = prop.value.start; 7782 if (prop.kind === "get") 7783 { this.raiseRecoverable(start, "getter should have no params"); } 7784 else 7785 { this.raiseRecoverable(start, "setter should have exactly one param"); } 7786 } else { 7787 if (prop.kind === "set" && prop.value.params[0].type === "RestElement") 7788 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } 7789 } 7790 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { 7791 if (isGenerator || isAsync) { this.unexpected(); } 7792 this.checkUnreserved(prop.key); 7793 if (prop.key.name === "await" && !this.awaitIdentPos) 7794 { this.awaitIdentPos = startPos; } 7795 prop.kind = "init"; 7796 if (isPattern) { 7797 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); 7798 } else if (this.type === types.eq && refDestructuringErrors) { 7799 if (refDestructuringErrors.shorthandAssign < 0) 7800 { refDestructuringErrors.shorthandAssign = this.start; } 7801 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key); 7802 } else { 7803 prop.value = prop.key; 7804 } 7805 prop.shorthand = true; 7806 } else { this.unexpected(); } 7807 }; 7808 7809 pp$3.parsePropertyName = function(prop) { 7810 if (this.options.ecmaVersion >= 6) { 7811 if (this.eat(types.bracketL)) { 7812 prop.computed = true; 7813 prop.key = this.parseMaybeAssign(); 7814 this.expect(types.bracketR); 7815 return prop.key 7816 } else { 7817 prop.computed = false; 7818 } 7819 } 7820 return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") 7821 }; 7822 7823 // Initialize empty function node. 7824 7825 pp$3.initFunction = function(node) { 7826 node.id = null; 7827 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } 7828 if (this.options.ecmaVersion >= 8) { node.async = false; } 7829 }; 7830 7831 // Parse object or class method. 7832 7833 pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { 7834 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; 7835 7836 this.initFunction(node); 7837 if (this.options.ecmaVersion >= 6) 7838 { node.generator = isGenerator; } 7839 if (this.options.ecmaVersion >= 8) 7840 { node.async = !!isAsync; } 7841 7842 this.yieldPos = 0; 7843 this.awaitPos = 0; 7844 this.awaitIdentPos = 0; 7845 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); 7846 7847 this.expect(types.parenL); 7848 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8); 7849 this.checkYieldAwaitInDefaultParams(); 7850 this.parseFunctionBody(node, false, true); 7851 7852 this.yieldPos = oldYieldPos; 7853 this.awaitPos = oldAwaitPos; 7854 this.awaitIdentPos = oldAwaitIdentPos; 7855 return this.finishNode(node, "FunctionExpression") 7856 }; 7857 7858 // Parse arrow function expression with given parameters. 7859 7860 pp$3.parseArrowExpression = function(node, params, isAsync) { 7861 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; 7862 7863 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); 7864 this.initFunction(node); 7865 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } 7866 7867 this.yieldPos = 0; 7868 this.awaitPos = 0; 7869 this.awaitIdentPos = 0; 7870 7871 node.params = this.toAssignableList(params, true); 7872 this.parseFunctionBody(node, true, false); 7873 7874 this.yieldPos = oldYieldPos; 7875 this.awaitPos = oldAwaitPos; 7876 this.awaitIdentPos = oldAwaitIdentPos; 7877 return this.finishNode(node, "ArrowFunctionExpression") 7878 }; 7879 7880 // Parse function body and check parameters. 7881 7882 pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) { 7883 var isExpression = isArrowFunction && this.type !== types.braceL; 7884 var oldStrict = this.strict, useStrict = false; 7885 7886 if (isExpression) { 7887 node.body = this.parseMaybeAssign(); 7888 node.expression = true; 7889 this.checkParams(node, false); 7890 } else { 7891 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); 7892 if (!oldStrict || nonSimple) { 7893 useStrict = this.strictDirective(this.end); 7894 // If this is a strict mode function, verify that argument names 7895 // are not repeated, and it does not try to bind the words `eval` 7896 // or `arguments`. 7897 if (useStrict && nonSimple) 7898 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } 7899 } 7900 // Start a new scope with regard to labels and the `inFunction` 7901 // flag (restore them to their old value afterwards). 7902 var oldLabels = this.labels; 7903 this.labels = []; 7904 if (useStrict) { this.strict = true; } 7905 7906 // Add the params to varDeclaredNames to ensure that an error is thrown 7907 // if a let/const declaration in the function clashes with one of the params. 7908 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); 7909 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' 7910 if (this.strict && node.id) { this.checkLVal(node.id, BIND_OUTSIDE); } 7911 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); 7912 node.expression = false; 7913 this.adaptDirectivePrologue(node.body.body); 7914 this.labels = oldLabels; 7915 } 7916 this.exitScope(); 7917 }; 7918 7919 pp$3.isSimpleParamList = function(params) { 7920 for (var i = 0, list = params; i < list.length; i += 1) 7921 { 7922 var param = list[i]; 7923 7924 if (param.type !== "Identifier") { return false 7925 } } 7926 return true 7927 }; 7928 7929 // Checks function params for various disallowed patterns such as using "eval" 7930 // or "arguments" and duplicate parameters. 7931 7932 pp$3.checkParams = function(node, allowDuplicates) { 7933 var nameHash = {}; 7934 for (var i = 0, list = node.params; i < list.length; i += 1) 7935 { 7936 var param = list[i]; 7937 7938 this.checkLVal(param, BIND_VAR, allowDuplicates ? null : nameHash); 7939 } 7940 }; 7941 7942 // Parses a comma-separated list of expressions, and returns them as 7943 // an array. `close` is the token type that ends the list, and 7944 // `allowEmpty` can be turned on to allow subsequent commas with 7945 // nothing in between them to be parsed as `null` (which is needed 7946 // for array literals). 7947 7948 pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { 7949 var elts = [], first = true; 7950 while (!this.eat(close)) { 7951 if (!first) { 7952 this.expect(types.comma); 7953 if (allowTrailingComma && this.afterTrailingComma(close)) { break } 7954 } else { first = false; } 7955 7956 var elt = (void 0); 7957 if (allowEmpty && this.type === types.comma) 7958 { elt = null; } 7959 else if (this.type === types.ellipsis) { 7960 elt = this.parseSpread(refDestructuringErrors); 7961 if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0) 7962 { refDestructuringErrors.trailingComma = this.start; } 7963 } else { 7964 elt = this.parseMaybeAssign(false, refDestructuringErrors); 7965 } 7966 elts.push(elt); 7967 } 7968 return elts 7969 }; 7970 7971 pp$3.checkUnreserved = function(ref) { 7972 var start = ref.start; 7973 var end = ref.end; 7974 var name = ref.name; 7975 7976 if (this.inGenerator && name === "yield") 7977 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } 7978 if (this.inAsync && name === "await") 7979 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } 7980 if (this.keywords.test(name)) 7981 { this.raise(start, ("Unexpected keyword '" + name + "'")); } 7982 if (this.options.ecmaVersion < 6 && 7983 this.input.slice(start, end).indexOf("\\") !== -1) { return } 7984 var re = this.strict ? this.reservedWordsStrict : this.reservedWords; 7985 if (re.test(name)) { 7986 if (!this.inAsync && name === "await") 7987 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } 7988 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); 7989 } 7990 }; 7991 7992 // Parse the next token as an identifier. If `liberal` is true (used 7993 // when parsing properties), it will also convert keywords into 7994 // identifiers. 7995 7996 pp$3.parseIdent = function(liberal, isBinding) { 7997 var node = this.startNode(); 7998 if (this.type === types.name) { 7999 node.name = this.value; 8000 } else if (this.type.keyword) { 8001 node.name = this.type.keyword; 8002 8003 // To fix https://github.com/acornjs/acorn/issues/575 8004 // `class` and `function` keywords push new context into this.context. 8005 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. 8006 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword 8007 if ((node.name === "class" || node.name === "function") && 8008 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { 8009 this.context.pop(); 8010 } 8011 } else { 8012 this.unexpected(); 8013 } 8014 this.next(!!liberal); 8015 this.finishNode(node, "Identifier"); 8016 if (!liberal) { 8017 this.checkUnreserved(node); 8018 if (node.name === "await" && !this.awaitIdentPos) 8019 { this.awaitIdentPos = node.start; } 8020 } 8021 return node 8022 }; 8023 8024 // Parses yield expression inside generator. 8025 8026 pp$3.parseYield = function(noIn) { 8027 if (!this.yieldPos) { this.yieldPos = this.start; } 8028 8029 var node = this.startNode(); 8030 this.next(); 8031 if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) { 8032 node.delegate = false; 8033 node.argument = null; 8034 } else { 8035 node.delegate = this.eat(types.star); 8036 node.argument = this.parseMaybeAssign(noIn); 8037 } 8038 return this.finishNode(node, "YieldExpression") 8039 }; 8040 8041 pp$3.parseAwait = function() { 8042 if (!this.awaitPos) { this.awaitPos = this.start; } 8043 8044 var node = this.startNode(); 8045 this.next(); 8046 node.argument = this.parseMaybeUnary(null, false); 8047 return this.finishNode(node, "AwaitExpression") 8048 }; 8049 8050 var pp$4 = Parser.prototype; 8051 8052 // This function is used to raise exceptions on parse errors. It 8053 // takes an offset integer (into the current `input`) to indicate 8054 // the location of the error, attaches the position to the end 8055 // of the error message, and then raises a `SyntaxError` with that 8056 // message. 8057 8058 pp$4.raise = function(pos, message) { 8059 var loc = getLineInfo(this.input, pos); 8060 message += " (" + loc.line + ":" + loc.column + ")"; 8061 var err = new SyntaxError(message); 8062 err.pos = pos; err.loc = loc; err.raisedAt = this.pos; 8063 throw err 8064 }; 8065 8066 pp$4.raiseRecoverable = pp$4.raise; 8067 8068 pp$4.curPosition = function() { 8069 if (this.options.locations) { 8070 return new Position(this.curLine, this.pos - this.lineStart) 8071 } 8072 }; 8073 8074 var pp$5 = Parser.prototype; 8075 8076 var Scope = function Scope(flags) { 8077 this.flags = flags; 8078 // A list of var-declared names in the current lexical scope 8079 this.var = []; 8080 // A list of lexically-declared names in the current lexical scope 8081 this.lexical = []; 8082 // A list of lexically-declared FunctionDeclaration names in the current lexical scope 8083 this.functions = []; 8084 }; 8085 8086 // The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. 8087 8088 pp$5.enterScope = function(flags) { 8089 this.scopeStack.push(new Scope(flags)); 8090 }; 8091 8092 pp$5.exitScope = function() { 8093 this.scopeStack.pop(); 8094 }; 8095 8096 // The spec says: 8097 // > At the top level of a function, or script, function declarations are 8098 // > treated like var declarations rather than like lexical declarations. 8099 pp$5.treatFunctionsAsVarInScope = function(scope) { 8100 return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP) 8101 }; 8102 8103 pp$5.declareName = function(name, bindingType, pos) { 8104 var redeclared = false; 8105 if (bindingType === BIND_LEXICAL) { 8106 var scope = this.currentScope(); 8107 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; 8108 scope.lexical.push(name); 8109 if (this.inModule && (scope.flags & SCOPE_TOP)) 8110 { delete this.undefinedExports[name]; } 8111 } else if (bindingType === BIND_SIMPLE_CATCH) { 8112 var scope$1 = this.currentScope(); 8113 scope$1.lexical.push(name); 8114 } else if (bindingType === BIND_FUNCTION) { 8115 var scope$2 = this.currentScope(); 8116 if (this.treatFunctionsAsVar) 8117 { redeclared = scope$2.lexical.indexOf(name) > -1; } 8118 else 8119 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } 8120 scope$2.functions.push(name); 8121 } else { 8122 for (var i = this.scopeStack.length - 1; i >= 0; --i) { 8123 var scope$3 = this.scopeStack[i]; 8124 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || 8125 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { 8126 redeclared = true; 8127 break 8128 } 8129 scope$3.var.push(name); 8130 if (this.inModule && (scope$3.flags & SCOPE_TOP)) 8131 { delete this.undefinedExports[name]; } 8132 if (scope$3.flags & SCOPE_VAR) { break } 8133 } 8134 } 8135 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } 8136 }; 8137 8138 pp$5.checkLocalExport = function(id) { 8139 // scope.functions must be empty as Module code is always strict. 8140 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && 8141 this.scopeStack[0].var.indexOf(id.name) === -1) { 8142 this.undefinedExports[id.name] = id; 8143 } 8144 }; 8145 8146 pp$5.currentScope = function() { 8147 return this.scopeStack[this.scopeStack.length - 1] 8148 }; 8149 8150 pp$5.currentVarScope = function() { 8151 for (var i = this.scopeStack.length - 1;; i--) { 8152 var scope = this.scopeStack[i]; 8153 if (scope.flags & SCOPE_VAR) { return scope } 8154 } 8155 }; 8156 8157 // Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. 8158 pp$5.currentThisScope = function() { 8159 for (var i = this.scopeStack.length - 1;; i--) { 8160 var scope = this.scopeStack[i]; 8161 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } 8162 } 8163 }; 8164 8165 var Node = function Node(parser, pos, loc) { 8166 this.type = ""; 8167 this.start = pos; 8168 this.end = 0; 8169 if (parser.options.locations) 8170 { this.loc = new SourceLocation(parser, loc); } 8171 if (parser.options.directSourceFile) 8172 { this.sourceFile = parser.options.directSourceFile; } 8173 if (parser.options.ranges) 8174 { this.range = [pos, 0]; } 8175 }; 8176 8177 // Start an AST node, attaching a start offset. 8178 8179 var pp$6 = Parser.prototype; 8180 8181 pp$6.startNode = function() { 8182 return new Node(this, this.start, this.startLoc) 8183 }; 8184 8185 pp$6.startNodeAt = function(pos, loc) { 8186 return new Node(this, pos, loc) 8187 }; 8188 8189 // Finish an AST node, adding `type` and `end` properties. 8190 8191 function finishNodeAt(node, type, pos, loc) { 8192 node.type = type; 8193 node.end = pos; 8194 if (this.options.locations) 8195 { node.loc.end = loc; } 8196 if (this.options.ranges) 8197 { node.range[1] = pos; } 8198 return node 8199 } 8200 8201 pp$6.finishNode = function(node, type) { 8202 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) 8203 }; 8204 8205 // Finish node at given position 8206 8207 pp$6.finishNodeAt = function(node, type, pos, loc) { 8208 return finishNodeAt.call(this, node, type, pos, loc) 8209 }; 8210 8211 // The algorithm used to determine whether a regexp can appear at a 8212 8213 var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { 8214 this.token = token; 8215 this.isExpr = !!isExpr; 8216 this.preserveSpace = !!preserveSpace; 8217 this.override = override; 8218 this.generator = !!generator; 8219 }; 8220 8221 var types$1 = { 8222 b_stat: new TokContext("{", false), 8223 b_expr: new TokContext("{", true), 8224 b_tmpl: new TokContext("${", false), 8225 p_stat: new TokContext("(", false), 8226 p_expr: new TokContext("(", true), 8227 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), 8228 f_stat: new TokContext("function", false), 8229 f_expr: new TokContext("function", true), 8230 f_expr_gen: new TokContext("function", true, false, null, true), 8231 f_gen: new TokContext("function", false, false, null, true) 8232 }; 8233 8234 var pp$7 = Parser.prototype; 8235 8236 pp$7.initialContext = function() { 8237 return [types$1.b_stat] 8238 }; 8239 8240 pp$7.braceIsBlock = function(prevType) { 8241 var parent = this.curContext(); 8242 if (parent === types$1.f_expr || parent === types$1.f_stat) 8243 { return true } 8244 if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr)) 8245 { return !parent.isExpr } 8246 8247 // The check for `tt.name && exprAllowed` detects whether we are 8248 // after a `yield` or `of` construct. See the `updateContext` for 8249 // `tt.name`. 8250 if (prevType === types._return || prevType === types.name && this.exprAllowed) 8251 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } 8252 if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow) 8253 { return true } 8254 if (prevType === types.braceL) 8255 { return parent === types$1.b_stat } 8256 if (prevType === types._var || prevType === types._const || prevType === types.name) 8257 { return false } 8258 return !this.exprAllowed 8259 }; 8260 8261 pp$7.inGeneratorContext = function() { 8262 for (var i = this.context.length - 1; i >= 1; i--) { 8263 var context = this.context[i]; 8264 if (context.token === "function") 8265 { return context.generator } 8266 } 8267 return false 8268 }; 8269 8270 pp$7.updateContext = function(prevType) { 8271 var update, type = this.type; 8272 if (type.keyword && prevType === types.dot) 8273 { this.exprAllowed = false; } 8274 else if (update = type.updateContext) 8275 { update.call(this, prevType); } 8276 else 8277 { this.exprAllowed = type.beforeExpr; } 8278 }; 8279 8280 // Token-specific context update code 8281 8282 types.parenR.updateContext = types.braceR.updateContext = function() { 8283 if (this.context.length === 1) { 8284 this.exprAllowed = true; 8285 return 8286 } 8287 var out = this.context.pop(); 8288 if (out === types$1.b_stat && this.curContext().token === "function") { 8289 out = this.context.pop(); 8290 } 8291 this.exprAllowed = !out.isExpr; 8292 }; 8293 8294 types.braceL.updateContext = function(prevType) { 8295 this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr); 8296 this.exprAllowed = true; 8297 }; 8298 8299 types.dollarBraceL.updateContext = function() { 8300 this.context.push(types$1.b_tmpl); 8301 this.exprAllowed = true; 8302 }; 8303 8304 types.parenL.updateContext = function(prevType) { 8305 var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while; 8306 this.context.push(statementParens ? types$1.p_stat : types$1.p_expr); 8307 this.exprAllowed = true; 8308 }; 8309 8310 types.incDec.updateContext = function() { 8311 // tokExprAllowed stays unchanged 8312 }; 8313 8314 types._function.updateContext = types._class.updateContext = function(prevType) { 8315 if (prevType.beforeExpr && prevType !== types.semi && prevType !== types._else && 8316 !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && 8317 !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat)) 8318 { this.context.push(types$1.f_expr); } 8319 else 8320 { this.context.push(types$1.f_stat); } 8321 this.exprAllowed = false; 8322 }; 8323 8324 types.backQuote.updateContext = function() { 8325 if (this.curContext() === types$1.q_tmpl) 8326 { this.context.pop(); } 8327 else 8328 { this.context.push(types$1.q_tmpl); } 8329 this.exprAllowed = false; 8330 }; 8331 8332 types.star.updateContext = function(prevType) { 8333 if (prevType === types._function) { 8334 var index = this.context.length - 1; 8335 if (this.context[index] === types$1.f_expr) 8336 { this.context[index] = types$1.f_expr_gen; } 8337 else 8338 { this.context[index] = types$1.f_gen; } 8339 } 8340 this.exprAllowed = true; 8341 }; 8342 8343 types.name.updateContext = function(prevType) { 8344 var allowed = false; 8345 if (this.options.ecmaVersion >= 6 && prevType !== types.dot) { 8346 if (this.value === "of" && !this.exprAllowed || 8347 this.value === "yield" && this.inGeneratorContext()) 8348 { allowed = true; } 8349 } 8350 this.exprAllowed = allowed; 8351 }; 8352 8353 // This file contains Unicode properties extracted from the ECMAScript 8354 // specification. The lists are extracted like so: 8355 // $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) 8356 8357 // #table-binary-unicode-properties 8358 var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; 8359 var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; 8360 var ecma11BinaryProperties = ecma10BinaryProperties; 8361 var unicodeBinaryProperties = { 8362 9: ecma9BinaryProperties, 8363 10: ecma10BinaryProperties, 8364 11: ecma11BinaryProperties 8365 }; 8366 8367 // #table-unicode-general-category-values 8368 var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; 8369 8370 // #table-unicode-script-values 8371 var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; 8372 var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; 8373 var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; 8374 var unicodeScriptValues = { 8375 9: ecma9ScriptValues, 8376 10: ecma10ScriptValues, 8377 11: ecma11ScriptValues 8378 }; 8379 8380 var data = {}; 8381 function buildUnicodeData(ecmaVersion) { 8382 var d = data[ecmaVersion] = { 8383 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), 8384 nonBinary: { 8385 General_Category: wordsRegexp(unicodeGeneralCategoryValues), 8386 Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) 8387 } 8388 }; 8389 d.nonBinary.Script_Extensions = d.nonBinary.Script; 8390 8391 d.nonBinary.gc = d.nonBinary.General_Category; 8392 d.nonBinary.sc = d.nonBinary.Script; 8393 d.nonBinary.scx = d.nonBinary.Script_Extensions; 8394 } 8395 buildUnicodeData(9); 8396 buildUnicodeData(10); 8397 buildUnicodeData(11); 8398 8399 var pp$8 = Parser.prototype; 8400 8401 var RegExpValidationState = function RegExpValidationState(parser) { 8402 this.parser = parser; 8403 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : ""); 8404 this.unicodeProperties = data[parser.options.ecmaVersion >= 11 ? 11 : parser.options.ecmaVersion]; 8405 this.source = ""; 8406 this.flags = ""; 8407 this.start = 0; 8408 this.switchU = false; 8409 this.switchN = false; 8410 this.pos = 0; 8411 this.lastIntValue = 0; 8412 this.lastStringValue = ""; 8413 this.lastAssertionIsQuantifiable = false; 8414 this.numCapturingParens = 0; 8415 this.maxBackReference = 0; 8416 this.groupNames = []; 8417 this.backReferenceNames = []; 8418 }; 8419 8420 RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { 8421 var unicode = flags.indexOf("u") !== -1; 8422 this.start = start | 0; 8423 this.source = pattern + ""; 8424 this.flags = flags; 8425 this.switchU = unicode && this.parser.options.ecmaVersion >= 6; 8426 this.switchN = unicode && this.parser.options.ecmaVersion >= 9; 8427 }; 8428 8429 RegExpValidationState.prototype.raise = function raise (message) { 8430 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); 8431 }; 8432 8433 // If u flag is given, this returns the code point at the index (it combines a surrogate pair). 8434 // Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). 8435 RegExpValidationState.prototype.at = function at (i, forceU) { 8436 if ( forceU === void 0 ) forceU = false; 8437 8438 var s = this.source; 8439 var l = s.length; 8440 if (i >= l) { 8441 return -1 8442 } 8443 var c = s.charCodeAt(i); 8444 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { 8445 return c 8446 } 8447 var next = s.charCodeAt(i + 1); 8448 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c 8449 }; 8450 8451 RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { 8452 if ( forceU === void 0 ) forceU = false; 8453 8454 var s = this.source; 8455 var l = s.length; 8456 if (i >= l) { 8457 return l 8458 } 8459 var c = s.charCodeAt(i), next; 8460 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || 8461 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { 8462 return i + 1 8463 } 8464 return i + 2 8465 }; 8466 8467 RegExpValidationState.prototype.current = function current (forceU) { 8468 if ( forceU === void 0 ) forceU = false; 8469 8470 return this.at(this.pos, forceU) 8471 }; 8472 8473 RegExpValidationState.prototype.lookahead = function lookahead (forceU) { 8474 if ( forceU === void 0 ) forceU = false; 8475 8476 return this.at(this.nextIndex(this.pos, forceU), forceU) 8477 }; 8478 8479 RegExpValidationState.prototype.advance = function advance (forceU) { 8480 if ( forceU === void 0 ) forceU = false; 8481 8482 this.pos = this.nextIndex(this.pos, forceU); 8483 }; 8484 8485 RegExpValidationState.prototype.eat = function eat (ch, forceU) { 8486 if ( forceU === void 0 ) forceU = false; 8487 8488 if (this.current(forceU) === ch) { 8489 this.advance(forceU); 8490 return true 8491 } 8492 return false 8493 }; 8494 8495 function codePointToString(ch) { 8496 if (ch <= 0xFFFF) { return String.fromCharCode(ch) } 8497 ch -= 0x10000; 8498 return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00) 8499 } 8500 8501 /** 8502 * Validate the flags part of a given RegExpLiteral. 8503 * 8504 * @param {RegExpValidationState} state The state to validate RegExp. 8505 * @returns {void} 8506 */ 8507 pp$8.validateRegExpFlags = function(state) { 8508 var validFlags = state.validFlags; 8509 var flags = state.flags; 8510 8511 for (var i = 0; i < flags.length; i++) { 8512 var flag = flags.charAt(i); 8513 if (validFlags.indexOf(flag) === -1) { 8514 this.raise(state.start, "Invalid regular expression flag"); 8515 } 8516 if (flags.indexOf(flag, i + 1) > -1) { 8517 this.raise(state.start, "Duplicate regular expression flag"); 8518 } 8519 } 8520 }; 8521 8522 /** 8523 * Validate the pattern part of a given RegExpLiteral. 8524 * 8525 * @param {RegExpValidationState} state The state to validate RegExp. 8526 * @returns {void} 8527 */ 8528 pp$8.validateRegExpPattern = function(state) { 8529 this.regexp_pattern(state); 8530 8531 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of 8532 // parsing contains a |GroupName|, reparse with the goal symbol 8533 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* 8534 // exception if _P_ did not conform to the grammar, if any elements of _P_ 8535 // were not matched by the parse, or if any Early Error conditions exist. 8536 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { 8537 state.switchN = true; 8538 this.regexp_pattern(state); 8539 } 8540 }; 8541 8542 // https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern 8543 pp$8.regexp_pattern = function(state) { 8544 state.pos = 0; 8545 state.lastIntValue = 0; 8546 state.lastStringValue = ""; 8547 state.lastAssertionIsQuantifiable = false; 8548 state.numCapturingParens = 0; 8549 state.maxBackReference = 0; 8550 state.groupNames.length = 0; 8551 state.backReferenceNames.length = 0; 8552 8553 this.regexp_disjunction(state); 8554 8555 if (state.pos !== state.source.length) { 8556 // Make the same messages as V8. 8557 if (state.eat(0x29 /* ) */)) { 8558 state.raise("Unmatched ')'"); 8559 } 8560 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { 8561 state.raise("Lone quantifier brackets"); 8562 } 8563 } 8564 if (state.maxBackReference > state.numCapturingParens) { 8565 state.raise("Invalid escape"); 8566 } 8567 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { 8568 var name = list[i]; 8569 8570 if (state.groupNames.indexOf(name) === -1) { 8571 state.raise("Invalid named capture referenced"); 8572 } 8573 } 8574 }; 8575 8576 // https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction 8577 pp$8.regexp_disjunction = function(state) { 8578 this.regexp_alternative(state); 8579 while (state.eat(0x7C /* | */)) { 8580 this.regexp_alternative(state); 8581 } 8582 8583 // Make the same message as V8. 8584 if (this.regexp_eatQuantifier(state, true)) { 8585 state.raise("Nothing to repeat"); 8586 } 8587 if (state.eat(0x7B /* { */)) { 8588 state.raise("Lone quantifier brackets"); 8589 } 8590 }; 8591 8592 // https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative 8593 pp$8.regexp_alternative = function(state) { 8594 while (state.pos < state.source.length && this.regexp_eatTerm(state)) 8595 { } 8596 }; 8597 8598 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term 8599 pp$8.regexp_eatTerm = function(state) { 8600 if (this.regexp_eatAssertion(state)) { 8601 // Handle `QuantifiableAssertion Quantifier` alternative. 8602 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion 8603 // is a QuantifiableAssertion. 8604 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { 8605 // Make the same message as V8. 8606 if (state.switchU) { 8607 state.raise("Invalid quantifier"); 8608 } 8609 } 8610 return true 8611 } 8612 8613 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { 8614 this.regexp_eatQuantifier(state); 8615 return true 8616 } 8617 8618 return false 8619 }; 8620 8621 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion 8622 pp$8.regexp_eatAssertion = function(state) { 8623 var start = state.pos; 8624 state.lastAssertionIsQuantifiable = false;
vendor: 10,920 bytes, lines 8625-8999
8625 8626 // ^, $ 8627 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { 8628 return true 8629 } 8630 8631 // \b \B 8632 if (state.eat(0x5C /* \ */)) { 8633 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { 8634 return true 8635 } 8636 state.pos = start; 8637 } 8638 8639 // Lookahead / Lookbehind 8640 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { 8641 var lookbehind = false; 8642 if (this.options.ecmaVersion >= 9) { 8643 lookbehind = state.eat(0x3C /* < */); 8644 } 8645 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { 8646 this.regexp_disjunction(state); 8647 if (!state.eat(0x29 /* ) */)) { 8648 state.raise("Unterminated group"); 8649 } 8650 state.lastAssertionIsQuantifiable = !lookbehind; 8651 return true 8652 } 8653 } 8654 8655 state.pos = start; 8656 return false 8657 }; 8658 8659 // https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier 8660 pp$8.regexp_eatQuantifier = function(state, noError) { 8661 if ( noError === void 0 ) noError = false; 8662 8663 if (this.regexp_eatQuantifierPrefix(state, noError)) { 8664 state.eat(0x3F /* ? */); 8665 return true 8666 } 8667 return false 8668 }; 8669 8670 // https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix 8671 pp$8.regexp_eatQuantifierPrefix = function(state, noError) { 8672 return ( 8673 state.eat(0x2A /* * */) || 8674 state.eat(0x2B /* + */) || 8675 state.eat(0x3F /* ? */) || 8676 this.regexp_eatBracedQuantifier(state, noError) 8677 ) 8678 }; 8679 pp$8.regexp_eatBracedQuantifier = function(state, noError) { 8680 var start = state.pos; 8681 if (state.eat(0x7B /* { */)) { 8682 var min = 0, max = -1; 8683 if (this.regexp_eatDecimalDigits(state)) { 8684 min = state.lastIntValue; 8685 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { 8686 max = state.lastIntValue; 8687 } 8688 if (state.eat(0x7D /* } */)) { 8689 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term 8690 if (max !== -1 && max < min && !noError) { 8691 state.raise("numbers out of order in {} quantifier"); 8692 } 8693 return true 8694 } 8695 } 8696 if (state.switchU && !noError) { 8697 state.raise("Incomplete quantifier"); 8698 } 8699 state.pos = start; 8700 } 8701 return false 8702 }; 8703 8704 // https://www.ecma-international.org/ecma-262/8.0/#prod-Atom 8705 pp$8.regexp_eatAtom = function(state) { 8706 return ( 8707 this.regexp_eatPatternCharacters(state) || 8708 state.eat(0x2E /* . */) || 8709 this.regexp_eatReverseSolidusAtomEscape(state) || 8710 this.regexp_eatCharacterClass(state) || 8711 this.regexp_eatUncapturingGroup(state) || 8712 this.regexp_eatCapturingGroup(state) 8713 ) 8714 }; 8715 pp$8.regexp_eatReverseSolidusAtomEscape = function(state) { 8716 var start = state.pos; 8717 if (state.eat(0x5C /* \ */)) { 8718 if (this.regexp_eatAtomEscape(state)) { 8719 return true 8720 } 8721 state.pos = start; 8722 } 8723 return false 8724 }; 8725 pp$8.regexp_eatUncapturingGroup = function(state) { 8726 var start = state.pos; 8727 if (state.eat(0x28 /* ( */)) { 8728 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { 8729 this.regexp_disjunction(state); 8730 if (state.eat(0x29 /* ) */)) { 8731 return true 8732 } 8733 state.raise("Unterminated group"); 8734 } 8735 state.pos = start; 8736 } 8737 return false 8738 }; 8739 pp$8.regexp_eatCapturingGroup = function(state) { 8740 if (state.eat(0x28 /* ( */)) { 8741 if (this.options.ecmaVersion >= 9) { 8742 this.regexp_groupSpecifier(state); 8743 } else if (state.current() === 0x3F /* ? */) { 8744 state.raise("Invalid group"); 8745 } 8746 this.regexp_disjunction(state); 8747 if (state.eat(0x29 /* ) */)) { 8748 state.numCapturingParens += 1; 8749 return true 8750 } 8751 state.raise("Unterminated group"); 8752 } 8753 return false 8754 }; 8755 8756 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom 8757 pp$8.regexp_eatExtendedAtom = function(state) { 8758 return ( 8759 state.eat(0x2E /* . */) || 8760 this.regexp_eatReverseSolidusAtomEscape(state) || 8761 this.regexp_eatCharacterClass(state) || 8762 this.regexp_eatUncapturingGroup(state) || 8763 this.regexp_eatCapturingGroup(state) || 8764 this.regexp_eatInvalidBracedQuantifier(state) || 8765 this.regexp_eatExtendedPatternCharacter(state) 8766 ) 8767 }; 8768 8769 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier 8770 pp$8.regexp_eatInvalidBracedQuantifier = function(state) { 8771 if (this.regexp_eatBracedQuantifier(state, true)) { 8772 state.raise("Nothing to repeat"); 8773 } 8774 return false 8775 }; 8776 8777 // https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter 8778 pp$8.regexp_eatSyntaxCharacter = function(state) { 8779 var ch = state.current(); 8780 if (isSyntaxCharacter(ch)) { 8781 state.lastIntValue = ch; 8782 state.advance(); 8783 return true 8784 } 8785 return false 8786 }; 8787 function isSyntaxCharacter(ch) { 8788 return ( 8789 ch === 0x24 /* $ */ || 8790 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || 8791 ch === 0x2E /* . */ || 8792 ch === 0x3F /* ? */ || 8793 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || 8794 ch >= 0x7B /* { */ && ch <= 0x7D /* } */ 8795 ) 8796 } 8797 8798 // https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter 8799 // But eat eager. 8800 pp$8.regexp_eatPatternCharacters = function(state) { 8801 var start = state.pos; 8802 var ch = 0; 8803 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { 8804 state.advance(); 8805 } 8806 return state.pos !== start 8807 }; 8808 8809 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter 8810 pp$8.regexp_eatExtendedPatternCharacter = function(state) { 8811 var ch = state.current(); 8812 if ( 8813 ch !== -1 && 8814 ch !== 0x24 /* $ */ && 8815 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && 8816 ch !== 0x2E /* . */ && 8817 ch !== 0x3F /* ? */ && 8818 ch !== 0x5B /* [ */ && 8819 ch !== 0x5E /* ^ */ && 8820 ch !== 0x7C /* | */ 8821 ) { 8822 state.advance(); 8823 return true 8824 } 8825 return false 8826 }; 8827 8828 // GroupSpecifier :: 8829 // [empty] 8830 // `?` GroupName 8831 pp$8.regexp_groupSpecifier = function(state) { 8832 if (state.eat(0x3F /* ? */)) { 8833 if (this.regexp_eatGroupName(state)) { 8834 if (state.groupNames.indexOf(state.lastStringValue) !== -1) { 8835 state.raise("Duplicate capture group name"); 8836 } 8837 state.groupNames.push(state.lastStringValue); 8838 return 8839 } 8840 state.raise("Invalid group"); 8841 } 8842 }; 8843 8844 // GroupName :: 8845 // `<` RegExpIdentifierName `>` 8846 // Note: this updates `state.lastStringValue` property with the eaten name. 8847 pp$8.regexp_eatGroupName = function(state) { 8848 state.lastStringValue = ""; 8849 if (state.eat(0x3C /* < */)) { 8850 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { 8851 return true 8852 } 8853 state.raise("Invalid capture group name"); 8854 } 8855 return false 8856 }; 8857 8858 // RegExpIdentifierName :: 8859 // RegExpIdentifierStart 8860 // RegExpIdentifierName RegExpIdentifierPart 8861 // Note: this updates `state.lastStringValue` property with the eaten name. 8862 pp$8.regexp_eatRegExpIdentifierName = function(state) { 8863 state.lastStringValue = ""; 8864 if (this.regexp_eatRegExpIdentifierStart(state)) { 8865 state.lastStringValue += codePointToString(state.lastIntValue); 8866 while (this.regexp_eatRegExpIdentifierPart(state)) { 8867 state.lastStringValue += codePointToString(state.lastIntValue); 8868 } 8869 return true 8870 } 8871 return false 8872 }; 8873 8874 // RegExpIdentifierStart :: 8875 // UnicodeIDStart 8876 // `$` 8877 // `_` 8878 // `\` RegExpUnicodeEscapeSequence[+U] 8879 pp$8.regexp_eatRegExpIdentifierStart = function(state) { 8880 var start = state.pos; 8881 var forceU = this.options.ecmaVersion >= 11; 8882 var ch = state.current(forceU); 8883 state.advance(forceU); 8884 8885 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { 8886 ch = state.lastIntValue; 8887 } 8888 if (isRegExpIdentifierStart(ch)) { 8889 state.lastIntValue = ch; 8890 return true 8891 } 8892 8893 state.pos = start; 8894 return false 8895 }; 8896 function isRegExpIdentifierStart(ch) { 8897 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ 8898 } 8899 8900 // RegExpIdentifierPart :: 8901 // UnicodeIDContinue 8902 // `$` 8903 // `_` 8904 // `\` RegExpUnicodeEscapeSequence[+U] 8905 // <ZWNJ> 8906 // <ZWJ> 8907 pp$8.regexp_eatRegExpIdentifierPart = function(state) { 8908 var start = state.pos; 8909 var forceU = this.options.ecmaVersion >= 11; 8910 var ch = state.current(forceU); 8911 state.advance(forceU); 8912 8913 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { 8914 ch = state.lastIntValue; 8915 } 8916 if (isRegExpIdentifierPart(ch)) { 8917 state.lastIntValue = ch; 8918 return true 8919 } 8920 8921 state.pos = start; 8922 return false 8923 }; 8924 function isRegExpIdentifierPart(ch) { 8925 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */ 8926 } 8927 8928 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape 8929 pp$8.regexp_eatAtomEscape = function(state) { 8930 if ( 8931 this.regexp_eatBackReference(state) || 8932 this.regexp_eatCharacterClassEscape(state) || 8933 this.regexp_eatCharacterEscape(state) || 8934 (state.switchN && this.regexp_eatKGroupName(state)) 8935 ) { 8936 return true 8937 } 8938 if (state.switchU) { 8939 // Make the same message as V8. 8940 if (state.current() === 0x63 /* c */) { 8941 state.raise("Invalid unicode escape"); 8942 } 8943 state.raise("Invalid escape"); 8944 } 8945 return false 8946 }; 8947 pp$8.regexp_eatBackReference = function(state) { 8948 var start = state.pos; 8949 if (this.regexp_eatDecimalEscape(state)) { 8950 var n = state.lastIntValue; 8951 if (state.switchU) { 8952 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape 8953 if (n > state.maxBackReference) { 8954 state.maxBackReference = n; 8955 } 8956 return true 8957 } 8958 if (n <= state.numCapturingParens) { 8959 return true 8960 } 8961 state.pos = start; 8962 } 8963 return false 8964 }; 8965 pp$8.regexp_eatKGroupName = function(state) { 8966 if (state.eat(0x6B /* k */)) { 8967 if (this.regexp_eatGroupName(state)) { 8968 state.backReferenceNames.push(state.lastStringValue); 8969 return true 8970 } 8971 state.raise("Invalid named reference"); 8972 } 8973 return false 8974 }; 8975 8976 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape 8977 pp$8.regexp_eatCharacterEscape = function(state) { 8978 return ( 8979 this.regexp_eatControlEscape(state) || 8980 this.regexp_eatCControlLetter(state) || 8981 this.regexp_eatZero(state) || 8982 this.regexp_eatHexEscapeSequence(state) || 8983 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || 8984 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || 8985 this.regexp_eatIdentityEscape(state) 8986 ) 8987 }; 8988 pp$8.regexp_eatCControlLetter = function(state) { 8989 var start = state.pos; 8990 if (state.eat(0x63 /* c */)) { 8991 if (this.regexp_eatControlLetter(state)) { 8992 return true 8993 } 8994 state.pos = start; 8995 } 8996 return false 8997 }; 8998 pp$8.regexp_eatZero = function(state) { 8999 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())
vendor: 51,047 bytes, lines 8999-10630
8999) { 9000 state.lastIntValue = 0; 9001 state.advance(); 9002 return true 9003 } 9004 return false 9005 }; 9006 9007 // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape 9008 pp$8.regexp_eatControlEscape = function(state) { 9009 var ch = state.current(); 9010 if (ch === 0x74 /* t */) { 9011 state.lastIntValue = 0x09; /* \t */ 9012 state.advance(); 9013 return true 9014 } 9015 if (ch === 0x6E /* n */) { 9016 state.lastIntValue = 0x0A; /* \n */ 9017 state.advance(); 9018 return true 9019 } 9020 if (ch === 0x76 /* v */) { 9021 state.lastIntValue = 0x0B; /* \v */ 9022 state.advance(); 9023 return true 9024 } 9025 if (ch === 0x66 /* f */) { 9026 state.lastIntValue = 0x0C; /* \f */ 9027 state.advance(); 9028 return true 9029 } 9030 if (ch === 0x72 /* r */) { 9031 state.lastIntValue = 0x0D; /* \r */ 9032 state.advance(); 9033 return true 9034 } 9035 return false 9036 }; 9037 9038 // https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter 9039 pp$8.regexp_eatControlLetter = function(state) { 9040 var ch = state.current(); 9041 if (isControlLetter(ch)) { 9042 state.lastIntValue = ch % 0x20; 9043 state.advance(); 9044 return true 9045 } 9046 return false 9047 }; 9048 function isControlLetter(ch) { 9049 return ( 9050 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || 9051 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) 9052 ) 9053 } 9054 9055 // https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence 9056 pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { 9057 if ( forceU === void 0 ) forceU = false; 9058 9059 var start = state.pos; 9060 var switchU = forceU || state.switchU; 9061 9062 if (state.eat(0x75 /* u */)) { 9063 if (this.regexp_eatFixedHexDigits(state, 4)) { 9064 var lead = state.lastIntValue; 9065 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { 9066 var leadSurrogateEnd = state.pos; 9067 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { 9068 var trail = state.lastIntValue; 9069 if (trail >= 0xDC00 && trail <= 0xDFFF) { 9070 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; 9071 return true 9072 } 9073 } 9074 state.pos = leadSurrogateEnd; 9075 state.lastIntValue = lead; 9076 } 9077 return true 9078 } 9079 if ( 9080 switchU && 9081 state.eat(0x7B /* { */) && 9082 this.regexp_eatHexDigits(state) && 9083 state.eat(0x7D /* } */) && 9084 isValidUnicode(state.lastIntValue) 9085 ) { 9086 return true 9087 } 9088 if (switchU) { 9089 state.raise("Invalid unicode escape"); 9090 } 9091 state.pos = start; 9092 } 9093 9094 return false 9095 }; 9096 function isValidUnicode(ch) { 9097 return ch >= 0 && ch <= 0x10FFFF 9098 } 9099 9100 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape 9101 pp$8.regexp_eatIdentityEscape = function(state) { 9102 if (state.switchU) { 9103 if (this.regexp_eatSyntaxCharacter(state)) { 9104 return true 9105 } 9106 if (state.eat(0x2F /* / */)) { 9107 state.lastIntValue = 0x2F; /* / */ 9108 return true 9109 } 9110 return false 9111 } 9112 9113 var ch = state.current(); 9114 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { 9115 state.lastIntValue = ch; 9116 state.advance(); 9117 return true 9118 } 9119 9120 return false 9121 }; 9122 9123 // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape 9124 pp$8.regexp_eatDecimalEscape = function(state) { 9125 state.lastIntValue = 0; 9126 var ch = state.current(); 9127 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { 9128 do { 9129 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); 9130 state.advance(); 9131 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) 9132 return true 9133 } 9134 return false 9135 }; 9136 9137 // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape 9138 pp$8.regexp_eatCharacterClassEscape = function(state) { 9139 var ch = state.current(); 9140 9141 if (isCharacterClassEscape(ch)) { 9142 state.lastIntValue = -1; 9143 state.advance(); 9144 return true 9145 } 9146 9147 if ( 9148 state.switchU && 9149 this.options.ecmaVersion >= 9 && 9150 (ch === 0x50 /* P */ || ch === 0x70 /* p */) 9151 ) { 9152 state.lastIntValue = -1; 9153 state.advance(); 9154 if ( 9155 state.eat(0x7B /* { */) && 9156 this.regexp_eatUnicodePropertyValueExpression(state) && 9157 state.eat(0x7D /* } */) 9158 ) { 9159 return true 9160 } 9161 state.raise("Invalid property name"); 9162 } 9163 9164 return false 9165 }; 9166 function isCharacterClassEscape(ch) { 9167 return ( 9168 ch === 0x64 /* d */ || 9169 ch === 0x44 /* D */ || 9170 ch === 0x73 /* s */ || 9171 ch === 0x53 /* S */ || 9172 ch === 0x77 /* w */ || 9173 ch === 0x57 /* W */ 9174 ) 9175 } 9176 9177 // UnicodePropertyValueExpression :: 9178 // UnicodePropertyName `=` UnicodePropertyValue 9179 // LoneUnicodePropertyNameOrValue 9180 pp$8.regexp_eatUnicodePropertyValueExpression = function(state) { 9181 var start = state.pos; 9182 9183 // UnicodePropertyName `=` UnicodePropertyValue 9184 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { 9185 var name = state.lastStringValue; 9186 if (this.regexp_eatUnicodePropertyValue(state)) { 9187 var value = state.lastStringValue; 9188 this.regexp_validateUnicodePropertyNameAndValue(state, name, value); 9189 return true 9190 } 9191 } 9192 state.pos = start; 9193 9194 // LoneUnicodePropertyNameOrValue 9195 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { 9196 var nameOrValue = state.lastStringValue; 9197 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); 9198 return true 9199 } 9200 return false 9201 }; 9202 pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { 9203 if (!has(state.unicodeProperties.nonBinary, name)) 9204 { state.raise("Invalid property name"); } 9205 if (!state.unicodeProperties.nonBinary[name].test(value)) 9206 { state.raise("Invalid property value"); } 9207 }; 9208 pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { 9209 if (!state.unicodeProperties.binary.test(nameOrValue)) 9210 { state.raise("Invalid property name"); } 9211 }; 9212 9213 // UnicodePropertyName :: 9214 // UnicodePropertyNameCharacters 9215 pp$8.regexp_eatUnicodePropertyName = function(state) { 9216 var ch = 0; 9217 state.lastStringValue = ""; 9218 while (isUnicodePropertyNameCharacter(ch = state.current())) { 9219 state.lastStringValue += codePointToString(ch); 9220 state.advance(); 9221 } 9222 return state.lastStringValue !== "" 9223 }; 9224 function isUnicodePropertyNameCharacter(ch) { 9225 return isControlLetter(ch) || ch === 0x5F /* _ */ 9226 } 9227 9228 // UnicodePropertyValue :: 9229 // UnicodePropertyValueCharacters 9230 pp$8.regexp_eatUnicodePropertyValue = function(state) { 9231 var ch = 0; 9232 state.lastStringValue = ""; 9233 while (isUnicodePropertyValueCharacter(ch = state.current())) { 9234 state.lastStringValue += codePointToString(ch); 9235 state.advance(); 9236 } 9237 return state.lastStringValue !== "" 9238 }; 9239 function isUnicodePropertyValueCharacter(ch) { 9240 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) 9241 } 9242 9243 // LoneUnicodePropertyNameOrValue :: 9244 // UnicodePropertyValueCharacters 9245 pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { 9246 return this.regexp_eatUnicodePropertyValue(state) 9247 }; 9248 9249 // https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass 9250 pp$8.regexp_eatCharacterClass = function(state) { 9251 if (state.eat(0x5B /* [ */)) { 9252 state.eat(0x5E /* ^ */); 9253 this.regexp_classRanges(state); 9254 if (state.eat(0x5D /* ] */)) { 9255 return true 9256 } 9257 // Unreachable since it threw "unterminated regular expression" error before. 9258 state.raise("Unterminated character class"); 9259 } 9260 return false 9261 }; 9262 9263 // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges 9264 // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges 9265 // https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash 9266 pp$8.regexp_classRanges = function(state) { 9267 while (this.regexp_eatClassAtom(state)) { 9268 var left = state.lastIntValue; 9269 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { 9270 var right = state.lastIntValue; 9271 if (state.switchU && (left === -1 || right === -1)) { 9272 state.raise("Invalid character class"); 9273 } 9274 if (left !== -1 && right !== -1 && left > right) { 9275 state.raise("Range out of order in character class"); 9276 } 9277 } 9278 } 9279 }; 9280 9281 // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom 9282 // https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash 9283 pp$8.regexp_eatClassAtom = function(state) { 9284 var start = state.pos; 9285 9286 if (state.eat(0x5C /* \ */)) { 9287 if (this.regexp_eatClassEscape(state)) { 9288 return true 9289 } 9290 if (state.switchU) { 9291 // Make the same message as V8. 9292 var ch$1 = state.current(); 9293 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { 9294 state.raise("Invalid class escape"); 9295 } 9296 state.raise("Invalid escape"); 9297 } 9298 state.pos = start; 9299 } 9300 9301 var ch = state.current(); 9302 if (ch !== 0x5D /* ] */) { 9303 state.lastIntValue = ch; 9304 state.advance(); 9305 return true 9306 } 9307 9308 return false 9309 }; 9310 9311 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape 9312 pp$8.regexp_eatClassEscape = function(state) { 9313 var start = state.pos; 9314 9315 if (state.eat(0x62 /* b */)) { 9316 state.lastIntValue = 0x08; /* <BS> */ 9317 return true 9318 } 9319 9320 if (state.switchU && state.eat(0x2D /* - */)) { 9321 state.lastIntValue = 0x2D; /* - */ 9322 return true 9323 } 9324 9325 if (!state.switchU && state.eat(0x63 /* c */)) { 9326 if (this.regexp_eatClassControlLetter(state)) { 9327 return true 9328 } 9329 state.pos = start; 9330 } 9331 9332 return ( 9333 this.regexp_eatCharacterClassEscape(state) || 9334 this.regexp_eatCharacterEscape(state) 9335 ) 9336 }; 9337 9338 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter 9339 pp$8.regexp_eatClassControlLetter = function(state) { 9340 var ch = state.current(); 9341 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { 9342 state.lastIntValue = ch % 0x20; 9343 state.advance(); 9344 return true 9345 } 9346 return false 9347 }; 9348 9349 // https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence 9350 pp$8.regexp_eatHexEscapeSequence = function(state) { 9351 var start = state.pos; 9352 if (state.eat(0x78 /* x */)) { 9353 if (this.regexp_eatFixedHexDigits(state, 2)) { 9354 return true 9355 } 9356 if (state.switchU) { 9357 state.raise("Invalid escape"); 9358 } 9359 state.pos = start; 9360 } 9361 return false 9362 }; 9363 9364 // https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits 9365 pp$8.regexp_eatDecimalDigits = function(state) { 9366 var start = state.pos; 9367 var ch = 0; 9368 state.lastIntValue = 0; 9369 while (isDecimalDigit(ch = state.current())) { 9370 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); 9371 state.advance(); 9372 } 9373 return state.pos !== start 9374 }; 9375 function isDecimalDigit(ch) { 9376 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ 9377 } 9378 9379 // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits 9380 pp$8.regexp_eatHexDigits = function(state) { 9381 var start = state.pos; 9382 var ch = 0; 9383 state.lastIntValue = 0; 9384 while (isHexDigit(ch = state.current())) { 9385 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); 9386 state.advance(); 9387 } 9388 return state.pos !== start 9389 }; 9390 function isHexDigit(ch) { 9391 return ( 9392 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || 9393 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || 9394 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) 9395 ) 9396 } 9397 function hexToInt(ch) { 9398 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { 9399 return 10 + (ch - 0x41 /* A */) 9400 } 9401 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { 9402 return 10 + (ch - 0x61 /* a */) 9403 } 9404 return ch - 0x30 /* 0 */ 9405 } 9406 9407 // https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence 9408 // Allows only 0-377(octal) i.e. 0-255(decimal). 9409 pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) { 9410 if (this.regexp_eatOctalDigit(state)) { 9411 var n1 = state.lastIntValue; 9412 if (this.regexp_eatOctalDigit(state)) { 9413 var n2 = state.lastIntValue; 9414 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { 9415 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; 9416 } else { 9417 state.lastIntValue = n1 * 8 + n2; 9418 } 9419 } else { 9420 state.lastIntValue = n1; 9421 } 9422 return true 9423 } 9424 return false 9425 }; 9426 9427 // https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit 9428 pp$8.regexp_eatOctalDigit = function(state) { 9429 var ch = state.current(); 9430 if (isOctalDigit(ch)) { 9431 state.lastIntValue = ch - 0x30; /* 0 */ 9432 state.advance(); 9433 return true 9434 } 9435 state.lastIntValue = 0; 9436 return false 9437 }; 9438 function isOctalDigit(ch) { 9439 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ 9440 } 9441 9442 // https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits 9443 // https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit 9444 // And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence 9445 pp$8.regexp_eatFixedHexDigits = function(state, length) { 9446 var start = state.pos; 9447 state.lastIntValue = 0; 9448 for (var i = 0; i < length; ++i) { 9449 var ch = state.current(); 9450 if (!isHexDigit(ch)) { 9451 state.pos = start; 9452 return false 9453 } 9454 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); 9455 state.advance(); 9456 } 9457 return true 9458 }; 9459 9460 // Object type used to represent tokens. Note that normally, tokens 9461 // simply exist as properties on the parser object. This is only 9462 // used for the onToken callback and the external tokenizer. 9463 9464 var Token = function Token(p) { 9465 this.type = p.type; 9466 this.value = p.value; 9467 this.start = p.start; 9468 this.end = p.end; 9469 if (p.options.locations) 9470 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } 9471 if (p.options.ranges) 9472 { this.range = [p.start, p.end]; } 9473 }; 9474 9475 // ## Tokenizer 9476 9477 var pp$9 = Parser.prototype; 9478 9479 // Move to the next token 9480 9481 pp$9.next = function(ignoreEscapeSequenceInKeyword) { 9482 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) 9483 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } 9484 if (this.options.onToken) 9485 { this.options.onToken(new Token(this)); } 9486 9487 this.lastTokEnd = this.end; 9488 this.lastTokStart = this.start; 9489 this.lastTokEndLoc = this.endLoc; 9490 this.lastTokStartLoc = this.startLoc; 9491 this.nextToken(); 9492 }; 9493 9494 pp$9.getToken = function() { 9495 this.next(); 9496 return new Token(this) 9497 }; 9498 9499 // If we're in an ES6 environment, make parsers iterable 9500 if (typeof Symbol !== "undefined") 9501 { pp$9[Symbol.iterator] = function() { 9502 var this$1$1 = this; 9503 9504 return { 9505 next: function () { 9506 var token = this$1$1.getToken(); 9507 return { 9508 done: token.type === types.eof, 9509 value: token 9510 } 9511 } 9512 } 9513 }; } 9514 9515 // Toggle strict mode. Re-reads the next number or string to please 9516 // pedantic tests (`"use strict"; 010;` should fail). 9517 9518 pp$9.curContext = function() { 9519 return this.context[this.context.length - 1] 9520 }; 9521 9522 // Read a single token, updating the parser object's token-related 9523 // properties. 9524 9525 pp$9.nextToken = function() { 9526 var curContext = this.curContext(); 9527 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } 9528 9529 this.start = this.pos; 9530 if (this.options.locations) { this.startLoc = this.curPosition(); } 9531 if (this.pos >= this.input.length) { return this.finishToken(types.eof) } 9532 9533 if (curContext.override) { return curContext.override(this) } 9534 else { this.readToken(this.fullCharCodeAtPos()); } 9535 }; 9536 9537 pp$9.readToken = function(code) { 9538 // Identifier or keyword. '\uXXXX' sequences are allowed in 9539 // identifiers, so '\' also dispatches to that. 9540 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) 9541 { return this.readWord() } 9542 9543 return this.getTokenFromCode(code) 9544 }; 9545 9546 pp$9.fullCharCodeAtPos = function() { 9547 var code = this.input.charCodeAt(this.pos); 9548 if (code <= 0xd7ff || code >= 0xe000) { return code } 9549 var next = this.input.charCodeAt(this.pos + 1); 9550 return (code << 10) + next - 0x35fdc00 9551 }; 9552 9553 pp$9.skipBlockComment = function() { 9554 var startLoc = this.options.onComment && this.curPosition(); 9555 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); 9556 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } 9557 this.pos = end + 2; 9558 if (this.options.locations) { 9559 lineBreakG.lastIndex = start; 9560 var match; 9561 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) { 9562 ++this.curLine; 9563 this.lineStart = match.index + match[0].length; 9564 } 9565 } 9566 if (this.options.onComment) 9567 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, 9568 startLoc, this.curPosition()); } 9569 }; 9570 9571 pp$9.skipLineComment = function(startSkip) { 9572 var start = this.pos; 9573 var startLoc = this.options.onComment && this.curPosition(); 9574 var ch = this.input.charCodeAt(this.pos += startSkip); 9575 while (this.pos < this.input.length && !isNewLine(ch)) { 9576 ch = this.input.charCodeAt(++this.pos); 9577 } 9578 if (this.options.onComment) 9579 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, 9580 startLoc, this.curPosition()); } 9581 }; 9582 9583 // Called at the start of the parse and after every token. Skips 9584 // whitespace and comments, and. 9585 9586 pp$9.skipSpace = function() { 9587 loop: while (this.pos < this.input.length) { 9588 var ch = this.input.charCodeAt(this.pos); 9589 switch (ch) { 9590 case 32: case 160: // ' ' 9591 ++this.pos; 9592 break 9593 case 13: 9594 if (this.input.charCodeAt(this.pos + 1) === 10) { 9595 ++this.pos; 9596 } 9597 case 10: case 8232: case 8233: 9598 ++this.pos; 9599 if (this.options.locations) { 9600 ++this.curLine; 9601 this.lineStart = this.pos; 9602 } 9603 break 9604 case 47: // '/' 9605 switch (this.input.charCodeAt(this.pos + 1)) { 9606 case 42: // '*' 9607 this.skipBlockComment(); 9608 break 9609 case 47: 9610 this.skipLineComment(2); 9611 break 9612 default: 9613 break loop 9614 } 9615 break 9616 default: 9617 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { 9618 ++this.pos; 9619 } else { 9620 break loop 9621 } 9622 } 9623 } 9624 }; 9625 9626 // Called at the end of every token. Sets `end`, `val`, and 9627 // maintains `context` and `exprAllowed`, and skips the space after 9628 // the token, so that the next one's `start` will point at the 9629 // right position. 9630 9631 pp$9.finishToken = function(type, val) { 9632 this.end = this.pos; 9633 if (this.options.locations) { this.endLoc = this.curPosition(); } 9634 var prevType = this.type; 9635 this.type = type; 9636 this.value = val; 9637 9638 this.updateContext(prevType); 9639 }; 9640 9641 // ### Token reading 9642 9643 // This is the function that is called to fetch the next token. It 9644 // is somewhat obscure, because it works in character codes rather 9645 // than characters, and because operator parsing has been inlined 9646 // into it. 9647 // 9648 // All in the name of speed. 9649 // 9650 pp$9.readToken_dot = function() { 9651 var next = this.input.charCodeAt(this.pos + 1); 9652 if (next >= 48 && next <= 57) { return this.readNumber(true) } 9653 var next2 = this.input.charCodeAt(this.pos + 2); 9654 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' 9655 this.pos += 3; 9656 return this.finishToken(types.ellipsis) 9657 } else { 9658 ++this.pos; 9659 return this.finishToken(types.dot) 9660 } 9661 }; 9662 9663 pp$9.readToken_slash = function() { // '/' 9664 var next = this.input.charCodeAt(this.pos + 1); 9665 if (this.exprAllowed) { ++this.pos; return this.readRegexp() } 9666 if (next === 61) { return this.finishOp(types.assign, 2) } 9667 return this.finishOp(types.slash, 1) 9668 }; 9669 9670 pp$9.readToken_mult_modulo_exp = function(code) { // '%*' 9671 var next = this.input.charCodeAt(this.pos + 1); 9672 var size = 1; 9673 var tokentype = code === 42 ? types.star : types.modulo; 9674 9675 // exponentiation operator ** and **= 9676 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { 9677 ++size; 9678 tokentype = types.starstar; 9679 next = this.input.charCodeAt(this.pos + 2); 9680 } 9681 9682 if (next === 61) { return this.finishOp(types.assign, size + 1) } 9683 return this.finishOp(tokentype, size) 9684 }; 9685 9686 pp$9.readToken_pipe_amp = function(code) { // '|&' 9687 var next = this.input.charCodeAt(this.pos + 1); 9688 if (next === code) { 9689 if (this.options.ecmaVersion >= 12) { 9690 var next2 = this.input.charCodeAt(this.pos + 2); 9691 if (next2 === 61) { return this.finishOp(types.assign, 3) } 9692 } 9693 return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2) 9694 } 9695 if (next === 61) { return this.finishOp(types.assign, 2) } 9696 return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1) 9697 }; 9698 9699 pp$9.readToken_caret = function() { // '^' 9700 var next = this.input.charCodeAt(this.pos + 1); 9701 if (next === 61) { return this.finishOp(types.assign, 2) } 9702 return this.finishOp(types.bitwiseXOR, 1) 9703 }; 9704 9705 pp$9.readToken_plus_min = function(code) { // '+-' 9706 var next = this.input.charCodeAt(this.pos + 1); 9707 if (next === code) { 9708 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && 9709 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { 9710 // A `-->` line comment 9711 this.skipLineComment(3); 9712 this.skipSpace(); 9713 return this.nextToken() 9714 } 9715 return this.finishOp(types.incDec, 2) 9716 } 9717 if (next === 61) { return this.finishOp(types.assign, 2) } 9718 return this.finishOp(types.plusMin, 1) 9719 }; 9720 9721 pp$9.readToken_lt_gt = function(code) { // '<>' 9722 var next = this.input.charCodeAt(this.pos + 1); 9723 var size = 1; 9724 if (next === code) { 9725 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; 9726 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) } 9727 return this.finishOp(types.bitShift, size) 9728 } 9729 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && 9730 this.input.charCodeAt(this.pos + 3) === 45) { 9731 // `<!--`, an XML-style comment that should be interpreted as a line comment 9732 this.skipLineComment(4); 9733 this.skipSpace(); 9734 return this.nextToken() 9735 } 9736 if (next === 61) { size = 2; } 9737 return this.finishOp(types.relational, size) 9738 }; 9739 9740 pp$9.readToken_eq_excl = function(code) { // '=!' 9741 var next = this.input.charCodeAt(this.pos + 1); 9742 if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) } 9743 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>' 9744 this.pos += 2; 9745 return this.finishToken(types.arrow) 9746 } 9747 return this.finishOp(code === 61 ? types.eq : types.prefix, 1) 9748 }; 9749 9750 pp$9.readToken_question = function() { // '?' 9751 var ecmaVersion = this.options.ecmaVersion; 9752 if (ecmaVersion >= 11) { 9753 var next = this.input.charCodeAt(this.pos + 1); 9754 if (next === 46) { 9755 var next2 = this.input.charCodeAt(this.pos + 2); 9756 if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) } 9757 } 9758 if (next === 63) { 9759 if (ecmaVersion >= 12) { 9760 var next2$1 = this.input.charCodeAt(this.pos + 2); 9761 if (next2$1 === 61) { return this.finishOp(types.assign, 3) } 9762 } 9763 return this.finishOp(types.coalesce, 2) 9764 } 9765 } 9766 return this.finishOp(types.question, 1) 9767 }; 9768 9769 pp$9.getTokenFromCode = function(code) { 9770 switch (code) { 9771 // The interpretation of a dot depends on whether it is followed 9772 // by a digit or another two dots. 9773 case 46: // '.' 9774 return this.readToken_dot() 9775 9776 // Punctuation tokens. 9777 case 40: ++this.pos; return this.finishToken(types.parenL) 9778 case 41: ++this.pos; return this.finishToken(types.parenR) 9779 case 59: ++this.pos; return this.finishToken(types.semi) 9780 case 44: ++this.pos; return this.finishToken(types.comma) 9781 case 91: ++this.pos; return this.finishToken(types.bracketL) 9782 case 93: ++this.pos; return this.finishToken(types.bracketR) 9783 case 123: ++this.pos; return this.finishToken(types.braceL) 9784 case 125: ++this.pos; return this.finishToken(types.braceR) 9785 case 58: ++this.pos; return this.finishToken(types.colon) 9786 9787 case 96: // '`' 9788 if (this.options.ecmaVersion < 6) { break } 9789 ++this.pos; 9790 return this.finishToken(types.backQuote) 9791 9792 case 48: // '0' 9793 var next = this.input.charCodeAt(this.pos + 1); 9794 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number 9795 if (this.options.ecmaVersion >= 6) { 9796 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number 9797 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number 9798 } 9799 9800 // Anything else beginning with a digit is an integer, octal 9801 // number, or float. 9802 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9 9803 return this.readNumber(false) 9804 9805 // Quotes produce strings. 9806 case 34: case 39: // '"', "'" 9807 return this.readString(code) 9808 9809 // Operators are parsed inline in tiny state machines. '=' (61) is 9810 // often referred to. `finishOp` simply skips the amount of 9811 // characters it is given as second argument, and returns a token 9812 // of the type given by its first argument. 9813 9814 case 47: // '/' 9815 return this.readToken_slash() 9816 9817 case 37: case 42: // '%*' 9818 return this.readToken_mult_modulo_exp(code) 9819 9820 case 124: case 38: // '|&' 9821 return this.readToken_pipe_amp(code) 9822 9823 case 94: // '^' 9824 return this.readToken_caret() 9825 9826 case 43: case 45: // '+-' 9827 return this.readToken_plus_min(code) 9828 9829 case 60: case 62: // '<>' 9830 return this.readToken_lt_gt(code) 9831 9832 case 61: case 33: // '=!' 9833 return this.readToken_eq_excl(code) 9834 9835 case 63: // '?' 9836 return this.readToken_question() 9837 9838 case 126: // '~' 9839 return this.finishOp(types.prefix, 1) 9840 } 9841 9842 this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'"); 9843 }; 9844 9845 pp$9.finishOp = function(type, size) { 9846 var str = this.input.slice(this.pos, this.pos + size); 9847 this.pos += size; 9848 return this.finishToken(type, str) 9849 }; 9850 9851 pp$9.readRegexp = function() { 9852 var escaped, inClass, start = this.pos; 9853 for (;;) { 9854 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); } 9855 var ch = this.input.charAt(this.pos); 9856 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); } 9857 if (!escaped) { 9858 if (ch === "[") { inClass = true; } 9859 else if (ch === "]" && inClass) { inClass = false; } 9860 else if (ch === "/" && !inClass) { break } 9861 escaped = ch === "\\"; 9862 } else { escaped = false; } 9863 ++this.pos; 9864 } 9865 var pattern = this.input.slice(start, this.pos); 9866 ++this.pos; 9867 var flagsStart = this.pos; 9868 var flags = this.readWord1(); 9869 if (this.containsEsc) { this.unexpected(flagsStart); } 9870 9871 // Validate pattern 9872 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this)); 9873 state.reset(start, pattern, flags); 9874 this.validateRegExpFlags(state); 9875 this.validateRegExpPattern(state); 9876 9877 // Create Literal#value property value. 9878 var value = null; 9879 try { 9880 value = new RegExp(pattern, flags); 9881 } catch (e) { 9882 // ESTree requires null if it failed to instantiate RegExp object. 9883 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral 9884 } 9885 9886 return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value}) 9887 }; 9888 9889 // Read an integer in the given radix. Return null if zero digits 9890 // were read, the integer value otherwise. When `len` is given, this 9891 // will return `null` unless the integer has exactly `len` digits. 9892 9893 pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) { 9894 // `len` is used for character escape sequences. In that case, disallow separators. 9895 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined; 9896 9897 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b) 9898 // and isn't fraction part nor exponent part. In that case, if the first digit 9899 // is zero then disallow separators. 9900 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48; 9901 9902 var start = this.pos, total = 0, lastCode = 0; 9903 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) { 9904 var code = this.input.charCodeAt(this.pos), val = (void 0); 9905 9906 if (allowSeparators && code === 95) { 9907 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); } 9908 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); } 9909 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); } 9910 lastCode = code; 9911 continue 9912 } 9913 9914 if (code >= 97) { val = code - 97 + 10; } // a 9915 else if (code >= 65) { val = code - 65 + 10; } // A 9916 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9 9917 else { val = Infinity; } 9918 if (val >= radix) { break } 9919 lastCode = code; 9920 total = total * radix + val; 9921 } 9922 9923 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); } 9924 if (this.pos === start || len != null && this.pos - start !== len) { return null } 9925 9926 return total 9927 }; 9928 9929 function stringToNumber(str, isLegacyOctalNumericLiteral) { 9930 if (isLegacyOctalNumericLiteral) { 9931 return parseInt(str, 8) 9932 } 9933 9934 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value. 9935 return parseFloat(str.replace(/_/g, "")) 9936 } 9937 9938 function stringToBigInt(str) { 9939 if (typeof BigInt !== "function") { 9940 return null 9941 } 9942 9943 // `BigInt(value)` throws syntax error if the string contains numeric separators. 9944 return BigInt(str.replace(/_/g, "")) 9945 } 9946 9947 pp$9.readRadixNumber = function(radix) { 9948 var start = this.pos; 9949 this.pos += 2; // 0x 9950 var val = this.readInt(radix); 9951 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); } 9952 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) { 9953 val = stringToBigInt(this.input.slice(start, this.pos)); 9954 ++this.pos; 9955 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } 9956 return this.finishToken(types.num, val) 9957 }; 9958 9959 // Read an integer, octal integer, or floating-point number. 9960 9961 pp$9.readNumber = function(startsWithDot) { 9962 var start = this.pos; 9963 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); } 9964 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48; 9965 if (octal && this.strict) { this.raise(start, "Invalid number"); } 9966 var next = this.input.charCodeAt(this.pos); 9967 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) { 9968 var val$1 = stringToBigInt(this.input.slice(start, this.pos)); 9969 ++this.pos; 9970 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } 9971 return this.finishToken(types.num, val$1) 9972 } 9973 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; } 9974 if (next === 46 && !octal) { // '.' 9975 ++this.pos; 9976 this.readInt(10); 9977 next = this.input.charCodeAt(this.pos); 9978 } 9979 if ((next === 69 || next === 101) && !octal) { // 'eE' 9980 next = this.input.charCodeAt(++this.pos); 9981 if (next === 43 || next === 45) { ++this.pos; } // '+-' 9982 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); } 9983 } 9984 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } 9985 9986 var val = stringToNumber(this.input.slice(start, this.pos), octal); 9987 return this.finishToken(types.num, val) 9988 }; 9989 9990 // Read a string value, interpreting backslash-escapes. 9991 9992 pp$9.readCodePoint = function() { 9993 var ch = this.input.charCodeAt(this.pos), code; 9994 9995 if (ch === 123) { // '{' 9996 if (this.options.ecmaVersion < 6) { this.unexpected(); } 9997 var codePos = ++this.pos; 9998 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos); 9999 ++this.pos; 10000 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); } 10001 } else { 10002 code = this.readHexChar(4); 10003 } 10004 return code 10005 }; 10006 10007 function codePointToString$1(code) { 10008 // UTF-16 Decoding 10009 if (code <= 0xFFFF) { return String.fromCharCode(code) } 10010 code -= 0x10000; 10011 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) 10012 } 10013 10014 pp$9.readString = function(quote) { 10015 var out = "", chunkStart = ++this.pos; 10016 for (;;) { 10017 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); } 10018 var ch = this.input.charCodeAt(this.pos); 10019 if (ch === quote) { break } 10020 if (ch === 92) { // '\' 10021 out += this.input.slice(chunkStart, this.pos); 10022 out += this.readEscapedChar(false); 10023 chunkStart = this.pos; 10024 } else { 10025 if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); } 10026 ++this.pos; 10027 } 10028 } 10029 out += this.input.slice(chunkStart, this.pos++); 10030 return this.finishToken(types.string, out) 10031 }; 10032 10033 // Reads template string tokens. 10034 10035 var INVALID_TEMPLATE_ESCAPE_ERROR = {}; 10036 10037 pp$9.tryReadTemplateToken = function() { 10038 this.inTemplateElement = true; 10039 try { 10040 this.readTmplToken(); 10041 } catch (err) { 10042 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) { 10043 this.readInvalidTemplateToken(); 10044 } else { 10045 throw err 10046 } 10047 } 10048 10049 this.inTemplateElement = false; 10050 }; 10051 10052 pp$9.invalidStringToken = function(position, message) { 10053 if (this.inTemplateElement && this.options.ecmaVersion >= 9) { 10054 throw INVALID_TEMPLATE_ESCAPE_ERROR 10055 } else { 10056 this.raise(position, message); 10057 } 10058 }; 10059 10060 pp$9.readTmplToken = function() { 10061 var out = "", chunkStart = this.pos; 10062 for (;;) { 10063 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); } 10064 var ch = this.input.charCodeAt(this.pos); 10065 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${' 10066 if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) { 10067 if (ch === 36) { 10068 this.pos += 2; 10069 return this.finishToken(types.dollarBraceL) 10070 } else { 10071 ++this.pos; 10072 return this.finishToken(types.backQuote) 10073 } 10074 } 10075 out += this.input.slice(chunkStart, this.pos); 10076 return this.finishToken(types.template, out) 10077 } 10078 if (ch === 92) { // '\' 10079 out += this.input.slice(chunkStart, this.pos); 10080 out += this.readEscapedChar(true); 10081 chunkStart = this.pos; 10082 } else if (isNewLine(ch)) { 10083 out += this.input.slice(chunkStart, this.pos); 10084 ++this.pos; 10085 switch (ch) { 10086 case 13: 10087 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } 10088 case 10: 10089 out += "\n"; 10090 break 10091 default: 10092 out += String.fromCharCode(ch); 10093 break 10094 } 10095 if (this.options.locations) { 10096 ++this.curLine; 10097 this.lineStart = this.pos; 10098 } 10099 chunkStart = this.pos; 10100 } else { 10101 ++this.pos; 10102 } 10103 } 10104 }; 10105 10106 // Reads a template token to search for the end, without validating any escape sequences 10107 pp$9.readInvalidTemplateToken = function() { 10108 for (; this.pos < this.input.length; this.pos++) { 10109 switch (this.input[this.pos]) { 10110 case "\\": 10111 ++this.pos; 10112 break 10113 10114 case "$": 10115 if (this.input[this.pos + 1] !== "{") { 10116 break 10117 } 10118 // falls through 10119 10120 case "`": 10121 return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos)) 10122 10123 // no default 10124 } 10125 } 10126 this.raise(this.start, "Unterminated template"); 10127 }; 10128 10129 // Used to read escaped characters 10130 10131 pp$9.readEscapedChar = function(inTemplate) { 10132 var ch = this.input.charCodeAt(++this.pos); 10133 ++this.pos; 10134 switch (ch) { 10135 case 110: return "\n" // 'n' -> '\n' 10136 case 114: return "\r" // 'r' -> '\r' 10137 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x' 10138 case 117: return codePointToString$1(this.readCodePoint()) // 'u' 10139 case 116: return "\t" // 't' -> '\t' 10140 case 98: return "\b" // 'b' -> '\b' 10141 case 118: return "\u000b" // 'v' -> '\u000b' 10142 case 102: return "\f" // 'f' -> '\f' 10143 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n' 10144 case 10: // ' \n' 10145 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; } 10146 return "" 10147 case 56: 10148 case 57: 10149 if (inTemplate) { 10150 var codePos = this.pos - 1; 10151 10152 this.invalidStringToken( 10153 codePos, 10154 "Invalid escape sequence in template string" 10155 ); 10156 10157 return null 10158 } 10159 default: 10160 if (ch >= 48 && ch <= 55) { 10161 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]; 10162 var octal = parseInt(octalStr, 8); 10163 if (octal > 255) { 10164 octalStr = octalStr.slice(0, -1); 10165 octal = parseInt(octalStr, 8); 10166 } 10167 this.pos += octalStr.length - 1; 10168 ch = this.input.charCodeAt(this.pos); 10169 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) { 10170 this.invalidStringToken( 10171 this.pos - 1 - octalStr.length, 10172 inTemplate 10173 ? "Octal literal in template string" 10174 : "Octal literal in strict mode" 10175 ); 10176 } 10177 return String.fromCharCode(octal) 10178 } 10179 if (isNewLine(ch)) { 10180 // Unicode new line characters after \ get removed from output in both 10181 // template literals and strings 10182 return "" 10183 } 10184 return String.fromCharCode(ch) 10185 } 10186 }; 10187 10188 // Used to read character escape sequences ('\x', '\u', '\U'). 10189 10190 pp$9.readHexChar = function(len) { 10191 var codePos = this.pos; 10192 var n = this.readInt(16, len); 10193 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); } 10194 return n 10195 }; 10196 10197 // Read an identifier, and return it as a string. Sets `this.containsEsc` 10198 // to whether the word contained a '\u' escape. 10199 // 10200 // Incrementally adds only escaped chars, adding other chunks as-is 10201 // as a micro-optimization. 10202 10203 pp$9.readWord1 = function() { 10204 this.containsEsc = false; 10205 var word = "", first = true, chunkStart = this.pos; 10206 var astral = this.options.ecmaVersion >= 6; 10207 while (this.pos < this.input.length) { 10208 var ch = this.fullCharCodeAtPos(); 10209 if (isIdentifierChar(ch, astral)) { 10210 this.pos += ch <= 0xffff ? 1 : 2; 10211 } else if (ch === 92) { // "\" 10212 this.containsEsc = true; 10213 word += this.input.slice(chunkStart, this.pos); 10214 var escStart = this.pos; 10215 if (this.input.charCodeAt(++this.pos) !== 117) // "u" 10216 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); } 10217 ++this.pos; 10218 var esc = this.readCodePoint(); 10219 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) 10220 { this.invalidStringToken(escStart, "Invalid Unicode escape"); } 10221 word += codePointToString$1(esc); 10222 chunkStart = this.pos; 10223 } else { 10224 break 10225 } 10226 first = false; 10227 } 10228 return word + this.input.slice(chunkStart, this.pos) 10229 }; 10230 10231 // Read an identifier or keyword token. Will check for reserved 10232 // words when necessary. 10233 10234 pp$9.readWord = function() { 10235 var word = this.readWord1(); 10236 var type = types.name; 10237 if (this.keywords.test(word)) { 10238 type = keywords$1[word]; 10239 } 10240 return this.finishToken(type, word) 10241 }; 10242 10243 // Acorn is a tiny, fast JavaScript parser written in JavaScript. 10244 10245 var version = "7.4.1"; 10246 10247 Parser.acorn = { 10248 Parser: Parser, 10249 version: version, 10250 defaultOptions: defaultOptions, 10251 Position: Position, 10252 SourceLocation: SourceLocation, 10253 getLineInfo: getLineInfo, 10254 Node: Node, 10255 TokenType: TokenType, 10256 tokTypes: types, 10257 keywordTypes: keywords$1, 10258 TokContext: TokContext, 10259 tokContexts: types$1, 10260 isIdentifierChar: isIdentifierChar, 10261 isIdentifierStart: isIdentifierStart, 10262 Token: Token, 10263 isNewLine: isNewLine, 10264 lineBreak: lineBreak, 10265 lineBreakG: lineBreakG, 10266 nonASCIIwhitespace: nonASCIIwhitespace 10267 };var defaultGlobals = new Set([ 10268 "Array", 10269 "ArrayBuffer", 10270 "atob", 10271 "AudioContext", 10272 "Blob", 10273 "Boolean", 10274 "BigInt", 10275 "btoa", 10276 "clearInterval", 10277 "clearTimeout", 10278 "console", 10279 "crypto", 10280 "CustomEvent", 10281 "DataView", 10282 "Date", 10283 "decodeURI", 10284 "decodeURIComponent", 10285 "devicePixelRatio", 10286 "document", 10287 "encodeURI", 10288 "encodeURIComponent", 10289 "Error", 10290 "escape", 10291 "eval", 10292 "fetch", 10293 "File", 10294 "FileList", 10295 "FileReader", 10296 "Float32Array", 10297 "Float64Array", 10298 "Function", 10299 "Headers", 10300 "Image", 10301 "ImageData", 10302 "Infinity", 10303 "Int16Array", 10304 "Int32Array", 10305 "Int8Array", 10306 "Intl", 10307 "isFinite", 10308 "isNaN", 10309 "JSON", 10310 "Map", 10311 "Math", 10312 "NaN", 10313 "Number", 10314 "navigator", 10315 "Object", 10316 "parseFloat", 10317 "parseInt", 10318 "performance", 10319 "Path2D", 10320 "Promise", 10321 "Proxy", 10322 "RangeError", 10323 "ReferenceError", 10324 "Reflect", 10325 "RegExp", 10326 "cancelAnimationFrame", 10327 "requestAnimationFrame", 10328 "Set", 10329 "setInterval", 10330 "setTimeout", 10331 "String", 10332 "Symbol", 10333 "SyntaxError", 10334 "TextDecoder", 10335 "TextEncoder", 10336 "this", 10337 "TypeError", 10338 "Uint16Array", 10339 "Uint32Array", 10340 "Uint8Array", 10341 "Uint8ClampedArray", 10342 "undefined", 10343 "unescape", 10344 "URIError", 10345 "URL", 10346 "WeakMap", 10347 "WeakSet", 10348 "WebSocket", 10349 "Worker", 10350 "window" 10351 ]);// AST walker module for Mozilla Parser API compatible trees 10352 10353 // A simple walk is one where you simply specify callbacks to be 10354 // called on specific nodes. The last two arguments are optional. A 10355 // simple use would be 10356 // 10357 // walk.simple(myTree, { 10358 // Expression: function(node) { ... } 10359 // }); 10360 // 10361 // to do something with all expressions. All Parser API node types 10362 // can be used to identify node types, as well as Expression and 10363 // Statement, which denote categories of nodes. 10364 // 10365 // The base argument can be used to pass a custom (recursive) 10366 // walker, and state can be used to give this walked an initial 10367 // state. 10368 10369 function simple(node, visitors, baseVisitor, state, override) { 10370 if (!baseVisitor) { baseVisitor = base 10371 ; }(function c(node, st, override) { 10372 var type = override || node.type, found = visitors[type]; 10373 baseVisitor[type](node, st, c); 10374 if (found) { found(node, st); } 10375 })(node, state, override); 10376 } 10377 10378 // An ancestor walk keeps an array of ancestor nodes (including the 10379 // current node) and passes them to the callback as third parameter 10380 // (and also as state parameter when no other state is present). 10381 function ancestor(node, visitors, baseVisitor, state, override) { 10382 var ancestors = []; 10383 if (!baseVisitor) { baseVisitor = base 10384 ; }(function c(node, st, override) { 10385 var type = override || node.type, found = visitors[type]; 10386 var isNew = node !== ancestors[ancestors.length - 1]; 10387 if (isNew) { ancestors.push(node); } 10388 baseVisitor[type](node, st, c); 10389 if (found) { found(node, st || ancestors, ancestors); } 10390 if (isNew) { ancestors.pop(); } 10391 })(node, state, override); 10392 } 10393 10394 // A full walk triggers the callback on each node 10395 function full(node, callback, baseVisitor, state, override) { 10396 if (!baseVisitor) { baseVisitor = base 10397 ; }(function c(node, st, override) { 10398 var type = override || node.type; 10399 baseVisitor[type](node, st, c); 10400 if (!override) { callback(node, st, type); } 10401 })(node, state, override); 10402 } 10403 10404 // Fallback to an Object.create polyfill for older environments. 10405 var create = Object.create || function(proto) { 10406 function Ctor() {} 10407 Ctor.prototype = proto; 10408 return new Ctor 10409 }; 10410 10411 // Used to create a custom walker. Will fill in all missing node 10412 // type properties with the defaults. 10413 function make(funcs, baseVisitor) { 10414 var visitor = create(baseVisitor || base); 10415 for (var type in funcs) { visitor[type] = funcs[type]; } 10416 return visitor 10417 } 10418 10419 function skipThrough(node, st, c) { c(node, st); } 10420 function ignore(_node, _st, _c) {} 10421 10422 // Node walkers. 10423 10424 var base = {}; 10425 10426 base.Program = base.BlockStatement = function (node, st, c) { 10427 for (var i = 0, list = node.body; i < list.length; i += 1) 10428 { 10429 var stmt = list[i]; 10430 10431 c(stmt, st, "Statement"); 10432 } 10433 }; 10434 base.Statement = skipThrough; 10435 base.EmptyStatement = ignore; 10436 base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = 10437 function (node, st, c) { return c(node.expression, st, "Expression"); }; 10438 base.IfStatement = function (node, st, c) { 10439 c(node.test, st, "Expression"); 10440 c(node.consequent, st, "Statement"); 10441 if (node.alternate) { c(node.alternate, st, "Statement"); } 10442 }; 10443 base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; 10444 base.BreakStatement = base.ContinueStatement = ignore; 10445 base.WithStatement = function (node, st, c) { 10446 c(node.object, st, "Expression"); 10447 c(node.body, st, "Statement"); 10448 }; 10449 base.SwitchStatement = function (node, st, c) { 10450 c(node.discriminant, st, "Expression"); 10451 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { 10452 var cs = list$1[i$1]; 10453 10454 if (cs.test) { c(cs.test, st, "Expression"); } 10455 for (var i = 0, list = cs.consequent; i < list.length; i += 1) 10456 { 10457 var cons = list[i]; 10458 10459 c(cons, st, "Statement"); 10460 } 10461 } 10462 }; 10463 base.SwitchCase = function (node, st, c) { 10464 if (node.test) { c(node.test, st, "Expression"); } 10465 for (var i = 0, list = node.consequent; i < list.length; i += 1) 10466 { 10467 var cons = list[i]; 10468 10469 c(cons, st, "Statement"); 10470 } 10471 }; 10472 base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { 10473 if (node.argument) { c(node.argument, st, "Expression"); } 10474 }; 10475 base.ThrowStatement = base.SpreadElement = 10476 function (node, st, c) { return c(node.argument, st, "Expression"); }; 10477 base.TryStatement = function (node, st, c) { 10478 c(node.block, st, "Statement"); 10479 if (node.handler) { c(node.handler, st); } 10480 if (node.finalizer) { c(node.finalizer, st, "Statement"); } 10481 }; 10482 base.CatchClause = function (node, st, c) { 10483 if (node.param) { c(node.param, st, "Pattern"); } 10484 c(node.body, st, "Statement"); 10485 }; 10486 base.WhileStatement = base.DoWhileStatement = function (node, st, c) { 10487 c(node.test, st, "Expression"); 10488 c(node.body, st, "Statement"); 10489 }; 10490 base.ForStatement = function (node, st, c) { 10491 if (node.init) { c(node.init, st, "ForInit"); } 10492 if (node.test) { c(node.test, st, "Expression"); } 10493 if (node.update) { c(node.update, st, "Expression"); } 10494 c(node.body, st, "Statement"); 10495 }; 10496 base.ForInStatement = base.ForOfStatement = function (node, st, c) { 10497 c(node.left, st, "ForInit"); 10498 c(node.right, st, "Expression"); 10499 c(node.body, st, "Statement"); 10500 }; 10501 base.ForInit = function (node, st, c) { 10502 if (node.type === "VariableDeclaration") { c(node, st); } 10503 else { c(node, st, "Expression"); } 10504 }; 10505 base.DebuggerStatement = ignore; 10506 10507 base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; 10508 base.VariableDeclaration = function (node, st, c) { 10509 for (var i = 0, list = node.declarations; i < list.length; i += 1) 10510 { 10511 var decl = list[i]; 10512 10513 c(decl, st); 10514 } 10515 }; 10516 base.VariableDeclarator = function (node, st, c) { 10517 c(node.id, st, "Pattern"); 10518 if (node.init) { c(node.init, st, "Expression"); } 10519 }; 10520 10521 base.Function = function (node, st, c) { 10522 if (node.id) { c(node.id, st, "Pattern"); } 10523 for (var i = 0, list = node.params; i < list.length; i += 1) 10524 { 10525 var param = list[i]; 10526 10527 c(param, st, "Pattern"); 10528 } 10529 c(node.body, st, node.expression ? "Expression" : "Statement"); 10530 }; 10531 10532 base.Pattern = function (node, st, c) { 10533 if (node.type === "Identifier") 10534 { c(node, st, "VariablePattern"); } 10535 else if (node.type === "MemberExpression") 10536 { c(node, st, "MemberPattern"); } 10537 else 10538 { c(node, st); } 10539 }; 10540 base.VariablePattern = ignore; 10541 base.MemberPattern = skipThrough; 10542 base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; 10543 base.ArrayPattern = function (node, st, c) { 10544 for (var i = 0, list = node.elements; i < list.length; i += 1) { 10545 var elt = list[i]; 10546 10547 if (elt) { c(elt, st, "Pattern"); } 10548 } 10549 }; 10550 base.ObjectPattern = function (node, st, c) { 10551 for (var i = 0, list = node.properties; i < list.length; i += 1) { 10552 var prop = list[i]; 10553 10554 if (prop.type === "Property") { 10555 if (prop.computed) { c(prop.key, st, "Expression"); } 10556 c(prop.value, st, "Pattern"); 10557 } else if (prop.type === "RestElement") { 10558 c(prop.argument, st, "Pattern"); 10559 } 10560 } 10561 }; 10562 10563 base.Expression = skipThrough; 10564 base.ThisExpression = base.Super = base.MetaProperty = ignore; 10565 base.ArrayExpression = function (node, st, c) { 10566 for (var i = 0, list = node.elements; i < list.length; i += 1) { 10567 var elt = list[i]; 10568 10569 if (elt) { c(elt, st, "Expression"); } 10570 } 10571 }; 10572 base.ObjectExpression = function (node, st, c) { 10573 for (var i = 0, list = node.properties; i < list.length; i += 1) 10574 { 10575 var prop = list[i]; 10576 10577 c(prop, st); 10578 } 10579 }; 10580 base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; 10581 base.SequenceExpression = function (node, st, c) { 10582 for (var i = 0, list = node.expressions; i < list.length; i += 1) 10583 { 10584 var expr = list[i]; 10585 10586 c(expr, st, "Expression"); 10587 } 10588 }; 10589 base.TemplateLiteral = function (node, st, c) { 10590 for (var i = 0, list = node.quasis; i < list.length; i += 1) 10591 { 10592 var quasi = list[i]; 10593 10594 c(quasi, st); 10595 } 10596 10597 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) 10598 { 10599 var expr = list$1[i$1]; 10600 10601 c(expr, st, "Expression"); 10602 } 10603 }; 10604 base.TemplateElement = ignore; 10605 base.UnaryExpression = base.UpdateExpression = function (node, st, c) { 10606 c(node.argument, st, "Expression"); 10607 }; 10608 base.BinaryExpression = base.LogicalExpression = function (node, st, c) { 10609 c(node.left, st, "Expression"); 10610 c(node.right, st, "Expression"); 10611 }; 10612 base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { 10613 c(node.left, st, "Pattern"); 10614 c(node.right, st, "Expression"); 10615 }; 10616 base.ConditionalExpression = function (node, st, c) { 10617 c(node.test, st, "Expression"); 10618 c(node.consequent, st, "Expression"); 10619 c(node.alternate, st, "Expression"); 10620 }; 10621 base.NewExpression = base.CallExpression = function (node, st, c) { 10622 c(node.callee, st, "Expression"); 10623 if (node.arguments) 10624 { for (var i = 0, list = node.arguments; i < list.length; i += 1) 10625 { 10626 var arg = list[i]; 10627 10628 c(arg, st, "Expression"); 10629 } } 10630 };
10631 base.MemberExpression = function (node, st, c) { 10632 c(node.object, st, "Expression"); 10633 if (node.computed) { c(node.property, st, "Expression"); } 10634 }; 10635 base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { 10636 if (node.declaration) 10637 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } 10638 if (node.source) { c(node.source, st, "Expression"); } 10639 }; 10640 base.ExportAllDeclaration = function (node, st, c) { 10641 if (node.exported) 10642 { c(node.exported, st); } 10643 c(node.source, st, "Expression"); 10644 }; 10645 base.ImportDeclaration = function (node, st, c) { 10646 for (var i = 0, list = node.specifiers; i < list.length; i += 1) 10647 { 10648 var spec = list[i]; 10649 10650 c(spec, st); 10651 } 10652 c(node.source, st, "Expression"); 10653 }; 10654 base.ImportExpression = function (node, st, c) { 10655 c(node.source, st, "Expression"); 10656 }; 10657 base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore; 10658 10659 base.TaggedTemplateExpression = function (node, st, c) { 10660 c(node.tag, st, "Expression"); 10661 c(node.quasi, st, "Expression"); 10662 }; 10663 base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; 10664 base.Class = function (node, st, c) { 10665 if (node.id) { c(node.id, st, "Pattern"); } 10666 if (node.superClass) { c(node.superClass, st, "Expression"); } 10667 c(node.body, st); 10668 }; 10669 base.ClassBody = function (node, st, c) { 10670 for (var i = 0, list = node.body; i < list.length; i += 1) 10671 { 10672 var elt = list[i]; 10673 10674 c(elt, st); 10675 } 10676 }; 10677 base.MethodDefinition = base.Property = function (node, st, c) { 10678 if (node.computed) { c(node.key, st, "Expression"); } 10679 c(node.value, st, "Expression"); 10680 };var walk = make({ 10681 Import() {}, 10682 ViewExpression(node, st, c) { 10683 c(node.id, st, "Identifier"); 10684 }, 10685 MutableExpression(node, st, c) { 10686 c(node.id, st, "Identifier"); 10687 } 10688 });// Based on https://github.com/ForbesLindesay/acorn-globals 10689 10690 function isScope(node) { 10691 return node.type === "FunctionExpression" 10692 || node.type === "FunctionDeclaration" 10693 || node.type === "ArrowFunctionExpression" 10694 || node.type === "Program"; 10695 } 10696 10697 function isBlockScope(node) { 10698 return node.type === "BlockStatement" 10699 || node.type === "ForInStatement" 10700 || node.type === "ForOfStatement" 10701 || node.type === "ForStatement" 10702 || isScope(node); 10703 } 10704 10705 function declaresArguments(node) { 10706 return node.type === "FunctionExpression" 10707 || node.type === "FunctionDeclaration"; 10708 } 10709 10710 function findReferences(cell, globals) { 10711 const ast = {type: "Program", body: [cell.body]}; 10712 const locals = new Map; 10713 const globalSet = new Set(globals); 10714 const references = []; 10715 10716 function hasLocal(node, name) { 10717 const l = locals.get(node); 10718 return l ? l.has(name) : false; 10719 } 10720 10721 function declareLocal(node, id) { 10722 const l = locals.get(node); 10723 if (l) l.add(id.name); 10724 else locals.set(node, new Set([id.name])); 10725 } 10726 10727 function declareClass(node) { 10728 if (node.id) declareLocal(node, node.id); 10729 } 10730 10731 function declareFunction(node) { 10732 node.params.forEach(param => declarePattern(param, node)); 10733 if (node.id) declareLocal(node, node.id); 10734 } 10735 10736 function declareCatchClause(node) { 10737 if (node.param) declarePattern(node.param, node); 10738 } 10739 10740 function declarePattern(node, parent) { 10741 switch (node.type) { 10742 case "Identifier": 10743 declareLocal(parent, node); 10744 break; 10745 case "ObjectPattern": 10746 node.properties.forEach(node => declarePattern(node, parent)); 10747 break; 10748 case "ArrayPattern": 10749 node.elements.forEach(node => node && declarePattern(node, parent)); 10750 break; 10751 case "Property": 10752 declarePattern(node.value, parent); 10753 break; 10754 case "RestElement": 10755 declarePattern(node.argument, parent); 10756 break; 10757 case "AssignmentPattern": 10758 declarePattern(node.left, parent); 10759 break; 10760 default: 10761 throw new Error("Unrecognized pattern type: " + node.type); 10762 } 10763 } 10764 10765 function declareModuleSpecifier(node) { 10766 declareLocal(ast, node.local); 10767 } 10768 10769 ancestor( 10770 ast, 10771 { 10772 VariableDeclaration: (node, parents) => { 10773 let parent = null; 10774 for (let i = parents.length - 1; i >= 0 && parent === null; --i) { 10775 if (node.kind === "var" ? isScope(parents[i]) : isBlockScope(parents[i])) { 10776 parent = parents[i]; 10777 } 10778 } 10779 node.declarations.forEach(declaration => declarePattern(declaration.id, parent)); 10780 }, 10781 FunctionDeclaration: (node, parents) => { 10782 let parent = null; 10783 for (let i = parents.length - 2; i >= 0 && parent === null; --i) { 10784 if (isScope(parents[i])) { 10785 parent = parents[i]; 10786 } 10787 } 10788 declareLocal(parent, node.id); 10789 declareFunction(node); 10790 }, 10791 Function: declareFunction, 10792 ClassDeclaration: (node, parents) => { 10793 let parent = null; 10794 for (let i = parents.length - 2; i >= 0 && parent === null; i--) { 10795 if (isScope(parents[i])) { 10796 parent = parents[i]; 10797 } 10798 } 10799 declareLocal(parent, node.id); 10800 }, 10801 Class: declareClass, 10802 CatchClause: declareCatchClause, 10803 ImportDefaultSpecifier: declareModuleSpecifier, 10804 ImportSpecifier: declareModuleSpecifier, 10805 ImportNamespaceSpecifier: declareModuleSpecifier 10806 }, 10807 walk 10808 ); 10809 10810 function identifier(node, parents) { 10811 let name = node.name; 10812 if (name === "undefined") return; 10813 for (let i = parents.length - 2; i >= 0; --i) { 10814 if (name === "arguments") { 10815 if (declaresArguments(parents[i])) { 10816 return; 10817 } 10818 } 10819 if (hasLocal(parents[i], name)) { 10820 return; 10821 } 10822 if (parents[i].type === "ViewExpression") { 10823 node = parents[i]; 10824 name = `viewof ${node.id.name}`; 10825 } 10826 if (parents[i].type === "MutableExpression") { 10827 node = parents[i]; 10828 name = `mutable ${node.id.name}`; 10829 } 10830 } 10831 if (!globalSet.has(name)) { 10832 if (name === "arguments") { 10833 throw Object.assign(new SyntaxError(`arguments is not allowed`), {node}); 10834 } 10835 references.push(node); 10836 } 10837 } 10838 10839 ancestor( 10840 ast, 10841 { 10842 VariablePattern: identifier, 10843 Identifier: identifier 10844 }, 10845 walk 10846 ); 10847 10848 function checkConst(node, parents) { 10849 switch (node.type) { 10850 case "Identifier": 10851 case "VariablePattern": { 10852 identifier(node, parents); 10853 break; 10854 } 10855 case "ArrayPattern": 10856 case "ObjectPattern": { 10857 ancestor( 10858 node, 10859 { 10860 Identifier: identifier, 10861 VariablePattern: identifier 10862 }, 10863 walk 10864 ); 10865 break; 10866 } 10867 } 10868 function identifier(node, nodeParents) { 10869 for (const parent of parents) { 10870 if (hasLocal(parent, node.name)) { 10871 return; 10872 } 10873 } 10874 if (nodeParents[nodeParents.length - 2].type === "MutableExpression") { 10875 return; 10876 } 10877 throw Object.assign(new SyntaxError(`Assignment to constant variable ${node.name}`), {node}); 10878 } 10879 } 10880 10881 function checkConstArgument(node, parents) { 10882 checkConst(node.argument, parents); 10883 } 10884 10885 function checkConstLeft(node, parents) { 10886 checkConst(node.left, parents); 10887 } 10888 10889 ancestor( 10890 ast, 10891 { 10892 AssignmentExpression: checkConstLeft, 10893 UpdateExpression: checkConstArgument, 10894 ForOfStatement: checkConstLeft, 10895 ForInStatement: checkConstLeft 10896 }, 10897 walk 10898 ); 10899 10900 return references; 10901 }function findFeatures(cell, featureName) { 10902 const ast = {type: "Program", body: [cell.body]}; 10903 const features = new Map(); 10904 const {references} = cell; 10905 10906 simple( 10907 ast, 10908 { 10909 CallExpression: node => { 10910 const {callee, arguments: args} = node; 10911 10912 // Ignore function calls that are not references to the feature. 10913 if ( 10914 callee.type !== "Identifier" || 10915 callee.name !== featureName || 10916 references.indexOf(callee) < 0 10917 ) return; 10918 10919 // Forbid dynamic calls. 10920 if ( 10921 args.length !== 1 || 10922 !((args[0].type === "Literal" && /^['"]/.test(args[0].raw)) || 10923 (args[0].type === "TemplateLiteral" && args[0].expressions.length === 0)) 10924 ) { 10925 throw Object.assign(new SyntaxError(`${featureName} requires a single literal string argument`), {node}); 10926 } 10927 10928 const [arg] = args; 10929 const name = arg.type === "Literal" ? arg.value : arg.quasis[0].value.cooked; 10930 const location = {start: arg.start, end: arg.end}; 10931 if (features.has(name)) features.get(name).push(location); 10932 else features.set(name, [location]); 10933 } 10934 }, 10935 walk 10936 ); 10937 10938 return features; 10939 }const SCOPE_FUNCTION$1 = 2; 10940 const SCOPE_ASYNC$1 = 4; 10941 const SCOPE_GENERATOR$1 = 8; 10942 10943 const STATE_START = Symbol("start"); 10944 const STATE_MODIFIER = Symbol("modifier"); 10945 const STATE_FUNCTION = Symbol("function"); 10946 const STATE_NAME = Symbol("name"); 10947 10948 function parseCell(input, {globals} = {}) { 10949 const cell = CellParser.parse(input); 10950 parseReferences(cell, input, globals); 10951 parseFeatures(cell); 10952 return cell; 10953 } 10954 10955 /* 10956 âââââââ 10957 âââââââââââââSTARTââfunction|class 10958 â âââââââ â 10959 viewof|mutable|async â â¼ 10960 â â ââââââââââ âââ 10961 â¼ â âFUNCTIONââââââ¶â*â 10962 ââââââââââ â ââââââââââ âââ 10963 âMODIFIERâ â â 10964 ââââââââââ name name 10965 â â â 10966 ââânameââ â â¼ 10967 â¼ â âââââââââââââââ 10968 ââââââââââ â âFUNCTION_NAMEâ 10969 â NAME ââââ âââââââââââââââ 10970 ââââââââââ 10971 â 10972 = 10973 â¼ 10974 ââââââââââ 10975 â EQ â 10976 ââââââââââ 10977 */ 10978 10979 function peekId(input) { 10980 let state = STATE_START; 10981 let name; 10982 try { 10983 for (const token of Parser.tokenizer(input, {ecmaVersion: 11})) { 10984 switch (state) {
10985 case STATE_START: 10986 case STATE_MODIFIER: { 10987 if (token.type === types.name) { 10988 if ( 10989 state === STATE_START && 10990 (token.value === "viewof" || 10991 token.value === "mutable" || 10992 token.value === "async") 10993 ) { 10994 state = STATE_MODIFIER; 10995 continue; 10996 } 10997 state = STATE_NAME; 10998 name = token; 10999 continue; 11000 } 11001 if (token.type === types._function || token.type === types._class) { 11002 state = STATE_FUNCTION; 11003 continue; 11004 } 11005 break; 11006 } 11007 case STATE_NAME: { 11008 if (token.type === types.eq) return name.value; 11009 break; 11010 } 11011 case STATE_FUNCTION: { 11012 if (token.type === types.star) continue; 11013 if (token.type === types.name && token.end < input.length) 11014 return token.value; 11015 break; 11016 } 11017 } 11018 return; 11019 } 11020 } catch (ignore) { 11021 return; 11022 } 11023 } 11024 11025 class CellParser extends Parser { 11026 constructor(options, ...args) { 11027 super(Object.assign({ecmaVersion: 12}, options), ...args); 11028 } 11029 enterScope(flags) { 11030 if (flags & SCOPE_FUNCTION$1) ++this.O_function; 11031 return super.enterScope(flags); 11032 } 11033 exitScope() { 11034 if (this.currentScope().flags & SCOPE_FUNCTION$1) --this.O_function; 11035 return super.exitScope(); 11036 } 11037 parseForIn(node, init) { 11038 if (this.O_function === 1 && node.await) this.O_async = true; 11039 return super.parseForIn(node, init); 11040 } 11041 parseAwait() { 11042 if (this.O_function === 1) this.O_async = true; 11043 return super.parseAwait(); 11044 } 11045 parseYield(noIn) { 11046 if (this.O_function === 1) this.O_generator = true; 11047 return super.parseYield(noIn); 11048 } 11049 parseImport(node) { 11050 this.next(); 11051 node.specifiers = this.parseImportSpecifiers(); 11052 if (this.type === types._with) { 11053 this.next(); 11054 node.injections = this.parseImportSpecifiers(); 11055 } 11056 this.expectContextual("from"); 11057 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected(); 11058 return this.finishNode(node, "ImportDeclaration"); 11059 } 11060 parseImportSpecifiers() { 11061 const nodes = []; 11062 const identifiers = new Set; 11063 let first = true; 11064 this.expect(types.braceL); 11065 while (!this.eat(types.braceR)) { 11066 if (first) { 11067 first = false; 11068 } else { 11069 this.expect(types.comma); 11070 if (this.afterTrailingComma(types.braceR)) break; 11071 } 11072 const node = this.startNode(); 11073 node.view = this.eatContextual("viewof"); 11074 node.mutable = node.view ? false : this.eatContextual("mutable"); 11075 node.imported = this.parseIdent(); 11076 this.checkUnreserved(node.imported); 11077 this.checkLocal(node.imported); 11078 if (this.eatContextual("as")) { 11079 node.local = this.parseIdent(); 11080 this.checkUnreserved(node.local); 11081 this.checkLocal(node.local); 11082 } else { 11083 node.local = node.imported; 11084 } 11085 this.checkLVal(node.local, "let"); 11086 if (identifiers.has(node.local.name)) { 11087 this.raise(node.local.start, `Identifier '${node.local.name}' has already been declared`); 11088 } 11089 identifiers.add(node.local.name); 11090 nodes.push(this.finishNode(node, "ImportSpecifier")); 11091 } 11092 return nodes; 11093 } 11094 parseExprAtom(refDestructuringErrors) { 11095 return ( 11096 this.parseMaybeKeywordExpression("viewof", "ViewExpression") || 11097 this.parseMaybeKeywordExpression("mutable", "MutableExpression") || 11098 super.parseExprAtom(refDestructuringErrors) 11099 ); 11100 } 11101 parseCell(node, eof) { 11102 const lookahead = new CellParser({}, this.input, this.start); 11103 let token = lookahead.getToken(); 11104 let body = null; 11105 let id = null; 11106 11107 this.O_function = 0; 11108 this.O_async = false; 11109 this.O_generator = false; 11110 this.strict = true; 11111 this.enterScope(SCOPE_FUNCTION$1 | SCOPE_ASYNC$1 | SCOPE_GENERATOR$1); 11112 11113 // An import? 11114 if (token.type === types._import && lookahead.getToken().type !== types.parenL) { 11115 body = this.parseImport(this.startNode()); 11116 } 11117 11118 // A non-empty cell? 11119 else if (token.type !== types.eof && token.type !== types.semi) { 11120 // A named cell? 11121 if (token.type === types.name) { 11122 if (token.value === "viewof" || token.value === "mutable") { 11123 token = lookahead.getToken(); 11124 if (token.type !== types.name) {
11125 lookahead.unexpected(); 11126 } 11127 } 11128 token = lookahead.getToken(); 11129 if (token.type === types.eq) { 11130 id = 11131 this.parseMaybeKeywordExpression("viewof", "ViewExpression") || 11132 this.parseMaybeKeywordExpression("mutable", "MutableExpression") || 11133 this.parseIdent(); 11134 token = lookahead.getToken(); 11135 this.expect(types.eq); 11136 } 11137 } 11138 11139 // A block? 11140 if (token.type === types.braceL) { 11141 body = this.parseBlock(); 11142 } 11143 11144 // An expression? 11145 // Possibly a function or class declaration? 11146 else { 11147 body = this.parseExpression(); 11148 if ( 11149 id === null && 11150 (body.type === "FunctionExpression" || 11151 body.type === "ClassExpression") 11152 ) { 11153 id = body.id; 11154 } 11155 } 11156 } 11157 11158 this.semicolon(); 11159 if (eof) this.expect(types.eof); // TODO 11160 11161 if (id) this.checkLocal(id); 11162 node.id = id; 11163 node.async = this.O_async; 11164 node.generator = this.O_generator; 11165 node.body = body; 11166 this.exitScope(); 11167 return this.finishNode(node, "Cell"); 11168 } 11169 parseTopLevel(node) { 11170 return this.parseCell(node, true); 11171 } 11172 toAssignable(node, isBinding, refDestructuringErrors) { 11173 return node.type === "MutableExpression" 11174 ? node 11175 : super.toAssignable(node, isBinding, refDestructuringErrors); 11176 } 11177 checkLocal(id) { 11178 const node = id.id || id; 11179 if (defaultGlobals.has(node.name) || node.name === "arguments") { 11180 this.raise(node.start, `Identifier '${node.name}' is reserved`); 11181 } 11182 } 11183 checkUnreserved(node) { 11184 if (node.name === "viewof" || node.name === "mutable") { 11185 this.raise(node.start, `Unexpected keyword '${node.name}'`); 11186 } 11187 return super.checkUnreserved(node); 11188 } 11189 checkLVal(expr, bindingType, checkClashes) { 11190 return super.checkLVal( 11191 expr.type === "MutableExpression" ? expr.id : expr, 11192 bindingType, 11193 checkClashes 11194 ); 11195 } 11196 unexpected(pos) { 11197 this.raise( 11198 pos != null ? pos : this.start, 11199 this.type === types.eof ? "Unexpected end of input" : "Unexpected token" 11200 ); 11201 } 11202 parseMaybeKeywordExpression(keyword, type) { 11203 if (this.isContextual(keyword)) { 11204 const node = this.startNode(); 11205 this.next(); 11206 node.id = this.parseIdent(); 11207 return this.finishNode(node, type); 11208 } 11209 } 11210 } 11211 11212 function parseModule(input, {globals} = {}) { 11213 const program = ModuleParser.parse(input); 11214 for (const cell of program.cells) { 11215 parseReferences(cell, input, globals); 11216 parseFeatures(cell, input); 11217 } 11218 return program; 11219 } 11220 11221 class ModuleParser extends CellParser { 11222 parseTopLevel(node) { 11223 if (!node.cells) node.cells = []; 11224 while (this.type !== types.eof) { 11225 const cell = this.parseCell(this.startNode()); 11226 cell.input = this.input; 11227 node.cells.push(cell); 11228 } 11229 this.next(); 11230 return this.finishNode(node, "Program"); 11231 } 11232 } 11233 11234 // Find references. 11235 // Check for illegal references to arguments. 11236 // Check for illegal assignments to global references. 11237 function parseReferences(cell, input, globals = defaultGlobals) { 11238 if (cell.body && cell.body.type !== "ImportDeclaration") { 11239 try { 11240 cell.references = findReferences(cell, globals); 11241 } catch (error) { 11242 if (error.node) { 11243 const loc = getLineInfo(input, error.node.start); 11244 error.message += ` (${loc.line}:${loc.column})`; 11245 error.pos = error.node.start; 11246 error.loc = loc; 11247 delete error.node; 11248 } 11249 throw error; 11250 } 11251 } 11252 return cell; 11253 } 11254 11255 // Find features: file attachments, secrets, database clients. 11256 // Check for illegal references to arguments. 11257 // Check for illegal assignments to global references. 11258 function parseFeatures(cell, input) { 11259 if (cell.body && cell.body.type !== "ImportDeclaration") { 11260 try { 11261 cell.fileAttachments = findFeatures(cell, "FileAttachment"); 11262 cell.databaseClients = findFeatures(cell, "DatabaseClient"); 11263 cell.secrets = findFeatures(cell, "Secret"); 11264 } catch (error) { 11265 if (error.node) { 11266 const loc = getLineInfo(input, error.node.start); 11267 error.message += ` (${loc.line}:${loc.column})`; 11268 error.pos = error.node.start; 11269 error.loc = loc;
11270 delete error.node; 11271 } 11272 throw error; 11273 } 11274 } else { 11275 cell.fileAttachments = new Map(); 11276 cell.databaseClients = new Map(); 11277 cell.secrets = new Map(); 11278 } 11279 return cell; 11280 }var index=/*#__PURE__*/Object.freeze({__proto__:null,parseCell: parseCell,peekId: peekId,CellParser: CellParser,parseModule: parseModule,ModuleParser: ModuleParser,walk: walk});/** 11281 * FINISH REPLACING THE SIMPLE WALKER WITH A FULL WALKER THAT DOES SUBSTITUTION ALL AT ONCE. 11282 * 11283 */ 11284 11285 const extractPath = path => { 11286 let source = path; 11287 let m; 11288 11289 // "https://api.observablehq.com/@jashkenas/inputs.js?v=3" => strip off ".js" 11290 if ((m = /\.js(\?|$)/i.exec(source))) source = source.slice(0, m.index); 11291 11292 // "74f872c4fde62e35" => "d/..." 11293 if ((m = /^[0-9a-f]{16}$/i.test(source))) source = `d/${source}`; 11294 11295 // link of notebook 11296 if ((m = /^https:\/\/(api\.|beta\.|)observablehq\.com\//i.exec(source))) 11297 source = source.slice(m[0].length); 11298 return source; 11299 }; 11300 11301 function setupImportCell(cell) { 11302 const specifiers = []; 11303 11304 if (cell.body.specifiers) 11305 for (const specifier of cell.body.specifiers) { 11306 if (specifier.view) { 11307 specifiers.push({ 11308 name: "viewof " + specifier.imported.name, 11309 alias: "viewof " + specifier.local.name 11310 }); 11311 } else if (specifier.mutable) { 11312 specifiers.push({ 11313 name: "mutable " + specifier.imported.name, 11314 alias: "mutable " + specifier.local.name 11315 }); 11316 } 11317 specifiers.push({ 11318 name: specifier.imported.name, 11319 alias: specifier.local.name 11320 }); 11321 } 11322 // If injections is undefined, do not derive! 11323 const hasInjections = cell.body.injections !== undefined; 11324 const injections = []; 11325 if (hasInjections) 11326 for (const injection of cell.body.injections) { 11327 // This currently behaves like notebooks on observablehq.com 11328 // Commenting out the if & else if blocks result in behavior like Example 3 here: https://observablehq.com/d/7ccad009e4d89969 11329 if (injection.view) { 11330 injections.push({ 11331 name: "viewof " + injection.imported.name, 11332 alias: "viewof " + injection.local.name 11333 }); 11334 } else if (injection.mutable) { 11335 injections.push({ 11336 name: "mutable " + injection.imported.name, 11337 alias: "mutable " + injection.local.name 11338 }); 11339 } 11340 injections.push({ 11341 name: injection.imported.name, 11342 alias: injection.local.name 11343 }); 11344 } 11345 const importString = `import {${specifiers 11346 .map(specifier => `${specifier.name} as ${specifier.alias}`) 11347 .join(", ")}} ${ 11348 hasInjections 11349 ? `with {${injections 11350 .map(injection => `${injection.name} as ${injection.alias}`) 11351 .join(", ")}} ` 11352 : `` 11353 }from "${cell.body.source.value}"`; 11354 11355 return { specifiers, hasInjections, injections, importString }; 11356 } 11357 11358 function setupRegularCell(cell) { 11359 let name = null; 11360 if (cell.id && cell.id.name) name = cell.id.name; 11361 else if (cell.id && cell.id.id && cell.id.id.name) name = cell.id.id.name; 11362 let bodyText = cell.input.substring(cell.body.start, cell.body.end); 11363 let expressionMap = {}; 11364 let references = []; 11365 const cellReferences = Array.from(new Set((cell.references || []).map(ref => { 11366 if (ref.type === "ViewExpression") { 11367 if (expressionMap[ref.id.name] === undefined) { 11368 expressionMap[ref.id.name] = ref.id.name; 11369 references.push(ref.id.name); 11370 } 11371 return "viewof " + ref.id.name; 11372 } else if (ref.type === "MutableExpression") { 11373 if (expressionMap[ref.id.name] === undefined) { 11374 expressionMap[ref.id.name] = ref.id.name; 11375 references.push(ref.id.name); 11376 } 11377 return "mutable " + ref.id.name; 11378 } else { 11379 references.push(ref.name); 11380 return ref.name; 11381 } 11382 }))); 11383 const uniq = (lst) => { 11384 const result = []; 11385 const s = new Set(); 11386 for (const v of lst) { 11387 if (s.has(v)) continue; 11388 s.add(v); 11389 result.push(v); 11390 } 11391 return result; 11392 }; 11393 const patches = []; 11394 let latestPatch = { newStr: "", span: [cell.body.start, cell.body.start] }; 11395 full(cell.body, node => { 11396 if (node.type === "ViewExpression" || node.type === "MutableExpression") { 11397 // cover previous ground? 11398 if (node.start !== latestPatch.span[1]) { 11399 patches.push({ newStr: cell.input.substring(latestPatch.span[1], node.start)}); 11400 } 11401 const suffix = node.type === "MutableExpression" ? ".value" : ""; 11402 const newStr = `${expressionMap[node.id.name]}${suffix}`; 11403 const patch = { 11404 newStr, 11405 span: [node.start, node.end] 11406 }; 11407 latestPatch = patch; 11408 patches.push(patch); 11409 } 11410 }, walk); 11411 patches.push({newStr: cell.input.substring(latestPatch.span[1], cell.body.end), span: [latestPatch.span[1], cell.body.end]}); 11412 bodyText = patches.map(x => x.newStr).join(""); 11413 11414 return { 11415 cellName: name, 11416 references: uniq(references), 11417 bodyText, 11418 cellReferences: uniq(cellReferences) 11419 }; 11420 }function names(cell) { 11421 if (cell.body && cell.body.specifiers) 11422 return cell.body.specifiers.map( 11423 d => `${d.view ? "viewof " : d.mutable ? "mutable " : ""}${d.local.name}` 11424 ); 11425 11426 if (cell.id && cell.id.type && cell.id) { 11427 if (cell.id.type === "ViewExpression") return [`viewof ${cell.id.id.name}`]; 11428 if (cell.id.type === "MutableExpression") 11429 return [`mutable ${cell.id.id.name}`]; 11430 if (cell.id.name) return [cell.id.name]; 11431 } 11432 11433 return []; 11434 } 11435 11436 function references(cell) { 11437 if (cell.references) 11438 return cell.references.map(d => { 11439 if (d.name) return d.name; 11440 if (d.type === "ViewExpression") return `viewof ${d.id.name}`; 11441 if (d.type === "MutableExpression") return `mutable ${d.id.name}`; 11442 return null; 11443 }); 11444 11445 if (cell.body && cell.body.injections) 11446 return cell.body.injections.map( 11447 d => 11448 `${d.view ? "viewof " : d.mutable ? "mutable " : ""}${d.imported.name}` 11449 ); 11450 11451 return []; 11452 } 11453 11454 function getCellRefs(module) { 11455 const cells = []; 11456 for (const cell of module.cells) { 11457 const ns = names(cell); 11458 const refs = references(cell); 11459 if (!ns || !ns.length) continue; 11460 for (const name of ns) { 11461 cells.push([name, refs]); 11462 if (name.startsWith("viewof "))
11463 cells.push([name.substring("viewof ".length), [name]]); 11464 } 11465 } 11466 return new Map(cells); 11467 } 11468 11469 function treeShakeModule(module, targets) { 11470 const cellRefs = getCellRefs(module); 11471 11472 const embed = new Set(); 11473 const todo = targets.slice(); 11474 while (todo.length) { 11475 const d = todo.pop(); 11476 embed.add(d); 11477 // happens when 1) d is an stdlib cell, 2) d doesnt have a defintion, 11478 // or 3) d is in the window/global object. Let's be forgiving 11479 // and let it happen 11480 if (!cellRefs.has(d)) continue; 11481 const refs = cellRefs.get(d); 11482 for (const ref of refs) if (!embed.has(ref)) todo.push(ref); 11483 } 11484 return { 11485 cells: module.cells.filter( 11486 cell => names(cell).filter(name => embed.has(name)).length 11487 ) 11488 }; 11489 }function ESMImports(moduleObject, resolveImportPath) { 11490 const importMap = new Map(); 11491 let importSrc = ""; 11492 let j = 0; 11493 11494 for (const { body } of moduleObject.cells) { 11495 if (body.type !== "ImportDeclaration" || importMap.has(body.source.value)) 11496 continue; 11497 11498 const defineName = `define${++j}`; 11499 // TODO get cell specififiers here and pass in as 2nd param to resolveImportPath 11500 // need to use same logic as tree-shake name()s 11501 const specifiers = body.specifiers.map(d => { 11502 const prefix = d.view ? "viewof " : d.mutable ? "mutable " : ""; 11503 return `${prefix}${d.imported.name}`; 11504 }); 11505 const fromPath = resolveImportPath(body.source.value, specifiers); 11506 importMap.set(body.source.value, { defineName, fromPath }); 11507 importSrc += `import ${defineName} from "${fromPath}";\n`; 11508 } 11509 11510 if (importSrc.length) importSrc += "\n"; 11511 return { importSrc, importMap }; 11512 } 11513 11514 // by default, file attachments get resolved like: 11515 // [ ["a", "https://example.com/files/a"] ] 11516 // but sometimes, you'll want to write JS code when resolving 11517 // instead of being limiting by strings. The third param 11518 // enables that, allowing for resolving like: 11519 // [ ["a", new URL("./files/a", import.meta.url)] ] 11520 function ESMAttachments( 11521 moduleObject, 11522 resolveFileAttachments, 11523 UNSAFE_allowJavascriptFileAttachments = false 11524 ) { 11525 let mapValue; 11526 if (UNSAFE_allowJavascriptFileAttachments) { 11527 const attachmentMapEntries = []; 11528 for (const cell of moduleObject.cells) { 11529 if (cell.fileAttachments.size === 0) continue; 11530 for (const file of cell.fileAttachments.keys()) 11531 attachmentMapEntries.push([file, resolveFileAttachments(file)]); 11532 } 11533 if (attachmentMapEntries.length) 11534 mapValue = `[${attachmentMapEntries 11535 .map(([key, value]) => `[${JSON.stringify(key)}, ${value}]`) 11536 .join(",")}]`; 11537 } else { 11538 const attachmentMapEntries = []; 11539 // loop over cells with fileAttachments 11540 for (const cell of moduleObject.cells) { 11541 if (cell.fileAttachments.size === 0) continue; 11542 // add filenames and resolved URLs to array 11543 for (const file of cell.fileAttachments.keys()) 11544 attachmentMapEntries.push([file, resolveFileAttachments(file)]); 11545 } 11546 if (attachmentMapEntries.length) 11547 mapValue = JSON.stringify(attachmentMapEntries); 11548 } 11549 11550 if (!mapValue) return ""; 11551 return ` const fileAttachments = new Map(${mapValue}); 11552 main.builtin("FileAttachment", runtime.fileAttachments(name => fileAttachments.get(name)));`; 11553 } 11554 11555 function ESMVariables(moduleObject, importMap, params) { 11556 const { 11557 defineImportMarkdown, 11558 observeViewofValues, 11559 observeMutableValues 11560 } = params; 11561 11562 let childJ = 0; 11563 return moduleObject.cells 11564 .map(cell => { 11565 let src = ""; 11566 11567 if (cell.body.type === "ImportDeclaration") { 11568 const { 11569 specifiers, 11570 hasInjections, 11571 injections, 11572 importString 11573 } = setupImportCell(cell); 11574 11575 if (defineImportMarkdown) 11576 src += 11577 ` main.variable(observer()).define( 11578 null, 11579 ["md"], 11580 md => md\`~~~javascript 11581${importString} 11582~~~\` 11583 );` + "\n"; 11584 11585 // name imported notebook define functions 11586 const childName = `child${++childJ}`; 11587 src += ` const ${childName} = runtime.module(${ 11588 importMap.get(cell.body.source.value).defineName 11589 })${ 11590 hasInjections ? `.derive(${JSON.stringify(injections)}, main)` : "" 11591 }; 11592${specifiers 11593 .map( 11594 specifier =>
11595 ` main.import("${specifier.name}", "${specifier.alias}", ${childName});` 11596 ) 11597 .join("\n")}`; 11598 } else { 11599 const { 11600 cellName, 11601 references, 11602 bodyText, 11603 cellReferences 11604 } = setupRegularCell(cell); 11605 11606 const cellNameString = cellName ? `"${cellName}"` : ""; 11607 const referenceString = references.join(","); 11608 let code = ""; 11609 if (cell.body.type !== "BlockStatement") 11610 code = `{return( 11611${bodyText} 11612)}`; 11613 else code = "\n" + bodyText + "\n"; 11614 const cellReferencesString = cellReferences.length 11615 ? JSON.stringify(cellReferences) + ", " 11616 : ""; 11617 let cellFunction = ""; 11618 if (cell.generator && cell.async) 11619 cellFunction = `async function*(${referenceString})${code}`; 11620 else if (cell.async) 11621 cellFunction = `async function(${referenceString})${code}`; 11622 else if (cell.generator) 11623 cellFunction = `function*(${referenceString})${code}`; 11624 else cellFunction = `function(${referenceString})${code}`; 11625 11626 if (cell.id && cell.id.type === "ViewExpression") { 11627 const reference = `"viewof ${cellName}"`; 11628 src += ` main.variable(observer(${reference})).define(${reference}, ${cellReferencesString}${cellFunction}); 11629 main.variable(${ 11630 observeViewofValues ? `observer("${cellName}")` : `null` 11631 }).define("${cellName}", ["Generators", ${reference}], (G, _) => G.input(_));`; 11632 } else if (cell.id && cell.id.type === "MutableExpression") { 11633 const initialName = `"initial ${cellName}"`; 11634 const mutableName = `"mutable ${cellName}"`; 11635 src += ` main.define(${initialName}, ${cellReferencesString}${cellFunction}); 11636 main.variable(observer(${mutableName})).define(${mutableName}, ["Mutable", ${initialName}], (M, _) => new M(_)); 11637 main.variable(${ 11638 observeMutableValues ? `observer("${cellName}")` : `null` 11639 }).define("${cellName}", [${mutableName}], _ => _.generator);`; 11640 } else { 11641 src += ` main.variable(observer(${cellNameString})).define(${ 11642 cellName ? cellNameString + ", " : "" 11643 }${cellReferencesString}${cellFunction});`; 11644 } 11645 } 11646 return src; 11647 }) 11648 .join("\n"); 11649 } 11650 function createESModule(moduleObject, params = {}) { 11651 const { 11652 resolveImportPath, 11653 resolveFileAttachments, 11654 defineImportMarkdown, 11655 observeViewofValues, 11656 observeMutableValues, 11657 UNSAFE_allowJavascriptFileAttachments 11658 } = params; 11659 const { importSrc, importMap } = ESMImports(moduleObject, resolveImportPath); 11660 return `${importSrc}export default function define(runtime, observer) { 11661 const main = runtime.module(); 11662${ESMAttachments( 11663 moduleObject, 11664 resolveFileAttachments, 11665 UNSAFE_allowJavascriptFileAttachments 11666 )} 11667${ESMVariables(moduleObject, importMap, { 11668 defineImportMarkdown, 11669 observeViewofValues, 11670 observeMutableValues 11671 }) || ""} 11672 return main; 11673}`; 11674 } 11675 11676 function defaultResolveImportPath(path) { 11677 const source = extractPath(path); 11678 return `https://api.observablehq.com/${source}.js?v=3`; 11679 } 11680 11681 function defaultResolveFileAttachments(name) { 11682 return name; 11683 } 11684 class Compiler { 11685 constructor(params = {}) { 11686 const { 11687 resolveFileAttachments = defaultResolveFileAttachments, 11688 resolveImportPath = defaultResolveImportPath, 11689 defineImportMarkdown = true, 11690 observeViewofValues = true, 11691 observeMutableValues = true, 11692 UNSAFE_allowJavascriptFileAttachments = false 11693 } = params; 11694 this.resolveFileAttachments = resolveFileAttachments; 11695 this.resolveImportPath = resolveImportPath; 11696 this.defineImportMarkdown = defineImportMarkdown; 11697 this.observeViewofValues = observeViewofValues; 11698 this.observeMutableValues = observeMutableValues; 11699 this.UNSAFE_allowJavascriptFileAttachments = UNSAFE_allowJavascriptFileAttachments; 11700 } 11701 module(input, params = {}) { 11702 let m1 = typeof input === "string" ? parseModule(input) : input; 11703 11704 if (params.treeShake) m1 = treeShakeModule(m1, params.treeShake); 11705 11706 return createESModule(m1, { 11707 resolveImportPath: this.resolveImportPath, 11708 resolveFileAttachments: this.resolveFileAttachments, 11709 defineImportMarkdown: this.defineImportMarkdown, 11710 observeViewofValues: this.observeViewofValues, 11711 observeMutableValues: this.observeMutableValues, 11712 UNSAFE_allowJavascriptFileAttachments: this 11713 .UNSAFE_allowJavascriptFileAttachments 11714 }); 11715 } 11716 notebook(obj) { 11717 const cells = obj.nodes.map(({ value }) => { 11718 const cell = parseCell(value); 11719 cell.input = value; 11720 return cell; 11721 }); 11722 return createESModule( 11723 { cells }, 11724 { 11725 resolveImportPath: this.resolveImportPath, 11726 resolveFileAttachments: this.resolveFileAttachments, 11727 defineImportMarkdown: this.defineImportMarkdown, 11728 observeViewofValues: this.observeViewofValues, 11729 observeMutableValues: this.observeMutableValues 11730 } 11731 ); 11732 } 11733 }const AsyncFunction = Object.getPrototypeOf(async function() {}).constructor; 11734 const GeneratorFunction = Object.getPrototypeOf(function*() {}).constructor; 11735 const AsyncGeneratorFunction = Object.getPrototypeOf(async function*() {}) 11736 .constructor; 11737 11738 function createRegularCellDefinition(cell) { 11739 const { cellName, references, bodyText, cellReferences } = setupRegularCell( 11740 cell 11741 ); 11742 11743 let code; 11744 if (cell.body.type !== "BlockStatement") { 11745 if (cell.async) 11746 code = `return (async function(){ return (${bodyText});})()`; 11747 else code = `return (function(){ return (${bodyText});})()`; 11748 } else code = bodyText; 11749 11750 let f; 11751 if (cell.generator && cell.async) 11752 f = new AsyncGeneratorFunction(...references, code); 11753 else if (cell.async) f = new AsyncFunction(...references, code); 11754 else if (cell.generator) f = new GeneratorFunction(...references, code); 11755 else f = new Function(...references, code); 11756 return { 11757 cellName, 11758 cellFunction: f, 11759 cellReferences 11760 }; 11761 } 11762 11763 function defaultResolveImportPath$1(path) { 11764 const source = extractPath(path); 11765 return import(`https://api.observablehq.com/${source}.js?v=3`).then( 11766 m => m.default 11767 ); 11768 } 11769 11770 function defaultResolveFileAttachments$1(name) { 11771 return name; 11772 } 11773 11774 class Interpreter { 11775 constructor(params = {}) { 11776 const { 11777 module = null, 11778 observer = null, 11779 resolveImportPath = defaultResolveImportPath$1, 11780 resolveFileAttachments = defaultResolveFileAttachments$1, 11781 defineImportMarkdown = true, 11782 observeViewofValues = true, 11783 observeMutableValues = true 11784 } = params; 11785 11786 // can't be this.module bc of async module(). 11787 // so make defaultObserver follow same convention. 11788 this.defaultModule = module; 11789 this.defaultObserver = observer; 11790 11791 this.resolveImportPath = resolveImportPath; 11792 this.resolveFileAttachments = resolveFileAttachments; 11793 this.defineImportMarkdown = defineImportMarkdown; 11794 this.observeViewofValues = observeViewofValues; 11795 this.observeMutableValues = observeMutableValues; 11796 } 11797 11798 async module(input, module, observer) { 11799 module = module || this.defaultModule; 11800 observer = observer || this.defaultObserver; 11801 11802 if (!module) throw Error("No module provided."); 11803 if (!observer) throw Error("No observer provided."); 11804 11805 const parsedModule = parseModule(input); 11806 const cellPromises = []; 11807 for (const cell of parsedModule.cells) { 11808 cell.input = input; 11809 cellPromises.push(this.cell(cell, module, observer)); 11810 } 11811 return Promise.all(cellPromises); 11812 } 11813 11814 async cell(input, module, observer) { 11815 module = module || this.defaultModule; 11816 observer = observer || this.defaultObserver; 11817 11818 if (!module) throw Error("No module provided."); 11819 if (!observer) throw Error("No observer provided."); 11820 11821 let cell; 11822 if (typeof input === "string") { 11823 cell = parseCell(input); 11824 cell.input = input; 11825 } else { 11826 cell = input; 11827 } 11828 11829 if (cell.body.type === "ImportDeclaration") { 11830 const path = cell.body.source.value; 11831 const specs = cell.body.specifiers.map(d => { 11832 const prefix = d.view ? "viewof " : d.mutable ? "mutable " : ""; 11833 return `${prefix}${d.imported.name}`; 11834 }); 11835 const fromModule = await this.resolveImportPath(path, specs); 11836 let mdVariable, vars; 11837 11838 const { 11839 specifiers, 11840 hasInjections, 11841 injections, 11842 importString 11843 } = setupImportCell(cell); 11844 11845 const other = module._runtime.module(fromModule); 11846 11847 if (this.defineImportMarkdown) 11848 mdVariable = module.variable(observer()).define( 11849 null, 11850 ["md"], 11851 md => md`~~~javascript 11852 ${importString} 11853 ~~~` 11854 ); 11855 if (hasInjections) { 11856 const child = other.derive(injections, module); 11857 vars = specifiers.map(({ name, alias }) => 11858 module.import(name, alias, child) 11859 ); 11860 } else { 11861 vars = specifiers.map(({ name, alias }) => 11862 module.import(name, alias, other) 11863 ); 11864 } 11865 return mdVariable ? [mdVariable, ...vars] : vars; 11866 } else { 11867 const { 11868 cellName, 11869 cellFunction, 11870 cellReferences 11871 } = createRegularCellDefinition(cell); 11872 if (cell.id && cell.id.type === "ViewExpression") { 11873 const reference = `viewof ${cellName}`; 11874 return [ 11875 module 11876 .variable(observer(reference)) 11877 .define(reference, cellReferences, cellFunction.bind(this)), 11878 module 11879 .variable(this.observeViewofValues ? observer(cellName) : null) 11880 .define(cellName, ["Generators", reference], (G, _) => G.input(_)) 11881 ]; 11882 } else if (cell.id && cell.id.type === "MutableExpression") { 11883 const initialName = `initial ${cellName}`; 11884 const mutableName = `mutable ${cellName}`; 11885 return [ 11886 module 11887 .variable(null) 11888 .define(initialName, cellReferences, cellFunction), 11889 module 11890 .variable(observer(mutableName)) 11891 .define(mutableName, ["Mutable", initialName], (M, _) => new M(_)), 11892 module 11893 .variable(this.observeMutableValues ? observer(cellName) : null) 11894 .define(cellName, [mutableName], _ => _.generator) 11895 ]; 11896 } else { 11897 return [ 11898 module 11899 .variable(observer(cellName)) 11900 .define(cellName, cellReferences, cellFunction.bind(this)) 11901 ]; 11902 } 11903 } 11904 } 11905 }exports.Compiler=Compiler;exports.Interpreter=Interpreter;exports.parser=index;exports.treeShakeModule=treeShakeModule;Object.defineProperty(exports,'__esModule',{value:true});}))); 11906} (dist, dist.exports)); 11907 11908// This file was generated. Do not modify manually! 11909var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 50, 3, 123, 2, 54, 14, 32, 10, 3, 1, 11, 3, 46, 10, 8, 0, 46, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4,
11909193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 87, 9, 39, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 4706, 45, 3, 22, 543, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 357, 0, 62, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; 11910 11911// This file was generated. Do not modify manually! 11912var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 13, 10, 2, 14, 2, 6, 2, 1, 2, 10, 2, 14, 2, 6, 2, 1, 68, 310, 10, 21, 11, 7, 25, 5, 2, 41, 2, 8, 70, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 43, 17, 47, 20, 28, 22, 13, 52, 58, 1, 3, 0, 14, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 38, 6, 186, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 19, 72, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2637, 96, 16, 1070, 4050, 582, 8634, 568, 8, 30, 18, 78, 18, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8936, 3, 2, 6, 2, 1, 2, 290, 46, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 1845, 30, 482, 44, 11, 6, 17, 0, 322, 29, 19, 43, 1269, 6, 2, 3, 2, 1, 2, 14, 2, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42719, 33, 4152, 8, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; 11913 11914// This file was generated. Do not modify manually! 11915var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u0898-\u089f\u08ca-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3c\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u10
1191571-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1715\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u180f-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf-\u1ace\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; 11916 11917// This file was generated. Do not modify manually! 11918var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u0870-\u0887\u0889-\u088e\u08a0-\u08c9\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c5d\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cdd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u1711\u171f-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4c\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7ca\ua7d0\ua7d1\ua7d3\ua7d5-\ua7d9\ua7f2-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; 11919 11920// These are a run-length and offset encoded representation of the 11921 11922// Reserved word lists for various dialects of the language 11923 11924var reservedWords = { 11925 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile", 11926 5: "class enum extends super const export import", 11927 6: "enum", 11928 strict: "implements interface let package private protected public static yield", 11929 strictBind: "eval arguments" 11930}; 11931 11932// And the keywords 11933 11934var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"; 11935 11936var keywords$1 = { 11937 5: ecma5AndLessKeywords,
11938 "5module": ecma5AndLessKeywords + " export import", 11939 6: ecma5AndLessKeywords + " const class extends export import super" 11940}; 11941 11942var keywordRelationalOperator = /^in(stanceof)?$/; 11943 11944// ## Character categories 11945 11946var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); 11947var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); 11948 11949// This has a complexity linear to the value of the code. The 11950// assumption is that looking up astral identifier characters is 11951// rare. 11952function isInAstralSet(code, set) { 11953 var pos = 0x10000; 11954 for (var i = 0; i < set.length; i += 2) { 11955 pos += set[i]; 11956 if (pos > code) { return false } 11957 pos += set[i + 1]; 11958 if (pos >= code) { return true } 11959 }
vendor: 7,711 bytes, lines 11959-12178
11959 11960} 11961 11962// Test whether a given character code starts an identifier. 11963 11964function isIdentifierStart(code, astral) { 11965 if (code < 65) { return code === 36 } 11966 if (code < 91) { return true } 11967 if (code < 97) { return code === 95 } 11968 if (code < 123) { return true } 11969 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) } 11970 if (astral === false) { return false } 11971 return isInAstralSet(code, astralIdentifierStartCodes) 11972} 11973 11974// Test whether a given character is part of an identifier. 11975 11976function isIdentifierChar(code, astral) { 11977 if (code < 48) { return code === 36 } 11978 if (code < 58) { return true } 11979 if (code < 65) { return false } 11980 if (code < 91) { return true } 11981 if (code < 97) { return code === 95 } 11982 if (code < 123) { return true } 11983 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) } 11984 if (astral === false) { return false } 11985 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes) 11986} 11987 11988// ## Token types 11989 11990// The assignment of fine-grained, information-carrying type objects 11991// allows the tokenizer to store the information it has about a 11992// token in a way that is very cheap for the parser to look up. 11993 11994// All token type variables start with an underscore, to make them 11995// easy to recognize. 11996 11997// The `beforeExpr` property is used to disambiguate between regular 11998// expressions and divisions. It is set on all token types that can 11999// be followed by an expression (thus, a slash after them would be a 12000// regular expression). 12001// 12002// The `startsExpr` property is used to check if the token ends a 12003// `yield` expression. It is set on all token types that either can 12004// directly start an expression (like a quotation mark) or can 12005// continue an expression (like the body of a string). 12006// 12007// `isLoop` marks a keyword as starting a loop, which is important 12008// to know when parsing a label, in order to allow or disallow 12009// continue jumps to that label. 12010 12011var TokenType = function TokenType(label, conf) { 12012 if ( conf === void 0 ) conf = {}; 12013 12014 this.label = label; 12015 this.keyword = conf.keyword; 12016 this.beforeExpr = !!conf.beforeExpr; 12017 this.startsExpr = !!conf.startsExpr; 12018 this.isLoop = !!conf.isLoop; 12019 this.isAssign = !!conf.isAssign; 12020 this.prefix = !!conf.prefix; 12021 this.postfix = !!conf.postfix; 12022 this.binop = conf.binop || null; 12023 this.updateContext = null; 12024}; 12025 12026function binop(name, prec) { 12027 return new TokenType(name, {beforeExpr: true, binop: prec}) 12028} 12029var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true}; 12030 12031// Map keyword names to token types. 12032 12033var keywords = {}; 12034 12035// Succinct definitions of keyword token types 12036function kw(name, options) { 12037 if ( options === void 0 ) options = {}; 12038 12039 options.keyword = name; 12040 return keywords[name] = new TokenType(name, options) 12041} 12042 12043var types$1 = { 12044 num: new TokenType("num", startsExpr), 12045 regexp: new TokenType("regexp", startsExpr), 12046 string: new TokenType("string", startsExpr), 12047 name: new TokenType("name", startsExpr), 12048 privateId: new TokenType("privateId", startsExpr), 12049 eof: new TokenType("eof"), 12050 12051 // Punctuation token types. 12052 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}), 12053 bracketR: new TokenType("]"), 12054 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}), 12055 braceR: new TokenType("}"), 12056 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}), 12057 parenR: new TokenType(")"), 12058 comma: new TokenType(",", beforeExpr), 12059 semi: new TokenType(";", beforeExpr), 12060 colon: new TokenType(":", beforeExpr), 12061 dot: new TokenType("."), 12062 question: new TokenType("?", beforeExpr), 12063 questionDot: new TokenType("?."), 12064 arrow: new TokenType("=>", beforeExpr), 12065 template: new TokenType("template"), 12066 invalidTemplate: new TokenType("invalidTemplate"), 12067 ellipsis: new TokenType("...", beforeExpr), 12068 backQuote: new TokenType("`", startsExpr), 12069 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}), 12070 12071 // Operators. These carry several kinds of properties to help the 12072 // parser use them properly (the presence of these properties is 12073 // what categorizes them as operators). 12074 // 12075 // `binop`, when present, specifies that this operator is a binary 12076 // operator, and will refer to its precedence. 12077 // 12078 // `prefix` and `postfix` mark the operator as a prefix or postfix 12079 // unary operator. 12080 // 12081 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as 12082 // binary operators with a very low precedence, that should result 12083 // in AssignmentExpression nodes. 12084 12085 eq: new TokenType("=", {beforeExpr: true, isAssign: true}), 12086 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}), 12087 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}), 12088 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}), 12089 logicalOR: binop("||", 1), 12090 logicalAND: binop("&&", 2), 12091 bitwiseOR: binop("|", 3), 12092 bitwiseXOR: binop("^", 4), 12093 bitwiseAND: binop("&", 5), 12094 equality: binop("==/!=/===/!==", 6), 12095 relational: binop("</>/<=/>=", 7), 12096 bitShift: binop("<</>>/>>>", 8), 12097 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}), 12098 modulo: binop("%", 10), 12099 star: binop("*", 10), 12100 slash: binop("/", 10), 12101 starstar: new TokenType("**", {beforeExpr: true}), 12102 coalesce: binop("??", 1), 12103 12104 // Keyword token types. 12105 _break: kw("break"), 12106 _case: kw("case", beforeExpr), 12107 _catch: kw("catch"), 12108 _continue: kw("continue"), 12109 _debugger: kw("debugger"), 12110 _default: kw("default", beforeExpr), 12111 _do: kw("do", {isLoop: true, beforeExpr: true}), 12112 _else: kw("else", beforeExpr), 12113 _finally: kw("finally"), 12114 _for: kw("for", {isLoop: true}), 12115 _function: kw("function", startsExpr), 12116 _if: kw("if"), 12117 _return: kw("return", beforeExpr), 12118 _switch: kw("switch"), 12119 _throw: kw("throw", beforeExpr), 12120 _try: kw("try"), 12121 _var: kw("var"), 12122 _const: kw("const"), 12123 _while: kw("while", {isLoop: true}), 12124 _with: kw("with"), 12125 _new: kw("new", {beforeExpr: true, startsExpr: true}), 12126 _this: kw("this", startsExpr), 12127 _super: kw("super", startsExpr), 12128 _class: kw("class", startsExpr), 12129 _extends: kw("extends", beforeExpr), 12130 _export: kw("export"), 12131 _import: kw("import", startsExpr), 12132 _null: kw("null", startsExpr), 12133 _true: kw("true", startsExpr), 12134 _false: kw("false", startsExpr), 12135 _in: kw("in", {beforeExpr: true, binop: 7}), 12136 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}), 12137 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}), 12138 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}), 12139 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true}) 12140}; 12141 12142// Matches a whole line break (where CRLF is considered a single 12143// line break). Used to count lines. 12144 12145var lineBreak = /\r\n?|\n|\u2028|\u2029/; 12146var lineBreakG = new RegExp(lineBreak.source, "g"); 12147 12148function isNewLine(code) { 12149 return code === 10 || code === 13 || code === 0x2028 || code === 0x2029 12150} 12151 12152function nextLineBreak(code, from, end) { 12153 if ( end === void 0 ) end = code.length; 12154 12155 for (var i = from; i < end; i++) { 12156 var next = code.charCodeAt(i); 12157 if (isNewLine(next)) 12158 { return i < end - 1 && next === 13 && code.charCodeAt(i + 1) === 10 ? i + 2 : i + 1 } 12159 } 12160 return -1 12161} 12162 12163var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/; 12164 12165var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g; 12166 12167var ref = Object.prototype; 12168var hasOwnProperty = ref.hasOwnProperty; 12169var toString = ref.toString; 12170 12171var hasOwn = Object.hasOwn || (function (obj, propName) { return ( 12172 hasOwnProperty.call(obj, propName) 12173); }); 12174 12175var isArray = Array.isArray || (function (obj) { return ( 12176 toString.call(obj) === "[object Array]" 12177); }); 12178
vendor: 14,099 bytes, lines 12179-12523
12179function wordsRegexp(words) { 12180 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$") 12181} 12182 12183function codePointToString(code) { 12184 // UTF-16 Decoding 12185 if (code <= 0xFFFF) { return String.fromCharCode(code) } 12186 code -= 0x10000; 12187 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00) 12188} 12189 12190var loneSurrogate = /(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/; 12191 12192// These are used when `options.locations` is on, for the 12193// `startLoc` and `endLoc` properties. 12194 12195var Position = function Position(line, col) { 12196 this.line = line; 12197 this.column = col; 12198}; 12199 12200Position.prototype.offset = function offset (n) { 12201 return new Position(this.line, this.column + n) 12202}; 12203 12204var SourceLocation = function SourceLocation(p, start, end) { 12205 this.start = start; 12206 this.end = end; 12207 if (p.sourceFile !== null) { this.source = p.sourceFile; } 12208}; 12209 12210// The `getLineInfo` function is mostly useful when the 12211// `locations` option is off (for performance reasons) and you 12212// want to find the line/column position for a given character 12213// offset. `input` should be the code string that the offset refers 12214// into. 12215 12216function getLineInfo(input, offset) { 12217 for (var line = 1, cur = 0;;) { 12218 var nextBreak = nextLineBreak(input, cur, offset); 12219 if (nextBreak < 0) { return new Position(line, offset - cur) } 12220 ++line; 12221 cur = nextBreak; 12222 } 12223} 12224 12225// A second argument must be given to configure the parser process. 12226// These options are recognized (only `ecmaVersion` is required): 12227 12228var defaultOptions = { 12229 // `ecmaVersion` indicates the ECMAScript version to parse. Must be 12230 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10 12231 // (2019), 11 (2020), 12 (2021), 13 (2022), 14 (2023), or `"latest"` 12232 // (the latest version the library supports). This influences 12233 // support for strict mode, the set of reserved words, and support 12234 // for new syntax features. 12235 ecmaVersion: null, 12236 // `sourceType` indicates the mode the code should be parsed in. 12237 // Can be either `"script"` or `"module"`. This influences global 12238 // strict mode and parsing of `import` and `export` declarations. 12239 sourceType: "script", 12240 // `onInsertedSemicolon` can be a callback that will be called 12241 // when a semicolon is automatically inserted. It will be passed 12242 // the position of the comma as an offset, and if `locations` is 12243 // enabled, it is given the location as a `{line, column}` object 12244 // as second argument. 12245 onInsertedSemicolon: null, 12246 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for 12247 // trailing commas. 12248 onTrailingComma: null, 12249 // By default, reserved words are only enforced if ecmaVersion >= 5. 12250 // Set `allowReserved` to a boolean value to explicitly turn this on 12251 // an off. When this option has the value "never", reserved words 12252 // and keywords can also not be used as property names. 12253 allowReserved: null, 12254 // When enabled, a return at the top level is not considered an 12255 // error. 12256 allowReturnOutsideFunction: false, 12257 // When enabled, import/export statements are not constrained to 12258 // appearing at the top of the program, and an import.meta expression 12259 // in a script isn't considered an error. 12260 allowImportExportEverywhere: false, 12261 // By default, await identifiers are allowed to appear at the top-level scope only if ecmaVersion >= 2022. 12262 // When enabled, await identifiers are allowed to appear at the top-level scope, 12263 // but they are still not allowed in non-async functions. 12264 allowAwaitOutsideFunction: null, 12265 // When enabled, super identifiers are not constrained to 12266 // appearing in methods and do not raise an error when they appear elsewhere. 12267 allowSuperOutsideMethod: null, 12268 // When enabled, hashbang directive in the beginning of file is 12269 // allowed and treated as a line comment. Enabled by default when 12270 // `ecmaVersion` >= 2023. 12271 allowHashBang: false, 12272 // When `locations` is on, `loc` properties holding objects with 12273 // `start` and `end` properties in `{line, column}` form (with 12274 // line being 1-based and column 0-based) will be attached to the 12275 // nodes. 12276 locations: false, 12277 // A function can be passed as `onToken` option, which will 12278 // cause Acorn to call that function with object in the same 12279 // format as tokens returned from `tokenizer().getToken()`. Note 12280 // that you are not allowed to call the parser from the 12281 // callbackâthat will corrupt its internal state. 12282 onToken: null, 12283 // A function can be passed as `onComment` option, which will 12284 // cause Acorn to call that function with `(block, text, start, 12285 // end)` parameters whenever a comment is skipped. `block` is a 12286 // boolean indicating whether this is a block (`/* */`) comment, 12287 // `text` is the content of the comment, and `start` and `end` are 12288 // character offsets that denote the start and end of the comment. 12289 // When the `locations` option is on, two more parameters are 12290 // passed, the full `{line, column}` locations of the start and 12291 // end of the comments. Note that you are not allowed to call the 12292 // parser from the callbackâthat will corrupt its internal state. 12293 onComment: null, 12294 // Nodes have their start and end characters offsets recorded in 12295 // `start` and `end` properties (directly on the node, rather than 12296 // the `loc` object, which holds line/column data. To also add a 12297 // [semi-standardized][range] `range` property holding a `[start, 12298 // end]` array with the same numbers, set the `ranges` option to 12299 // `true`. 12300 // 12301 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 12302 ranges: false, 12303 // It is possible to parse multiple files into a single AST by 12304 // passing the tree produced by parsing the first file as 12305 // `program` option in subsequent parses. This will add the 12306 // toplevel forms of the parsed file to the `Program` (top) node 12307 // of an existing parse tree. 12308 program: null, 12309 // When `locations` is on, you can pass this to record the source 12310 // file in every node's `loc` object. 12311 sourceFile: null, 12312 // This value, if given, is stored in every node, whether 12313 // `locations` is on or off. 12314 directSourceFile: null, 12315 // When enabled, parenthesized expressions are represented by 12316 // (non-standard) ParenthesizedExpression nodes 12317 preserveParens: false 12318}; 12319 12320// Interpret and default an options object 12321 12322var warnedAboutEcmaVersion = false; 12323 12324function getOptions(opts) { 12325 var options = {}; 12326 12327 for (var opt in defaultOptions) 12328 { options[opt] = opts && hasOwn(opts, opt) ? opts[opt] : defaultOptions[opt]; } 12329 12330 if (options.ecmaVersion === "latest") { 12331 options.ecmaVersion = 1e8; 12332 } else if (options.ecmaVersion == null) { 12333 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) { 12334 warnedAboutEcmaVersion = true; 12335 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future."); 12336 } 12337 options.ecmaVersion = 11; 12338 } else if (options.ecmaVersion >= 2015) { 12339 options.ecmaVersion -= 2009; 12340 } 12341 12342 if (options.allowReserved == null) 12343 { options.allowReserved = options.ecmaVersion < 5; } 12344 12345 if (opts.allowHashBang == null) 12346 { options.allowHashBang = options.ecmaVersion >= 14; } 12347 12348 if (isArray(options.onToken)) { 12349 var tokens = options.onToken; 12350 options.onToken = function (token) { return tokens.push(token); }; 12351 } 12352 if (isArray(options.onComment)) 12353 { options.onComment = pushComment(options, options.onComment); } 12354 12355 return options 12356} 12357 12358function pushComment(options, array) { 12359 return function(block, text, start, end, startLoc, endLoc) { 12360 var comment = { 12361 type: block ? "Block" : "Line", 12362 value: text, 12363 start: start, 12364 end: end 12365 }; 12366 if (options.locations) 12367 { comment.loc = new SourceLocation(this, startLoc, endLoc); } 12368 if (options.ranges) 12369 { comment.range = [start, end]; } 12370 array.push(comment); 12371 } 12372} 12373 12374// Each scope gets a bitset that may contain these flags 12375var 12376 SCOPE_TOP = 1, 12377 SCOPE_FUNCTION$1 = 2, 12378 SCOPE_ASYNC$1 = 4, 12379 SCOPE_GENERATOR$1 = 8, 12380 SCOPE_ARROW = 16, 12381 SCOPE_SIMPLE_CATCH = 32, 12382 SCOPE_SUPER = 64, 12383 SCOPE_DIRECT_SUPER = 128, 12384 SCOPE_CLASS_STATIC_BLOCK = 256, 12385 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION$1 | SCOPE_CLASS_STATIC_BLOCK; 12386 12387function functionFlags(async, generator) { 12388 return SCOPE_FUNCTION$1 | (async ? SCOPE_ASYNC$1 : 0) | (generator ? SCOPE_GENERATOR$1 : 0) 12389} 12390 12391// Used in checkLVal* and declareName to determine the type of a binding 12392var 12393 BIND_NONE = 0, // Not a binding 12394 BIND_VAR = 1, // Var-style binding 12395 BIND_LEXICAL = 2, // Let- or const-style binding 12396 BIND_FUNCTION = 3, // Function declaration 12397 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding 12398 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function 12399 12400var Parser = function Parser(options, input, startPos) { 12401 this.options = options = getOptions(options); 12402 this.sourceFile = options.sourceFile; 12403 this.keywords = wordsRegexp(keywords$1[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]); 12404 var reserved = ""; 12405 if (options.allowReserved !== true) { 12406 reserved = reservedWords[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3]; 12407 if (options.sourceType === "module") { reserved += " await"; } 12408 } 12409 this.reservedWords = wordsRegexp(reserved); 12410 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords.strict; 12411 this.reservedWordsStrict = wordsRegexp(reservedStrict); 12412 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords.strictBind); 12413 this.input = String(input); 12414 12415 // Used to signal to callers of `readWord1` whether the word 12416 // contained any escape sequences. This is needed because words with 12417 // escape sequences must not be interpreted as keywords. 12418 this.containsEsc = false; 12419 12420 // Set up token state 12421 12422 // The current position of the tokenizer in the input. 12423 if (startPos) { 12424 this.pos = startPos; 12425 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1; 12426 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length; 12427 } else { 12428 this.pos = this.lineStart = 0; 12429 this.curLine = 1; 12430 } 12431 12432 // Properties of the current token: 12433 // Its type 12434 this.type = types$1.eof; 12435 // For tokens that include more information than their type, the value 12436 this.value = null; 12437 // Its start and end offset 12438 this.start = this.end = this.pos; 12439 // And, if locations are used, the {line, column} object 12440 // corresponding to those offsets 12441 this.startLoc = this.endLoc = this.curPosition(); 12442 12443 // Position information for the previous token 12444 this.lastTokEndLoc = this.lastTokStartLoc = null; 12445 this.lastTokStart = this.lastTokEnd = this.pos; 12446 12447 // The context stack is used to superficially track syntactic 12448 // context to predict whether a regular expression is allowed in a 12449 // given position. 12450 this.context = this.initialContext(); 12451 this.exprAllowed = true; 12452 12453 // Figure out if it's a module code. 12454 this.inModule = options.sourceType === "module"; 12455 this.strict = this.inModule || this.strictDirective(this.pos); 12456 12457 // Used to signify the start of a potential arrow function 12458 this.potentialArrowAt = -1; 12459 this.potentialArrowInForAwait = false; 12460 12461 // Positions to delayed-check that yield/await does not exist in default parameters. 12462 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0; 12463 // Labels in scope. 12464 this.labels = []; 12465 // Thus-far undefined exports. 12466 this.undefinedExports = Object.create(null); 12467 12468 // If enabled, skip leading hashbang line. 12469 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!") 12470 { this.skipLineComment(2); } 12471 12472 // Scope tracking for duplicate variable names (see scope.js) 12473 this.scopeStack = []; 12474 this.enterScope(SCOPE_TOP); 12475 12476 // For RegExp validation 12477 this.regexpState = null; 12478 12479 // The stack of private names. 12480 // Each element has two properties: 'declared' and 'used'. 12481 // When it exited from the outermost class definition, all used private names must be declared. 12482 this.privateNameStack = []; 12483}; 12484 12485var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },canAwait: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },allowNewDotTarget: { configurable: true },inClassStaticBlock: { configurable: true } }; 12486 12487Parser.prototype.parse = function parse () { 12488 var node = this.options.program || this.startNode(); 12489 this.nextToken(); 12490 return this.parseTopLevel(node) 12491}; 12492 12493prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION$1) > 0 }; 12494 12495prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR$1) > 0 && !this.currentVarScope().inClassFieldInit }; 12496 12497prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC$1) > 0 && !this.currentVarScope().inClassFieldInit }; 12498 12499prototypeAccessors.canAwait.get = function () { 12500 for (var i = this.scopeStack.length - 1; i >= 0; i--) { 12501 var scope = this.scopeStack[i]; 12502 if (scope.inClassFieldInit || scope.flags & SCOPE_CLASS_STATIC_BLOCK) { return false } 12503 if (scope.flags & SCOPE_FUNCTION$1) { return (scope.flags & SCOPE_ASYNC$1) > 0 } 12504 } 12505 return (this.inModule && this.options.ecmaVersion >= 13) || this.options.allowAwaitOutsideFunction 12506}; 12507 12508prototypeAccessors.allowSuper.get = function () { 12509 var ref = this.currentThisScope(); 12510 var flags = ref.flags; 12511 var inClassFieldInit = ref.inClassFieldInit; 12512 return (flags & SCOPE_SUPER) > 0 || inClassFieldInit || this.options.allowSuperOutsideMethod 12513}; 12514 12515prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 }; 12516 12517prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) }; 12518 12519prototypeAccessors.allowNewDotTarget.get = function () { 12520 var ref = this.currentThisScope(); 12521 var flags = ref.flags; 12522 var inClassFieldInit = ref.inClassFieldInit; 12523 return (flags & (SCOPE_FUNCTION$1
vendor: 7,441 bytes, lines 12523-12745
12523 | SCOPE_CLASS_STATIC_BLOCK)) > 0 || inClassFieldInit 12524}; 12525 12526prototypeAccessors.inClassStaticBlock.get = function () { 12527 return (this.currentVarScope().flags & SCOPE_CLASS_STATIC_BLOCK) > 0 12528}; 12529 12530Parser.extend = function extend () { 12531 var plugins = [], len = arguments.length; 12532 while ( len-- ) plugins[ len ] = arguments[ len ]; 12533 12534 var cls = this; 12535 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); } 12536 return cls 12537}; 12538 12539Parser.parse = function parse (input, options) { 12540 return new this(options, input).parse() 12541}; 12542 12543Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) { 12544 var parser = new this(options, input, pos); 12545 parser.nextToken(); 12546 return parser.parseExpression() 12547}; 12548 12549Parser.tokenizer = function tokenizer (input, options) { 12550 return new this(options, input) 12551}; 12552 12553Object.defineProperties( Parser.prototype, prototypeAccessors ); 12554 12555var pp$9 = Parser.prototype; 12556 12557// ## Parser utilities 12558 12559var literal = /^(?:'((?:\\.|[^'\\])*?)'|"((?:\\.|[^"\\])*?)")/; 12560pp$9.strictDirective = function(start) { 12561 if (this.options.ecmaVersion < 5) { return false } 12562 for (;;) { 12563 // Try to find string literal. 12564 skipWhiteSpace.lastIndex = start; 12565 start += skipWhiteSpace.exec(this.input)[0].length; 12566 var match = literal.exec(this.input.slice(start)); 12567 if (!match) { return false } 12568 if ((match[1] || match[2]) === "use strict") { 12569 skipWhiteSpace.lastIndex = start + match[0].length; 12570 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length; 12571 var next = this.input.charAt(end); 12572 return next === ";" || next === "}" || 12573 (lineBreak.test(spaceAfter[0]) && 12574 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "=")) 12575 } 12576 start += match[0].length; 12577 12578 // Skip semicolon, if any. 12579 skipWhiteSpace.lastIndex = start; 12580 start += skipWhiteSpace.exec(this.input)[0].length; 12581 if (this.input[start] === ";") 12582 { start++; } 12583 } 12584}; 12585 12586// Predicate that tests whether the next token is of the given 12587// type, and if yes, consumes it as a side effect. 12588 12589pp$9.eat = function(type) { 12590 if (this.type === type) { 12591 this.next(); 12592 return true 12593 } else { 12594 return false 12595 } 12596}; 12597 12598// Tests whether parsed token is a contextual keyword. 12599 12600pp$9.isContextual = function(name) { 12601 return this.type === types$1.name && this.value === name && !this.containsEsc 12602}; 12603 12604// Consumes contextual keyword if possible. 12605 12606pp$9.eatContextual = function(name) { 12607 if (!this.isContextual(name)) { return false } 12608 this.next(); 12609 return true 12610}; 12611 12612// Asserts that following token is given contextual keyword. 12613 12614pp$9.expectContextual = function(name) { 12615 if (!this.eatContextual(name)) { this.unexpected(); } 12616}; 12617 12618// Test whether a semicolon can be inserted at the current position. 12619 12620pp$9.canInsertSemicolon = function() { 12621 return this.type === types$1.eof || 12622 this.type === types$1.braceR || 12623 lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) 12624}; 12625 12626pp$9.insertSemicolon = function() { 12627 if (this.canInsertSemicolon()) { 12628 if (this.options.onInsertedSemicolon) 12629 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); } 12630 return true 12631 } 12632}; 12633 12634// Consume a semicolon, or, failing that, see if we are allowed to 12635// pretend that there is a semicolon at this position. 12636 12637pp$9.semicolon = function() { 12638 if (!this.eat(types$1.semi) && !this.insertSemicolon()) { this.unexpected(); } 12639}; 12640 12641pp$9.afterTrailingComma = function(tokType, notNext) { 12642 if (this.type === tokType) { 12643 if (this.options.onTrailingComma) 12644 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); } 12645 if (!notNext) 12646 { this.next(); } 12647 return true 12648 } 12649}; 12650 12651// Expect a token of a given type. If found, consume it, otherwise, 12652// raise an unexpected token error. 12653 12654pp$9.expect = function(type) { 12655 this.eat(type) || this.unexpected(); 12656}; 12657 12658// Raise an unexpected token error. 12659 12660pp$9.unexpected = function(pos) { 12661 this.raise(pos != null ? pos : this.start, "Unexpected token"); 12662}; 12663 12664var DestructuringErrors = function DestructuringErrors() { 12665 this.shorthandAssign = 12666 this.trailingComma = 12667 this.parenthesizedAssign = 12668 this.parenthesizedBind = 12669 this.doubleProto = 12670 -1; 12671}; 12672 12673pp$9.checkPatternErrors = function(refDestructuringErrors, isAssign) { 12674 if (!refDestructuringErrors) { return } 12675 if (refDestructuringErrors.trailingComma > -1) 12676 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); } 12677 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind; 12678 if (parens > -1) { this.raiseRecoverable(parens, isAssign ? "Assigning to rvalue" : "Parenthesized pattern"); } 12679}; 12680 12681pp$9.checkExpressionErrors = function(refDestructuringErrors, andThrow) { 12682 if (!refDestructuringErrors) { return false } 12683 var shorthandAssign = refDestructuringErrors.shorthandAssign; 12684 var doubleProto = refDestructuringErrors.doubleProto; 12685 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 } 12686 if (shorthandAssign >= 0) 12687 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); } 12688 if (doubleProto >= 0) 12689 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); } 12690}; 12691 12692pp$9.checkYieldAwaitInDefaultParams = function() { 12693 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos)) 12694 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); } 12695 if (this.awaitPos) 12696 { this.raise(this.awaitPos, "Await expression cannot be a default value"); } 12697}; 12698 12699pp$9.isSimpleAssignTarget = function(expr) { 12700 if (expr.type === "ParenthesizedExpression") 12701 { return this.isSimpleAssignTarget(expr.expression) } 12702 return expr.type === "Identifier" || expr.type === "MemberExpression" 12703}; 12704 12705var pp$8 = Parser.prototype; 12706 12707// ### Statement parsing 12708 12709// Parse a program. Initializes the parser, reads any number of 12710// statements, and wraps them in a Program node. Optionally takes a 12711// `program` argument. If present, the statements will be appended 12712// to its body instead of creating a new node. 12713 12714pp$8.parseTopLevel = function(node) { 12715 var exports = Object.create(null); 12716 if (!node.body) { node.body = []; } 12717 while (this.type !== types$1.eof) { 12718 var stmt = this.parseStatement(null, true, exports); 12719 node.body.push(stmt); 12720 } 12721 if (this.inModule) 12722 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1) 12723 { 12724 var name = list[i]; 12725 12726 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined")); 12727 } } 12728 this.adaptDirectivePrologue(node.body); 12729 this.next(); 12730 node.sourceType = this.options.sourceType; 12731 return this.finishNode(node, "Program") 12732}; 12733 12734var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; 12735 12736pp$8.isLet = function(context) { 12737 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false } 12738 skipWhiteSpace.lastIndex = this.pos; 12739 var skip = skipWhiteSpace.exec(this.input); 12740 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); 12741 // For ambiguous cases, determine if a LexicalDeclaration (or only a 12742 // Statement) is allowed here. If context is not empty then only a Statement 12743 // is allowed. However, `let [` is an explicit negative lookahead for 12744 // ExpressionStatement, so special-case it first. 12745 if (nextCh === 91 || nextCh === 92
12745 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } // '[', '/', astral 12746 if (context) { return false } 12747 12748 if (nextCh === 123) { return true } // '{'
vendor: 11,465 bytes, lines 12748-13038
12748 12749 if (isIdentifierStart(nextCh, true)) { 12750 var pos = next + 1; 12751 while (isIdentifierChar(nextCh = this.input.charCodeAt(pos), true)) { ++pos; } 12752 if (nextCh === 92 || nextCh > 0xd7ff && nextCh < 0xdc00) { return true } 12753 var ident = this.input.slice(next, pos); 12754 if (!keywordRelationalOperator.test(ident)) { return true } 12755 } 12756 return false 12757}; 12758 12759// check 'async [no LineTerminator here] function' 12760// - 'async /*foo*/ function' is OK. 12761// - 'async /*\n*/ function' is invalid. 12762pp$8.isAsyncFunction = function() { 12763 if (this.options.ecmaVersion < 8 || !this.isContextual("async")) 12764 { return false } 12765 12766 skipWhiteSpace.lastIndex = this.pos; 12767 var skip = skipWhiteSpace.exec(this.input); 12768 var next = this.pos + skip[0].length, after; 12769 return !lineBreak.test(this.input.slice(this.pos, next)) && 12770 this.input.slice(next, next + 8) === "function" && 12771 (next + 8 === this.input.length || 12772 !(isIdentifierChar(after = this.input.charCodeAt(next + 8)) || after > 0xd7ff && after < 0xdc00)) 12773}; 12774 12775// Parse a single statement. 12776// 12777// If expecting a statement and finding a slash operator, parse a 12778// regular expression literal. This is to handle cases like 12779// `if (foo) /blah/.exec(foo)`, where looking at the previous token 12780// does not help. 12781 12782pp$8.parseStatement = function(context, topLevel, exports) { 12783 var starttype = this.type, node = this.startNode(), kind; 12784 12785 if (this.isLet(context)) { 12786 starttype = types$1._var; 12787 kind = "let"; 12788 } 12789 12790 // Most types of statements are recognized by the keyword they 12791 // start with. Many are trivial to parse, some require a bit of 12792 // complexity. 12793 12794 switch (starttype) { 12795 case types$1._break: case types$1._continue: return this.parseBreakContinueStatement(node, starttype.keyword) 12796 case types$1._debugger: return this.parseDebuggerStatement(node) 12797 case types$1._do: return this.parseDoStatement(node) 12798 case types$1._for: return this.parseForStatement(node) 12799 case types$1._function: 12800 // Function as sole body of either an if statement or a labeled statement 12801 // works, but not when it is part of a labeled statement that is the sole 12802 // body of an if statement. 12803 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); } 12804 return this.parseFunctionStatement(node, false, !context) 12805 case types$1._class: 12806 if (context) { this.unexpected(); } 12807 return this.parseClass(node, true) 12808 case types$1._if: return this.parseIfStatement(node) 12809 case types$1._return: return this.parseReturnStatement(node) 12810 case types$1._switch: return this.parseSwitchStatement(node) 12811 case types$1._throw: return this.parseThrowStatement(node) 12812 case types$1._try: return this.parseTryStatement(node) 12813 case types$1._const: case types$1._var: 12814 kind = kind || this.value; 12815 if (context && kind !== "var") { this.unexpected(); } 12816 return this.parseVarStatement(node, kind) 12817 case types$1._while: return this.parseWhileStatement(node) 12818 case types$1._with: return this.parseWithStatement(node) 12819 case types$1.braceL: return this.parseBlock(true, node) 12820 case types$1.semi: return this.parseEmptyStatement(node) 12821 case types$1._export: 12822 case types$1._import: 12823 if (this.options.ecmaVersion > 10 && starttype === types$1._import) { 12824 skipWhiteSpace.lastIndex = this.pos; 12825 var skip = skipWhiteSpace.exec(this.input); 12826 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next); 12827 if (nextCh === 40 || nextCh === 46) // '(' or '.' 12828 { return this.parseExpressionStatement(node, this.parseExpression()) } 12829 } 12830 12831 if (!this.options.allowImportExportEverywhere) { 12832 if (!topLevel) 12833 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); } 12834 if (!this.inModule) 12835 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); } 12836 } 12837 return starttype === types$1._import ? this.parseImport(node) : this.parseExport(node, exports) 12838 12839 // If the statement does not start with a statement keyword or a 12840 // brace, it's an ExpressionStatement or LabeledStatement. We 12841 // simply start parsing an expression, and afterwards, if the 12842 // next token is a colon and the expression was a simple 12843 // Identifier node, we switch to interpreting it as a label. 12844 default: 12845 if (this.isAsyncFunction()) { 12846 if (context) { this.unexpected(); } 12847 this.next(); 12848 return this.parseFunctionStatement(node, true, !context) 12849 } 12850 12851 var maybeName = this.value, expr = this.parseExpression(); 12852 if (starttype === types$1.name && expr.type === "Identifier" && this.eat(types$1.colon)) 12853 { return this.parseLabeledStatement(node, maybeName, expr, context) } 12854 else { return this.parseExpressionStatement(node, expr) } 12855 } 12856}; 12857 12858pp$8.parseBreakContinueStatement = function(node, keyword) { 12859 var isBreak = keyword === "break"; 12860 this.next(); 12861 if (this.eat(types$1.semi) || this.insertSemicolon()) { node.label = null; } 12862 else if (this.type !== types$1.name) { this.unexpected(); } 12863 else { 12864 node.label = this.parseIdent(); 12865 this.semicolon(); 12866 } 12867 12868 // Verify that there is an actual destination to break or 12869 // continue to. 12870 var i = 0; 12871 for (; i < this.labels.length; ++i) { 12872 var lab = this.labels[i]; 12873 if (node.label == null || lab.name === node.label.name) { 12874 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break } 12875 if (node.label && isBreak) { break } 12876 } 12877 } 12878 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); } 12879 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement") 12880}; 12881 12882pp$8.parseDebuggerStatement = function(node) { 12883 this.next(); 12884 this.semicolon(); 12885 return this.finishNode(node, "DebuggerStatement") 12886}; 12887 12888pp$8.parseDoStatement = function(node) { 12889 this.next(); 12890 this.labels.push(loopLabel); 12891 node.body = this.parseStatement("do"); 12892 this.labels.pop(); 12893 this.expect(types$1._while); 12894 node.test = this.parseParenExpression(); 12895 if (this.options.ecmaVersion >= 6) 12896 { this.eat(types$1.semi); } 12897 else 12898 { this.semicolon(); } 12899 return this.finishNode(node, "DoWhileStatement") 12900}; 12901 12902// Disambiguating between a `for` and a `for`/`in` or `for`/`of` 12903// loop is non-trivial. Basically, we have to parse the init `var` 12904// statement or expression, disallowing the `in` operator (see 12905// the second parameter to `parseExpression`), and then check 12906// whether the next token is `in` or `of`. When there is no init 12907// part (semicolon immediately after the opening parenthesis), it 12908// is a regular `for` loop. 12909 12910pp$8.parseForStatement = function(node) { 12911 this.next(); 12912 var awaitAt = (this.options.ecmaVersion >= 9 && this.canAwait && this.eatContextual("await")) ? this.lastTokStart : -1; 12913 this.labels.push(loopLabel); 12914 this.enterScope(0); 12915 this.expect(types$1.parenL); 12916 if (this.type === types$1.semi) { 12917 if (awaitAt > -1) { this.unexpected(awaitAt); } 12918 return this.parseFor(node, null) 12919 } 12920 var isLet = this.isLet(); 12921 if (this.type === types$1._var || this.type === types$1._const || isLet) { 12922 var init$1 = this.startNode(), kind = isLet ? "let" : this.value; 12923 this.next(); 12924 this.parseVar(init$1, true, kind); 12925 this.finishNode(init$1, "VariableDeclaration"); 12926 if ((this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) { 12927 if (this.options.ecmaVersion >= 9) { 12928 if (this.type === types$1._in) { 12929 if (awaitAt > -1) { this.unexpected(awaitAt); } 12930 } else { node.await = awaitAt > -1; } 12931 } 12932 return this.parseForIn(node, init$1) 12933 } 12934 if (awaitAt > -1) { this.unexpected(awaitAt); } 12935 return this.parseFor(node, init$1) 12936 } 12937 var startsWithLet = this.isContextual("let"), isForOf = false; 12938 var refDestructuringErrors = new DestructuringErrors; 12939 var init = this.parseExpression(awaitAt > -1 ? "await" : true, refDestructuringErrors); 12940 if (this.type === types$1._in || (isForOf = this.options.ecmaVersion >= 6 && this.isContextual("of"))) { 12941 if (this.options.ecmaVersion >= 9) { 12942 if (this.type === types$1._in) { 12943 if (awaitAt > -1) { this.unexpected(awaitAt); } 12944 } else { node.await = awaitAt > -1; } 12945 } 12946 if (startsWithLet && isForOf) { this.raise(init.start, "The left-hand side of a for-of loop may not start with 'let'."); } 12947 this.toAssignable(init, false, refDestructuringErrors); 12948 this.checkLValPattern(init); 12949 return this.parseForIn(node, init) 12950 } else { 12951 this.checkExpressionErrors(refDestructuringErrors, true); 12952 } 12953 if (awaitAt > -1) { this.unexpected(awaitAt); } 12954 return this.parseFor(node, init) 12955}; 12956 12957pp$8.parseFunctionStatement = function(node, isAsync, declarationPosition) { 12958 this.next(); 12959 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync) 12960}; 12961 12962pp$8.parseIfStatement = function(node) { 12963 this.next(); 12964 node.test = this.parseParenExpression(); 12965 // allow function declarations in branches, but only in non-strict mode 12966 node.consequent = this.parseStatement("if"); 12967 node.alternate = this.eat(types$1._else) ? this.parseStatement("if") : null; 12968 return this.finishNode(node, "IfStatement") 12969}; 12970 12971pp$8.parseReturnStatement = function(node) { 12972 if (!this.inFunction && !this.options.allowReturnOutsideFunction) 12973 { this.raise(this.start, "'return' outside of function"); } 12974 this.next(); 12975 12976 // In `return` (and `break`/`continue`), the keywords with 12977 // optional arguments, we eagerly look for a semicolon or the 12978 // possibility to insert one. 12979 12980 if (this.eat(types$1.semi) || this.insertSemicolon()) { node.argument = null; } 12981 else { node.argument = this.parseExpression(); this.semicolon(); } 12982 return this.finishNode(node, "ReturnStatement") 12983}; 12984 12985pp$8.parseSwitchStatement = function(node) { 12986 this.next(); 12987 node.discriminant = this.parseParenExpression(); 12988 node.cases = []; 12989 this.expect(types$1.braceL); 12990 this.labels.push(switchLabel); 12991 this.enterScope(0); 12992 12993 // Statements under must be grouped (by label) in SwitchCase 12994 // nodes. `cur` is used to keep the node that we are currently 12995 // adding statements to. 12996 12997 var cur; 12998 for (var sawDefault = false; this.type !== types$1.braceR;) { 12999 if (this.type === types$1._case || this.type === types$1._default) { 13000 var isCase = this.type === types$1._case; 13001 if (cur) { this.finishNode(cur, "SwitchCase"); } 13002 node.cases.push(cur = this.startNode()); 13003 cur.consequent = []; 13004 this.next(); 13005 if (isCase) { 13006 cur.test = this.parseExpression(); 13007 } else { 13008 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); } 13009 sawDefault = true; 13010 cur.test = null; 13011 } 13012 this.expect(types$1.colon); 13013 } else { 13014 if (!cur) { this.unexpected(); } 13015 cur.consequent.push(this.parseStatement(null)); 13016 } 13017 } 13018 this.exitScope(); 13019 if (cur) { this.finishNode(cur, "SwitchCase"); } 13020 this.next(); // Closing brace 13021 this.labels.pop(); 13022 return this.finishNode(node, "SwitchStatement") 13023}; 13024 13025pp$8.parseThrowStatement = function(node) { 13026 this.next(); 13027 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) 13028 { this.raise(this.lastTokEnd, "Illegal newline after throw"); } 13029 node.argument = this.parseExpression(); 13030 this.semicolon(); 13031 return this.finishNode(node, "ThrowStatement") 13032}; 13033 13034// Reused empty array added for node fields that are always empty. 13035 13036var empty$1 = []; 13037 13038pp$8.parse
13038TryStatement = function(node) { 13039 this.next(); 13040 node.block = this.parseBlock(); 13041 node.handler = null;
vendor: 9,013 bytes, lines 13042-13296
13042 if (this.type === types$1._catch) { 13043 var clause = this.startNode(); 13044 this.next(); 13045 if (this.eat(types$1.parenL)) { 13046 clause.param = this.parseBindingAtom(); 13047 var simple = clause.param.type === "Identifier"; 13048 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0); 13049 this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL); 13050 this.expect(types$1.parenR); 13051 } else { 13052 if (this.options.ecmaVersion < 10) { this.unexpected(); } 13053 clause.param = null; 13054 this.enterScope(0); 13055 } 13056 clause.body = this.parseBlock(false); 13057 this.exitScope(); 13058 node.handler = this.finishNode(clause, "CatchClause"); 13059 } 13060 node.finalizer = this.eat(types$1._finally) ? this.parseBlock() : null; 13061 if (!node.handler && !node.finalizer) 13062 { this.raise(node.start, "Missing catch or finally clause"); } 13063 return this.finishNode(node, "TryStatement") 13064}; 13065 13066pp$8.parseVarStatement = function(node, kind) { 13067 this.next(); 13068 this.parseVar(node, false, kind); 13069 this.semicolon(); 13070 return this.finishNode(node, "VariableDeclaration") 13071}; 13072 13073pp$8.parseWhileStatement = function(node) { 13074 this.next(); 13075 node.test = this.parseParenExpression(); 13076 this.labels.push(loopLabel); 13077 node.body = this.parseStatement("while"); 13078 this.labels.pop(); 13079 return this.finishNode(node, "WhileStatement") 13080}; 13081 13082pp$8.parseWithStatement = function(node) { 13083 if (this.strict) { this.raise(this.start, "'with' in strict mode"); } 13084 this.next(); 13085 node.object = this.parseParenExpression(); 13086 node.body = this.parseStatement("with"); 13087 return this.finishNode(node, "WithStatement") 13088}; 13089 13090pp$8.parseEmptyStatement = function(node) { 13091 this.next(); 13092 return this.finishNode(node, "EmptyStatement") 13093}; 13094 13095pp$8.parseLabeledStatement = function(node, maybeName, expr, context) { 13096 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1) 13097 { 13098 var label = list[i$1]; 13099 13100 if (label.name === maybeName) 13101 { this.raise(expr.start, "Label '" + maybeName + "' is already declared"); 13102 } } 13103 var kind = this.type.isLoop ? "loop" : this.type === types$1._switch ? "switch" : null; 13104 for (var i = this.labels.length - 1; i >= 0; i--) { 13105 var label$1 = this.labels[i]; 13106 if (label$1.statementStart === node.start) { 13107 // Update information about previous labels on this node 13108 label$1.statementStart = this.start; 13109 label$1.kind = kind; 13110 } else { break } 13111 } 13112 this.labels.push({name: maybeName, kind: kind, statementStart: this.start}); 13113 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label"); 13114 this.labels.pop(); 13115 node.label = expr; 13116 return this.finishNode(node, "LabeledStatement") 13117}; 13118 13119pp$8.parseExpressionStatement = function(node, expr) { 13120 node.expression = expr; 13121 this.semicolon(); 13122 return this.finishNode(node, "ExpressionStatement") 13123}; 13124 13125// Parse a semicolon-enclosed block of statements, handling `"use 13126// strict"` declarations when `allowStrict` is true (used for 13127// function bodies). 13128 13129pp$8.parseBlock = function(createNewLexicalScope, node, exitStrict) { 13130 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true; 13131 if ( node === void 0 ) node = this.startNode(); 13132 13133 node.body = []; 13134 this.expect(types$1.braceL); 13135 if (createNewLexicalScope) { this.enterScope(0); } 13136 while (this.type !== types$1.braceR) { 13137 var stmt = this.parseStatement(null); 13138 node.body.push(stmt); 13139 } 13140 if (exitStrict) { this.strict = false; } 13141 this.next(); 13142 if (createNewLexicalScope) { this.exitScope(); } 13143 return this.finishNode(node, "BlockStatement") 13144}; 13145 13146// Parse a regular `for` loop. The disambiguation code in 13147// `parseStatement` will already have parsed the init statement or 13148// expression. 13149 13150pp$8.parseFor = function(node, init) { 13151 node.init = init; 13152 this.expect(types$1.semi); 13153 node.test = this.type === types$1.semi ? null : this.parseExpression(); 13154 this.expect(types$1.semi); 13155 node.update = this.type === types$1.parenR ? null : this.parseExpression(); 13156 this.expect(types$1.parenR); 13157 node.body = this.parseStatement("for"); 13158 this.exitScope(); 13159 this.labels.pop(); 13160 return this.finishNode(node, "ForStatement") 13161}; 13162 13163// Parse a `for`/`in` and `for`/`of` loop, which are almost 13164// same from parser's perspective. 13165 13166pp$8.parseForIn = function(node, init) { 13167 var isForIn = this.type === types$1._in; 13168 this.next(); 13169 13170 if ( 13171 init.type === "VariableDeclaration" && 13172 init.declarations[0].init != null && 13173 ( 13174 !isForIn || 13175 this.options.ecmaVersion < 8 || 13176 this.strict || 13177 init.kind !== "var" || 13178 init.declarations[0].id.type !== "Identifier" 13179 ) 13180 ) { 13181 this.raise( 13182 init.start, 13183 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer") 13184 ); 13185 } 13186 node.left = init; 13187 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign(); 13188 this.expect(types$1.parenR); 13189 node.body = this.parseStatement("for"); 13190 this.exitScope(); 13191 this.labels.pop(); 13192 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement") 13193}; 13194 13195// Parse a list of variable declarations. 13196 13197pp$8.parseVar = function(node, isFor, kind) { 13198 node.declarations = []; 13199 node.kind = kind; 13200 for (;;) { 13201 var decl = this.startNode(); 13202 this.parseVarId(decl, kind); 13203 if (this.eat(types$1.eq)) { 13204 decl.init = this.parseMaybeAssign(isFor); 13205 } else if (kind === "const" && !(this.type === types$1._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) { 13206 this.unexpected(); 13207 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types$1._in || this.isContextual("of")))) { 13208 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value"); 13209 } else { 13210 decl.init = null; 13211 } 13212 node.declarations.push(this.finishNode(decl, "VariableDeclarator")); 13213 if (!this.eat(types$1.comma)) { break } 13214 } 13215 return node 13216}; 13217 13218pp$8.parseVarId = function(decl, kind) { 13219 decl.id = this.parseBindingAtom(); 13220 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false); 13221}; 13222 13223var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4; 13224 13225// Parse a function declaration or literal (depending on the 13226// `statement & FUNC_STATEMENT`). 13227 13228// Remove `allowExpressionBody` for 7.0.0, as it is only called with false 13229pp$8.parseFunction = function(node, statement, allowExpressionBody, isAsync, forInit) { 13230 this.initFunction(node); 13231 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) { 13232 if (this.type === types$1.star && (statement & FUNC_HANGING_STATEMENT)) 13233 { this.unexpected(); } 13234 node.generator = this.eat(types$1.star); 13235 } 13236 if (this.options.ecmaVersion >= 8) 13237 { node.async = !!isAsync; } 13238 13239 if (statement & FUNC_STATEMENT) { 13240 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types$1.name ? null : this.parseIdent(); 13241 if (node.id && !(statement & FUNC_HANGING_STATEMENT)) 13242 // If it is a regular function declaration in sloppy mode, then it is 13243 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding 13244 // mode depends on properties of the current scope (see 13245 // treatFunctionsAsVar). 13246 { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); } 13247 } 13248 13249 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; 13250 this.yieldPos = 0; 13251 this.awaitPos = 0; 13252 this.awaitIdentPos = 0; 13253 this.enterScope(functionFlags(node.async, node.generator)); 13254 13255 if (!(statement & FUNC_STATEMENT)) 13256 { node.id = this.type === types$1.name ? this.parseIdent() : null; } 13257 13258 this.parseFunctionParams(node); 13259 this.parseFunctionBody(node, allowExpressionBody, false, forInit); 13260 13261 this.yieldPos = oldYieldPos; 13262 this.awaitPos = oldAwaitPos; 13263 this.awaitIdentPos = oldAwaitIdentPos; 13264 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") 13265}; 13266 13267pp$8.parseFunctionParams = function(node) { 13268 this.expect(types$1.parenL); 13269 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); 13270 this.checkYieldAwaitInDefaultParams(); 13271}; 13272 13273// Parse a class declaration or literal (depending on the 13274// `isStatement` parameter). 13275 13276pp$8.parseClass = function(node, isStatement) { 13277 this.next(); 13278 13279 // ecma-262 14.6 Class Definitions 13280 // A class definition is always strict mode code. 13281 var oldStrict = this.strict; 13282 this.strict = true; 13283 13284 this.parseClassId(node, isStatement); 13285 this.parseClassSuper(node); 13286 var privateNameMap = this.enterClassBody(); 13287 var classBody = this.startNode(); 13288 var hadConstructor = false; 13289 classBody.body = []; 13290 this.expect(types$1.braceL); 13291 while (this.type !== types$1.braceR) { 13292 var element = this.parseClassElement(node.superClass !== null); 13293 if (element) { 13294 classBody.body.push(element); 13295 if (element.type === "MethodDefinition" && element.kind === "constructor") { 13296 if (hadConstructor) { this.rais
vendor: 6,255 bytes, lines 13296-13481
13296e(element.start, "Duplicate constructor in the same class"); } 13297 hadConstructor = true; 13298 } else if (element.key && element.key.type === "PrivateIdentifier" && isPrivateNameConflicted(privateNameMap, element)) { 13299 this.raiseRecoverable(element.key.start, ("Identifier '#" + (element.key.name) + "' has already been declared")); 13300 } 13301 } 13302 } 13303 this.strict = oldStrict; 13304 this.next(); 13305 node.body = this.finishNode(classBody, "ClassBody"); 13306 this.exitClassBody(); 13307 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression") 13308}; 13309 13310pp$8.parseClassElement = function(constructorAllowsSuper) { 13311 if (this.eat(types$1.semi)) { return null } 13312 13313 var ecmaVersion = this.options.ecmaVersion; 13314 var node = this.startNode(); 13315 var keyName = ""; 13316 var isGenerator = false; 13317 var isAsync = false; 13318 var kind = "method"; 13319 var isStatic = false; 13320 13321 if (this.eatContextual("static")) { 13322 // Parse static init block 13323 if (ecmaVersion >= 13 && this.eat(types$1.braceL)) { 13324 this.parseClassStaticBlock(node); 13325 return node 13326 } 13327 if (this.isClassElementNameStart() || this.type === types$1.star) { 13328 isStatic = true; 13329 } else { 13330 keyName = "static"; 13331 } 13332 } 13333 node.static = isStatic; 13334 if (!keyName && ecmaVersion >= 8 && this.eatContextual("async")) { 13335 if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) { 13336 isAsync = true; 13337 } else { 13338 keyName = "async"; 13339 } 13340 } 13341 if (!keyName && (ecmaVersion >= 9 || !isAsync) && this.eat(types$1.star)) { 13342 isGenerator = true; 13343 } 13344 if (!keyName && !isAsync && !isGenerator) { 13345 var lastValue = this.value; 13346 if (this.eatContextual("get") || this.eatContextual("set")) { 13347 if (this.isClassElementNameStart()) { 13348 kind = lastValue; 13349 } else { 13350 keyName = lastValue; 13351 } 13352 } 13353 } 13354 13355 // Parse element name 13356 if (keyName) { 13357 // 'async', 'get', 'set', or 'static' were not a keyword contextually. 13358 // The last token is any of those. Make it the element name. 13359 node.computed = false; 13360 node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc); 13361 node.key.name = keyName; 13362 this.finishNode(node.key, "Identifier"); 13363 } else { 13364 this.parseClassElementName(node); 13365 } 13366 13367 // Parse element value 13368 if (ecmaVersion < 13 || this.type === types$1.parenL || kind !== "method" || isGenerator || isAsync) { 13369 var isConstructor = !node.static && checkKeyName(node, "constructor"); 13370 var allowsDirectSuper = isConstructor && constructorAllowsSuper; 13371 // Couldn't move this check into the 'parseClassMethod' method for backward compatibility. 13372 if (isConstructor && kind !== "method") { this.raise(node.key.start, "Constructor can't have get/set modifier"); } 13373 node.kind = isConstructor ? "constructor" : kind; 13374 this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper); 13375 } else { 13376 this.parseClassField(node); 13377 } 13378 13379 return node 13380}; 13381 13382pp$8.isClassElementNameStart = function() { 13383 return ( 13384 this.type === types$1.name || 13385 this.type === types$1.privateId || 13386 this.type === types$1.num || 13387 this.type === types$1.string || 13388 this.type === types$1.bracketL || 13389 this.type.keyword 13390 ) 13391}; 13392 13393pp$8.parseClassElementName = function(element) { 13394 if (this.type === types$1.privateId) { 13395 if (this.value === "constructor") { 13396 this.raise(this.start, "Classes can't have an element named '#constructor'"); 13397 } 13398 element.computed = false; 13399 element.key = this.parsePrivateIdent(); 13400 } else { 13401 this.parsePropertyName(element); 13402 } 13403}; 13404 13405pp$8.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) { 13406 // Check key and flags 13407 var key = method.key; 13408 if (method.kind === "constructor") { 13409 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); } 13410 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); } 13411 } else if (method.static && checkKeyName(method, "prototype")) { 13412 this.raise(key.start, "Classes may not have a static property named prototype"); 13413 } 13414 13415 // Parse value 13416 var value = method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper); 13417 13418 // Check value 13419 if (method.kind === "get" && value.params.length !== 0) 13420 { this.raiseRecoverable(value.start, "getter should have no params"); } 13421 if (method.kind === "set" && value.params.length !== 1) 13422 { this.raiseRecoverable(value.start, "setter should have exactly one param"); } 13423 if (method.kind === "set" && value.params[0].type === "RestElement") 13424 { this.raiseRecoverable(value.params[0].start, "Setter cannot use rest params"); } 13425 13426 return this.finishNode(method, "MethodDefinition") 13427}; 13428 13429pp$8.parseClassField = function(field) { 13430 if (checkKeyName(field, "constructor")) { 13431 this.raise(field.key.start, "Classes can't have a field named 'constructor'"); 13432 } else if (field.static && checkKeyName(field, "prototype")) { 13433 this.raise(field.key.start, "Classes can't have a static field named 'prototype'"); 13434 } 13435 13436 if (this.eat(types$1.eq)) { 13437 // To raise SyntaxError if 'arguments' exists in the initializer. 13438 var scope = this.currentThisScope(); 13439 var inClassFieldInit = scope.inClassFieldInit; 13440 scope.inClassFieldInit = true; 13441 field.value = this.parseMaybeAssign(); 13442 scope.inClassFieldInit = inClassFieldInit; 13443 } else { 13444 field.value = null; 13445 } 13446 this.semicolon(); 13447 13448 return this.finishNode(field, "PropertyDefinition") 13449}; 13450 13451pp$8.parseClassStaticBlock = function(node) { 13452 node.body = []; 13453 13454 var oldLabels = this.labels; 13455 this.labels = []; 13456 this.enterScope(SCOPE_CLASS_STATIC_BLOCK | SCOPE_SUPER); 13457 while (this.type !== types$1.braceR) { 13458 var stmt = this.parseStatement(null); 13459 node.body.push(stmt); 13460 } 13461 this.next(); 13462 this.exitScope(); 13463 this.labels = oldLabels; 13464 13465 return this.finishNode(node, "StaticBlock") 13466}; 13467 13468pp$8.parseClassId = function(node, isStatement) { 13469 if (this.type === types$1.name) { 13470 node.id = this.parseIdent(); 13471 if (isStatement) 13472 { this.checkLValSimple(node.id, BIND_LEXICAL, false); } 13473 } else { 13474 if (isStatement === true) 13475 { this.unexpected(); } 13476 node.id = null; 13477 } 13478}; 13479 13480pp$8.parseClassSuper = function(node) { 13481 node.superClass = this.eat(types$1._extends) ? this.parseExprSubscripts(
vendor: 12,305 bytes, lines 13481-13856
13481false) : null; 13482}; 13483 13484pp$8.enterClassBody = function() { 13485 var element = {declared: Object.create(null), used: []}; 13486 this.privateNameStack.push(element); 13487 return element.declared 13488}; 13489 13490pp$8.exitClassBody = function() { 13491 var ref = this.privateNameStack.pop(); 13492 var declared = ref.declared; 13493 var used = ref.used; 13494 var len = this.privateNameStack.length; 13495 var parent = len === 0 ? null : this.privateNameStack[len - 1]; 13496 for (var i = 0; i < used.length; ++i) { 13497 var id = used[i]; 13498 if (!hasOwn(declared, id.name)) { 13499 if (parent) { 13500 parent.used.push(id); 13501 } else { 13502 this.raiseRecoverable(id.start, ("Private field '#" + (id.name) + "' must be declared in an enclosing class")); 13503 } 13504 } 13505 } 13506}; 13507 13508function isPrivateNameConflicted(privateNameMap, element) { 13509 var name = element.key.name; 13510 var curr = privateNameMap[name]; 13511 13512 var next = "true"; 13513 if (element.type === "MethodDefinition" && (element.kind === "get" || element.kind === "set")) { 13514 next = (element.static ? "s" : "i") + element.kind; 13515 } 13516 13517 // `class { get #a(){}; static set #a(_){} }` is also conflict. 13518 if ( 13519 curr === "iget" && next === "iset" || 13520 curr === "iset" && next === "iget" || 13521 curr === "sget" && next === "sset" || 13522 curr === "sset" && next === "sget" 13523 ) { 13524 privateNameMap[name] = "true"; 13525 return false 13526 } else if (!curr) { 13527 privateNameMap[name] = next; 13528 return false 13529 } else { 13530 return true 13531 } 13532} 13533 13534function checkKeyName(node, name) { 13535 var computed = node.computed; 13536 var key = node.key; 13537 return !computed && ( 13538 key.type === "Identifier" && key.name === name || 13539 key.type === "Literal" && key.value === name 13540 ) 13541} 13542 13543// Parses module export declaration. 13544 13545pp$8.parseExport = function(node, exports) { 13546 this.next(); 13547 // export * from '...' 13548 if (this.eat(types$1.star)) { 13549 if (this.options.ecmaVersion >= 11) { 13550 if (this.eatContextual("as")) { 13551 node.exported = this.parseModuleExportName(); 13552 this.checkExport(exports, node.exported, this.lastTokStart); 13553 } else { 13554 node.exported = null; 13555 } 13556 } 13557 this.expectContextual("from"); 13558 if (this.type !== types$1.string) { this.unexpected(); } 13559 node.source = this.parseExprAtom(); 13560 this.semicolon(); 13561 return this.finishNode(node, "ExportAllDeclaration") 13562 } 13563 if (this.eat(types$1._default)) { // export default ... 13564 this.checkExport(exports, "default", this.lastTokStart); 13565 var isAsync; 13566 if (this.type === types$1._function || (isAsync = this.isAsyncFunction())) { 13567 var fNode = this.startNode(); 13568 this.next(); 13569 if (isAsync) { this.next(); } 13570 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync); 13571 } else if (this.type === types$1._class) { 13572 var cNode = this.startNode(); 13573 node.declaration = this.parseClass(cNode, "nullableID"); 13574 } else { 13575 node.declaration = this.parseMaybeAssign(); 13576 this.semicolon(); 13577 } 13578 return this.finishNode(node, "ExportDefaultDeclaration") 13579 } 13580 // export var|const|let|function|class ... 13581 if (this.shouldParseExportStatement()) { 13582 node.declaration = this.parseStatement(null); 13583 if (node.declaration.type === "VariableDeclaration") 13584 { this.checkVariableExport(exports, node.declaration.declarations); } 13585 else 13586 { this.checkExport(exports, node.declaration.id, node.declaration.id.start); } 13587 node.specifiers = []; 13588 node.source = null; 13589 } else { // export { x, y as z } [from '...'] 13590 node.declaration = null; 13591 node.specifiers = this.parseExportSpecifiers(exports); 13592 if (this.eatContextual("from")) { 13593 if (this.type !== types$1.string) { this.unexpected(); } 13594 node.source = this.parseExprAtom(); 13595 } else { 13596 for (var i = 0, list = node.specifiers; i < list.length; i += 1) { 13597 // check for keywords used as local names 13598 var spec = list[i]; 13599 13600 this.checkUnreserved(spec.local); 13601 // check if export is defined 13602 this.checkLocalExport(spec.local); 13603 13604 if (spec.local.type === "Literal") { 13605 this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`."); 13606 } 13607 } 13608 13609 node.source = null; 13610 } 13611 this.semicolon(); 13612 } 13613 return this.finishNode(node, "ExportNamedDeclaration") 13614}; 13615 13616pp$8.checkExport = function(exports, name, pos) { 13617 if (!exports) { return } 13618 if (typeof name !== "string") 13619 { name = name.type === "Identifier" ? name.name : name.value; } 13620 if (hasOwn(exports, name)) 13621 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); } 13622 exports[name] = true; 13623}; 13624 13625pp$8.checkPatternExport = function(exports, pat) { 13626 var type = pat.type; 13627 if (type === "Identifier") 13628 { this.checkExport(exports, pat, pat.start); } 13629 else if (type === "ObjectPattern") 13630 { for (var i = 0, list = pat.properties; i < list.length; i += 1) 13631 { 13632 var prop = list[i]; 13633 13634 this.checkPatternExport(exports, prop); 13635 } } 13636 else if (type === "ArrayPattern") 13637 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) { 13638 var elt = list$1[i$1]; 13639 13640 if (elt) { this.checkPatternExport(exports, elt); } 13641 } } 13642 else if (type === "Property") 13643 { this.checkPatternExport(exports, pat.value); } 13644 else if (type === "AssignmentPattern") 13645 { this.checkPatternExport(exports, pat.left); } 13646 else if (type === "RestElement") 13647 { this.checkPatternExport(exports, pat.argument); } 13648 else if (type === "ParenthesizedExpression") 13649 { this.checkPatternExport(exports, pat.expression); } 13650}; 13651 13652pp$8.checkVariableExport = function(exports, decls) { 13653 if (!exports) { return } 13654 for (var i = 0, list = decls; i < list.length; i += 1) 13655 { 13656 var decl = list[i]; 13657 13658 this.checkPatternExport(exports, decl.id); 13659 } 13660}; 13661 13662pp$8.shouldParseExportStatement = function() { 13663 return this.type.keyword === "var" || 13664 this.type.keyword === "const" || 13665 this.type.keyword === "class" || 13666 this.type.keyword === "function" || 13667 this.isLet() || 13668 this.isAsyncFunction() 13669}; 13670 13671// Parses a comma-separated list of module exports. 13672 13673pp$8.parseExportSpecifiers = function(exports) { 13674 var nodes = [], first = true; 13675 // export { x, y as z } [from '...'] 13676 this.expect(types$1.braceL); 13677 while (!this.eat(types$1.braceR)) { 13678 if (!first) { 13679 this.expect(types$1.comma); 13680 if (this.afterTrailingComma(types$1.braceR)) { break } 13681 } else { first = false; } 13682 13683 var node = this.startNode(); 13684 node.local = this.parseModuleExportName(); 13685 node.exported = this.eatContextual("as") ? this.parseModuleExportName() : node.local; 13686 this.checkExport( 13687 exports, 13688 node.exported, 13689 node.exported.start 13690 ); 13691 nodes.push(this.finishNode(node, "ExportSpecifier")); 13692 } 13693 return nodes 13694}; 13695 13696// Parses import declaration. 13697 13698pp$8.parseImport = function(node) { 13699 this.next(); 13700 // import '...' 13701 if (this.type === types$1.string) { 13702 node.specifiers = empty$1; 13703 node.source = this.parseExprAtom(); 13704 } else { 13705 node.specifiers = this.parseImportSpecifiers(); 13706 this.expectContextual("from"); 13707 node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); 13708 } 13709 this.semicolon(); 13710 return this.finishNode(node, "ImportDeclaration") 13711}; 13712 13713// Parses a comma-separated list of module imports. 13714 13715pp$8.parseImportSpecifiers = function() { 13716 var nodes = [], first = true; 13717 if (this.type === types$1.name) { 13718 // import defaultObj, { x, y as z } from '...' 13719 var node = this.startNode(); 13720 node.local = this.parseIdent(); 13721 this.checkLValSimple(node.local, BIND_LEXICAL); 13722 nodes.push(this.finishNode(node, "ImportDefaultSpecifier")); 13723 if (!this.eat(types$1.comma)) { return nodes } 13724 } 13725 if (this.type === types$1.star) { 13726 var node$1 = this.startNode(); 13727 this.next(); 13728 this.expectContextual("as"); 13729 node$1.local = this.parseIdent(); 13730 this.checkLValSimple(node$1.local, BIND_LEXICAL); 13731 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier")); 13732 return nodes 13733 } 13734 this.expect(types$1.braceL); 13735 while (!this.eat(types$1.braceR)) { 13736 if (!first) { 13737 this.expect(types$1.comma); 13738 if (this.afterTrailingComma(types$1.braceR)) { break } 13739 } else { first = false; } 13740 13741 var node$2 = this.startNode(); 13742 node$2.imported = this.parseModuleExportName(); 13743 if (this.eatContextual("as")) { 13744 node$2.local = this.parseIdent(); 13745 } else { 13746 this.checkUnreserved(node$2.imported); 13747 node$2.local = node$2.imported; 13748 } 13749 this.checkLValSimple(node$2.local, BIND_LEXICAL); 13750 nodes.push(this.finishNode(node$2, "ImportSpecifier")); 13751 } 13752 return nodes 13753}; 13754 13755pp$8.parseModuleExportName = function() { 13756 if (this.options.ecmaVersion >= 13 && this.type === types$1.string) { 13757 var stringLiteral = this.parseLiteral(this.value); 13758 if (loneSurrogate.test(stringLiteral.value)) { 13759 this.raise(stringLiteral.start, "An export name cannot include a lone surrogate."); 13760 } 13761 return stringLiteral 13762 } 13763 return this.parseIdent(true) 13764}; 13765 13766// Set `ExpressionStatement#directive` property for directive prologues. 13767pp$8.adaptDirectivePrologue = function(statements) { 13768 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) { 13769 statements[i].directive = statements[i].expression.raw.slice(1, -1); 13770 } 13771}; 13772pp$8.isDirectiveCandidate = function(statement) { 13773 return ( 13774 this.options.ecmaVersion >= 5 && 13775 statement.type === "ExpressionStatement" && 13776 statement.expression.type === "Literal" && 13777 typeof statement.expression.value === "string" && 13778 // Reject parenthesized strings. 13779 (this.input[statement.start] === "\"" || this.input[statement.start] === "'") 13780 ) 13781}; 13782 13783var pp$7 = Parser.prototype; 13784 13785// Convert existing expression atom to assignable pattern 13786// if possible. 13787 13788pp$7.toAssignable = function(node, isBinding, refDestructuringErrors) { 13789 if (this.options.ecmaVersion >= 6 && node) { 13790 switch (node.type) { 13791 case "Identifier": 13792 if (this.inAsync && node.name === "await") 13793 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); } 13794 break 13795 13796 case "ObjectPattern": 13797 case "ArrayPattern": 13798 case "AssignmentPattern": 13799 case "RestElement": 13800 break 13801 13802 case "ObjectExpression": 13803 node.type = "ObjectPattern"; 13804 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } 13805 for (var i = 0, list = node.properties; i < list.length; i += 1) { 13806 var prop = list[i]; 13807 13808 this.toAssignable(prop, isBinding); 13809 // Early error: 13810 // AssignmentRestProperty[Yield, Await] : 13811 // `...` DestructuringAssignmentTarget[Yield, Await] 13812 // 13813 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|. 13814 if ( 13815 prop.type === "RestElement" && 13816 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern") 13817 ) { 13818 this.raise(prop.argument.start, "Unexpected token"); 13819 } 13820 } 13821 break 13822 13823 case "Property": 13824 // AssignmentProperty has type === "Property" 13825 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); } 13826 this.toAssignable(node.value, isBinding); 13827 break 13828 13829 case "ArrayExpression": 13830 node.type = "ArrayPattern"; 13831 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } 13832 this.toAssignableList(node.elements, isBinding); 13833 break 13834 13835 case "SpreadElement": 13836 node.type = "RestElement"; 13837 this.toAssignable(node.argument, isBinding); 13838 if (node.argument.type === "AssignmentPattern") 13839 { this.raise(node.argument.start, "Rest elements cannot have a default value"); } 13840 break 13841 13842 case "AssignmentExpression": 13843 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); } 13844 node.type = "AssignmentPattern"; 13845 delete node.operator; 13846 this.toAssignable(node.left, isBinding); 13847 break 13848 13849 case "ParenthesizedExpression": 13850 this.toAssignable(node.expression, isBinding, refDestructuringErrors); 13851 break 13852 13853 case "ChainExpression": 13854 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side"); 13855 break 13856
vendor: 4,243 bytes, lines 13857-13986
13857 case "MemberExpression": 13858 if (!isBinding) { break } 13859 13860 default: 13861 this.raise(node.start, "Assigning to rvalue"); 13862 } 13863 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); } 13864 return node 13865}; 13866 13867// Convert list of expression atoms to binding list. 13868 13869pp$7.toAssignableList = function(exprList, isBinding) { 13870 var end = exprList.length; 13871 for (var i = 0; i < end; i++) { 13872 var elt = exprList[i]; 13873 if (elt) { this.toAssignable(elt, isBinding); } 13874 } 13875 if (end) { 13876 var last = exprList[end - 1]; 13877 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier") 13878 { this.unexpected(last.argument.start); } 13879 } 13880 return exprList 13881}; 13882 13883// Parses spread element. 13884 13885pp$7.parseSpread = function(refDestructuringErrors) { 13886 var node = this.startNode(); 13887 this.next(); 13888 node.argument = this.parseMaybeAssign(false, refDestructuringErrors); 13889 return this.finishNode(node, "SpreadElement") 13890}; 13891 13892pp$7.parseRestBinding = function() { 13893 var node = this.startNode(); 13894 this.next(); 13895 13896 // RestElement inside of a function parameter must be an identifier 13897 if (this.options.ecmaVersion === 6 && this.type !== types$1.name) 13898 { this.unexpected(); } 13899 13900 node.argument = this.parseBindingAtom(); 13901 13902 return this.finishNode(node, "RestElement") 13903}; 13904 13905// Parses lvalue (assignable) atom. 13906 13907pp$7.parseBindingAtom = function() { 13908 if (this.options.ecmaVersion >= 6) { 13909 switch (this.type) { 13910 case types$1.bracketL: 13911 var node = this.startNode(); 13912 this.next(); 13913 node.elements = this.parseBindingList(types$1.bracketR, true, true); 13914 return this.finishNode(node, "ArrayPattern") 13915 13916 case types$1.braceL: 13917 return this.parseObj(true) 13918 } 13919 } 13920 return this.parseIdent() 13921}; 13922 13923pp$7.parseBindingList = function(close, allowEmpty, allowTrailingComma) { 13924 var elts = [], first = true; 13925 while (!this.eat(close)) { 13926 if (first) { first = false; } 13927 else { this.expect(types$1.comma); } 13928 if (allowEmpty && this.type === types$1.comma) { 13929 elts.push(null); 13930 } else if (allowTrailingComma && this.afterTrailingComma(close)) { 13931 break 13932 } else if (this.type === types$1.ellipsis) { 13933 var rest = this.parseRestBinding(); 13934 this.parseBindingListItem(rest); 13935 elts.push(rest); 13936 if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } 13937 this.expect(close); 13938 break 13939 } else { 13940 var elem = this.parseMaybeDefault(this.start, this.startLoc); 13941 this.parseBindingListItem(elem); 13942 elts.push(elem); 13943 } 13944 } 13945 return elts 13946}; 13947 13948pp$7.parseBindingListItem = function(param) { 13949 return param 13950}; 13951 13952// Parses assignment pattern around given atom if possible. 13953 13954pp$7.parseMaybeDefault = function(startPos, startLoc, left) { 13955 left = left || this.parseBindingAtom(); 13956 if (this.options.ecmaVersion < 6 || !this.eat(types$1.eq)) { return left } 13957 var node = this.startNodeAt(startPos, startLoc); 13958 node.left = left; 13959 node.right = this.parseMaybeAssign(); 13960 return this.finishNode(node, "AssignmentPattern") 13961}; 13962 13963// The following three functions all verify that a node is an lvalue â 13964// something that can be bound, or assigned to. In order to do so, they perform 13965// a variety of checks: 13966// 13967// - Check that none of the bound/assigned-to identifiers are reserved words. 13968// - Record name declarations for bindings in the appropriate scope. 13969// - Check duplicate argument names, if checkClashes is set. 13970// 13971// If a complex binding pattern is encountered (e.g., object and array 13972// destructuring), the entire pattern is recursively checked. 13973// 13974// There are three versions of checkLVal*() appropriate for different 13975// circumstances: 13976// 13977// - checkLValSimple() shall be used if the syntactic construct supports 13978// nothing other than identifiers and member expressions. Parenthesized 13979// expressions are also correctly handled. This is generally appropriate for 13980// constructs for which the spec says 13981// 13982// > It is a Syntax Error if AssignmentTargetType of [the production] is not 13983// > simple. 13984// 13985// It is also appropriate for checking if an identifier is valid and not 13986// defined elsewhere, like import declarations or function/class i
vendor: 12,563 bytes, lines 13986-14349
13986dentifiers. 13987// 13988// Examples where this is used include: 13989// a += â¦; 13990// import a from 'â¦'; 13991// where a is the node to be checked. 13992// 13993// - checkLValPattern() shall be used if the syntactic construct supports 13994// anything checkLValSimple() supports, as well as object and array 13995// destructuring patterns. This is generally appropriate for constructs for 13996// which the spec says 13997// 13998// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor 13999// > an ArrayLiteral and AssignmentTargetType of [the production] is not 14000// > simple. 14001// 14002// Examples where this is used include: 14003// (a = â¦); 14004// const a = â¦; 14005// try { ⦠} catch (a) { ⦠} 14006// where a is the node to be checked. 14007// 14008// - checkLValInnerPattern() shall be used if the syntactic construct supports 14009// anything checkLValPattern() supports, as well as default assignment 14010// patterns, rest elements, and other constructs that may appear within an 14011// object or array destructuring pattern. 14012// 14013// As a special case, function parameters also use checkLValInnerPattern(), 14014// as they also support defaults and rest constructs. 14015// 14016// These functions deliberately support both assignment and binding constructs, 14017// as the logic for both is exceedingly similar. If the node is the target of 14018// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it 14019// should be set to the appropriate BIND_* constant, like BIND_VAR or 14020// BIND_LEXICAL. 14021// 14022// If the function is called with a non-BIND_NONE bindingType, then 14023// additionally a checkClashes object may be specified to allow checking for 14024// duplicate argument names. checkClashes is ignored if the provided construct 14025// is an assignment (i.e., bindingType is BIND_NONE). 14026 14027pp$7.checkLValSimple = function(expr, bindingType, checkClashes) { 14028 if ( bindingType === void 0 ) bindingType = BIND_NONE; 14029 14030 var isBind = bindingType !== BIND_NONE; 14031 14032 switch (expr.type) { 14033 case "Identifier": 14034 if (this.strict && this.reservedWordsStrictBind.test(expr.name)) 14035 { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); } 14036 if (isBind) { 14037 if (bindingType === BIND_LEXICAL && expr.name === "let") 14038 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); } 14039 if (checkClashes) { 14040 if (hasOwn(checkClashes, expr.name)) 14041 { this.raiseRecoverable(expr.start, "Argument name clash"); } 14042 checkClashes[expr.name] = true; 14043 } 14044 if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); } 14045 } 14046 break 14047 14048 case "ChainExpression": 14049 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side"); 14050 break 14051 14052 case "MemberExpression": 14053 if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); } 14054 break 14055 14056 case "ParenthesizedExpression": 14057 if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); } 14058 return this.checkLValSimple(expr.expression, bindingType, checkClashes) 14059 14060 default: 14061 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue"); 14062 } 14063}; 14064 14065pp$7.checkLValPattern = function(expr, bindingType, checkClashes) { 14066 if ( bindingType === void 0 ) bindingType = BIND_NONE; 14067 14068 switch (expr.type) { 14069 case "ObjectPattern": 14070 for (var i = 0, list = expr.properties; i < list.length; i += 1) { 14071 var prop = list[i]; 14072 14073 this.checkLValInnerPattern(prop, bindingType, checkClashes); 14074 } 14075 break 14076 14077 case "ArrayPattern": 14078 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) { 14079 var elem = list$1[i$1]; 14080 14081 if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); } 14082 } 14083 break 14084 14085 default: 14086 this.checkLValSimple(expr, bindingType, checkClashes); 14087 } 14088}; 14089 14090pp$7.checkLValInnerPattern = function(expr, bindingType, checkClashes) { 14091 if ( bindingType === void 0 ) bindingType = BIND_NONE; 14092 14093 switch (expr.type) { 14094 case "Property": 14095 // AssignmentProperty has type === "Property" 14096 this.checkLValInnerPattern(expr.value, bindingType, checkClashes); 14097 break 14098 14099 case "AssignmentPattern": 14100 this.checkLValPattern(expr.left, bindingType, checkClashes); 14101 break 14102 14103 case "RestElement": 14104 this.checkLValPattern(expr.argument, bindingType, checkClashes); 14105 break 14106 14107 default: 14108 this.checkLValPattern(expr, bindingType, checkClashes); 14109 } 14110}; 14111 14112// The algorithm used to determine whether a regexp can appear at a 14113 14114var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) { 14115 this.token = token; 14116 this.isExpr = !!isExpr; 14117 this.preserveSpace = !!preserveSpace; 14118 this.override = override; 14119 this.generator = !!generator; 14120}; 14121 14122var types = { 14123 b_stat: new TokContext("{", false), 14124 b_expr: new TokContext("{", true), 14125 b_tmpl: new TokContext("${", false), 14126 p_stat: new TokContext("(", false), 14127 p_expr: new TokContext("(", true), 14128 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }), 14129 f_stat: new TokContext("function", false), 14130 f_expr: new TokContext("function", true), 14131 f_expr_gen: new TokContext("function", true, false, null, true), 14132 f_gen: new TokContext("function", false, false, null, true) 14133}; 14134 14135var pp$6 = Parser.prototype; 14136 14137pp$6.initialContext = function() { 14138 return [types.b_stat] 14139}; 14140 14141pp$6.curContext = function() { 14142 return this.context[this.context.length - 1] 14143}; 14144 14145pp$6.braceIsBlock = function(prevType) { 14146 var parent = this.curContext(); 14147 if (parent === types.f_expr || parent === types.f_stat) 14148 { return true } 14149 if (prevType === types$1.colon && (parent === types.b_stat || parent === types.b_expr)) 14150 { return !parent.isExpr } 14151 14152 // The check for `tt.name && exprAllowed` detects whether we are 14153 // after a `yield` or `of` construct. See the `updateContext` for 14154 // `tt.name`. 14155 if (prevType === types$1._return || prevType === types$1.name && this.exprAllowed) 14156 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) } 14157 if (prevType === types$1._else || prevType === types$1.semi || prevType === types$1.eof || prevType === types$1.parenR || prevType === types$1.arrow) 14158 { return true } 14159 if (prevType === types$1.braceL) 14160 { return parent === types.b_stat } 14161 if (prevType === types$1._var || prevType === types$1._const || prevType === types$1.name) 14162 { return false } 14163 return !this.exprAllowed 14164}; 14165 14166pp$6.inGeneratorContext = function() { 14167 for (var i = this.context.length - 1; i >= 1; i--) { 14168 var context = this.context[i]; 14169 if (context.token === "function") 14170 { return context.generator } 14171 } 14172 return false 14173}; 14174 14175pp$6.updateContext = function(prevType) { 14176 var update, type = this.type; 14177 if (type.keyword && prevType === types$1.dot) 14178 { this.exprAllowed = false; } 14179 else if (update = type.updateContext) 14180 { update.call(this, prevType); } 14181 else 14182 { this.exprAllowed = type.beforeExpr; } 14183}; 14184 14185// Used to handle egde cases when token context could not be inferred correctly during tokenization phase 14186 14187pp$6.overrideContext = function(tokenCtx) { 14188 if (this.curContext() !== tokenCtx) { 14189 this.context[this.context.length - 1] = tokenCtx; 14190 } 14191}; 14192 14193// Token-specific context update code 14194 14195types$1.parenR.updateContext = types$1.braceR.updateContext = function() { 14196 if (this.context.length === 1) { 14197 this.exprAllowed = true; 14198 return 14199 } 14200 var out = this.context.pop(); 14201 if (out === types.b_stat && this.curContext().token === "function") { 14202 out = this.context.pop(); 14203 } 14204 this.exprAllowed = !out.isExpr; 14205}; 14206 14207types$1.braceL.updateContext = function(prevType) { 14208 this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr); 14209 this.exprAllowed = true; 14210}; 14211 14212types$1.dollarBraceL.updateContext = function() { 14213 this.context.push(types.b_tmpl); 14214 this.exprAllowed = true; 14215}; 14216 14217types$1.parenL.updateContext = function(prevType) { 14218 var statementParens = prevType === types$1._if || prevType === types$1._for || prevType === types$1._with || prevType === types$1._while; 14219 this.context.push(statementParens ? types.p_stat : types.p_expr); 14220 this.exprAllowed = true; 14221}; 14222 14223types$1.incDec.updateContext = function() { 14224 // tokExprAllowed stays unchanged 14225}; 14226 14227types$1._function.updateContext = types$1._class.updateContext = function(prevType) { 14228 if (prevType.beforeExpr && prevType !== types$1._else && 14229 !(prevType === types$1.semi && this.curContext() !== types.p_stat) && 14230 !(prevType === types$1._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) && 14231 !((prevType === types$1.colon || prevType === types$1.braceL) && this.curContext() === types.b_stat)) 14232 { this.context.push(types.f_expr); } 14233 else 14234 { this.context.push(types.f_stat); } 14235 this.exprAllowed = false; 14236}; 14237 14238types$1.backQuote.updateContext = function() { 14239 if (this.curContext() === types.q_tmpl) 14240 { this.context.pop(); } 14241 else 14242 { this.context.push(types.q_tmpl); } 14243 this.exprAllowed = false; 14244}; 14245 14246types$1.star.updateContext = function(prevType) { 14247 if (prevType === types$1._function) { 14248 var index = this.context.length - 1; 14249 if (this.context[index] === types.f_expr) 14250 { this.context[index] = types.f_expr_gen; } 14251 else 14252 { this.context[index] = types.f_gen; } 14253 } 14254 this.exprAllowed = true; 14255}; 14256 14257types$1.name.updateContext = function(prevType) { 14258 var allowed = false; 14259 if (this.options.ecmaVersion >= 6 && prevType !== types$1.dot) { 14260 if (this.value === "of" && !this.exprAllowed || 14261 this.value === "yield" && this.inGeneratorContext()) 14262 { allowed = true; } 14263 } 14264 this.exprAllowed = allowed; 14265}; 14266 14267// A recursive descent parser operates by defining functions for all 14268 14269var pp$5 = Parser.prototype; 14270 14271// Check if property name clashes with already added. 14272// Object/class getters and setters are not allowed to clash â 14273// either with each other or with an init property â and in 14274// strict mode, init properties are also not allowed to be repeated. 14275 14276pp$5.checkPropClash = function(prop, propHash, refDestructuringErrors) { 14277 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement") 14278 { return } 14279 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) 14280 { return } 14281 var key = prop.key; 14282 var name; 14283 switch (key.type) { 14284 case "Identifier": name = key.name; break 14285 case "Literal": name = String(key.value); break 14286 default: return 14287 } 14288 var kind = prop.kind; 14289 if (this.options.ecmaVersion >= 6) { 14290 if (name === "__proto__" && kind === "init") { 14291 if (propHash.proto) { 14292 if (refDestructuringErrors) { 14293 if (refDestructuringErrors.doubleProto < 0) { 14294 refDestructuringErrors.doubleProto = key.start; 14295 } 14296 } else { 14297 this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); 14298 } 14299 } 14300 propHash.proto = true; 14301 } 14302 return 14303 } 14304 name = "$" + name; 14305 var other = propHash[name]; 14306 if (other) { 14307 var redefinition; 14308 if (kind === "init") { 14309 redefinition = this.strict && other.init || other.get || other.set; 14310 } else { 14311 redefinition = other.init || other[kind]; 14312 } 14313 if (redefinition) 14314 { this.raiseRecoverable(key.start, "Redefinition of property"); } 14315 } else { 14316 other = propHash[name] = { 14317 init: false, 14318 get: false, 14319 set: false 14320 }; 14321 } 14322 other[kind] = true; 14323}; 14324 14325// ### Expression parsing 14326 14327// These nest, from the most general expression type at the top to 14328// 'atomic', nondivisible expression types at the bottom. Most of 14329// the functions will simply let the function(s) below them parse, 14330// and, *if* the syntactic construct they handle is present, wrap 14331// the AST node that the inner parser gave them in another node. 14332 14333// Parse a full expression. The optional arguments are used to 14334// forbid the `in` operator (in for loops initalization expressions) 14335// and provide reference for storing '=' operator inside shorthand 14336// property assignment in contexts where both object expression 14337// and object pattern might appear (so it's possible to raise 14338// delayed syntax error at correct position). 14339 14340pp$5.parseExpression = function(forInit, refDestructuringErrors) { 14341 var startPos = this.start, startLoc = this.startLoc; 14342 var expr = this.parseMaybeAssign(forInit, refDestructuringErrors); 14343 if (this.type === types$1.comma) { 14344 var node = this.startNodeAt(startPos, startLoc); 14345 node.expressions = [expr]; 14346 while (this.eat(types$1.comma)) { node.expressions.push(this.parseMaybeAssign(forInit, refDestructuringErrors)); } 14347 return this.finishNode(node, "SequenceExpression") 14348 } 14349 return expr
vendor: 1,788 bytes, lines 14349-14389
14349 14350}; 14351 14352// Parse an assignment expression. This includes applications of 14353// operators like `+=`. 14354 14355pp$5.parseMaybeAssign = function(forInit, refDestructuringErrors, afterLeftParse) { 14356 if (this.isContextual("yield")) { 14357 if (this.inGenerator) { return this.parseYield(forInit) } 14358 // The tokenizer will assume an expression is allowed after 14359 // `yield`, but this isn't that kind of yield 14360 else { this.exprAllowed = false; } 14361 } 14362 14363 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1, oldDoubleProto = -1; 14364 if (refDestructuringErrors) { 14365 oldParenAssign = refDestructuringErrors.parenthesizedAssign; 14366 oldTrailingComma = refDestructuringErrors.trailingComma; 14367 oldDoubleProto = refDestructuringErrors.doubleProto; 14368 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1; 14369 } else { 14370 refDestructuringErrors = new DestructuringErrors; 14371 ownDestructuringErrors = true; 14372 } 14373 14374 var startPos = this.start, startLoc = this.startLoc; 14375 if (this.type === types$1.parenL || this.type === types$1.name) { 14376 this.potentialArrowAt = this.start; 14377 this.potentialArrowInForAwait = forInit === "await"; 14378 } 14379 var left = this.parseMaybeConditional(forInit, refDestructuringErrors); 14380 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); } 14381 if (this.type.isAssign) { 14382 var node = this.startNodeAt(startPos, startLoc); 14383 node.operator = this.value; 14384 if (this.type === types$1.eq) 14385 { left = this.toAssignable(left, false, refDestructuringErrors); } 14386 if (!ownDestructuringErrors) { 14387 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1; 14388 } 14389 if (refDestructuringErrors.shorthandAssign >= left.start)
vendor: 5,168 bytes, lines 14390-14497
14390 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly 14391 if (this.type === types$1.eq) 14392 { this.checkLValPattern(left); } 14393 else 14394 { this.checkLValSimple(left); } 14395 node.left = left; 14396 this.next(); 14397 node.right = this.parseMaybeAssign(forInit); 14398 if (oldDoubleProto > -1) { refDestructuringErrors.doubleProto = oldDoubleProto; } 14399 return this.finishNode(node, "AssignmentExpression") 14400 } else { 14401 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); } 14402 } 14403 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; } 14404 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; } 14405 return left 14406}; 14407 14408// Parse a ternary conditional (`?:`) operator. 14409 14410pp$5.parseMaybeConditional = function(forInit, refDestructuringErrors) { 14411 var startPos = this.start, startLoc = this.startLoc; 14412 var expr = this.parseExprOps(forInit, refDestructuringErrors); 14413 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } 14414 if (this.eat(types$1.question)) { 14415 var node = this.startNodeAt(startPos, startLoc); 14416 node.test = expr; 14417 node.consequent = this.parseMaybeAssign(); 14418 this.expect(types$1.colon); 14419 node.alternate = this.parseMaybeAssign(forInit); 14420 return this.finishNode(node, "ConditionalExpression") 14421 } 14422 return expr 14423}; 14424 14425// Start the precedence parser. 14426 14427pp$5.parseExprOps = function(forInit, refDestructuringErrors) { 14428 var startPos = this.start, startLoc = this.startLoc; 14429 var expr = this.parseMaybeUnary(refDestructuringErrors, false, false, forInit); 14430 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } 14431 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, forInit) 14432}; 14433 14434// Parse binary operators with the operator precedence parsing 14435// algorithm. `left` is the left-hand side of the operator. 14436// `minPrec` provides context that allows the function to stop and 14437// defer further parser to one of its callers when it encounters an 14438// operator that has a lower precedence than the set it is parsing. 14439 14440pp$5.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, forInit) { 14441 var prec = this.type.binop; 14442 if (prec != null && (!forInit || this.type !== types$1._in)) { 14443 if (prec > minPrec) { 14444 var logical = this.type === types$1.logicalOR || this.type === types$1.logicalAND; 14445 var coalesce = this.type === types$1.coalesce; 14446 if (coalesce) { 14447 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions. 14448 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error. 14449 prec = types$1.logicalAND.binop; 14450 } 14451 var op = this.value; 14452 this.next(); 14453 var startPos = this.start, startLoc = this.startLoc; 14454 var right = this.parseExprOp(this.parseMaybeUnary(null, false, false, forInit), startPos, startLoc, prec, forInit); 14455 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce); 14456 if ((logical && this.type === types$1.coalesce) || (coalesce && (this.type === types$1.logicalOR || this.type === types$1.logicalAND))) { 14457 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses"); 14458 } 14459 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, forInit) 14460 } 14461 } 14462 return left 14463}; 14464 14465pp$5.buildBinary = function(startPos, startLoc, left, right, op, logical) { 14466 if (right.type === "PrivateIdentifier") { this.raise(right.start, "Private identifier can only be left side of binary expression"); } 14467 var node = this.startNodeAt(startPos, startLoc); 14468 node.left = left; 14469 node.operator = op; 14470 node.right = right; 14471 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression") 14472}; 14473 14474// Parse unary operators, both prefix and postfix. 14475 14476pp$5.parseMaybeUnary = function(refDestructuringErrors, sawUnary, incDec, forInit) { 14477 var startPos = this.start, startLoc = this.startLoc, expr; 14478 if (this.isContextual("await") && this.canAwait) { 14479 expr = this.parseAwait(forInit); 14480 sawUnary = true; 14481 } else if (this.type.prefix) { 14482 var node = this.startNode(), update = this.type === types$1.incDec; 14483 node.operator = this.value; 14484 node.prefix = true; 14485 this.next(); 14486 node.argument = this.parseMaybeUnary(null, true, update, forInit); 14487 this.checkExpressionErrors(refDestructuringErrors, true); 14488 if (update) { this.checkLValSimple(node.argument); } 14489 else if (this.strict && node.operator === "delete" && 14490 node.argument.type === "Identifier") 14491 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); } 14492 else if (node.operator === "delete" && isPrivateFieldAccess(node.argument)) 14493 { this.raiseRecoverable(node.start, "Private fields can not be deleted"); } 14494 else { sawUnary = true; } 14495 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); 14496 } else if (!sawUnary && this.type === types$1.privateId) { 14497 if (
vendor: 12,750 bytes, lines 14497-14824
14497forInit || this.privateNameStack.length === 0) { this.unexpected(); } 14498 expr = this.parsePrivateIdent(); 14499 // only could be private fields in 'in', such as #x in obj 14500 if (this.type !== types$1._in) { this.unexpected(); } 14501 } else { 14502 expr = this.parseExprSubscripts(refDestructuringErrors, forInit); 14503 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr } 14504 while (this.type.postfix && !this.canInsertSemicolon()) { 14505 var node$1 = this.startNodeAt(startPos, startLoc); 14506 node$1.operator = this.value; 14507 node$1.prefix = false; 14508 node$1.argument = expr; 14509 this.checkLValSimple(expr); 14510 this.next(); 14511 expr = this.finishNode(node$1, "UpdateExpression"); 14512 } 14513 } 14514 14515 if (!incDec && this.eat(types$1.starstar)) { 14516 if (sawUnary) 14517 { this.unexpected(this.lastTokStart); } 14518 else 14519 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false, false, forInit), "**", false) } 14520 } else { 14521 return expr 14522 } 14523}; 14524 14525function isPrivateFieldAccess(node) { 14526 return ( 14527 node.type === "MemberExpression" && node.property.type === "PrivateIdentifier" || 14528 node.type === "ChainExpression" && isPrivateFieldAccess(node.expression) 14529 ) 14530} 14531 14532// Parse call, dot, and `[]`-subscript expressions. 14533 14534pp$5.parseExprSubscripts = function(refDestructuringErrors, forInit) { 14535 var startPos = this.start, startLoc = this.startLoc; 14536 var expr = this.parseExprAtom(refDestructuringErrors, forInit); 14537 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")") 14538 { return expr } 14539 var result = this.parseSubscripts(expr, startPos, startLoc, false, forInit); 14540 if (refDestructuringErrors && result.type === "MemberExpression") { 14541 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; } 14542 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; } 14543 if (refDestructuringErrors.trailingComma >= result.start) { refDestructuringErrors.trailingComma = -1; } 14544 } 14545 return result 14546}; 14547 14548pp$5.parseSubscripts = function(base, startPos, startLoc, noCalls, forInit) { 14549 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" && 14550 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 && 14551 this.potentialArrowAt === base.start; 14552 var optionalChained = false; 14553 14554 while (true) { 14555 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit); 14556 14557 if (element.optional) { optionalChained = true; } 14558 if (element === base || element.type === "ArrowFunctionExpression") { 14559 if (optionalChained) { 14560 var chainNode = this.startNodeAt(startPos, startLoc); 14561 chainNode.expression = element; 14562 element = this.finishNode(chainNode, "ChainExpression"); 14563 } 14564 return element 14565 } 14566 14567 base = element; 14568 } 14569}; 14570 14571pp$5.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained, forInit) { 14572 var optionalSupported = this.options.ecmaVersion >= 11; 14573 var optional = optionalSupported && this.eat(types$1.questionDot); 14574 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); } 14575 14576 var computed = this.eat(types$1.bracketL); 14577 if (computed || (optional && this.type !== types$1.parenL && this.type !== types$1.backQuote) || this.eat(types$1.dot)) { 14578 var node = this.startNodeAt(startPos, startLoc); 14579 node.object = base; 14580 if (computed) { 14581 node.property = this.parseExpression(); 14582 this.expect(types$1.bracketR); 14583 } else if (this.type === types$1.privateId && base.type !== "Super") { 14584 node.property = this.parsePrivateIdent(); 14585 } else { 14586 node.property = this.parseIdent(this.options.allowReserved !== "never"); 14587 } 14588 node.computed = !!computed; 14589 if (optionalSupported) { 14590 node.optional = optional; 14591 } 14592 base = this.finishNode(node, "MemberExpression"); 14593 } else if (!noCalls && this.eat(types$1.parenL)) { 14594 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; 14595 this.yieldPos = 0; 14596 this.awaitPos = 0; 14597 this.awaitIdentPos = 0; 14598 var exprList = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors); 14599 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types$1.arrow)) { 14600 this.checkPatternErrors(refDestructuringErrors, false); 14601 this.checkYieldAwaitInDefaultParams(); 14602 if (this.awaitIdentPos > 0) 14603 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); } 14604 this.yieldPos = oldYieldPos; 14605 this.awaitPos = oldAwaitPos; 14606 this.awaitIdentPos = oldAwaitIdentPos; 14607 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true, forInit) 14608 } 14609 this.checkExpressionErrors(refDestructuringErrors, true); 14610 this.yieldPos = oldYieldPos || this.yieldPos; 14611 this.awaitPos = oldAwaitPos || this.awaitPos; 14612 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos; 14613 var node$1 = this.startNodeAt(startPos, startLoc); 14614 node$1.callee = base; 14615 node$1.arguments = exprList; 14616 if (optionalSupported) { 14617 node$1.optional = optional; 14618 } 14619 base = this.finishNode(node$1, "CallExpression"); 14620 } else if (this.type === types$1.backQuote) { 14621 if (optional || optionalChained) { 14622 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions"); 14623 } 14624 var node$2 = this.startNodeAt(startPos, startLoc); 14625 node$2.tag = base; 14626 node$2.quasi = this.parseTemplate({isTagged: true}); 14627 base = this.finishNode(node$2, "TaggedTemplateExpression"); 14628 } 14629 return base 14630}; 14631 14632// Parse an atomic expression â either a single token that is an 14633// expression, an expression started by a keyword like `function` or 14634// `new`, or an expression wrapped in punctuation like `()`, `[]`, 14635// or `{}`. 14636 14637pp$5.parseExprAtom = function(refDestructuringErrors, forInit) { 14638 // If a division operator appears in an expression position, the 14639 // tokenizer got confused, and we force it to read a regexp instead. 14640 if (this.type === types$1.slash) { this.readRegexp(); } 14641 14642 var node, canBeArrow = this.potentialArrowAt === this.start; 14643 switch (this.type) { 14644 case types$1._super: 14645 if (!this.allowSuper) 14646 { this.raise(this.start, "'super' keyword outside a method"); } 14647 node = this.startNode(); 14648 this.next(); 14649 if (this.type === types$1.parenL && !this.allowDirectSuper) 14650 { this.raise(node.start, "super() call outside constructor of a subclass"); } 14651 // The `super` keyword can appear at below: 14652 // SuperProperty: 14653 // super [ Expression ] 14654 // super . IdentifierName 14655 // SuperCall: 14656 // super ( Arguments ) 14657 if (this.type !== types$1.dot && this.type !== types$1.bracketL && this.type !== types$1.parenL) 14658 { this.unexpected(); } 14659 return this.finishNode(node, "Super") 14660 14661 case types$1._this: 14662 node = this.startNode(); 14663 this.next(); 14664 return this.finishNode(node, "ThisExpression") 14665 14666 case types$1.name: 14667 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc; 14668 var id = this.parseIdent(false); 14669 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types$1._function)) { 14670 this.overrideContext(types.f_expr); 14671 return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true, forInit) 14672 } 14673 if (canBeArrow && !this.canInsertSemicolon()) { 14674 if (this.eat(types$1.arrow)) 14675 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false, forInit) } 14676 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types$1.name && !containsEsc && 14677 (!this.potentialArrowInForAwait || this.value !== "of" || this.containsEsc)) { 14678 id = this.parseIdent(false); 14679 if (this.canInsertSemicolon() || !this.eat(types$1.arrow)) 14680 { this.unexpected(); } 14681 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true, forInit) 14682 } 14683 } 14684 return id 14685 14686 case types$1.regexp: 14687 var value = this.value; 14688 node = this.parseLiteral(value.value); 14689 node.regex = {pattern: value.pattern, flags: value.flags}; 14690 return node 14691 14692 case types$1.num: case types$1.string: 14693 return this.parseLiteral(this.value) 14694 14695 case types$1._null: case types$1._true: case types$1._false: 14696 node = this.startNode(); 14697 node.value = this.type === types$1._null ? null : this.type === types$1._true; 14698 node.raw = this.type.keyword; 14699 this.next(); 14700 return this.finishNode(node, "Literal") 14701 14702 case types$1.parenL: 14703 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow, forInit); 14704 if (refDestructuringErrors) { 14705 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr)) 14706 { refDestructuringErrors.parenthesizedAssign = start; } 14707 if (refDestructuringErrors.parenthesizedBind < 0) 14708 { refDestructuringErrors.parenthesizedBind = start; } 14709 } 14710 return expr 14711 14712 case types$1.bracketL: 14713 node = this.startNode(); 14714 this.next(); 14715 node.elements = this.parseExprList(types$1.bracketR, true, true, refDestructuringErrors); 14716 return this.finishNode(node, "ArrayExpression") 14717 14718 case types$1.braceL: 14719 this.overrideContext(types.b_expr); 14720 return this.parseObj(false, refDestructuringErrors) 14721 14722 case types$1._function: 14723 node = this.startNode(); 14724 this.next(); 14725 return this.parseFunction(node, 0) 14726 14727 case types$1._class: 14728 return this.parseClass(this.startNode(), false) 14729 14730 case types$1._new: 14731 return this.parseNew() 14732 14733 case types$1.backQuote: 14734 return this.parseTemplate() 14735 14736 case types$1._import: 14737 if (this.options.ecmaVersion >= 11) { 14738 return this.parseExprImport() 14739 } else { 14740 return this.unexpected() 14741 } 14742 14743 default: 14744 this.unexpected(); 14745 } 14746}; 14747 14748pp$5.parseExprImport = function() { 14749 var node = this.startNode(); 14750 14751 // Consume `import` as an identifier for `import.meta`. 14752 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`. 14753 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); } 14754 var meta = this.parseIdent(true); 14755 14756 switch (this.type) { 14757 case types$1.parenL: 14758 return this.parseDynamicImport(node) 14759 case types$1.dot: 14760 node.meta = meta; 14761 return this.parseImportMeta(node) 14762 default: 14763 this.unexpected(); 14764 } 14765}; 14766 14767pp$5.parseDynamicImport = function(node) { 14768 this.next(); // skip `(` 14769 14770 // Parse node.source. 14771 node.source = this.parseMaybeAssign(); 14772 14773 // Verify ending. 14774 if (!this.eat(types$1.parenR)) { 14775 var errorPos = this.start; 14776 if (this.eat(types$1.comma) && this.eat(types$1.parenR)) { 14777 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()"); 14778 } else { 14779 this.unexpected(errorPos); 14780 } 14781 } 14782 14783 return this.finishNode(node, "ImportExpression") 14784}; 14785 14786pp$5.parseImportMeta = function(node) { 14787 this.next(); // skip `.` 14788 14789 var containsEsc = this.containsEsc; 14790 node.property = this.parseIdent(true); 14791 14792 if (node.property.name !== "meta") 14793 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); } 14794 if (containsEsc) 14795 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); } 14796 if (this.options.sourceType !== "module" && !this.options.allowImportExportEverywhere) 14797 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); } 14798 14799 return this.finishNode(node, "MetaProperty") 14800}; 14801 14802pp$5.parseLiteral = function(value) { 14803 var node = this.startNode(); 14804 node.value = value; 14805 node.raw = this.input.slice(this.start, this.end); 14806 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); } 14807 this.next(); 14808 return this.finishNode(node, "Literal") 14809}; 14810 14811pp$5.parseParenExpression = function() { 14812 this.expect(types$1.parenL); 14813 var val = this.parseExpression(); 14814 this.expect(types$1.parenR); 14815 return val 14816}; 14817 14818pp$5.parseParenAndDistinguishExpression = function(canBeArrow, forInit) { 14819 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8; 14820 if (this.options.ecmaVersion >= 6) { 14821 this.next(); 14822 14823 var innerStartPos = this.start, innerStartLoc = this.startLoc; 14824 var exprList = [], first = true, lastIsComma = false;
vendor: 3,837 bytes, lines 14825-14916
14825 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart; 14826 this.yieldPos = 0; 14827 this.awaitPos = 0; 14828 // Do not save awaitIdentPos to allow checking awaits nested in parameters 14829 while (this.type !== types$1.parenR) { 14830 first ? first = false : this.expect(types$1.comma); 14831 if (allowTrailingComma && this.afterTrailingComma(types$1.parenR, true)) { 14832 lastIsComma = true; 14833 break 14834 } else if (this.type === types$1.ellipsis) { 14835 spreadStart = this.start; 14836 exprList.push(this.parseParenItem(this.parseRestBinding())); 14837 if (this.type === types$1.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); } 14838 break 14839 } else { 14840 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem)); 14841 } 14842 } 14843 var innerEndPos = this.lastTokEnd, innerEndLoc = this.lastTokEndLoc; 14844 this.expect(types$1.parenR); 14845 14846 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types$1.arrow)) { 14847 this.checkPatternErrors(refDestructuringErrors, false); 14848 this.checkYieldAwaitInDefaultParams(); 14849 this.yieldPos = oldYieldPos; 14850 this.awaitPos = oldAwaitPos; 14851 return this.parseParenArrowList(startPos, startLoc, exprList, forInit) 14852 } 14853 14854 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); } 14855 if (spreadStart) { this.unexpected(spreadStart); } 14856 this.checkExpressionErrors(refDestructuringErrors, true); 14857 this.yieldPos = oldYieldPos || this.yieldPos; 14858 this.awaitPos = oldAwaitPos || this.awaitPos; 14859 14860 if (exprList.length > 1) { 14861 val = this.startNodeAt(innerStartPos, innerStartLoc); 14862 val.expressions = exprList; 14863 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc); 14864 } else { 14865 val = exprList[0]; 14866 } 14867 } else { 14868 val = this.parseParenExpression(); 14869 } 14870 14871 if (this.options.preserveParens) { 14872 var par = this.startNodeAt(startPos, startLoc); 14873 par.expression = val; 14874 return this.finishNode(par, "ParenthesizedExpression") 14875 } else { 14876 return val 14877 } 14878}; 14879 14880pp$5.parseParenItem = function(item) { 14881 return item 14882}; 14883 14884pp$5.parseParenArrowList = function(startPos, startLoc, exprList, forInit) { 14885 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, false, forInit) 14886}; 14887 14888// New's precedence is slightly tricky. It must allow its argument to 14889// be a `[]` or dot subscript expression, but not a call â at least, 14890// not without wrapping it in parentheses. Thus, it uses the noCalls 14891// argument to parseSubscripts to prevent it from consuming the 14892// argument list. 14893 14894var empty = []; 14895 14896pp$5.parseNew = function() { 14897 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); } 14898 var node = this.startNode(); 14899 var meta = this.parseIdent(true); 14900 if (this.options.ecmaVersion >= 6 && this.eat(types$1.dot)) { 14901 node.meta = meta; 14902 var containsEsc = this.containsEsc; 14903 node.property = this.parseIdent(true); 14904 if (node.property.name !== "target") 14905 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); } 14906 if (containsEsc) 14907 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); } 14908 if (!this.allowNewDotTarget) 14909 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions and class static block"); } 14910 return this.finishNode(node, "MetaProperty") 14911 } 14912 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types$1._import; 14913 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true, false); 14914 if (isImport && node.callee.type === "ImportExpression") { 14915 this.raise(startPos, "Cannot use new with import()"); 14916 }
vendor: 2,998 bytes, lines 14916-14998
14916 14917 if (this.eat(types$1.parenL)) { node.arguments = this.parseExprList(types$1.parenR, this.options.ecmaVersion >= 8, false); } 14918 else { node.arguments = empty; } 14919 return this.finishNode(node, "NewExpression") 14920}; 14921 14922// Parse template expression. 14923 14924pp$5.parseTemplateElement = function(ref) { 14925 var isTagged = ref.isTagged; 14926 14927 var elem = this.startNode(); 14928 if (this.type === types$1.invalidTemplate) { 14929 if (!isTagged) { 14930 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal"); 14931 } 14932 elem.value = { 14933 raw: this.value, 14934 cooked: null 14935 }; 14936 } else { 14937 elem.value = { 14938 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"), 14939 cooked: this.value 14940 }; 14941 } 14942 this.next(); 14943 elem.tail = this.type === types$1.backQuote; 14944 return this.finishNode(elem, "TemplateElement") 14945}; 14946 14947pp$5.parseTemplate = function(ref) { 14948 if ( ref === void 0 ) ref = {}; 14949 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false; 14950 14951 var node = this.startNode(); 14952 this.next(); 14953 node.expressions = []; 14954 var curElt = this.parseTemplateElement({isTagged: isTagged}); 14955 node.quasis = [curElt]; 14956 while (!curElt.tail) { 14957 if (this.type === types$1.eof) { this.raise(this.pos, "Unterminated template literal"); } 14958 this.expect(types$1.dollarBraceL); 14959 node.expressions.push(this.parseExpression()); 14960 this.expect(types$1.braceR); 14961 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged})); 14962 } 14963 this.next(); 14964 return this.finishNode(node, "TemplateLiteral") 14965}; 14966 14967pp$5.isAsyncProp = function(prop) { 14968 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" && 14969 (this.type === types$1.name || this.type === types$1.num || this.type === types$1.string || this.type === types$1.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types$1.star)) && 14970 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) 14971}; 14972 14973// Parse an object literal or binding pattern. 14974 14975pp$5.parseObj = function(isPattern, refDestructuringErrors) { 14976 var node = this.startNode(), first = true, propHash = {}; 14977 node.properties = []; 14978 this.next(); 14979 while (!this.eat(types$1.braceR)) { 14980 if (!first) { 14981 this.expect(types$1.comma); 14982 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types$1.braceR)) { break } 14983 } else { first = false; } 14984 14985 var prop = this.parseProperty(isPattern, refDestructuringErrors); 14986 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); } 14987 node.properties.push(prop); 14988 } 14989 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression") 14990}; 14991 14992pp$5.parseProperty = function(isPattern, refDestructuringErrors) { 14993 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc; 14994 if (this.options.ecmaVersion >= 9 && this.eat(types$1.ellipsis)) { 14995 if (isPattern) { 14996 prop.argument = this.parseIdent(false); 14997 if (this.type === types$1.comma) { 14998 this.raise
vendor: 2,810 bytes, lines 14998-15061
14998(this.start, "Comma is not permitted after the rest element"); 14999 } 15000 return this.finishNode(prop, "RestElement") 15001 } 15002 // Parse argument. 15003 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors); 15004 // To disallow trailing comma via `this.toAssignable()`. 15005 if (this.type === types$1.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) { 15006 refDestructuringErrors.trailingComma = this.start; 15007 } 15008 // Finish 15009 return this.finishNode(prop, "SpreadElement") 15010 } 15011 if (this.options.ecmaVersion >= 6) { 15012 prop.method = false; 15013 prop.shorthand = false; 15014 if (isPattern || refDestructuringErrors) { 15015 startPos = this.start; 15016 startLoc = this.startLoc; 15017 } 15018 if (!isPattern) 15019 { isGenerator = this.eat(types$1.star); } 15020 } 15021 var containsEsc = this.containsEsc; 15022 this.parsePropertyName(prop); 15023 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) { 15024 isAsync = true; 15025 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types$1.star); 15026 this.parsePropertyName(prop, refDestructuringErrors); 15027 } else { 15028 isAsync = false; 15029 } 15030 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc); 15031 return this.finishNode(prop, "Property") 15032}; 15033 15034pp$5.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) { 15035 if ((isGenerator || isAsync) && this.type === types$1.colon) 15036 { this.unexpected(); } 15037 15038 if (this.eat(types$1.colon)) { 15039 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors); 15040 prop.kind = "init"; 15041 } else if (this.options.ecmaVersion >= 6 && this.type === types$1.parenL) { 15042 if (isPattern) { this.unexpected(); } 15043 prop.kind = "init"; 15044 prop.method = true; 15045 prop.value = this.parseMethod(isGenerator, isAsync); 15046 } else if (!isPattern && !containsEsc && 15047 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && 15048 (prop.key.name === "get" || prop.key.name === "set") && 15049 (this.type !== types$1.comma && this.type !== types$1.braceR && this.type !== types$1.eq)) { 15050 if (isGenerator || isAsync) { this.unexpected(); } 15051 prop.kind = prop.key.name; 15052 this.parsePropertyName(prop); 15053 prop.value = this.parseMethod(false); 15054 var paramCount = prop.kind === "get" ? 0 : 1; 15055 if (prop.value.params.length !== paramCount) { 15056 var start = prop.value.start; 15057 if (prop.kind === "get") 15058 { this.raiseRecoverable(start, "getter should have no params"); } 15059 else 15060 { this.raiseRecoverable(start, "setter should have exactly one param"); } 15061 } else {
vendor: 22,528 bytes, lines 15062-15584
15062 if (prop.kind === "set" && prop.value.params[0].type === "RestElement") 15063 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); } 15064 } 15065 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") { 15066 if (isGenerator || isAsync) { this.unexpected(); } 15067 this.checkUnreserved(prop.key); 15068 if (prop.key.name === "await" && !this.awaitIdentPos) 15069 { this.awaitIdentPos = startPos; } 15070 prop.kind = "init"; 15071 if (isPattern) { 15072 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); 15073 } else if (this.type === types$1.eq && refDestructuringErrors) { 15074 if (refDestructuringErrors.shorthandAssign < 0) 15075 { refDestructuringErrors.shorthandAssign = this.start; } 15076 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key)); 15077 } else { 15078 prop.value = this.copyNode(prop.key); 15079 } 15080 prop.shorthand = true; 15081 } else { this.unexpected(); } 15082}; 15083 15084pp$5.parsePropertyName = function(prop) { 15085 if (this.options.ecmaVersion >= 6) { 15086 if (this.eat(types$1.bracketL)) { 15087 prop.computed = true; 15088 prop.key = this.parseMaybeAssign(); 15089 this.expect(types$1.bracketR); 15090 return prop.key 15091 } else { 15092 prop.computed = false; 15093 } 15094 } 15095 return prop.key = this.type === types$1.num || this.type === types$1.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never") 15096}; 15097 15098// Initialize empty function node. 15099 15100pp$5.initFunction = function(node) { 15101 node.id = null; 15102 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; } 15103 if (this.options.ecmaVersion >= 8) { node.async = false; } 15104}; 15105 15106// Parse object or class method. 15107 15108pp$5.parseMethod = function(isGenerator, isAsync, allowDirectSuper) { 15109 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; 15110 15111 this.initFunction(node); 15112 if (this.options.ecmaVersion >= 6) 15113 { node.generator = isGenerator; } 15114 if (this.options.ecmaVersion >= 8) 15115 { node.async = !!isAsync; } 15116 15117 this.yieldPos = 0; 15118 this.awaitPos = 0; 15119 this.awaitIdentPos = 0; 15120 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0)); 15121 15122 this.expect(types$1.parenL); 15123 node.params = this.parseBindingList(types$1.parenR, false, this.options.ecmaVersion >= 8); 15124 this.checkYieldAwaitInDefaultParams(); 15125 this.parseFunctionBody(node, false, true, false); 15126 15127 this.yieldPos = oldYieldPos; 15128 this.awaitPos = oldAwaitPos; 15129 this.awaitIdentPos = oldAwaitIdentPos; 15130 return this.finishNode(node, "FunctionExpression") 15131}; 15132 15133// Parse arrow function expression with given parameters. 15134 15135pp$5.parseArrowExpression = function(node, params, isAsync, forInit) { 15136 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos; 15137 15138 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW); 15139 this.initFunction(node); 15140 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; } 15141 15142 this.yieldPos = 0; 15143 this.awaitPos = 0; 15144 this.awaitIdentPos = 0; 15145 15146 node.params = this.toAssignableList(params, true); 15147 this.parseFunctionBody(node, true, false, forInit); 15148 15149 this.yieldPos = oldYieldPos; 15150 this.awaitPos = oldAwaitPos; 15151 this.awaitIdentPos = oldAwaitIdentPos; 15152 return this.finishNode(node, "ArrowFunctionExpression") 15153}; 15154 15155// Parse function body and check parameters. 15156 15157pp$5.parseFunctionBody = function(node, isArrowFunction, isMethod, forInit) { 15158 var isExpression = isArrowFunction && this.type !== types$1.braceL; 15159 var oldStrict = this.strict, useStrict = false; 15160 15161 if (isExpression) { 15162 node.body = this.parseMaybeAssign(forInit); 15163 node.expression = true; 15164 this.checkParams(node, false); 15165 } else { 15166 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params); 15167 if (!oldStrict || nonSimple) { 15168 useStrict = this.strictDirective(this.end); 15169 // If this is a strict mode function, verify that argument names 15170 // are not repeated, and it does not try to bind the words `eval` 15171 // or `arguments`. 15172 if (useStrict && nonSimple) 15173 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); } 15174 } 15175 // Start a new scope with regard to labels and the `inFunction` 15176 // flag (restore them to their old value afterwards). 15177 var oldLabels = this.labels; 15178 this.labels = []; 15179 if (useStrict) { this.strict = true; } 15180 15181 // Add the params to varDeclaredNames to ensure that an error is thrown 15182 // if a let/const declaration in the function clashes with one of the params. 15183 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params)); 15184 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval' 15185 if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); } 15186 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict); 15187 node.expression = false; 15188 this.adaptDirectivePrologue(node.body.body); 15189 this.labels = oldLabels; 15190 } 15191 this.exitScope(); 15192}; 15193 15194pp$5.isSimpleParamList = function(params) { 15195 for (var i = 0, list = params; i < list.length; i += 1) 15196 { 15197 var param = list[i]; 15198 15199 if (param.type !== "Identifier") { return false 15200 } } 15201 return true 15202}; 15203 15204// Checks function params for various disallowed patterns such as using "eval" 15205// or "arguments" and duplicate parameters. 15206 15207pp$5.checkParams = function(node, allowDuplicates) { 15208 var nameHash = Object.create(null); 15209 for (var i = 0, list = node.params; i < list.length; i += 1) 15210 { 15211 var param = list[i]; 15212 15213 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash); 15214 } 15215}; 15216 15217// Parses a comma-separated list of expressions, and returns them as 15218// an array. `close` is the token type that ends the list, and 15219// `allowEmpty` can be turned on to allow subsequent commas with 15220// nothing in between them to be parsed as `null` (which is needed 15221// for array literals). 15222 15223pp$5.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) { 15224 var elts = [], first = true; 15225 while (!this.eat(close)) { 15226 if (!first) { 15227 this.expect(types$1.comma); 15228 if (allowTrailingComma && this.afterTrailingComma(close)) { break } 15229 } else { first = false; } 15230 15231 var elt = (void 0); 15232 if (allowEmpty && this.type === types$1.comma) 15233 { elt = null; } 15234 else if (this.type === types$1.ellipsis) { 15235 elt = this.parseSpread(refDestructuringErrors); 15236 if (refDestructuringErrors && this.type === types$1.comma && refDestructuringErrors.trailingComma < 0) 15237 { refDestructuringErrors.trailingComma = this.start; } 15238 } else { 15239 elt = this.parseMaybeAssign(false, refDestructuringErrors); 15240 } 15241 elts.push(elt); 15242 } 15243 return elts 15244}; 15245 15246pp$5.checkUnreserved = function(ref) { 15247 var start = ref.start; 15248 var end = ref.end; 15249 var name = ref.name; 15250 15251 if (this.inGenerator && name === "yield") 15252 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); } 15253 if (this.inAsync && name === "await") 15254 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); } 15255 if (this.currentThisScope().inClassFieldInit && name === "arguments") 15256 { this.raiseRecoverable(start, "Cannot use 'arguments' in class field initializer"); } 15257 if (this.inClassStaticBlock && (name === "arguments" || name === "await")) 15258 { this.raise(start, ("Cannot use " + name + " in class static initialization block")); } 15259 if (this.keywords.test(name)) 15260 { this.raise(start, ("Unexpected keyword '" + name + "'")); } 15261 if (this.options.ecmaVersion < 6 && 15262 this.input.slice(start, end).indexOf("\\") !== -1) { return } 15263 var re = this.strict ? this.reservedWordsStrict : this.reservedWords; 15264 if (re.test(name)) { 15265 if (!this.inAsync && name === "await") 15266 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); } 15267 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved")); 15268 } 15269}; 15270 15271// Parse the next token as an identifier. If `liberal` is true (used 15272// when parsing properties), it will also convert keywords into 15273// identifiers. 15274 15275pp$5.parseIdent = function(liberal, isBinding) { 15276 var node = this.startNode(); 15277 if (this.type === types$1.name) { 15278 node.name = this.value; 15279 } else if (this.type.keyword) { 15280 node.name = this.type.keyword; 15281 15282 // To fix https://github.com/acornjs/acorn/issues/575 15283 // `class` and `function` keywords push new context into this.context. 15284 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name. 15285 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword 15286 if ((node.name === "class" || node.name === "function") && 15287 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) { 15288 this.context.pop(); 15289 } 15290 } else { 15291 this.unexpected(); 15292 } 15293 this.next(!!liberal); 15294 this.finishNode(node, "Identifier"); 15295 if (!liberal) { 15296 this.checkUnreserved(node); 15297 if (node.name === "await" && !this.awaitIdentPos) 15298 { this.awaitIdentPos = node.start; } 15299 } 15300 return node 15301}; 15302 15303pp$5.parsePrivateIdent = function() { 15304 var node = this.startNode(); 15305 if (this.type === types$1.privateId) { 15306 node.name = this.value; 15307 } else { 15308 this.unexpected(); 15309 } 15310 this.next(); 15311 this.finishNode(node, "PrivateIdentifier"); 15312 15313 // For validating existence 15314 if (this.privateNameStack.length === 0) { 15315 this.raise(node.start, ("Private field '#" + (node.name) + "' must be declared in an enclosing class")); 15316 } else { 15317 this.privateNameStack[this.privateNameStack.length - 1].used.push(node); 15318 } 15319 15320 return node 15321}; 15322 15323// Parses yield expression inside generator. 15324 15325pp$5.parseYield = function(forInit) { 15326 if (!this.yieldPos) { this.yieldPos = this.start; } 15327 15328 var node = this.startNode(); 15329 this.next(); 15330 if (this.type === types$1.semi || this.canInsertSemicolon() || (this.type !== types$1.star && !this.type.startsExpr)) { 15331 node.delegate = false; 15332 node.argument = null; 15333 } else { 15334 node.delegate = this.eat(types$1.star); 15335 node.argument = this.parseMaybeAssign(forInit); 15336 } 15337 return this.finishNode(node, "YieldExpression") 15338}; 15339 15340pp$5.parseAwait = function(forInit) { 15341 if (!this.awaitPos) { this.awaitPos = this.start; } 15342 15343 var node = this.startNode(); 15344 this.next(); 15345 node.argument = this.parseMaybeUnary(null, true, false, forInit); 15346 return this.finishNode(node, "AwaitExpression") 15347}; 15348 15349var pp$4 = Parser.prototype; 15350 15351// This function is used to raise exceptions on parse errors. It 15352// takes an offset integer (into the current `input`) to indicate 15353// the location of the error, attaches the position to the end 15354// of the error message, and then raises a `SyntaxError` with that 15355// message. 15356 15357pp$4.raise = function(pos, message) { 15358 var loc = getLineInfo(this.input, pos); 15359 message += " (" + loc.line + ":" + loc.column + ")"; 15360 var err = new SyntaxError(message); 15361 err.pos = pos; err.loc = loc; err.raisedAt = this.pos; 15362 throw err 15363}; 15364 15365pp$4.raiseRecoverable = pp$4.raise; 15366 15367pp$4.curPosition = function() { 15368 if (this.options.locations) { 15369 return new Position(this.curLine, this.pos - this.lineStart) 15370 } 15371}; 15372 15373var pp$3 = Parser.prototype; 15374 15375var Scope = function Scope(flags) { 15376 this.flags = flags; 15377 // A list of var-declared names in the current lexical scope 15378 this.var = []; 15379 // A list of lexically-declared names in the current lexical scope 15380 this.lexical = []; 15381 // A list of lexically-declared FunctionDeclaration names in the current lexical scope 15382 this.functions = []; 15383 // A switch to disallow the identifier reference 'arguments' 15384 this.inClassFieldInit = false; 15385}; 15386 15387// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names. 15388 15389pp$3.enterScope = function(flags) { 15390 this.scopeStack.push(new Scope(flags)); 15391}; 15392 15393pp$3.exitScope = function() { 15394 this.scopeStack.pop(); 15395}; 15396 15397// The spec says: 15398// > At the top level of a function, or script, function declarations are 15399// > treated like var declarations rather than like lexical declarations. 15400pp$3.treatFunctionsAsVarInScope = function(scope) { 15401 return (scope.flags & SCOPE_FUNCTION$1) || !this.inModule && (scope.flags & SCOPE_TOP) 15402}; 15403 15404pp$3.declareName = function(name, bindingType, pos) { 15405 var redeclared = false; 15406 if (bindingType === BIND_LEXICAL) { 15407 var scope = this.currentScope(); 15408 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1; 15409 scope.lexical.push(name); 15410 if (this.inModule && (scope.flags & SCOPE_TOP)) 15411 { delete this.undefinedExports[name]; } 15412 } else if (bindingType === BIND_SIMPLE_CATCH) { 15413 var scope$1 = this.currentScope(); 15414 scope$1.lexical.push(name); 15415 } else if (bindingType === BIND_FUNCTION) { 15416 var scope$2 = this.currentScope(); 15417 if (this.treatFunctionsAsVar) 15418 { redeclared = scope$2.lexical.indexOf(name) > -1; } 15419 else 15420 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; } 15421 scope$2.functions.push(name); 15422 } else { 15423 for (var i = this.scopeStack.length - 1; i >= 0; --i) { 15424 var scope$3 = this.scopeStack[i]; 15425 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) || 15426 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) { 15427 redeclared = true; 15428 break 15429 } 15430 scope$3.var.push(name); 15431 if (this.inModule && (scope$3.flags & SCOPE_TOP)) 15432 { delete this.undefinedExports[name]; } 15433 if (scope$3.flags & SCOPE_VAR) { break } 15434 } 15435 } 15436 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); } 15437}; 15438 15439pp$3.checkLocalExport = function(id) { 15440 // scope.functions must be empty as Module code is always strict. 15441 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 && 15442 this.scopeStack[0].var.indexOf(id.name) === -1) { 15443 this.undefinedExports[id.name] = id; 15444 } 15445}; 15446 15447pp$3.currentScope = function() { 15448 return this.scopeStack[this.scopeStack.length - 1] 15449}; 15450 15451pp$3.currentVarScope = function() { 15452 for (var i = this.scopeStack.length - 1;; i--) { 15453 var scope = this.scopeStack[i]; 15454 if (scope.flags & SCOPE_VAR) { return scope } 15455 } 15456}; 15457 15458// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`. 15459pp$3.currentThisScope = function() { 15460 for (var i = this.scopeStack.length - 1;; i--) { 15461 var scope = this.scopeStack[i]; 15462 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope } 15463 } 15464}; 15465 15466var Node$1 = function Node(parser, pos, loc) { 15467 this.type = ""; 15468 this.start = pos; 15469 this.end = 0; 15470 if (parser.options.locations) 15471 { this.loc = new SourceLocation(parser, loc); } 15472 if (parser.options.directSourceFile) 15473 { this.sourceFile = parser.options.directSourceFile; } 15474 if (parser.options.ranges) 15475 { this.range = [pos, 0]; } 15476}; 15477 15478// Start an AST node, attaching a start offset. 15479 15480var pp$2 = Parser.prototype; 15481 15482pp$2.startNode = function() { 15483 return new Node$1(this, this.start, this.startLoc) 15484}; 15485 15486pp$2.startNodeAt = function(pos, loc) { 15487 return new Node$1(this, pos, loc) 15488}; 15489 15490// Finish an AST node, adding `type` and `end` properties. 15491 15492function finishNodeAt(node, type, pos, loc) { 15493 node.type = type; 15494 node.end = pos; 15495 if (this.options.locations) 15496 { node.loc.end = loc; } 15497 if (this.options.ranges) 15498 { node.range[1] = pos; } 15499 return node 15500} 15501 15502pp$2.finishNode = function(node, type) { 15503 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc) 15504}; 15505 15506// Finish node at given position 15507 15508pp$2.finishNodeAt = function(node, type, pos, loc) { 15509 return finishNodeAt.call(this, node, type, pos, loc) 15510}; 15511 15512pp$2.copyNode = function(node) { 15513 var newNode = new Node$1(this, node.start, this.startLoc); 15514 for (var prop in node) { newNode[prop] = node[prop]; } 15515 return newNode 15516}; 15517 15518// This file contains Unicode properties extracted from the ECMAScript 15519// specification. The lists are extracted like so: 15520// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText) 15521 15522// #table-binary-unicode-properties 15523var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS"; 15524var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic"; 15525var ecma11BinaryProperties = ecma10BinaryProperties; 15526var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict"; 15527var ecma13BinaryProperties = ecma12BinaryProperties; 15528var unicodeBinaryProperties = { 15529 9: ecma9BinaryProperties, 15530 10: ecma10BinaryProperties, 15531 11: ecma11BinaryProperties, 15532 12: ecma12BinaryProperties, 15533 13: ecma13BinaryProperties 15534}; 15535 15536// #table-unicode-general-category-values 15537var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu"; 15538 15539// #table-unicode-script-values 15540var ecma9ScriptValues = "Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb"; 15541var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd"; 15542var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho"; 15543var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi"; 15544var ecma13ScriptValues = ecma12ScriptValues + " Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith"; 15545var unicodeScriptValues = { 15546 9: ecma9ScriptValues, 15547 10: ecma10ScriptValues, 15548 11: ecma11ScriptValues, 15549 12: ecma12ScriptValues, 15550 13: ecma13ScriptValues 15551}; 15552 15553var data = {}; 15554function buildUnicodeData(ecmaVersion) { 15555 var d = data[ecmaVersion] = { 15556 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues), 15557 nonBinary: { 15558 General_Category: wordsRegexp(unicodeGeneralCategoryValues), 15559 Script: wordsRegexp(unicodeScriptValues[ecmaVersion]) 15560 } 15561 }; 15562 d.nonBinary.Script_Extensions = d.nonBinary.Script; 15563 15564 d.nonBinary.gc = d.nonBinary.General_Category; 15565 d.nonBinary.sc = d.nonBinary.Script; 15566 d.nonBinary.scx = d.nonBinary.Script_Extensions; 15567} 15568 15569for (var i = 0, list = [9, 10, 11, 12, 13]; i < list.length; i += 1) { 15570 var ecmaVersion = list[i]; 15571 15572 buildUnicodeData(ecmaVersion); 15573} 15574 15575var pp$1 = Parser.prototype; 15576 15577var RegExpValidationState = function RegExpValidationState(parser) { 15578 this.parser = parser; 15579 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "") + (parser.options.ecmaVersion >= 13 ? "d" : ""); 15580 this.unicodeProperties = data[parser.options.ecmaVersion >= 13 ? 13 : parser.options.ecmaVersion]; 15581 this.source = ""; 15582 this.flags = ""; 15583 this.start = 0; 15584 this.switchU = false;
vendor: 3,094 bytes, lines 15585-15688
15585 this.switchN = false; 15586 this.pos = 0; 15587 this.lastIntValue = 0; 15588 this.lastStringValue = ""; 15589 this.lastAssertionIsQuantifiable = false; 15590 this.numCapturingParens = 0; 15591 this.maxBackReference = 0; 15592 this.groupNames = []; 15593 this.backReferenceNames = []; 15594}; 15595 15596RegExpValidationState.prototype.reset = function reset (start, pattern, flags) { 15597 var unicode = flags.indexOf("u") !== -1; 15598 this.start = start | 0; 15599 this.source = pattern + ""; 15600 this.flags = flags; 15601 this.switchU = unicode && this.parser.options.ecmaVersion >= 6; 15602 this.switchN = unicode && this.parser.options.ecmaVersion >= 9; 15603}; 15604 15605RegExpValidationState.prototype.raise = function raise (message) { 15606 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message)); 15607}; 15608 15609// If u flag is given, this returns the code point at the index (it combines a surrogate pair). 15610// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair). 15611RegExpValidationState.prototype.at = function at (i, forceU) { 15612 if ( forceU === void 0 ) forceU = false; 15613 15614 var s = this.source; 15615 var l = s.length; 15616 if (i >= l) { 15617 return -1 15618 } 15619 var c = s.charCodeAt(i); 15620 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) { 15621 return c 15622 } 15623 var next = s.charCodeAt(i + 1); 15624 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c 15625}; 15626 15627RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) { 15628 if ( forceU === void 0 ) forceU = false; 15629 15630 var s = this.source; 15631 var l = s.length; 15632 if (i >= l) { 15633 return l 15634 } 15635 var c = s.charCodeAt(i), next; 15636 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l || 15637 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) { 15638 return i + 1 15639 } 15640 return i + 2 15641}; 15642 15643RegExpValidationState.prototype.current = function current (forceU) { 15644 if ( forceU === void 0 ) forceU = false; 15645 15646 return this.at(this.pos, forceU) 15647}; 15648 15649RegExpValidationState.prototype.lookahead = function lookahead (forceU) { 15650 if ( forceU === void 0 ) forceU = false; 15651 15652 return this.at(this.nextIndex(this.pos, forceU), forceU) 15653}; 15654 15655RegExpValidationState.prototype.advance = function advance (forceU) { 15656 if ( forceU === void 0 ) forceU = false; 15657 15658 this.pos = this.nextIndex(this.pos, forceU); 15659}; 15660 15661RegExpValidationState.prototype.eat = function eat (ch, forceU) { 15662 if ( forceU === void 0 ) forceU = false; 15663 15664 if (this.current(forceU) === ch) { 15665 this.advance(forceU); 15666 return true 15667 } 15668 return false 15669}; 15670 15671/** 15672 * Validate the flags part of a given RegExpLiteral. 15673 * 15674 * @param {RegExpValidationState} state The state to validate RegExp. 15675 * @returns {void} 15676 */ 15677pp$1.validateRegExpFlags = function(state) { 15678 var validFlags = state.validFlags; 15679 var flags = state.flags; 15680 15681 for (var i = 0; i < flags.length; i++) { 15682 var flag = flags.charAt(i); 15683 if (validFlags.indexOf(flag) === -1) { 15684 this.raise(state.start, "Invalid regular expression flag"); 15685 } 15686 if (flags.indexOf(flag, i + 1) > -1) { 15687 this.raise(state.start, "Duplicate regular expression flag"); 15688 }
vendor: 17,384 bytes, lines 15688-16307
15688 15689 } 15690}; 15691 15692/** 15693 * Validate the pattern part of a given RegExpLiteral. 15694 * 15695 * @param {RegExpValidationState} state The state to validate RegExp. 15696 * @returns {void} 15697 */ 15698pp$1.validateRegExpPattern = function(state) { 15699 this.regexp_pattern(state); 15700 15701 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of 15702 // parsing contains a |GroupName|, reparse with the goal symbol 15703 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError* 15704 // exception if _P_ did not conform to the grammar, if any elements of _P_ 15705 // were not matched by the parse, or if any Early Error conditions exist. 15706 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) { 15707 state.switchN = true; 15708 this.regexp_pattern(state); 15709 } 15710}; 15711 15712// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern 15713pp$1.regexp_pattern = function(state) { 15714 state.pos = 0; 15715 state.lastIntValue = 0; 15716 state.lastStringValue = ""; 15717 state.lastAssertionIsQuantifiable = false; 15718 state.numCapturingParens = 0; 15719 state.maxBackReference = 0; 15720 state.groupNames.length = 0; 15721 state.backReferenceNames.length = 0; 15722 15723 this.regexp_disjunction(state); 15724 15725 if (state.pos !== state.source.length) { 15726 // Make the same messages as V8. 15727 if (state.eat(0x29 /* ) */)) { 15728 state.raise("Unmatched ')'"); 15729 } 15730 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) { 15731 state.raise("Lone quantifier brackets"); 15732 } 15733 } 15734 if (state.maxBackReference > state.numCapturingParens) { 15735 state.raise("Invalid escape"); 15736 } 15737 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) { 15738 var name = list[i]; 15739 15740 if (state.groupNames.indexOf(name) === -1) { 15741 state.raise("Invalid named capture referenced"); 15742 } 15743 } 15744}; 15745 15746// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction 15747pp$1.regexp_disjunction = function(state) { 15748 this.regexp_alternative(state); 15749 while (state.eat(0x7C /* | */)) { 15750 this.regexp_alternative(state); 15751 } 15752 15753 // Make the same message as V8. 15754 if (this.regexp_eatQuantifier(state, true)) { 15755 state.raise("Nothing to repeat"); 15756 } 15757 if (state.eat(0x7B /* { */)) { 15758 state.raise("Lone quantifier brackets"); 15759 } 15760}; 15761 15762// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative 15763pp$1.regexp_alternative = function(state) { 15764 while (state.pos < state.source.length && this.regexp_eatTerm(state)) 15765 { } 15766}; 15767 15768// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term 15769pp$1.regexp_eatTerm = function(state) { 15770 if (this.regexp_eatAssertion(state)) { 15771 // Handle `QuantifiableAssertion Quantifier` alternative. 15772 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion 15773 // is a QuantifiableAssertion. 15774 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) { 15775 // Make the same message as V8. 15776 if (state.switchU) { 15777 state.raise("Invalid quantifier"); 15778 } 15779 } 15780 return true 15781 } 15782 15783 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) { 15784 this.regexp_eatQuantifier(state); 15785 return true 15786 } 15787 15788 return false 15789}; 15790 15791// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion 15792pp$1.regexp_eatAssertion = function(state) { 15793 var start = state.pos; 15794 state.lastAssertionIsQuantifiable = false; 15795 15796 // ^, $ 15797 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) { 15798 return true 15799 } 15800 15801 // \b \B 15802 if (state.eat(0x5C /* \ */)) { 15803 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) { 15804 return true 15805 } 15806 state.pos = start; 15807 } 15808 15809 // Lookahead / Lookbehind 15810 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) { 15811 var lookbehind = false; 15812 if (this.options.ecmaVersion >= 9) { 15813 lookbehind = state.eat(0x3C /* < */); 15814 } 15815 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) { 15816 this.regexp_disjunction(state); 15817 if (!state.eat(0x29 /* ) */)) { 15818 state.raise("Unterminated group"); 15819 } 15820 state.lastAssertionIsQuantifiable = !lookbehind; 15821 return true 15822 } 15823 } 15824 15825 state.pos = start; 15826 return false 15827}; 15828 15829// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier 15830pp$1.regexp_eatQuantifier = function(state, noError) { 15831 if ( noError === void 0 ) noError = false; 15832 15833 if (this.regexp_eatQuantifierPrefix(state, noError)) { 15834 state.eat(0x3F /* ? */); 15835 return true 15836 } 15837 return false 15838}; 15839 15840// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix 15841pp$1.regexp_eatQuantifierPrefix = function(state, noError) { 15842 return ( 15843 state.eat(0x2A /* * */) || 15844 state.eat(0x2B /* + */) || 15845 state.eat(0x3F /* ? */) || 15846 this.regexp_eatBracedQuantifier(state, noError) 15847 ) 15848}; 15849pp$1.regexp_eatBracedQuantifier = function(state, noError) { 15850 var start = state.pos; 15851 if (state.eat(0x7B /* { */)) { 15852 var min = 0, max = -1; 15853 if (this.regexp_eatDecimalDigits(state)) { 15854 min = state.lastIntValue; 15855 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) { 15856 max = state.lastIntValue; 15857 } 15858 if (state.eat(0x7D /* } */)) { 15859 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term 15860 if (max !== -1 && max < min && !noError) { 15861 state.raise("numbers out of order in {} quantifier"); 15862 } 15863 return true 15864 } 15865 } 15866 if (state.switchU && !noError) { 15867 state.raise("Incomplete quantifier"); 15868 } 15869 state.pos = start; 15870 } 15871 return false 15872}; 15873 15874// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom 15875pp$1.regexp_eatAtom = function(state) { 15876 return ( 15877 this.regexp_eatPatternCharacters(state) || 15878 state.eat(0x2E /* . */) || 15879 this.regexp_eatReverseSolidusAtomEscape(state) || 15880 this.regexp_eatCharacterClass(state) || 15881 this.regexp_eatUncapturingGroup(state) || 15882 this.regexp_eatCapturingGroup(state) 15883 ) 15884}; 15885pp$1.regexp_eatReverseSolidusAtomEscape = function(state) { 15886 var start = state.pos; 15887 if (state.eat(0x5C /* \ */)) { 15888 if (this.regexp_eatAtomEscape(state)) { 15889 return true 15890 } 15891 state.pos = start; 15892 } 15893 return false 15894}; 15895pp$1.regexp_eatUncapturingGroup = function(state) { 15896 var start = state.pos; 15897 if (state.eat(0x28 /* ( */)) { 15898 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) { 15899 this.regexp_disjunction(state); 15900 if (state.eat(0x29 /* ) */)) { 15901 return true 15902 } 15903 state.raise("Unterminated group"); 15904 } 15905 state.pos = start; 15906 } 15907 return false 15908}; 15909pp$1.regexp_eatCapturingGroup = function(state) { 15910 if (state.eat(0x28 /* ( */)) { 15911 if (this.options.ecmaVersion >= 9) { 15912 this.regexp_groupSpecifier(state); 15913 } else if (state.current() === 0x3F /* ? */) { 15914 state.raise("Invalid group"); 15915 } 15916 this.regexp_disjunction(state); 15917 if (state.eat(0x29 /* ) */)) { 15918 state.numCapturingParens += 1; 15919 return true 15920 } 15921 state.raise("Unterminated group"); 15922 } 15923 return false 15924}; 15925 15926// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom 15927pp$1.regexp_eatExtendedAtom = function(state) { 15928 return ( 15929 state.eat(0x2E /* . */) || 15930 this.regexp_eatReverseSolidusAtomEscape(state) || 15931 this.regexp_eatCharacterClass(state) || 15932 this.regexp_eatUncapturingGroup(state) || 15933 this.regexp_eatCapturingGroup(state) || 15934 this.regexp_eatInvalidBracedQuantifier(state) || 15935 this.regexp_eatExtendedPatternCharacter(state) 15936 ) 15937}; 15938 15939// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier 15940pp$1.regexp_eatInvalidBracedQuantifier = function(state) { 15941 if (this.regexp_eatBracedQuantifier(state, true)) { 15942 state.raise("Nothing to repeat"); 15943 } 15944 return false 15945}; 15946 15947// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter 15948pp$1.regexp_eatSyntaxCharacter = function(state) { 15949 var ch = state.current(); 15950 if (isSyntaxCharacter(ch)) { 15951 state.lastIntValue = ch; 15952 state.advance(); 15953 return true 15954 } 15955 return false 15956}; 15957function isSyntaxCharacter(ch) { 15958 return ( 15959 ch === 0x24 /* $ */ || 15960 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ || 15961 ch === 0x2E /* . */ || 15962 ch === 0x3F /* ? */ || 15963 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ || 15964 ch >= 0x7B /* { */ && ch <= 0x7D /* } */ 15965 ) 15966} 15967 15968// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter 15969// But eat eager. 15970pp$1.regexp_eatPatternCharacters = function(state) { 15971 var start = state.pos; 15972 var ch = 0; 15973 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) { 15974 state.advance(); 15975 } 15976 return state.pos !== start 15977}; 15978 15979// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter 15980pp$1.regexp_eatExtendedPatternCharacter = function(state) { 15981 var ch = state.current(); 15982 if ( 15983 ch !== -1 && 15984 ch !== 0x24 /* $ */ && 15985 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) && 15986 ch !== 0x2E /* . */ && 15987 ch !== 0x3F /* ? */ && 15988 ch !== 0x5B /* [ */ && 15989 ch !== 0x5E /* ^ */ && 15990 ch !== 0x7C /* | */ 15991 ) { 15992 state.advance(); 15993 return true 15994 } 15995 return false 15996}; 15997 15998// GroupSpecifier :: 15999// [empty] 16000// `?` GroupName 16001pp$1.regexp_groupSpecifier = function(state) { 16002 if (state.eat(0x3F /* ? */)) { 16003 if (this.regexp_eatGroupName(state)) { 16004 if (state.groupNames.indexOf(state.lastStringValue) !== -1) { 16005 state.raise("Duplicate capture group name"); 16006 } 16007 state.groupNames.push(state.lastStringValue); 16008 return 16009 } 16010 state.raise("Invalid group"); 16011 } 16012}; 16013 16014// GroupName :: 16015// `<` RegExpIdentifierName `>` 16016// Note: this updates `state.lastStringValue` property with the eaten name. 16017pp$1.regexp_eatGroupName = function(state) { 16018 state.lastStringValue = ""; 16019 if (state.eat(0x3C /* < */)) { 16020 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) { 16021 return true 16022 } 16023 state.raise("Invalid capture group name"); 16024 } 16025 return false 16026}; 16027 16028// RegExpIdentifierName :: 16029// RegExpIdentifierStart 16030// RegExpIdentifierName RegExpIdentifierPart 16031// Note: this updates `state.lastStringValue` property with the eaten name. 16032pp$1.regexp_eatRegExpIdentifierName = function(state) { 16033 state.lastStringValue = ""; 16034 if (this.regexp_eatRegExpIdentifierStart(state)) { 16035 state.lastStringValue += codePointToString(state.lastIntValue); 16036 while (this.regexp_eatRegExpIdentifierPart(state)) { 16037 state.lastStringValue += codePointToString(state.lastIntValue); 16038 } 16039 return true 16040 } 16041 return false 16042}; 16043 16044// RegExpIdentifierStart :: 16045// UnicodeIDStart 16046// `$` 16047// `_` 16048// `\` RegExpUnicodeEscapeSequence[+U] 16049pp$1.regexp_eatRegExpIdentifierStart = function(state) { 16050 var start = state.pos; 16051 var forceU = this.options.ecmaVersion >= 11; 16052 var ch = state.current(forceU); 16053 state.advance(forceU); 16054 16055 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { 16056 ch = state.lastIntValue; 16057 } 16058 if (isRegExpIdentifierStart(ch)) { 16059 state.lastIntValue = ch; 16060 return true 16061 } 16062 16063 state.pos = start; 16064 return false 16065}; 16066function isRegExpIdentifierStart(ch) { 16067 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ 16068} 16069 16070// RegExpIdentifierPart :: 16071// UnicodeIDContinue 16072// `$` 16073// `_` 16074// `\` RegExpUnicodeEscapeSequence[+U] 16075// <ZWNJ> 16076// <ZWJ> 16077pp$1.regexp_eatRegExpIdentifierPart = function(state) { 16078 var start = state.pos; 16079 var forceU = this.options.ecmaVersion >= 11; 16080 var ch = state.current(forceU); 16081 state.advance(forceU); 16082 16083 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) { 16084 ch = state.lastIntValue; 16085 } 16086 if (isRegExpIdentifierPart(ch)) { 16087 state.lastIntValue = ch; 16088 return true 16089 } 16090 16091 state.pos = start; 16092 return false 16093}; 16094function isRegExpIdentifierPart(ch) { 16095 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */ 16096} 16097 16098// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape 16099pp$1.regexp_eatAtomEscape = function(state) { 16100 if ( 16101 this.regexp_eatBackReference(state) || 16102 this.regexp_eatCharacterClassEscape(state) || 16103 this.regexp_eatCharacterEscape(state) || 16104 (state.switchN && this.regexp_eatKGroupName(state)) 16105 ) { 16106 return true 16107 } 16108 if (state.switchU) { 16109 // Make the same message as V8. 16110 if (state.current() === 0x63 /* c */) { 16111 state.raise("Invalid unicode escape"); 16112 } 16113 state.raise("Invalid escape"); 16114 } 16115 return false 16116}; 16117pp$1.regexp_eatBackReference = function(state) { 16118 var start = state.pos; 16119 if (this.regexp_eatDecimalEscape(state)) { 16120 var n = state.lastIntValue; 16121 if (state.switchU) { 16122 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape 16123 if (n > state.maxBackReference) { 16124 state.maxBackReference = n; 16125 } 16126 return true 16127 } 16128 if (n <= state.numCapturingParens) { 16129 return true 16130 } 16131 state.pos = start; 16132 } 16133 return false 16134}; 16135pp$1.regexp_eatKGroupName = function(state) { 16136 if (state.eat(0x6B /* k */)) { 16137 if (this.regexp_eatGroupName(state)) { 16138 state.backReferenceNames.push(state.lastStringValue); 16139 return true 16140 } 16141 state.raise("Invalid named reference"); 16142 } 16143 return false 16144}; 16145 16146// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape 16147pp$1.regexp_eatCharacterEscape = function(state) { 16148 return ( 16149 this.regexp_eatControlEscape(state) || 16150 this.regexp_eatCControlLetter(state) || 16151 this.regexp_eatZero(state) || 16152 this.regexp_eatHexEscapeSequence(state) || 16153 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) || 16154 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) || 16155 this.regexp_eatIdentityEscape(state) 16156 ) 16157}; 16158pp$1.regexp_eatCControlLetter = function(state) { 16159 var start = state.pos; 16160 if (state.eat(0x63 /* c */)) { 16161 if (this.regexp_eatControlLetter(state)) { 16162 return true 16163 } 16164 state.pos = start; 16165 } 16166 return false 16167}; 16168pp$1.regexp_eatZero = function(state) { 16169 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) { 16170 state.lastIntValue = 0; 16171 state.advance(); 16172 return true 16173 } 16174 return false 16175}; 16176 16177// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape 16178pp$1.regexp_eatControlEscape = function(state) { 16179 var ch = state.current(); 16180 if (ch === 0x74 /* t */) { 16181 state.lastIntValue = 0x09; /* \t */ 16182 state.advance(); 16183 return true 16184 } 16185 if (ch === 0x6E /* n */) { 16186 state.lastIntValue = 0x0A; /* \n */ 16187 state.advance(); 16188 return true 16189 } 16190 if (ch === 0x76 /* v */) { 16191 state.lastIntValue = 0x0B; /* \v */ 16192 state.advance(); 16193 return true 16194 } 16195 if (ch === 0x66 /* f */) { 16196 state.lastIntValue = 0x0C; /* \f */ 16197 state.advance(); 16198 return true 16199 } 16200 if (ch === 0x72 /* r */) { 16201 state.lastIntValue = 0x0D; /* \r */ 16202 state.advance(); 16203 return true 16204 } 16205 return false 16206}; 16207 16208// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter 16209pp$1.regexp_eatControlLetter = function(state) { 16210 var ch = state.current(); 16211 if (isControlLetter(ch)) { 16212 state.lastIntValue = ch % 0x20; 16213 state.advance(); 16214 return true 16215 } 16216 return false 16217}; 16218function isControlLetter(ch) { 16219 return ( 16220 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) || 16221 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */) 16222 ) 16223} 16224 16225// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence 16226pp$1.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) { 16227 if ( forceU === void 0 ) forceU = false; 16228 16229 var start = state.pos; 16230 var switchU = forceU || state.switchU; 16231 16232 if (state.eat(0x75 /* u */)) { 16233 if (this.regexp_eatFixedHexDigits(state, 4)) { 16234 var lead = state.lastIntValue; 16235 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) { 16236 var leadSurrogateEnd = state.pos; 16237 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) { 16238 var trail = state.lastIntValue; 16239 if (trail >= 0xDC00 && trail <= 0xDFFF) { 16240 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; 16241 return true 16242 } 16243 } 16244 state.pos = leadSurrogateEnd; 16245 state.lastIntValue = lead; 16246 } 16247 return true 16248 } 16249 if ( 16250 switchU && 16251 state.eat(0x7B /* { */) && 16252 this.regexp_eatHexDigits(state) && 16253 state.eat(0x7D /* } */) && 16254 isValidUnicode(state.lastIntValue) 16255 ) { 16256 return true 16257 } 16258 if (switchU) { 16259 state.raise("Invalid unicode escape"); 16260 } 16261 state.pos = start; 16262 } 16263 16264 return false 16265}; 16266function isValidUnicode(ch) { 16267 return ch >= 0 && ch <= 0x10FFFF 16268} 16269 16270// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape 16271pp$1.regexp_eatIdentityEscape = function(state) { 16272 if (state.switchU) { 16273 if (this.regexp_eatSyntaxCharacter(state)) { 16274 return true 16275 } 16276 if (state.eat(0x2F /* / */)) { 16277 state.lastIntValue = 0x2F; /* / */ 16278 return true 16279 } 16280 return false 16281 } 16282 16283 var ch = state.current(); 16284 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) { 16285 state.lastIntValue = ch; 16286 state.advance(); 16287 return true 16288 } 16289 16290 return false 16291}; 16292 16293// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape 16294pp$1.regexp_eatDecimalEscape = function(state) { 16295 state.lastIntValue = 0; 16296 var ch = state.current(); 16297 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) { 16298 do { 16299 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); 16300 state.advance(); 16301 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) 16302 return true 16303 } 16304 return false 16305}; 16306 16307//
vendor: 5,826 bytes, lines 16307-16506
16307https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape 16308pp$1.regexp_eatCharacterClassEscape = function(state) { 16309 var ch = state.current(); 16310 16311 if (isCharacterClassEscape(ch)) { 16312 state.lastIntValue = -1; 16313 state.advance(); 16314 return true 16315 } 16316 16317 if ( 16318 state.switchU && 16319 this.options.ecmaVersion >= 9 && 16320 (ch === 0x50 /* P */ || ch === 0x70 /* p */) 16321 ) { 16322 state.lastIntValue = -1; 16323 state.advance(); 16324 if ( 16325 state.eat(0x7B /* { */) && 16326 this.regexp_eatUnicodePropertyValueExpression(state) && 16327 state.eat(0x7D /* } */) 16328 ) { 16329 return true 16330 } 16331 state.raise("Invalid property name"); 16332 } 16333 16334 return false 16335}; 16336function isCharacterClassEscape(ch) { 16337 return ( 16338 ch === 0x64 /* d */ || 16339 ch === 0x44 /* D */ || 16340 ch === 0x73 /* s */ || 16341 ch === 0x53 /* S */ || 16342 ch === 0x77 /* w */ || 16343 ch === 0x57 /* W */ 16344 ) 16345} 16346 16347// UnicodePropertyValueExpression :: 16348// UnicodePropertyName `=` UnicodePropertyValue 16349// LoneUnicodePropertyNameOrValue 16350pp$1.regexp_eatUnicodePropertyValueExpression = function(state) { 16351 var start = state.pos; 16352 16353 // UnicodePropertyName `=` UnicodePropertyValue 16354 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) { 16355 var name = state.lastStringValue; 16356 if (this.regexp_eatUnicodePropertyValue(state)) { 16357 var value = state.lastStringValue; 16358 this.regexp_validateUnicodePropertyNameAndValue(state, name, value); 16359 return true 16360 } 16361 } 16362 state.pos = start; 16363 16364 // LoneUnicodePropertyNameOrValue 16365 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) { 16366 var nameOrValue = state.lastStringValue; 16367 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue); 16368 return true 16369 } 16370 return false 16371}; 16372pp$1.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) { 16373 if (!hasOwn(state.unicodeProperties.nonBinary, name)) 16374 { state.raise("Invalid property name"); } 16375 if (!state.unicodeProperties.nonBinary[name].test(value)) 16376 { state.raise("Invalid property value"); } 16377}; 16378pp$1.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) { 16379 if (!state.unicodeProperties.binary.test(nameOrValue)) 16380 { state.raise("Invalid property name"); } 16381}; 16382 16383// UnicodePropertyName :: 16384// UnicodePropertyNameCharacters 16385pp$1.regexp_eatUnicodePropertyName = function(state) { 16386 var ch = 0; 16387 state.lastStringValue = ""; 16388 while (isUnicodePropertyNameCharacter(ch = state.current())) { 16389 state.lastStringValue += codePointToString(ch); 16390 state.advance(); 16391 } 16392 return state.lastStringValue !== "" 16393}; 16394function isUnicodePropertyNameCharacter(ch) { 16395 return isControlLetter(ch) || ch === 0x5F /* _ */ 16396} 16397 16398// UnicodePropertyValue :: 16399// UnicodePropertyValueCharacters 16400pp$1.regexp_eatUnicodePropertyValue = function(state) { 16401 var ch = 0; 16402 state.lastStringValue = ""; 16403 while (isUnicodePropertyValueCharacter(ch = state.current())) { 16404 state.lastStringValue += codePointToString(ch); 16405 state.advance(); 16406 } 16407 return state.lastStringValue !== "" 16408}; 16409function isUnicodePropertyValueCharacter(ch) { 16410 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch) 16411} 16412 16413// LoneUnicodePropertyNameOrValue :: 16414// UnicodePropertyValueCharacters 16415pp$1.regexp_eatLoneUnicodePropertyNameOrValue = function(state) { 16416 return this.regexp_eatUnicodePropertyValue(state) 16417}; 16418 16419// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass 16420pp$1.regexp_eatCharacterClass = function(state) { 16421 if (state.eat(0x5B /* [ */)) { 16422 state.eat(0x5E /* ^ */); 16423 this.regexp_classRanges(state); 16424 if (state.eat(0x5D /* ] */)) { 16425 return true 16426 } 16427 // Unreachable since it threw "unterminated regular expression" error before. 16428 state.raise("Unterminated character class"); 16429 } 16430 return false 16431}; 16432 16433// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges 16434// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges 16435// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash 16436pp$1.regexp_classRanges = function(state) { 16437 while (this.regexp_eatClassAtom(state)) { 16438 var left = state.lastIntValue; 16439 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) { 16440 var right = state.lastIntValue; 16441 if (state.switchU && (left === -1 || right === -1)) { 16442 state.raise("Invalid character class"); 16443 } 16444 if (left !== -1 && right !== -1 && left > right) { 16445 state.raise("Range out of order in character class"); 16446 } 16447 } 16448 } 16449}; 16450 16451// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom 16452// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash 16453pp$1.regexp_eatClassAtom = function(state) { 16454 var start = state.pos; 16455 16456 if (state.eat(0x5C /* \ */)) { 16457 if (this.regexp_eatClassEscape(state)) { 16458 return true 16459 } 16460 if (state.switchU) { 16461 // Make the same message as V8. 16462 var ch$1 = state.current(); 16463 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) { 16464 state.raise("Invalid class escape"); 16465 } 16466 state.raise("Invalid escape"); 16467 } 16468 state.pos = start; 16469 } 16470 16471 var ch = state.current(); 16472 if (ch !== 0x5D /* ] */) { 16473 state.lastIntValue = ch; 16474 state.advance(); 16475 return true 16476 } 16477 16478 return false 16479}; 16480 16481// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape 16482pp$1.regexp_eatClassEscape = function(state) { 16483 var start = state.pos; 16484 16485 if (state.eat(0x62 /* b */)) { 16486 state.lastIntValue = 0x08; /* <BS> */ 16487 return true 16488 } 16489 16490 if (state.switchU && state.eat(0x2D /* - */)) { 16491 state.lastIntValue = 0x2D; /* - */ 16492 return true 16493 } 16494 16495 if (!state.switchU && state.eat(0x63 /* c */)) { 16496 if (this.regexp_eatClassControlLetter(state)) { 16497 return true 16498 } 16499 state.pos = start; 16500 } 16501 16502 return ( 16503 this.regexp_eatCharacterClassEscape(state) || 16504 this.regexp_eatCharacterEscape(state) 16505 ) 16506};
vendor: 27,406 bytes, lines 16506-17341
16506 16507 16508// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter 16509pp$1.regexp_eatClassControlLetter = function(state) { 16510 var ch = state.current(); 16511 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) { 16512 state.lastIntValue = ch % 0x20; 16513 state.advance(); 16514 return true 16515 } 16516 return false 16517}; 16518 16519// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence 16520pp$1.regexp_eatHexEscapeSequence = function(state) { 16521 var start = state.pos; 16522 if (state.eat(0x78 /* x */)) { 16523 if (this.regexp_eatFixedHexDigits(state, 2)) { 16524 return true 16525 } 16526 if (state.switchU) { 16527 state.raise("Invalid escape"); 16528 } 16529 state.pos = start; 16530 } 16531 return false 16532}; 16533 16534// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits 16535pp$1.regexp_eatDecimalDigits = function(state) { 16536 var start = state.pos; 16537 var ch = 0; 16538 state.lastIntValue = 0; 16539 while (isDecimalDigit(ch = state.current())) { 16540 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */); 16541 state.advance(); 16542 } 16543 return state.pos !== start 16544}; 16545function isDecimalDigit(ch) { 16546 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */ 16547} 16548 16549// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits 16550pp$1.regexp_eatHexDigits = function(state) { 16551 var start = state.pos; 16552 var ch = 0; 16553 state.lastIntValue = 0; 16554 while (isHexDigit(ch = state.current())) { 16555 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); 16556 state.advance(); 16557 } 16558 return state.pos !== start 16559}; 16560function isHexDigit(ch) { 16561 return ( 16562 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) || 16563 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) || 16564 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) 16565 ) 16566} 16567function hexToInt(ch) { 16568 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) { 16569 return 10 + (ch - 0x41 /* A */) 16570 } 16571 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) { 16572 return 10 + (ch - 0x61 /* a */) 16573 } 16574 return ch - 0x30 /* 0 */ 16575} 16576 16577// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence 16578// Allows only 0-377(octal) i.e. 0-255(decimal). 16579pp$1.regexp_eatLegacyOctalEscapeSequence = function(state) { 16580 if (this.regexp_eatOctalDigit(state)) { 16581 var n1 = state.lastIntValue; 16582 if (this.regexp_eatOctalDigit(state)) { 16583 var n2 = state.lastIntValue; 16584 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) { 16585 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue; 16586 } else { 16587 state.lastIntValue = n1 * 8 + n2; 16588 } 16589 } else { 16590 state.lastIntValue = n1; 16591 } 16592 return true 16593 } 16594 return false 16595}; 16596 16597// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit 16598pp$1.regexp_eatOctalDigit = function(state) { 16599 var ch = state.current(); 16600 if (isOctalDigit(ch)) { 16601 state.lastIntValue = ch - 0x30; /* 0 */ 16602 state.advance(); 16603 return true 16604 } 16605 state.lastIntValue = 0; 16606 return false 16607}; 16608function isOctalDigit(ch) { 16609 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */ 16610} 16611 16612// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits 16613// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit 16614// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence 16615pp$1.regexp_eatFixedHexDigits = function(state, length) { 16616 var start = state.pos; 16617 state.lastIntValue = 0; 16618 for (var i = 0; i < length; ++i) { 16619 var ch = state.current(); 16620 if (!isHexDigit(ch)) { 16621 state.pos = start; 16622 return false 16623 } 16624 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch); 16625 state.advance(); 16626 } 16627 return true 16628}; 16629 16630// Object type used to represent tokens. Note that normally, tokens 16631// simply exist as properties on the parser object. This is only 16632// used for the onToken callback and the external tokenizer. 16633 16634var Token = function Token(p) { 16635 this.type = p.type; 16636 this.value = p.value; 16637 this.start = p.start; 16638 this.end = p.end; 16639 if (p.options.locations) 16640 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); } 16641 if (p.options.ranges) 16642 { this.range = [p.start, p.end]; } 16643}; 16644 16645// ## Tokenizer 16646 16647var pp = Parser.prototype; 16648 16649// Move to the next token 16650 16651pp.next = function(ignoreEscapeSequenceInKeyword) { 16652 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc) 16653 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); } 16654 if (this.options.onToken) 16655 { this.options.onToken(new Token(this)); } 16656 16657 this.lastTokEnd = this.end; 16658 this.lastTokStart = this.start; 16659 this.lastTokEndLoc = this.endLoc; 16660 this.lastTokStartLoc = this.startLoc; 16661 this.nextToken(); 16662}; 16663 16664pp.getToken = function() { 16665 this.next(); 16666 return new Token(this) 16667}; 16668 16669// If we're in an ES6 environment, make parsers iterable 16670if (typeof Symbol !== "undefined") 16671 { pp[Symbol.iterator] = function() { 16672 var this$1$1 = this; 16673 16674 return { 16675 next: function () { 16676 var token = this$1$1.getToken(); 16677 return { 16678 done: token.type === types$1.eof, 16679 value: token 16680 } 16681 } 16682 } 16683 }; } 16684 16685// Toggle strict mode. Re-reads the next number or string to please 16686// pedantic tests (`"use strict"; 010;` should fail). 16687 16688// Read a single token, updating the parser object's token-related 16689// properties. 16690 16691pp.nextToken = function() { 16692 var curContext = this.curContext(); 16693 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); } 16694 16695 this.start = this.pos; 16696 if (this.options.locations) { this.startLoc = this.curPosition(); } 16697 if (this.pos >= this.input.length) { return this.finishToken(types$1.eof) } 16698 16699 if (curContext.override) { return curContext.override(this) } 16700 else { this.readToken(this.fullCharCodeAtPos()); } 16701}; 16702 16703pp.readToken = function(code) { 16704 // Identifier or keyword. '\uXXXX' sequences are allowed in 16705 // identifiers, so '\' also dispatches to that. 16706 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) 16707 { return this.readWord() } 16708 16709 return this.getTokenFromCode(code) 16710}; 16711 16712pp.fullCharCodeAtPos = function() { 16713 var code = this.input.charCodeAt(this.pos); 16714 if (code <= 0xd7ff || code >= 0xdc00) { return code } 16715 var next = this.input.charCodeAt(this.pos + 1); 16716 return next <= 0xdbff || next >= 0xe000 ? code : (code << 10) + next - 0x35fdc00 16717}; 16718 16719pp.skipBlockComment = function() { 16720 var startLoc = this.options.onComment && this.curPosition(); 16721 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2); 16722 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); } 16723 this.pos = end + 2; 16724 if (this.options.locations) { 16725 for (var nextBreak = (void 0), pos = start; (nextBreak = nextLineBreak(this.input, pos, this.pos)) > -1;) { 16726 ++this.curLine; 16727 pos = this.lineStart = nextBreak; 16728 } 16729 } 16730 if (this.options.onComment) 16731 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, 16732 startLoc, this.curPosition()); } 16733}; 16734 16735pp.skipLineComment = function(startSkip) { 16736 var start = this.pos; 16737 var startLoc = this.options.onComment && this.curPosition(); 16738 var ch = this.input.charCodeAt(this.pos += startSkip); 16739 while (this.pos < this.input.length && !isNewLine(ch)) { 16740 ch = this.input.charCodeAt(++this.pos); 16741 } 16742 if (this.options.onComment) 16743 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, 16744 startLoc, this.curPosition()); } 16745}; 16746 16747// Called at the start of the parse and after every token. Skips 16748// whitespace and comments, and. 16749 16750pp.skipSpace = function() { 16751 loop: while (this.pos < this.input.length) { 16752 var ch = this.input.charCodeAt(this.pos); 16753 switch (ch) { 16754 case 32: case 160: // ' ' 16755 ++this.pos; 16756 break 16757 case 13: 16758 if (this.input.charCodeAt(this.pos + 1) === 10) { 16759 ++this.pos; 16760 } 16761 case 10: case 8232: case 8233: 16762 ++this.pos; 16763 if (this.options.locations) { 16764 ++this.curLine; 16765 this.lineStart = this.pos; 16766 } 16767 break 16768 case 47: // '/' 16769 switch (this.input.charCodeAt(this.pos + 1)) { 16770 case 42: // '*' 16771 this.skipBlockComment(); 16772 break 16773 case 47: 16774 this.skipLineComment(2); 16775 break 16776 default: 16777 break loop 16778 } 16779 break 16780 default: 16781 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { 16782 ++this.pos; 16783 } else { 16784 break loop 16785 } 16786 } 16787 } 16788}; 16789 16790// Called at the end of every token. Sets `end`, `val`, and 16791// maintains `context` and `exprAllowed`, and skips the space after 16792// the token, so that the next one's `start` will point at the 16793// right position. 16794 16795pp.finishToken = function(type, val) { 16796 this.end = this.pos; 16797 if (this.options.locations) { this.endLoc = this.curPosition(); } 16798 var prevType = this.type; 16799 this.type = type; 16800 this.value = val; 16801 16802 this.updateContext(prevType); 16803}; 16804 16805// ### Token reading 16806 16807// This is the function that is called to fetch the next token. It 16808// is somewhat obscure, because it works in character codes rather 16809// than characters, and because operator parsing has been inlined 16810// into it. 16811// 16812// All in the name of speed. 16813// 16814pp.readToken_dot = function() { 16815 var next = this.input.charCodeAt(this.pos + 1); 16816 if (next >= 48 && next <= 57) { return this.readNumber(true) } 16817 var next2 = this.input.charCodeAt(this.pos + 2); 16818 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.' 16819 this.pos += 3; 16820 return this.finishToken(types$1.ellipsis) 16821 } else { 16822 ++this.pos; 16823 return this.finishToken(types$1.dot) 16824 } 16825}; 16826 16827pp.readToken_slash = function() { // '/' 16828 var next = this.input.charCodeAt(this.pos + 1); 16829 if (this.exprAllowed) { ++this.pos; return this.readRegexp() } 16830 if (next === 61) { return this.finishOp(types$1.assign, 2) } 16831 return this.finishOp(types$1.slash, 1) 16832}; 16833 16834pp.readToken_mult_modulo_exp = function(code) { // '%*' 16835 var next = this.input.charCodeAt(this.pos + 1); 16836 var size = 1; 16837 var tokentype = code === 42 ? types$1.star : types$1.modulo; 16838 16839 // exponentiation operator ** and **= 16840 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) { 16841 ++size; 16842 tokentype = types$1.starstar; 16843 next = this.input.charCodeAt(this.pos + 2); 16844 } 16845 16846 if (next === 61) { return this.finishOp(types$1.assign, size + 1) } 16847 return this.finishOp(tokentype, size) 16848}; 16849 16850pp.readToken_pipe_amp = function(code) { // '|&' 16851 var next = this.input.charCodeAt(this.pos + 1); 16852 if (next === code) { 16853 if (this.options.ecmaVersion >= 12) { 16854 var next2 = this.input.charCodeAt(this.pos + 2); 16855 if (next2 === 61) { return this.finishOp(types$1.assign, 3) } 16856 } 16857 return this.finishOp(code === 124 ? types$1.logicalOR : types$1.logicalAND, 2) 16858 } 16859 if (next === 61) { return this.finishOp(types$1.assign, 2) } 16860 return this.finishOp(code === 124 ? types$1.bitwiseOR : types$1.bitwiseAND, 1) 16861}; 16862 16863pp.readToken_caret = function() { // '^' 16864 var next = this.input.charCodeAt(this.pos + 1); 16865 if (next === 61) { return this.finishOp(types$1.assign, 2) } 16866 return this.finishOp(types$1.bitwiseXOR, 1) 16867}; 16868 16869pp.readToken_plus_min = function(code) { // '+-' 16870 var next = this.input.charCodeAt(this.pos + 1); 16871 if (next === code) { 16872 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 && 16873 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) { 16874 // A `-->` line comment 16875 this.skipLineComment(3); 16876 this.skipSpace(); 16877 return this.nextToken() 16878 } 16879 return this.finishOp(types$1.incDec, 2) 16880 } 16881 if (next === 61) { return this.finishOp(types$1.assign, 2) } 16882 return this.finishOp(types$1.plusMin, 1) 16883}; 16884 16885pp.readToken_lt_gt = function(code) { // '<>' 16886 var next = this.input.charCodeAt(this.pos + 1); 16887 var size = 1; 16888 if (next === code) { 16889 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2; 16890 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types$1.assign, size + 1) } 16891 return this.finishOp(types$1.bitShift, size) 16892 } 16893 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 && 16894 this.input.charCodeAt(this.pos + 3) === 45) { 16895 // `<!--`, an XML-style comment that should be interpreted as a line comment 16896 this.skipLineComment(4); 16897 this.skipSpace(); 16898 return this.nextToken() 16899 } 16900 if (next === 61) { size = 2; } 16901 return this.finishOp(types$1.relational, size) 16902}; 16903 16904pp.readToken_eq_excl = function(code) { // '=!' 16905 var next = this.input.charCodeAt(this.pos + 1); 16906 if (next === 61) { return this.finishOp(types$1.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) } 16907 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>' 16908 this.pos += 2; 16909 return this.finishToken(types$1.arrow) 16910 } 16911 return this.finishOp(code === 61 ? types$1.eq : types$1.prefix, 1) 16912}; 16913 16914pp.readToken_question = function() { // '?' 16915 var ecmaVersion = this.options.ecmaVersion; 16916 if (ecmaVersion >= 11) { 16917 var next = this.input.charCodeAt(this.pos + 1); 16918 if (next === 46) { 16919 var next2 = this.input.charCodeAt(this.pos + 2); 16920 if (next2 < 48 || next2 > 57) { return this.finishOp(types$1.questionDot, 2) } 16921 } 16922 if (next === 63) { 16923 if (ecmaVersion >= 12) { 16924 var next2$1 = this.input.charCodeAt(this.pos + 2); 16925 if (next2$1 === 61) { return this.finishOp(types$1.assign, 3) } 16926 } 16927 return this.finishOp(types$1.coalesce, 2) 16928 } 16929 } 16930 return this.finishOp(types$1.question, 1) 16931}; 16932 16933pp.readToken_numberSign = function() { // '#' 16934 var ecmaVersion = this.options.ecmaVersion; 16935 var code = 35; // '#' 16936 if (ecmaVersion >= 13) { 16937 ++this.pos; 16938 code = this.fullCharCodeAtPos(); 16939 if (isIdentifierStart(code, true) || code === 92 /* '\' */) { 16940 return this.finishToken(types$1.privateId, this.readWord1()) 16941 } 16942 } 16943 16944 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); 16945}; 16946 16947pp.getTokenFromCode = function(code) { 16948 switch (code) { 16949 // The interpretation of a dot depends on whether it is followed 16950 // by a digit or another two dots. 16951 case 46: // '.' 16952 return this.readToken_dot() 16953 16954 // Punctuation tokens. 16955 case 40: ++this.pos; return this.finishToken(types$1.parenL) 16956 case 41: ++this.pos; return this.finishToken(types$1.parenR) 16957 case 59: ++this.pos; return this.finishToken(types$1.semi) 16958 case 44: ++this.pos; return this.finishToken(types$1.comma) 16959 case 91: ++this.pos; return this.finishToken(types$1.bracketL) 16960 case 93: ++this.pos; return this.finishToken(types$1.bracketR) 16961 case 123: ++this.pos; return this.finishToken(types$1.braceL) 16962 case 125: ++this.pos; return this.finishToken(types$1.braceR) 16963 case 58: ++this.pos; return this.finishToken(types$1.colon) 16964 16965 case 96: // '`' 16966 if (this.options.ecmaVersion < 6) { break } 16967 ++this.pos; 16968 return this.finishToken(types$1.backQuote) 16969 16970 case 48: // '0' 16971 var next = this.input.charCodeAt(this.pos + 1); 16972 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number 16973 if (this.options.ecmaVersion >= 6) { 16974 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number 16975 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number 16976 } 16977 16978 // Anything else beginning with a digit is an integer, octal 16979 // number, or float. 16980 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9 16981 return this.readNumber(false) 16982 16983 // Quotes produce strings. 16984 case 34: case 39: // '"', "'" 16985 return this.readString(code) 16986 16987 // Operators are parsed inline in tiny state machines. '=' (61) is 16988 // often referred to. `finishOp` simply skips the amount of 16989 // characters it is given as second argument, and returns a token 16990 // of the type given by its first argument. 16991 case 47: // '/' 16992 return this.readToken_slash() 16993 16994 case 37: case 42: // '%*' 16995 return this.readToken_mult_modulo_exp(code) 16996 16997 case 124: case 38: // '|&' 16998 return this.readToken_pipe_amp(code) 16999 17000 case 94: // '^' 17001 return this.readToken_caret() 17002 17003 case 43: case 45: // '+-' 17004 return this.readToken_plus_min(code) 17005 17006 case 60: case 62: // '<>' 17007 return this.readToken_lt_gt(code) 17008 17009 case 61: case 33: // '=!' 17010 return this.readToken_eq_excl(code) 17011 17012 case 63: // '?' 17013 return this.readToken_question() 17014 17015 case 126: // '~' 17016 return this.finishOp(types$1.prefix, 1) 17017 17018 case 35: // '#' 17019 return this.readToken_numberSign() 17020 } 17021 17022 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'"); 17023}; 17024 17025pp.finishOp = function(type, size) { 17026 var str = this.input.slice(this.pos, this.pos + size); 17027 this.pos += size; 17028 return this.finishToken(type, str) 17029}; 17030 17031pp.readRegexp = function() { 17032 var escaped, inClass, start = this.pos; 17033 for (;;) { 17034 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); } 17035 var ch = this.input.charAt(this.pos); 17036 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); } 17037 if (!escaped) { 17038 if (ch === "[") { inClass = true; } 17039 else if (ch === "]" && inClass) { inClass = false; } 17040 else if (ch === "/" && !inClass) { break } 17041 escaped = ch === "\\"; 17042 } else { escaped = false; } 17043 ++this.pos; 17044 } 17045 var pattern = this.input.slice(start, this.pos); 17046 ++this.pos; 17047 var flagsStart = this.pos; 17048 var flags = this.readWord1(); 17049 if (this.containsEsc) { this.unexpected(flagsStart); } 17050 17051 // Validate pattern 17052 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this)); 17053 state.reset(start, pattern, flags); 17054 this.validateRegExpFlags(state); 17055 this.validateRegExpPattern(state); 17056 17057 // Create Literal#value property value. 17058 var value = null; 17059 try { 17060 value = new RegExp(pattern, flags); 17061 } catch (e) { 17062 // ESTree requires null if it failed to instantiate RegExp object. 17063 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral 17064 } 17065 17066 return this.finishToken(types$1.regexp, {pattern: pattern, flags: flags, value: value}) 17067}; 17068 17069// Read an integer in the given radix. Return null if zero digits 17070// were read, the integer value otherwise. When `len` is given, this 17071// will return `null` unless the integer has exactly `len` digits. 17072 17073pp.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) { 17074 // `len` is used for character escape sequences. In that case, disallow separators. 17075 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined; 17076 17077 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b) 17078 // and isn't fraction part nor exponent part. In that case, if the first digit 17079 // is zero then disallow separators. 17080 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48; 17081 17082 var start = this.pos, total = 0, lastCode = 0; 17083 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) { 17084 var code = this.input.charCodeAt(this.pos), val = (void 0); 17085 17086 if (allowSeparators && code === 95) { 17087 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); } 17088 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); } 17089 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); } 17090 lastCode = code; 17091 continue 17092 } 17093 17094 if (code >= 97) { val = code - 97 + 10; } // a 17095 else if (code >= 65) { val = code - 65 + 10; } // A 17096 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9 17097 else { val = Infinity; } 17098 if (val >= radix) { break } 17099 lastCode = code; 17100 total = total * radix + val; 17101 } 17102 17103 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); } 17104 if (this.pos === start || len != null && this.pos - start !== len) { return null } 17105 17106 return total 17107}; 17108 17109function stringToNumber(str, isLegacyOctalNumericLiteral) { 17110 if (isLegacyOctalNumericLiteral) { 17111 return parseInt(str, 8) 17112 } 17113 17114 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value. 17115 return parseFloat(str.replace(/_/g, "")) 17116} 17117 17118function stringToBigInt(str) { 17119 if (typeof BigInt !== "function") { 17120 return null 17121 } 17122 17123 // `BigInt(value)` throws syntax error if the string contains numeric separators. 17124 return BigInt(str.replace(/_/g, "")) 17125} 17126 17127pp.readRadixNumber = function(radix) { 17128 var start = this.pos; 17129 this.pos += 2; // 0x 17130 var val = this.readInt(radix); 17131 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); } 17132 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) { 17133 val = stringToBigInt(this.input.slice(start, this.pos)); 17134 ++this.pos; 17135 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } 17136 return this.finishToken(types$1.num, val) 17137}; 17138 17139// Read an integer, octal integer, or floating-point number. 17140 17141pp.readNumber = function(startsWithDot) { 17142 var start = this.pos; 17143 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); } 17144 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48; 17145 if (octal && this.strict) { this.raise(start, "Invalid number"); } 17146 var next = this.input.charCodeAt(this.pos); 17147 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) { 17148 var val$1 = stringToBigInt(this.input.slice(start, this.pos)); 17149 ++this.pos; 17150 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } 17151 return this.finishToken(types$1.num, val$1) 17152 } 17153 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; } 17154 if (next === 46 && !octal) { // '.' 17155 ++this.pos; 17156 this.readInt(10); 17157 next = this.input.charCodeAt(this.pos); 17158 } 17159 if ((next === 69 || next === 101) && !octal) { // 'eE' 17160 next = this.input.charCodeAt(++this.pos); 17161 if (next === 43 || next === 45) { ++this.pos; } // '+-' 17162 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); } 17163 } 17164 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); } 17165 17166 var val = stringToNumber(this.input.slice(start, this.pos), octal); 17167 return this.finishToken(types$1.num, val) 17168}; 17169 17170// Read a string value, interpreting backslash-escapes. 17171 17172pp.readCodePoint = function() { 17173 var ch = this.input.charCodeAt(this.pos), code; 17174 17175 if (ch === 123) { // '{' 17176 if (this.options.ecmaVersion < 6) { this.unexpected(); } 17177 var codePos = ++this.pos; 17178 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos); 17179 ++this.pos; 17180 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); } 17181 } else { 17182 code = this.readHexChar(4); 17183 } 17184 return code 17185}; 17186 17187pp.readString = function(quote) { 17188 var out = "", chunkStart = ++this.pos; 17189 for (;;) { 17190 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); } 17191 var ch = this.input.charCodeAt(this.pos); 17192 if (ch === quote) { break } 17193 if (ch === 92) { // '\' 17194 out += this.input.slice(chunkStart, this.pos); 17195 out += this.readEscapedChar(false); 17196 chunkStart = this.pos; 17197 } else if (ch === 0x2028 || ch === 0x2029) { 17198 if (this.options.ecmaVersion < 10) { this.raise(this.start, "Unterminated string constant"); } 17199 ++this.pos; 17200 if (this.options.locations) { 17201 this.curLine++; 17202 this.lineStart = this.pos; 17203 } 17204 } else { 17205 if (isNewLine(ch)) { this.raise(this.start, "Unterminated string constant"); } 17206 ++this.pos; 17207 } 17208 } 17209 out += this.input.slice(chunkStart, this.pos++); 17210 return this.finishToken(types$1.string, out) 17211}; 17212 17213// Reads template string tokens. 17214 17215var INVALID_TEMPLATE_ESCAPE_ERROR = {}; 17216 17217pp.tryReadTemplateToken = function() { 17218 this.inTemplateElement = true; 17219 try { 17220 this.readTmplToken(); 17221 } catch (err) { 17222 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) { 17223 this.readInvalidTemplateToken(); 17224 } else { 17225 throw err 17226 } 17227 } 17228 17229 this.inTemplateElement = false; 17230}; 17231 17232pp.invalidStringToken = function(position, message) { 17233 if (this.inTemplateElement && this.options.ecmaVersion >= 9) { 17234 throw INVALID_TEMPLATE_ESCAPE_ERROR 17235 } else { 17236 this.raise(position, message); 17237 } 17238}; 17239 17240pp.readTmplToken = function() { 17241 var out = "", chunkStart = this.pos; 17242 for (;;) { 17243 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); } 17244 var ch = this.input.charCodeAt(this.pos); 17245 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${' 17246 if (this.pos === this.start && (this.type === types$1.template || this.type === types$1.invalidTemplate)) { 17247 if (ch === 36) { 17248 this.pos += 2; 17249 return this.finishToken(types$1.dollarBraceL) 17250 } else { 17251 ++this.pos; 17252 return this.finishToken(types$1.backQuote) 17253 } 17254 } 17255 out += this.input.slice(chunkStart, this.pos); 17256 return this.finishToken(types$1.template, out) 17257 } 17258 if (ch === 92) { // '\' 17259 out += this.input.slice(chunkStart, this.pos); 17260 out += this.readEscapedChar(true); 17261 chunkStart = this.pos; 17262 } else if (isNewLine(ch)) { 17263 out += this.input.slice(chunkStart, this.pos); 17264 ++this.pos; 17265 switch (ch) { 17266 case 13: 17267 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } 17268 case 10: 17269 out += "\n"; 17270 break 17271 default: 17272 out += String.fromCharCode(ch); 17273 break 17274 } 17275 if (this.options.locations) { 17276 ++this.curLine; 17277 this.lineStart = this.pos; 17278 } 17279 chunkStart = this.pos; 17280 } else { 17281 ++this.pos; 17282 } 17283 } 17284}; 17285 17286// Reads a template token to search for the end, without validating any escape sequences 17287pp.readInvalidTemplateToken = function() { 17288 for (; this.pos < this.input.length; this.pos++) { 17289 switch (this.input[this.pos]) { 17290 case "\\": 17291 ++this.pos; 17292 break 17293 17294 case "$": 17295 if (this.input[this.pos + 1] !== "{") { 17296 break 17297 } 17298 17299 // falls through 17300 case "`": 17301 return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos)) 17302 17303 // no default 17304 } 17305 } 17306 this.raise(this.start, "Unterminated template"); 17307}; 17308 17309// Used to read escaped characters 17310 17311pp.readEscapedChar = function(inTemplate) { 17312 var ch = this.input.charCodeAt(++this.pos); 17313 ++this.pos; 17314 switch (ch) { 17315 case 110: return "\n" // 'n' -> '\n' 17316 case 114: return "\r" // 'r' -> '\r' 17317 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x' 17318 case 117: return codePointToString(this.readCodePoint()) // 'u' 17319 case 116: return "\t" // 't' -> '\t' 17320 case 98: return "\b" // 'b' -> '\b' 17321 case 118: return "\u000b" // 'v' -> '\u000b' 17322 case 102: return "\f" // 'f' -> '\f' 17323 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n' 17324 case 10: // ' \n' 17325 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; } 17326 return "" 17327 case 56: 17328 case 57: 17329 if (this.strict) { 17330 this.invalidStringToken( 17331 this.pos - 1, 17332 "Invalid escape sequence" 17333 ); 17334 } 17335 if (inTemplate) { 17336 var codePos = this.pos - 1; 17337 17338 this.invalidStringToken( 17339 codePos, 17340 "Invalid escape sequence in template string" 17341 );
vendor: 1,471 bytes, lines 17342-17390
17342 17343 return null 17344 } 17345 default: 17346 if (ch >= 48 && ch <= 55) { 17347 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0]; 17348 var octal = parseInt(octalStr, 8); 17349 if (octal > 255) { 17350 octalStr = octalStr.slice(0, -1); 17351 octal = parseInt(octalStr, 8); 17352 } 17353 this.pos += octalStr.length - 1; 17354 ch = this.input.charCodeAt(this.pos); 17355 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) { 17356 this.invalidStringToken( 17357 this.pos - 1 - octalStr.length, 17358 inTemplate 17359 ? "Octal literal in template string" 17360 : "Octal literal in strict mode" 17361 ); 17362 } 17363 return String.fromCharCode(octal) 17364 } 17365 if (isNewLine(ch)) { 17366 // Unicode new line characters after \ get removed from output in both 17367 // template literals and strings 17368 return "" 17369 } 17370 return String.fromCharCode(ch) 17371 } 17372}; 17373 17374// Used to read character escape sequences ('\x', '\u', '\U'). 17375 17376pp.readHexChar = function(len) { 17377 var codePos = this.pos; 17378 var n = this.readInt(16, len); 17379 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); } 17380 return n 17381}; 17382 17383// Read an identifier, and return it as a string. Sets `this.containsEsc` 17384// to whether the word contained a '\u' escape. 17385// 17386// Incrementally adds only escaped chars, adding other chunks as-is 17387// as a micro-optimization. 17388 17389pp.readWord1 = function() { 17390 this.containsEsc = false;
vendor: 11,452 bytes, lines 17391-17803
17391 var word = "", first = true, chunkStart = this.pos; 17392 var astral = this.options.ecmaVersion >= 6; 17393 while (this.pos < this.input.length) { 17394 var ch = this.fullCharCodeAtPos(); 17395 if (isIdentifierChar(ch, astral)) { 17396 this.pos += ch <= 0xffff ? 1 : 2; 17397 } else if (ch === 92) { // "\" 17398 this.containsEsc = true; 17399 word += this.input.slice(chunkStart, this.pos); 17400 var escStart = this.pos; 17401 if (this.input.charCodeAt(++this.pos) !== 117) // "u" 17402 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); } 17403 ++this.pos; 17404 var esc = this.readCodePoint(); 17405 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) 17406 { this.invalidStringToken(escStart, "Invalid Unicode escape"); } 17407 word += codePointToString(esc); 17408 chunkStart = this.pos; 17409 } else { 17410 break 17411 } 17412 first = false; 17413 } 17414 return word + this.input.slice(chunkStart, this.pos) 17415}; 17416 17417// Read an identifier or keyword token. Will check for reserved 17418// words when necessary. 17419 17420pp.readWord = function() { 17421 var word = this.readWord1(); 17422 var type = types$1.name; 17423 if (this.keywords.test(word)) { 17424 type = keywords[word]; 17425 } 17426 return this.finishToken(type, word) 17427}; 17428 17429// Acorn is a tiny, fast JavaScript parser written in JavaScript. 17430 17431var version = "8.8.1"; 17432 17433Parser.acorn = { 17434 Parser: Parser, 17435 version: version, 17436 defaultOptions: defaultOptions, 17437 Position: Position, 17438 SourceLocation: SourceLocation, 17439 getLineInfo: getLineInfo, 17440 Node: Node$1, 17441 TokenType: TokenType, 17442 tokTypes: types$1, 17443 keywordTypes: keywords, 17444 TokContext: TokContext, 17445 tokContexts: types, 17446 isIdentifierChar: isIdentifierChar, 17447 isIdentifierStart: isIdentifierStart, 17448 Token: Token, 17449 isNewLine: isNewLine, 17450 lineBreak: lineBreak, 17451 lineBreakG: lineBreakG, 17452 nonASCIIwhitespace: nonASCIIwhitespace 17453}; 17454 17455var defaultGlobals = new Set([ 17456 "Array", 17457 "ArrayBuffer", 17458 "atob", 17459 "AudioContext", 17460 "Blob", 17461 "Boolean", 17462 "BigInt", 17463 "btoa", 17464 "clearInterval", 17465 "clearTimeout", 17466 "console", 17467 "crypto", 17468 "CustomEvent", 17469 "DataView", 17470 "Date", 17471 "decodeURI", 17472 "decodeURIComponent", 17473 "devicePixelRatio", 17474 "document", 17475 "encodeURI", 17476 "encodeURIComponent", 17477 "Error", 17478 "escape", 17479 "eval", 17480 "fetch", 17481 "File", 17482 "FileList", 17483 "FileReader", 17484 "Float32Array", 17485 "Float64Array", 17486 "Function", 17487 "Headers", 17488 "Image", 17489 "ImageData", 17490 "Infinity", 17491 "Int16Array", 17492 "Int32Array", 17493 "Int8Array", 17494 "Intl", 17495 "isFinite", 17496 "isNaN", 17497 "JSON", 17498 "Map", 17499 "Math", 17500 "NaN", 17501 "Number", 17502 "navigator", 17503 "Object", 17504 "parseFloat", 17505 "parseInt", 17506 "performance", 17507 "Path2D", 17508 "Promise", 17509 "Proxy", 17510 "RangeError", 17511 "ReferenceError", 17512 "Reflect", 17513 "RegExp", 17514 "cancelAnimationFrame", 17515 "requestAnimationFrame", 17516 "Set", 17517 "setInterval", 17518 "setTimeout", 17519 "String", 17520 "Symbol", 17521 "SyntaxError", 17522 "TextDecoder", 17523 "TextEncoder", 17524 "this", 17525 "TypeError", 17526 "Uint16Array", 17527 "Uint32Array", 17528 "Uint8Array", 17529 "Uint8ClampedArray", 17530 "undefined", 17531 "unescape", 17532 "URIError", 17533 "URL", 17534 "WeakMap", 17535 "WeakSet", 17536 "WebSocket", 17537 "Worker", 17538 "window" 17539]); 17540 17541// AST walker module for Mozilla Parser API compatible trees 17542 17543// A simple walk is one where you simply specify callbacks to be 17544// called on specific nodes. The last two arguments are optional. A 17545// simple use would be 17546// 17547// walk.simple(myTree, { 17548// Expression: function(node) { ... } 17549// }); 17550// 17551// to do something with all expressions. All Parser API node types 17552// can be used to identify node types, as well as Expression and 17553// Statement, which denote categories of nodes. 17554// 17555// The base argument can be used to pass a custom (recursive) 17556// walker, and state can be used to give this walked an initial 17557// state. 17558 17559function simple(node, visitors, baseVisitor, state, override) { 17560 if (!baseVisitor) { baseVisitor = base 17561 ; }(function c(node, st, override) { 17562 var type = override || node.type, found = visitors[type]; 17563 baseVisitor[type](node, st, c); 17564 if (found) { found(node, st); } 17565 })(node, state, override); 17566} 17567 17568// An ancestor walk keeps an array of ancestor nodes (including the 17569// current node) and passes them to the callback as third parameter 17570// (and also as state parameter when no other state is present). 17571function ancestor(node, visitors, baseVisitor, state, override) { 17572 var ancestors = []; 17573 if (!baseVisitor) { baseVisitor = base 17574 ; }(function c(node, st, override) { 17575 var type = override || node.type, found = visitors[type]; 17576 var isNew = node !== ancestors[ancestors.length - 1]; 17577 if (isNew) { ancestors.push(node); } 17578 baseVisitor[type](node, st, c); 17579 if (found) { found(node, st || ancestors, ancestors); } 17580 if (isNew) { ancestors.pop(); } 17581 })(node, state, override); 17582} 17583 17584// Used to create a custom walker. Will fill in all missing node 17585// type properties with the defaults. 17586function make(funcs, baseVisitor) { 17587 var visitor = Object.create(baseVisitor || base); 17588 for (var type in funcs) { visitor[type] = funcs[type]; } 17589 return visitor 17590} 17591 17592function skipThrough(node, st, c) { c(node, st); } 17593function ignore(_node, _st, _c) {} 17594 17595// Node walkers. 17596 17597var base = {}; 17598 17599base.Program = base.BlockStatement = base.StaticBlock = function (node, st, c) { 17600 for (var i = 0, list = node.body; i < list.length; i += 1) 17601 { 17602 var stmt = list[i]; 17603 17604 c(stmt, st, "Statement"); 17605 } 17606}; 17607base.Statement = skipThrough; 17608base.EmptyStatement = ignore; 17609base.ExpressionStatement = base.ParenthesizedExpression = base.ChainExpression = 17610 function (node, st, c) { return c(node.expression, st, "Expression"); }; 17611base.IfStatement = function (node, st, c) { 17612 c(node.test, st, "Expression"); 17613 c(node.consequent, st, "Statement"); 17614 if (node.alternate) { c(node.alternate, st, "Statement"); } 17615}; 17616base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); }; 17617base.BreakStatement = base.ContinueStatement = ignore; 17618base.WithStatement = function (node, st, c) { 17619 c(node.object, st, "Expression"); 17620 c(node.body, st, "Statement"); 17621}; 17622base.SwitchStatement = function (node, st, c) { 17623 c(node.discriminant, st, "Expression"); 17624 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) { 17625 var cs = list$1[i$1]; 17626 17627 if (cs.test) { c(cs.test, st, "Expression"); } 17628 for (var i = 0, list = cs.consequent; i < list.length; i += 1) 17629 { 17630 var cons = list[i]; 17631 17632 c(cons, st, "Statement"); 17633 } 17634 } 17635}; 17636base.SwitchCase = function (node, st, c) { 17637 if (node.test) { c(node.test, st, "Expression"); } 17638 for (var i = 0, list = node.consequent; i < list.length; i += 1) 17639 { 17640 var cons = list[i]; 17641 17642 c(cons, st, "Statement"); 17643 } 17644}; 17645base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) { 17646 if (node.argument) { c(node.argument, st, "Expression"); } 17647}; 17648base.ThrowStatement = base.SpreadElement = 17649 function (node, st, c) { return c(node.argument, st, "Expression"); }; 17650base.TryStatement = function (node, st, c) { 17651 c(node.block, st, "Statement"); 17652 if (node.handler) { c(node.handler, st); } 17653 if (node.finalizer) { c(node.finalizer, st, "Statement"); } 17654}; 17655base.CatchClause = function (node, st, c) { 17656 if (node.param) { c(node.param, st, "Pattern"); } 17657 c(node.body, st, "Statement"); 17658}; 17659base.WhileStatement = base.DoWhileStatement = function (node, st, c) { 17660 c(node.test, st, "Expression"); 17661 c(node.body, st, "Statement"); 17662}; 17663base.ForStatement = function (node, st, c) { 17664 if (node.init) { c(node.init, st, "ForInit"); } 17665 if (node.test) { c(node.test, st, "Expression"); } 17666 if (node.update) { c(node.update, st, "Expression"); } 17667 c(node.body, st, "Statement"); 17668}; 17669base.ForInStatement = base.ForOfStatement = function (node, st, c) { 17670 c(node.left, st, "ForInit"); 17671 c(node.right, st, "Expression"); 17672 c(node.body, st, "Statement"); 17673}; 17674base.ForInit = function (node, st, c) { 17675 if (node.type === "VariableDeclaration") { c(node, st); } 17676 else { c(node, st, "Expression"); } 17677}; 17678base.DebuggerStatement = ignore; 17679 17680base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); }; 17681base.VariableDeclaration = function (node, st, c) { 17682 for (var i = 0, list = node.declarations; i < list.length; i += 1) 17683 { 17684 var decl = list[i]; 17685 17686 c(decl, st); 17687 } 17688}; 17689base.VariableDeclarator = function (node, st, c) { 17690 c(node.id, st, "Pattern"); 17691 if (node.init) { c(node.init, st, "Expression"); } 17692}; 17693 17694base.Function = function (node, st, c) { 17695 if (node.id) { c(node.id, st, "Pattern"); } 17696 for (var i = 0, list = node.params; i < list.length; i += 1) 17697 { 17698 var param = list[i]; 17699 17700 c(param, st, "Pattern"); 17701 } 17702 c(node.body, st, node.expression ? "Expression" : "Statement"); 17703}; 17704 17705base.Pattern = function (node, st, c) { 17706 if (node.type === "Identifier") 17707 { c(node, st, "VariablePattern"); } 17708 else if (node.type === "MemberExpression") 17709 { c(node, st, "MemberPattern"); } 17710 else 17711 { c(node, st); } 17712}; 17713base.VariablePattern = ignore; 17714base.MemberPattern = skipThrough; 17715base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); }; 17716base.ArrayPattern = function (node, st, c) { 17717 for (var i = 0, list = node.elements; i < list.length; i += 1) { 17718 var elt = list[i]; 17719 17720 if (elt) { c(elt, st, "Pattern"); } 17721 } 17722}; 17723base.ObjectPattern = function (node, st, c) { 17724 for (var i = 0, list = node.properties; i < list.length; i += 1) { 17725 var prop = list[i]; 17726 17727 if (prop.type === "Property") { 17728 if (prop.computed) { c(prop.key, st, "Expression"); } 17729 c(prop.value, st, "Pattern"); 17730 } else if (prop.type === "RestElement") { 17731 c(prop.argument, st, "Pattern"); 17732 } 17733 } 17734}; 17735 17736base.Expression = skipThrough; 17737base.ThisExpression = base.Super = base.MetaProperty = ignore; 17738base.ArrayExpression = function (node, st, c) { 17739 for (var i = 0, list = node.elements; i < list.length; i += 1) { 17740 var elt = list[i]; 17741 17742 if (elt) { c(elt, st, "Expression"); } 17743 } 17744}; 17745base.ObjectExpression = function (node, st, c) { 17746 for (var i = 0, list = node.properties; i < list.length; i += 1) 17747 { 17748 var prop = list[i]; 17749 17750 c(prop, st); 17751 } 17752}; 17753base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration; 17754base.SequenceExpression = function (node, st, c) { 17755 for (var i = 0, list = node.expressions; i < list.length; i += 1) 17756 { 17757 var expr = list[i]; 17758 17759 c(expr, st, "Expression"); 17760 } 17761}; 17762base.TemplateLiteral = function (node, st, c) { 17763 for (var i = 0, list = node.quasis; i < list.length; i += 1) 17764 { 17765 var quasi = list[i]; 17766 17767 c(quasi, st); 17768 } 17769 17770 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1) 17771 { 17772 var expr = list$1[i$1]; 17773 17774 c(expr, st, "Expression"); 17775 } 17776}; 17777base.TemplateElement = ignore; 17778base.UnaryExpression = base.UpdateExpression = function (node, st, c) { 17779 c(node.argument, st, "Expression"); 17780}; 17781base.BinaryExpression = base.LogicalExpression = function (node, st, c) { 17782 c(node.left, st, "Expression"); 17783 c(node.right, st, "Expression"); 17784}; 17785base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) { 17786 c(node.left, st, "Pattern"); 17787 c(node.right, st, "Expression"); 17788}; 17789base.ConditionalExpression = function (node, st, c) { 17790 c(node.test, st, "Expression"); 17791 c(node.consequent, st, "Expression"); 17792 c(node.alternate, st, "Expression"); 17793}; 17794base.NewExpression = base.CallExpression = function (node, st, c) { 17795 c(node.callee, st, "Expression"); 17796 if (node.arguments) 17797 { for (var i = 0, list = node.arguments; i < list.length; i += 1) 17798 { 17799 var arg = list[i]; 17800 17801 c(arg, st, "Expression"); 17802 } } 17803};
17804base.MemberExpression = function (node, st, c) { 17805 c(node.object, st, "Expression"); 17806 if (node.computed) { c(node.property, st, "Expression"); } 17807}; 17808base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) { 17809 if (node.declaration) 17810 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); } 17811 if (node.source) { c(node.source, st, "Expression"); } 17812}; 17813base.ExportAllDeclaration = function (node, st, c) { 17814 if (node.exported) 17815 { c(node.exported, st); } 17816 c(node.source, st, "Expression"); 17817}; 17818base.ImportDeclaration = function (node, st, c) { 17819 for (var i = 0, list = node.specifiers; i < list.length; i += 1) 17820 { 17821 var spec = list[i]; 17822 17823 c(spec, st); 17824 } 17825 c(node.source, st, "Expression"); 17826}; 17827base.ImportExpression = function (node, st, c) { 17828 c(node.source, st, "Expression"); 17829}; 17830base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.PrivateIdentifier = base.Literal = ignore; 17831 17832base.TaggedTemplateExpression = function (node, st, c) { 17833 c(node.tag, st, "Expression"); 17834 c(node.quasi, st, "Expression"); 17835}; 17836base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); }; 17837base.Class = function (node, st, c) { 17838 if (node.id) { c(node.id, st, "Pattern"); } 17839 if (node.superClass) { c(node.superClass, st, "Expression"); } 17840 c(node.body, st); 17841}; 17842base.ClassBody = function (node, st, c) { 17843 for (var i = 0, list = node.body; i < list.length; i += 1) 17844 { 17845 var elt = list[i]; 17846 17847 c(elt, st); 17848 } 17849}; 17850base.MethodDefinition = base.PropertyDefinition = base.Property = function (node, st, c) { 17851 if (node.computed) { c(node.key, st, "Expression"); } 17852 if (node.value) { c(node.value, st, "Expression"); } 17853}; 17854 17855var walk = make({ 17856 Import() {}, 17857 ViewExpression(node, st, c) { 17858 c(node.id, st, "Identifier"); 17859 }, 17860 MutableExpression(node, st, c) { 17861 c(node.id, st, "Identifier"); 17862 } 17863}); 17864 17865// Based on https://github.com/ForbesLindesay/acorn-globals 17866 17867function isScope(node) { 17868 return node.type === "FunctionExpression" 17869 || node.type === "FunctionDeclaration" 17870 || node.type === "ArrowFunctionExpression" 17871 || node.type === "Program"; 17872} 17873 17874function isBlockScope(node) { 17875 return node.type === "BlockStatement" 17876 || node.type === "ForInStatement" 17877 || node.type === "ForOfStatement" 17878 || node.type === "ForStatement" 17879 || isScope(node); 17880} 17881 17882function declaresArguments(node) { 17883 return node.type === "FunctionExpression" 17884 || node.type === "FunctionDeclaration"; 17885} 17886 17887function findReferences(cell, globals) { 17888 const ast = {type: "Program", body: [cell.body]}; 17889 const locals = new Map; 17890 const globalSet = new Set(globals); 17891 const references = []; 17892 17893 function hasLocal(node, name) { 17894 const l = locals.get(node); 17895 return l ? l.has(name) : false; 17896 } 17897 17898 function declareLocal(node, id) { 17899 const l = locals.get(node); 17900 if (l) l.add(id.name); 17901 else locals.set(node, new Set([id.name])); 17902 } 17903 17904 function declareClass(node) { 17905 if (node.id) declareLocal(node, node.id); 17906 } 17907 17908 function declareFunction(node) { 17909 node.params.forEach(param => declarePattern(param, node)); 17910 if (node.id) declareLocal(node, node.id); 17911 } 17912 17913 function declareCatchClause(node) { 17914 if (node.param) declarePattern(node.param, node); 17915 } 17916 17917 function declarePattern(node, parent) { 17918 switch (node.type) { 17919 case "Identifier": 17920 declareLocal(parent, node); 17921 break; 17922 case "ObjectPattern": 17923 node.properties.forEach(node => declarePattern(node, parent)); 17924 break; 17925 case "ArrayPattern": 17926 node.elements.forEach(node => node && declarePattern(node, parent)); 17927 break; 17928 case "Property": 17929 declarePattern(node.value, parent); 17930 break; 17931 case "RestElement": 17932 declarePattern(node.argument, parent); 17933 break; 17934 case "AssignmentPattern": 17935 declarePattern(node.left, parent); 17936 break; 17937 default: 17938 throw new Error("Unrecognized pattern type: " + node.type); 17939 } 17940 } 17941 17942 function declareModuleSpecifier(node) { 17943 declareLocal(ast, node.local); 17944 } 17945 17946 ancestor( 17947 ast, 17948 { 17949 VariableDeclaration: (node, parents) => { 17950 let parent = null; 17951 for (let i = parents.length - 1; i >= 0 && parent === null; --i) { 17952 if (node.kind === "var" ? isScope(parents[i]) : isBlockScope(parents[i])) { 17953 parent = parents[i]; 17954 } 17955 } 17956 node.declarations.forEach(declaration => declarePattern(declaration.id, parent)); 17957 }, 17958 FunctionDeclaration: (node, parents) => { 17959 let parent = null; 17960 for (let i = parents.length - 2; i >= 0 && parent === null; --i) { 17961 if (isScope(parents[i])) { 17962 parent = parents[i]; 17963 } 17964 } 17965 declareLocal(parent, node.id); 17966 declareFunction(node); 17967 }, 17968 Function: declareFunction, 17969 ClassDeclaration: (node, parents) => { 17970 let parent = null; 17971 for (let i = parents.length - 2; i >= 0 && parent === null; i--) { 17972 if (isScope(parents[i])) { 17973 parent = parents[i]; 17974 } 17975 } 17976 declareLocal(parent, node.id); 17977 }, 17978 Class: declareClass, 17979 CatchClause: declareCatchClause, 17980 ImportDefaultSpecifier: declareModuleSpecifier, 17981 ImportSpecifier: declareModuleSpecifier, 17982 ImportNamespaceSpecifier: declareModuleSpecifier 17983 }, 17984 walk 17985 ); 17986 17987 function identifier(node, parents) { 17988 let name = node.name; 17989 if (name === "undefined") return; 17990 for (let i = parents.length - 2; i >= 0; --i) { 17991 if (name === "arguments") { 17992 if (declaresArguments(parents[i])) { 17993 return; 17994 } 17995 } 17996 if (hasLocal(parents[i], name)) { 17997 return; 17998 } 17999 if (parents[i].type === "ViewExpression") { 18000 node = parents[i]; 18001 name = `viewof ${node.id.name}`; 18002 } 18003 if (parents[i].type === "MutableExpression") { 18004 node = parents[i]; 18005 name = `mutable ${node.id.name}`; 18006 } 18007 } 18008 if (!globalSet.has(name)) { 18009 if (name === "arguments") { 18010 throw Object.assign(new SyntaxError(`arguments is not allowed`), {node}); 18011 } 18012 references.push(node); 18013 } 18014 } 18015 18016 ancestor( 18017 ast, 18018 { 18019 VariablePattern: identifier, 18020 Identifier: identifier 18021 }, 18022 walk 18023 ); 18024 18025 function checkConst(node, parents) { 18026 if (!node) return; 18027 switch (node.type) { 18028 case "Identifier": 18029 case "VariablePattern": { 18030 for (const parent of parents) { 18031 if (hasLocal(parent, node.name)) { 18032 return; 18033 } 18034 } 18035 if (parents[parents.length - 2].type === "MutableExpression") { 18036 return; 18037 } 18038 throw Object.assign(new SyntaxError(`Assignment to constant variable ${node.name}`), {node}); 18039 } 18040 case "ArrayPattern": { 18041 for (const element of node.elements) { 18042 checkConst(element, parents); 18043 } 18044 return; 18045 } 18046 case "ObjectPattern": { 18047 for (const property of node.properties) { 18048 checkConst(property, parents); 18049 } 18050 return; 18051 } 18052 case "Property": { 18053 checkConst(node.value, parents); 18054 return; 18055 } 18056 case "RestElement": { 18057 checkConst(node.argument, parents); 18058 return; 18059 } 18060 } 18061 } 18062 18063 function checkConstArgument(node, parents) { 18064 checkConst(node.argument, parents); 18065 } 18066 18067 function checkConstLeft(node, parents) { 18068 checkConst(node.left, parents); 18069 } 18070 18071 ancestor( 18072 ast, 18073 { 18074 AssignmentExpression: checkConstLeft, 18075 AssignmentPattern: checkConstLeft, 18076 UpdateExpression: checkConstArgument, 18077 ForOfStatement: checkConstLeft, 18078 ForInStatement: checkConstLeft 18079 }, 18080 walk 18081 ); 18082 18083 return references; 18084} 18085 18086function findFeatures(cell, featureName) { 18087 const ast = {type: "Program", body: [cell.body]}; 18088 const features = new Map(); 18089 const {references} = cell; 18090 18091 simple( 18092 ast, 18093 { 18094 CallExpression: node => { 18095 const {callee, arguments: args} = node; 18096 18097 // Ignore function calls that are not references to the feature. 18098 if ( 18099 callee.type !== "Identifier" || 18100 callee.name !== featureName || 18101 references.indexOf(callee) < 0 18102 ) return; 18103 18104 // Forbid dynamic calls. 18105 if ( 18106 args.length !== 1 || 18107 !((args[0].type === "Literal" && /^['"]/.test(args[0].raw)) || 18108 (args[0].type === "TemplateLiteral" && args[0].expressions.length === 0)) 18109 ) { 18110 throw Object.assign(new SyntaxError(`${featureName} requires a single literal string argument`), {node}); 18111 } 18112 18113 const [arg] = args; 18114 const name = arg.type === "Literal" ? arg.value : arg.quasis[0].value.cooked; 18115 const location = {start: arg.start, end: arg.end}; 18116 if (features.has(name)) features.get(name).push(location); 18117 else features.set(name, [location]); 18118 } 18119 }, 18120 walk 18121 ); 18122 18123 return features; 18124} 18125 18126const SCOPE_FUNCTION = 2; 18127const SCOPE_ASYNC = 4;
18128const SCOPE_GENERATOR = 8; 18129 18130class CellParser extends Parser { 18131 constructor(options, ...args) { 18132 super(Object.assign({ecmaVersion: 13}, options), ...args); 18133 } 18134 enterScope(flags) { 18135 if (flags & SCOPE_FUNCTION) ++this.O_function; 18136 return super.enterScope(flags); 18137 } 18138 exitScope() { 18139 if (this.currentScope().flags & SCOPE_FUNCTION) --this.O_function; 18140 return super.exitScope(); 18141 } 18142 parseForIn(node, init) { 18143 if (this.O_function === 1 && node.await) this.O_async = true; 18144 return super.parseForIn(node, init); 18145 } 18146 parseAwait() { 18147 if (this.O_function === 1) this.O_async = true; 18148 return super.parseAwait(); 18149 } 18150 parseYield(noIn) { 18151 if (this.O_function === 1) this.O_generator = true; 18152 return super.parseYield(noIn); 18153 } 18154 parseImport(node) { 18155 this.next(); 18156 node.specifiers = this.parseImportSpecifiers(); 18157 if (this.type === types$1._with) { 18158 this.next(); 18159 node.injections = this.parseImportSpecifiers(); 18160 } 18161 this.expectContextual("from"); 18162 node.source = this.type === types$1.string ? this.parseExprAtom() : this.unexpected(); 18163 return this.finishNode(node, "ImportDeclaration"); 18164 } 18165 parseImportSpecifiers() { 18166 const nodes = []; 18167 const identifiers = new Set; 18168 let first = true; 18169 this.expect(types$1.braceL); 18170 while (!this.eat(types$1.braceR)) { 18171 if (first) { 18172 first = false; 18173 } else { 18174 this.expect(types$1.comma); 18175 if (this.afterTrailingComma(types$1.braceR)) break; 18176 } 18177 const node = this.startNode(); 18178 node.view = this.eatContextual("viewof"); 18179 node.mutable = node.view ? false : this.eatContextual("mutable"); 18180 node.imported = this.parseIdent(); 18181 this.checkUnreserved(node.imported); 18182 this.checkLocal(node.imported); 18183 if (this.eatContextual("as")) { 18184 node.local = this.parseIdent(); 18185 this.checkUnreserved(node.local); 18186 this.checkLocal(node.local); 18187 } else { 18188 node.local = node.imported; 18189 } 18190 this.checkLValSimple(node.local, "let"); 18191 if (identifiers.has(node.local.name)) { 18192 this.raise(node.local.start, `Identifier '${node.local.name}' has already been declared`); 18193 } 18194 identifiers.add(node.local.name); 18195 nodes.push(this.finishNode(node, "ImportSpecifier")); 18196 } 18197 return nodes; 18198 } 18199 parseExprAtom(refDestructuringErrors) { 18200 return ( 18201 this.parseMaybeKeywordExpression("viewof", "ViewExpression") || 18202 this.parseMaybeKeywordExpression("mutable", "MutableExpression") || 18203 super.parseExprAtom(refDestructuringErrors) 18204 ); 18205 } 18206 startCell() { 18207 this.O_function = 0; 18208 this.O_async = false; 18209 this.O_generator = false; 18210 this.strict = true; 18211 this.enterScope(SCOPE_FUNCTION | SCOPE_ASYNC | SCOPE_GENERATOR); 18212 } 18213 finishCell(node, body, id) { 18214 if (id) this.checkLocal(id); 18215 node.id = id; 18216 node.body = body; 18217 node.async = this.O_async; 18218 node.generator = this.O_generator; 18219 this.exitScope(); 18220 return this.finishNode(node, "Cell"); 18221 } 18222 parseCell(node, eof) { 18223 const lookahead = new CellParser({}, this.input, this.start); 18224 let token = lookahead.getToken(); 18225 let body = null; 18226 let id = null; 18227 18228 this.startCell(); 18229 18230 // An import? 18231 if (token.type === types$1._import && lookahead.getToken().type !== types$1.parenL) { 18232 body = this.parseImport(this.startNode()); 18233 } 18234 18235 // A non-empty cell? 18236 else if (token.type !== types$1.eof && token.type !== types$1.semi) { 18237 // A named cell? 18238 if (token.type === types$1.name) { 18239 if (token.value === "viewof" || token.value === "mutable") { 18240 token = lookahead.getToken(); 18241 if (token.type !== types$1.name) { 18242 lookahead.unexpected(); 18243 } 18244 } 18245 token = lookahead.getToken(); 18246 if (token.type === types$1.eq) { 18247 id = 18248 this.parseMaybeKeywordExpression("viewof", "ViewExpression") || 18249 this.parseMaybeKeywordExpression("mutable", "MutableExpression") || 18250 this.parseIdent(); 18251 token = lookahead.getToken(); 18252 this.expect(types$1.eq); 18253 } 18254 } 18255 18256 // A block? 18257 if (token.type === types$1.braceL) { 18258 body = this.parseBlock(); 18259 } 18260 18261 // An expression? 18262 // Possibly a function or class declaration? 18263 else { 18264 body = this.parseExpression(); 18265 if ( 18266 id === null && 18267 (body.type === "FunctionExpression" || 18268 body.type === "ClassExpression") 18269 ) { 18270 id = body.id; 18271 } 18272 } 18273 } 18274 18275 this.semicolon(); 18276 if (eof) this.expect(types$1.eof); // TODO 18277 18278 return this.finishCell(node, body, id); 18279 } 18280 parseTopLevel(node) { 18281 return this.parseCell(node, true); 18282 } 18283 toAssignable(node, isBinding, refDestructuringErrors) { 18284 return node.type === "MutableExpression" 18285 ? node 18286 : super.toAssignable(node, isBinding, refDestructuringErrors); 18287 } 18288 checkLocal(id) { 18289 const node = id.id || id; 18290 if (defaultGlobals.has(node.name) || node.name === "arguments") { 18291 this.raise(node.start, `Identifier '${node.name}' is reserved`); 18292 } 18293 } 18294 checkUnreserved(node) { 18295 if (node.name === "viewof" || node.name === "mutable") { 18296 this.raise(node.start, `Unexpected keyword '${node.name}'`); 18297 } 18298 return super.checkUnreserved(node); 18299 } 18300 checkLValSimple(expr, bindingType, checkClashes) { 18301 return super.checkLValSimple( 18302 expr.type === "MutableExpression" ? expr.id : expr, 18303 bindingType, 18304 checkClashes 18305 ); 18306 } 18307 unexpected(pos) { 18308 this.raise( 18309 pos != null ? pos : this.start, 18310 this.type === types$1.eof ? "Unexpected end of input" : "Unexpected token" 18311 ); 18312 } 18313 parseMaybeKeywordExpression(keyword, type) { 18314 if (this.isContextual(keyword)) { 18315 const node = this.startNode(); 18316 this.next(); 18317 node.id = this.parseIdent(); 18318 return this.finishNode(node, type); 18319 } 18320 } 18321} 18322 18323// Based on acornâs q_tmpl. We will use this to initialize the 18324// parser context so our `readTemplateToken` override is called. 18325// `readTemplateToken` is based on acorn's `readTmplToken` which 18326// is used inside template literals. Our version allows backQuotes. 18327new TokContext( 18328 "`", // token 18329 true, // isExpr 18330 true, // preserveSpace 18331 parser => readTemplateToken.call(parser) // override 18332); 18333 18334// This is our custom override for parsing a template that allows backticks.
18335// Based on acorn's readInvalidTemplateToken. 18336function readTemplateToken() { 18337 out: for (; this.pos < this.input.length; this.pos++) { 18338 switch (this.input.charCodeAt(this.pos)) { 18339 case 92: { // slash 18340 if (this.pos < this.input.length - 1) ++this.pos; // not a terminal slash 18341 break; 18342 } 18343 case 36: { // dollar 18344 if (this.input.charCodeAt(this.pos + 1) === 123) { // dollar curly 18345 if (this.pos === this.start && this.type === types$1.invalidTemplate) { 18346 this.pos += 2; 18347 return this.finishToken(types$1.dollarBraceL); 18348 } 18349 break out; 18350 } 18351 break; 18352 } 18353 } 18354 } 18355 return this.finishToken(types$1.invalidTemplate, this.input.slice(this.start, this.pos)); 18356} 18357 18358// Find references. 18359// Check for illegal references to arguments. 18360// Check for illegal assignments to global references. 18361function parseReferences(cell, input, globals = defaultGlobals) { 18362 if (!cell.body) { 18363 cell.references = []; 18364 } else if (cell.body.type === "ImportDeclaration") { 18365 cell.references = cell.body.injections 18366 ? cell.body.injections.map(i => i.imported) 18367 : []; 18368 } else { 18369 try { 18370 cell.references = findReferences(cell, globals); 18371 } catch (error) { 18372 if (error.node) { 18373 const loc = getLineInfo(input, error.node.start); 18374 error.message += ` (${loc.line}:${loc.column})`; 18375 error.pos = error.node.start; 18376 error.loc = loc; 18377 delete error.node; 18378 } 18379 throw error; 18380 } 18381 } 18382 return cell; 18383} 18384 18385// Find features: file attachments, secrets, database clients. 18386// Check for illegal references to arguments. 18387// Check for illegal assignments to global references. 18388function parseFeatures(cell, input) { 18389 if (cell.body && cell.body.type !== "ImportDeclaration") { 18390 try { 18391 cell.fileAttachments = findFeatures(cell, "FileAttachment"); 18392 cell.databaseClients = findFeatures(cell, "DatabaseClient"); 18393 cell.secrets = findFeatures(cell, "Secret"); 18394 } catch (error) { 18395 if (error.node) { 18396 const loc = getLineInfo(input, error.node.start); 18397 error.message += ` (${loc.line}:${loc.column})`; 18398 error.pos = error.node.start; 18399 error.loc = loc; 18400 delete error.node; 18401 } 18402 throw error; 18403 } 18404 } else { 18405 cell.fileAttachments = new Map(); 18406 cell.databaseClients = new Map(); 18407 cell.secrets = new Map(); 18408 } 18409 return cell; 18410} 18411 18412/* Fork changes begin here */ 18413 18414function parseModule(input, {globals} = {}) { 18415 const program = ModuleParser.parse(input); 18416 for (const cell of program.cells) { 18417 parseReferences(cell, input, globals); 18418 parseFeatures(cell, input); 18419 } 18420 return program; 18421} 18422 18423class ModuleParser extends CellParser { 18424 parseTopLevel(node) { 18425 if (!node.cells) node.cells = []; 18426 while (this.type !== types$1.eof) { 18427 const cell = this.parseCell(this.startNode()); 18428 cell.input = this.input; 18429 node.cells.push(cell); 18430 } 18431 this.next(); 18432 return this.finishNode(node, "Program"); 18433 } 18434} 18435 18436/* Fork changes end here */ 18437 18438/*global Shiny, $, DOMParser, MutationObserver, URL 18439* 18440* ojs-connector.js 18441* 18442* Copyright (C) 2022 RStudio, PBC 18443* 18444*/ 18445 18446////////////////////////////////////////////////////////////////////////////// 18447 18448class EmptyInspector { 18449 pending() { 18450 } 18451 fulfilled(_value, _name) { 18452 } 18453 rejected(_error, _name) { 18454 // TODO we should probably communicate this upstream somehow. 18455 } 18456} 18457 18458// here we need to convert from an ES6 module to an observable module 18459// in, well, a best-effort kind of way. 18460function es6ImportAsObservableModule(modulePromise, specs) { 18461 const promiseMap = {}; 18462 const resolveMap = {}; 18463 specs.forEach(spec => { 18464 promiseMap[spec] = new Promise((resolve, reject) => { resolveMap[spec] = { resolve, reject }; }); 18465 }); 18466 modulePromise.then(m => { 18467 specs.forEach(spec => { 18468 resolveMap[spec].resolve(m[spec]); 18469 }); 18470 }).catch(error => { 18471 specs.forEach(spec => { 18472 resolveMap[spec].reject(error); 18473 }); 18474 }); 18475 return function (runtime, observer) { 18476 const main = runtime.module(); 18477 18478 specs.forEach(key => { 18479 main.variable(observer(key)).define(key, [], () => promiseMap[key]); 18480 }); 18481/*
18482 Object.keys(m).forEach((key) => { 18483 const v = m[key]; 18484 18485 main.variable(observer(key)).define(key, [], () => promiseMap[key]v); 18486 }); 18487 */ 18488 return main; 18489 }; 18490} 18491 18492 18493// this is essentially the import resolution code from observable's 18494// runtime. we change it to add a license check for permissive 18495// open-source licenses before resolving the import 18496async function defaultResolveImportPath(path) { 18497 const extractPath = (path) => { 18498 let source = path; 18499 let m; 18500 if ((m = /\.js(\?|$)/i.exec(source))) { 18501 source = source.slice(0, m.index); 18502 } 18503 if ((m = /^[0-9a-f]{16}$/i.test(source))) { 18504 source = `d/${source}`; 18505 } 18506 if ((m = /^https:\/\/(api\.|beta\.|)observablehq\.com\//i.exec(source))) { 18507 source = source.slice(m[0].length); 18508 } 18509 return source; 18510 }; 18511 const source = extractPath(path); 18512 const moduleURL = `https://api.observablehq.com/${source}.js?v=3`; 18513 18514 /* TODO This should be the implementation we use, once/if observable 18515 starts reporting notebook license on their metadata. 18516 18517 const metadata = await fetch(metadataURL, { mode: 'no-cors' }); 18518 const nbJson = metadata.json(); 18519 if (["isc", "mit", "bsd-3-clause", "apache-2.0"].indexOf(nbJson.license) === -1) { 18520 throw new Error(`Notebook doesn't have a permissive open-source license`); 18521 } */ 18522 18523 const m = await import(moduleURL); 18524 return m.default; 18525} 18526 18527/* 18528 importPathResolver encodes the rules for ojsconnector to resolve 18529 import statements. 18530 18531 This code doesn't depend have any dependencies on quarto, but some 18532 of the decisions here are influence by the needs of the quarto 18533 system. 18534 18535 We use the same name from observable's runtime so the intended 18536 functionality is clear. However, note that their name is slightly 18537 misleading. importPathResolver not only resolves import paths but 18538 performs module imports as well. This is useful for us because it 18539 allows us to extend the meaning of ojs's import statement, but it 18540 makes the name confusing. 18541 18542 Here are the rules for our version of the import statement. 18543 18544 The function returned by importPathResolver expects a "module specifier", and 18545 produces a module as defined by observable's runtime. 18546 18547 ## Local vs remote vs observable imports 18548 18549 A module specifier is a string, interpreted differently depending on 18550 the following properties: 18551 18552 - it starts with "." or "/", in which case we call it a "local module" 18553 18554 - it is a well-defined absolute URL which does _not_ match the regexp: 18555 /^https:\/\/(api\.|beta\.|)observablehq\.com\//i 18556 in which case we call it a "remote import" 18557 18558 - otherwise, it is an "observable import" 18559 18560 If the string is an observable import, it behaves exactly like the import 18561 statement inside observable notebooks (we actually defer to their function 18562 call.) Otherwise, the import statement first retrieves the text content 18563 of the resource referenced by the path, and then interprets it. 18564 18565 ## where resources come from 18566 18567 When operating in non-self-contained mode, local and remote import 18568 paths are then interpreted as relative URLs (RFC 1808) with base URL 18569 window.location (specifically as "relative path" and "absolute path" 18570 relative URLs). 18571 18572 In self-contained mode, these paths are interpreted as paths in the 18573 quarto project, either as root-relative or relative paths. The 18574 contents of these files are converted to data URLs and stored in a 18575 local resolution map. 18576 18577 ## how are contents interpreted 18578 18579 The contents of the resource are then interpreted differently 18580 depending on the file type of the requested resource. 18581 18582 For non-self-contained imports, the file type is determined by the 18583 extension of the URL pathname. If the extension is "js", we take the 18584 specifier to mean an ES module; If the extension is "ojs", we take 18585 the specifier to mean an "ojs" module (a collection of observable 18586 statements packaged into a module, suitable for reuse). If the 18587 extension is "ts" or "tsx", then this is an import that was actually transpiled 18588 into js during quarto render, and we change the extension to .js and 18589 resolve that. Finally, if the extension is "qmd", we take the specifier 18590 to mean an "implicit ojs module", equivalent to extracting all 18591 the ojs statements from the .qmd file and producing an OJS module. 18592
18593 For self-contained imports, the file type is determined by the MIME 18594 type of the data URL. "application/javascript" is interpreted to 18595 mean an ES module, and "application/ojs-javascript" is interpreted 18596 to mean an "ojs" module. (.qmd imports will have been 18597 translated to ojs modules by the compilation step.) 18598 18599 The resources are finally retrieved, compiled into modules 18600 compatible with the observable runtime, and returned as 18601 the result of the import statement. 18602 18603*/ 18604 18605function importPathResolver(paths, localResolverMap) { 18606 // NB: only resolve the field values in paths when calling rootPath 18607 // and relativePath. If we prematurely optimize this by moving the 18608 // const declarations outside, then we will capture the 18609 // uninitialized values. 18610 18611 // fetch() and import() have different relative path semantics, so 18612 // we need different paths for each use case 18613 18614 function importRootPath(path) { 18615 const { runtimeToRoot } = paths; 18616 if (!runtimeToRoot) { 18617 return path; 18618 } else { 18619 return `${runtimeToRoot}/${path}`;
18620 } 18621 } 18622 18623 function importRelativePath(path) { 18624 const { runtimeToDoc } = paths; 18625 if (!runtimeToDoc) { 18626 return path; 18627 } else { 18628 return `${runtimeToDoc}/${path}`; 18629 } 18630 } 18631 18632 // a fetch path of a root-relative path is resolved wrt to 18633 // the document root 18634 function fetchRootPath(path) { 18635 const { docToRoot } = paths; 18636 if (!docToRoot) { 18637 return path; 18638 } else { 18639 return `${docToRoot}/${path}`; 18640 } 18641 } 18642 18643 // a fetch path of a relative path is resolved the naive way 18644 function fetchRelativePath(path) { 18645 return path; 18646 } 18647 18648 return async (path, specs) => { 18649 const isLocalModule = path.startsWith("/") || path.startsWith("."); 18650 const isImportFromObservableWebsite = path.match( 18651 /^https:\/\/(api\.|beta\.|)observablehq\.com\//i, 18652 ); 18653 18654 if (!isLocalModule || isImportFromObservableWebsite) { 18655 return defaultResolveImportPath(path); 18656 } 18657 18658 let importPath, fetchPath; 18659 let moduleType; 18660 if (window._ojs.selfContained) { 18661 if (path.endsWith(".ts")) { 18662 path = path.replace(/\.ts$/, ".js"); 18663 } else if (path.endsWith(".tsx")) { 18664 path = path.replace(/\.tsx$/, ".js"); 18665 } 18666 const resolved = localResolverMap.get(path); 18667 if (resolved === undefined) { 18668 throw new Error(`missing local file ${path} in self-contained mode`); 18669 } 18670 // self-contained resolves to data URLs, so they behave the same. 18671 importPath = resolved; 18672 fetchPath = resolved; 18673 18674 // we have a data URL here. 18675 const mimeType = resolved.match(/data:(.*);base64/)[1]; 18676 switch (mimeType) { 18677 case "application/javascript": 18678 moduleType = "js"; 18679 break; 18680 case "application/ojs-javascript": 18681 moduleType = "ojs"; 18682 break; 18683 default: 18684 throw new Error(`unrecognized MIME type ${mimeType}`); 18685 } 18686 } else { 18687 // we have a relative URL here 18688 const resourceURL = new URL(path, window.location); 18689 moduleType = resourceURL.pathname.match(/\.(ojs|js|ts|tsx|qmd)$/)[1]; 18690 18691 // resolve path according to quarto path resolution rules. 18692 if (path.startsWith("/")) { 18693 importPath = importRootPath(path); 18694 fetchPath = fetchRootPath(path); 18695 } else { 18696 importPath = importRelativePath(path); 18697 fetchPath = fetchRelativePath(path); 18698 } 18699 } 18700 18701 if (moduleType === "ts" || moduleType === "tsx") { 18702 try { 18703 const modulePromise = import(window._ojs.selfContained ? 18704 importPath : 18705 importPath.replace(/\.ts$/, ".js").replace(/\.tsx$/, ".js")); 18706 return es6ImportAsObservableModule(modulePromise, specs); 18707 } catch (e) { 18708 // record the error on the browser console to make debugging 18709 // slightly more convenient. 18710 console.error(e); 18711 throw e; 18712 } 18713 } else if (moduleType === "js") { 18714 try { 18715 const modulePromise = import(importPath); 18716 return es6ImportAsObservableModule(modulePromise, specs); 18717 } catch (e) { 18718 // record the error on the browser console to make debugging 18719 // slightly more convenient. 18720 console.error(e); 18721 throw e; 18722 } 18723 } else if (moduleType === "ojs") { 18724 return importOjsFromURL(fetchPath); 18725 } else if (moduleType === "qmd") { 18726 const htmlPath = `${fetchPath.slice(0, -4)}.html`; 18727 const response = await fetch(htmlPath); 18728 const text = await response.text(); 18729 return createOjsModuleFromHTMLSrc(text); 18730 } else { 18731 throw new Error(`internal error, unrecognized module type ${moduleType}`); 18732 } 18733 }; 18734} 18735 18736function createOjsModuleFromHTMLSrc(text) { 18737 const parser = new DOMParser(); 18738 const doc = parser.parseFromString(text, "text/html"); 18739 const staticDefns = []; 18740 for (const el of doc.querySelectorAll('script[type="ojs-define"]')) { 18741 staticDefns.push(el.text); 18742 } 18743 const ojsSource = []; 18744 for ( 18745 const content of doc.querySelectorAll('script[type="ojs-module-contents"]') 18746 ) { 18747 for (const cell of JSON.parse(content.text).contents) { 18748 ojsSource.push(cell.source); 18749 } 18750 } 18751 return createOjsModuleFromSrc(ojsSource.join("\n"), staticDefns); 18752} 18753 18754function createOjsModuleFromSrc(src, staticDefns = []) { 18755 return (runtime, _observer) => { 18756 const newModule = runtime.module(); 18757 const interpreter = window._ojs.ojsConnector.interpreter; 18758 interpreter.module( 18759 src, 18760 newModule, 18761 (_name) => new EmptyInspector(), 18762 ); 18763 for (const defn of staticDefns) { 18764 for (const { name, value } of JSON.parse(defn).contents) { 18765 window._ojs.ojsConnector.define(name, newModule)(value); 18766 } 18767 } 18768 return newModule; 18769 }; 18770} 18771 18772/* 18773 * Given a URL, fetches the text content and creates a new observable module 18774 * exporting all of the names as variables 18775 */ 18776async function importOjsFromURL(path) { 18777 const r = await fetch(path); 18778 const src = await r.text(); 18779 return createOjsModuleFromSrc(src); 18780} 18781 18782class OJSConnector { 18783 constructor({ paths, inspectorClass, library, allowPendingGlobals = false }) { 18784 this.library = library || new Library(); 18785 18786 // this map contains a mapping from resource names to data URLs 18787 // that governs fileAttachment and import() resolutions in the 18788 // case of self-contained files. 18789 this.localResolverMap = new Map(); 18790 // Keeps track of variables that have been requested by ojs code, but do 18791 // not exist (not in the module, not in the library, not on window). 18792 // The keys are variable names, the values are {promise, resolve, reject}. 18793 // This is intended to allow for a (hopefully brief) phase during startup 18794 // in which, if an ojs code chunk references a variable that is not defined, 18795 // instead of treating it as an "x is not defined" error we instead 18796 // take a wait-and-see approach, in case the variable dynamically becomes 18797 // defined later. When the phase ends, killPendingGlobals() must be called 18798 // so any variables that are still missing do cause "x is not defined" 18799 // errors. 18800 this.pendingGlobals = {};
18801 // When true, the mechanism described in the `this.pendingGlobals` comment 18802 // is used. When false, the result of accessing undefined variables is just 18803 // "x is not defined". This should be considered private, only settable via 18804 // constructor or `killPendingGlobals`. 18805 this.allowPendingGlobals = allowPendingGlobals; 18806 // NB it looks like Runtime makes a local copy of the library object, 18807 // such that mutating library after this is initializaed doesn't actually 18808 // work. 18809 this.runtime = new Runtime(this.library, (name) => this.global(name)); 18810 this.mainModule = this.runtime.module(); 18811 this.interpreter = new dist.exports.Interpreter({ 18812 module: this.mainModule, 18813 resolveImportPath: importPathResolver(paths, this.localResolverMap), 18814 }); 18815 this.inspectorClass = inspectorClass || Inspector; 18816 18817 // state to handle flash of unevaluated js because of async module imports 18818 this.mainModuleHasImports = false; 18819 this.mainModuleOutstandingImportCount = 0; 18820 this.chunkPromises = []; 18821 } 18822 18823 // Customizes the Runtime's behavior when an undefined variable is accessed. 18824 // This is needed for cases where the ojs graph is not all present at the 18825 // time of initialization; in particular, the case where a dependent cell 18826 // starts executing before one or more of its dependencies have been defined. 18827 // Without this customization, the user would see a flash of errors while the 18828 // graph is constructed; with this customization, the dependents stay blank 18829 // while they wait. 18830 global(name) { 18831 if (typeof window[name] !== "undefined") { 18832 return window[name]; 18833 } 18834 if (!this.allowPendingGlobals) { 18835 return undefined; 18836 } 18837 18838 // deno-lint-ignore no-prototype-builtins 18839 if (!this.pendingGlobals.hasOwnProperty(name)) { 18840 // This is a pending global we haven't seen before. Stash a new promise, 18841 // along with its resolve/reject callbacks, in an object and remember it 18842 // for later. 18843 const info = {}; 18844 info.promise = new Promise((resolve, reject) => { 18845 info.resolve = resolve; 18846 info.reject = reject; 18847 }); 18848 this.pendingGlobals[name] = info; 18849 } 18850 return this.pendingGlobals[name].promise; 18851 } 18852 18853 // Signals the end of the "pending globals" phase. Any promises we've handed 18854 // out from the global() method now are rejected. (We never resolve these 18855 // promises to values; if these variables made an appearance, it would've 18856 // been as variables on modules.) 18857 killPendingGlobals() { 18858 this.allowPendingGlobals = false; 18859 for (const [name, { reject }] of Object.entries(this.pendingGlobals)) { 18860 reject(new RuntimeError(`${name} is not defined`)); 18861 } 18862 } 18863 18864 setLocalResolver(map) { 18865 for (const [key, value] of Object.entries(map)) { 18866 this.localResolverMap.set(key, value); 18867 } 18868 } 18869 18870 define(name, module = undefined) { 18871 if (!module) { 18872 module = this.mainModule; 18873 } 18874 let change; 18875 const obs = this.library.Generators.observe((change_) => { 18876 change = change_; 18877 // TODO do something about destruction 18878 }); 18879 module.variable().define(name, obs); 18880 return change; 18881 } 18882 18883 watch(name, k, module = undefined) { 18884 if (!module) { 18885 module = this.mainModule; 18886 } 18887 module.variable({ 18888 fulfilled: (x) => k(x, name), 18889 }).define([name], (val) => val); 18890 } 18891 18892 async value(val, module = undefined) { 18893 if (!module) { 18894 module = this.mainModule; 18895 } 18896 const result = await module.value(val); 18897 return result; 18898 } 18899 18900 finishInterpreting() { 18901 return Promise.all(this.chunkPromises); 18902 } 18903 18904 interpretWithRunner(src, runner) { 18905 try { 18906 const parse = parseModule(src); 18907 const chunkPromise = Promise.all(parse.cells.map(runner)); 18908 this.chunkPromises.push(chunkPromise); 18909 return chunkPromise; 18910 } catch (error) { 18911 return Promise.reject(error); 18912 } 18913 } 18914 18915 waitOnImports(cell, promise) { 18916 if (cell.body.type !== "ImportDeclaration") { 18917 return promise; 18918 } else { 18919 this.mainModuleHasImports = true; 18920 this.mainModuleOutstandingImportCount++; 18921 return promise.then((result) => { 18922 this.mainModuleOutstandingImportCount--; 18923 if (this.mainModuleOutstandingImportCount === 0) { 18924 this.clearImportModuleWait(); 18925 } 18926 return result; 18927 }); 18928 } 18929 } 18930 18931 interpretQuiet(src) { 18932 const runCell = (cell) => { 18933 const cellSrc = src.slice(cell.start, cell.end); 18934 const promise = this.interpreter.module( 18935 cellSrc, 18936 undefined, 18937 (_name) => new EmptyInspector(), 18938 ); 18939 return this.waitOnImports(cell, promise); 18940 }; 18941 return this.interpretWithRunner(src, runCell); 18942 } 18943} 18944 18945/*! 18946 * escape-html 18947 * Copyright(c) 2012-2013 TJ Holowaychuk 18948 * Copyright(c) 2015 Andreas Lubbe 18949 * Copyright(c) 2015 Tiancheng "Timothy" Gu 18950 * Copyright(c) 2022 RStudio, PBC 18951 * 18952 * MIT Licensed 18953 * 18954 * Minimal changes to make ES6 18955 * 18956 */ 18957 18958var matchHtmlRegExp = /["'&<>]/; 18959 18960/** 18961 * Escape special characters in the given string of text. 18962 * 18963 * @param {string} string The string to escape for inserting into HTML 18964 * @return {string} 18965 * @public 18966 */ 18967 18968function escapeHtml (string) { 18969 var str = '' + string; 18970 var match = matchHtmlRegExp.exec(str); 18971 18972 if (!match) { 18973 return str 18974 } 18975 18976 var escape; 18977 var html = ''; 18978 var index = 0; 18979 var lastIndex = 0; 18980 18981 for (index = match.index; index < str.length; index++) { 18982 switch (str.charCodeAt(index)) { 18983 case 34: // " 18984 escape = '"'; 18985 break 18986 case 38: // & 18987 escape = '&'; 18988 break 18989 case 39: // ' 18990 escape = '''; 18991 break 18992 case 60: // < 18993 escape = '<'; 18994 break 18995 case 62: // > 18996 escape = '>'; 18997 break 18998 default: 18999 continue 19000 } 19001 19002 if (lastIndex !== index) { 19003 html += str.substring(lastIndex, index); 19004 } 19005 19006 lastIndex = index + 1; 19007 html += escape; 19008 } 19009 19010 return lastIndex !== index 19011 ? html + str.substring(lastIndex, index) 19012 : html 19013} 19014 19015function createHtmlElement(tag, attrs, ...children) { 19016 const el = document.createElement(tag); 19017 for (const [key, val] of Object.entries(attrs || {})) { 19018 el.setAttribute(key, val); 19019 } 19020 while (children.length) { 19021 const child = children.shift(); 19022 if (Array.isArray(child)) { 19023 children.unshift(...child); 19024 } else if (child instanceof HTMLElement) { 19025 el.appendChild(child); 19026 } else { 19027 el.appendChild(document.createTextNode(escapeHtml(child))); 19028 } 19029 } 19030 return el; 19031} 19032 19033function createNamespacedElement(ns, tag, attrs, ...children) { 19034 const el = document.createElementNS(ns.namespace, tag); 19035 for (const [key, val] of Object.entries(attrs || {})) { 19036 el.setAttribute(key, val); 19037 } 19038 while (children.length) { 19039 const child = children.shift(); 19040 if (Array.isArray(child)) { 19041 children.unshift(...child); 19042 } else if (child instanceof HTMLElement || child instanceof ns.class) { 19043 el.appendChild(child); 19044 } else { 19045 el.appendChild(document.createTextNode(escapeHtml(child))); 19046 } 19047 } 19048 return el; 19049} 19050 19051const resolver = { 19052 a: "svg", 19053 animate: "svg", 19054 animateMotion: "svg", 19055 animateTransform: "svg", 19056 circle: "svg", 19057 clipPath: "svg", 19058 defs: "svg", 19059 desc: "svg", 19060 discard: "svg", 19061 ellipse: "svg", 19062 feBlend: "svg", 19063 feColorMatrix: "svg", 19064 feComponentTransfer: "svg", 19065 feComposite: "svg", 19066 feConvolveMatrix: "svg", 19067 feDiffuseLighting: "svg", 19068 feDisplacementMap: "svg", 19069 feDistantLight: "svg", 19070 feDropShadow: "svg", 19071 feFlood: "svg", 19072 feFuncA: "svg", 19073 feFuncB: "svg", 19074 feFuncG: "svg", 19075 feFuncR: "svg", 19076 feGaussianBlur: "svg", 19077 feImage: "svg", 19078 feMerge: "svg", 19079 feMergeNode: "svg", 19080 feMorphology: "svg",
19081 feOffset: "svg", 19082 fePointLight: "svg", 19083 feSpecularLighting: "svg", 19084 feSpotLight: "svg", 19085 feTile: "svg", 19086 feTurbulence: "svg", 19087 filter: "svg", 19088 foreignObject: "svg", 19089 g: "svg", 19090 image: "svg", 19091 line: "svg", 19092 linearGradient: "svg", 19093 marker: "svg", 19094 mask: "svg", 19095 metadata: "svg", 19096 mpath: "svg", 19097 path: "svg", 19098 pattern: "svg", 19099 polygon: "svg", 19100 polyline: "svg", 19101 radialGradient: "svg", 19102 rect: "svg", 19103 script: "svg", 19104 set: "svg", 19105 stop: "svg", 19106 style: "svg", 19107 svg: "svg", 19108 switch: "svg", 19109 symbol: "svg", 19110 text: "svg", 19111 textPath: "svg", 19112 title: "svg", 19113 tspan: "svg", 19114 use: "svg", 19115 view: "svg", 19116}; 19117 19118const nss = { 19119 "svg": { namespace: "http://www.w3.org/2000/svg", class: SVGElement } 19120}; 19121 19122function resolveCreator(tag) { 19123 const nsKey = resolver[tag]; 19124 if (nsKey === undefined) { 19125 return createHtmlElement; 19126 } 19127 const namespace = nss[nsKey]; 19128 19129 return function(tag, attrs, ...children) { 19130 return createNamespacedElement(namespace, tag, attrs, ...children); 19131 } 19132} 19133 19134function createQuartoJsxShim() 19135{ 19136 return { 19137 createElement(tag, attrs, ...children) { 19138 if (typeof tag === "function") { 19139 return tag({...attrs, children }); 19140 } 19141 19142 return resolveCreator(tag)(tag, attrs, ...children); 19143 } 19144 }; 19145} 19146 19147/** 19148 * @param typeMap [Object] Map of MIME type -> Array[extensions] 19149 * @param ... 19150 */ 19151function Mime$1() { 19152 this._types = Object.create(null); 19153 this._extensions = Object.create(null); 19154 19155 for (let i = 0; i < arguments.length; i++) { 19156 this.define(arguments[i]); 19157 } 19158 19159 this.define = this.define.bind(this); 19160 this.getType = this.getType.bind(this); 19161 this.getExtension = this.getExtension.bind(this); 19162} 19163 19164/** 19165 * Define mimetype -> extension mappings. Each key is a mime-type that maps 19166 * to an array of extensions associated with the type. The first extension is 19167 * used as the default extension for the type. 19168 * 19169 * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); 19170 * 19171 * If a type declares an extension that has already been defined, an error will 19172 * be thrown. To suppress this error and force the extension to be associated 19173 * with the new type, pass `force`=true. Alternatively, you may prefix the 19174 * extension with "*" to map the type to extension, without mapping the 19175 * extension to the type. 19176 * 19177 * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']}); 19178 * 19179 * 19180 * @param map (Object) type definitions 19181 * @param force (Boolean) if true, force overriding of existing definitions 19182 */ 19183Mime$1.prototype.define = function(typeMap, force) { 19184 for (let type in typeMap) { 19185 let extensions = typeMap[type].map(function(t) { 19186 return t.toLowerCase(); 19187 }); 19188 type = type.toLowerCase(); 19189 19190 for (let i = 0; i < extensions.length; i++) { 19191 const ext = extensions[i]; 19192 19193 // '*' prefix = not the preferred type for this extension. So fixup the 19194 // extension, and skip it. 19195 if (ext[0] === '*') { 19196 continue; 19197 } 19198 19199 if (!force && (ext in this._types)) { 19200 throw new Error( 19201 'Attempt to change mapping for "' + ext + 19202 '" extension from "' + this._types[ext] + '" to "' + type + 19203 '". Pass `force=true` to allow this, otherwise remove "' + ext + 19204 '" from the list of extensions for "' + type + '".' 19205 ); 19206 } 19207 19208 this._types[ext] = type; 19209 } 19210 19211 // Use first extension as default 19212 if (force || !this._extensions[type]) { 19213 const ext = extensions[0]; 19214 this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1); 19215 } 19216 } 19217}; 19218 19219/** 19220 * Lookup a mime type based on extension 19221 */ 19222Mime$1.prototype.getType = function(path) { 19223 path = String(path); 19224 let last = path.replace(/^.*[/\\]/, '').toLowerCase(); 19225 let ext = last.replace(/^.*\./, '').toLowerCase(); 19226 19227 let hasPath = last.length < path.length; 19228 let hasDot = ext.length < last.length - 1; 19229 19230 return (hasDot || !hasPath) && this._types[ext] || null; 19231}; 19232 19233/** 19234 * Return file extension associated with a mime type 19235 */ 19236Mime$1.prototype.getExtension = function(type) { 19237 type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; 19238 return type && this._extensions[type.toLowerCase()] || null; 19239}; 19240 19241var Mime_1 = Mime$1; 19242 19243var standard =
vendor: 9,512 bytes, line 19243
19243{"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]}
19243; 19244 19245var other =
vendor: 14,446 bytes, line 19245
19245{"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smz
vendor: 11,430 bytes, line 19245
19245ip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]}
19245; 19246 19247let Mime = Mime_1; 19248var mime = new Mime(standard, other); 19249 19250/*global Shiny, $, DOMParser, MutationObserver, URL 19251 * 19252 * quarto-ojs.js 19253 * 19254 * Copyright (C) 2021 RStudio, PBC 19255 * 19256 */ 19257 19258////////////////////////////////////////////////////////////////////////////// 19259 19260function displayOJSWarning(warning) 19261{ 19262 const cells = []; 19263 for ( 19264 const content of document.querySelectorAll('script[type="ojs-module-contents"]') 19265 ) { 19266 for (const cellJson of JSON.parse(content.text).contents) { 19267 let cell = document.getElementById(cellJson.cellName) || document.getElementById(`${cellJson.cellName}-1`); 19268 if (!cell) { 19269 // give up 19270 continue; 19271 } 19272 cells.push(cell); 19273 } 19274 } 19275 19276 debugger; 19277 cells.forEach((cell) => { 19278 debugger; 19279 cell.innerHTML = ""; 19280 19281 const message = warning(); 19282 19283 cell.appendChild( 19284 calloutBlock({ 19285 type: "error", 19286 message 19287 }) 19288 ); 19289 }); 19290} 19291 19292function displayQtWebEngineError() { 19293 displayOJSWarning(() => { 19294 const message = document.createElement("div"); 19295 message.appendChild(document.createTextNode("This document uses OJS, which requires JavaScript features not present in this version of QtWebEngine. If you're using RStudio IDE, please upgrade to a ")); 19296 const link = document.createElement("a"); 19297 link.appendChild(document.createTextNode("2022.12 build")); 19298 link.href = "https://dailies.rstudio.com/rstudio/elsbeth-geranium/"; 19299 message.appendChild(link); 19300 message.appendChild(document.createTextNode(".")); 19301 return message; 19302 }); 19303} 19304 19305function displayFileProtocolError() { 19306 displayOJSWarning(() => { 19307 const message = document.createElement("div"); 19308 message.appendChild(document.createTextNode("This document uses OJS, which requires JavaScript features disabled when running in file://... URLs. In order for these features to work, run this document in a web server.")); 19309 return message; 19310 }); 19311} 19312 19313 19314////////////////////////////////////////////////////////////////////////////// 19315// Quarto-specific code starts here. 19316 19317// For RStudio IDE integration 19318/** creates a click handler to point the IDE to a given line and column */ 19319const makeDevhostErrorClickHandler = (line, column) => { 19320 return function () { 19321 if (!window.quartoDevhost) { 19322 return false; 19323 } 19324 window.quartoDevhost.openInputFile(line, column, true); 19325 return false; 19326 }; 19327}; 19328 19329// we cannot depend on Object.fromEntries because the IDE 19330// doesn't support it. We minimally polyfill it 19331if (Object.fromEntries === undefined) { 19332 Object.fromEntries = function (obj) { 19333 const result = {}; 19334 for (const [key, value] of obj) { 19335 result[key] = value; 19336 } 19337 return result; 19338 }; 19339} 19340 19341/** create a callout block with the given opts, currently to be used 19342 to signal a runtime error in the observable runtime. 19343*/ 19344function calloutBlock(opts) { 19345 const { type, heading, message, onclick } = opts; 19346 19347 const outerBlock = document.createElement("div"); 19348 outerBlock.classList.add( 19349 `callout-${type}`, 19350 "callout", 19351 "callout-style-default", 19352 "callout-titled" 19353 ); 19354 const header = document.createElement("div"); 19355 header.classList.add("callout-header", "d-flex", "align-content-center"); 19356 const iconContainer = document.createElement("div"); 19357 iconContainer.classList.add("callout-icon-container"); 19358 const icon = document.createElement("i"); 19359 icon.classList.add("callout-icon"); 19360 iconContainer.appendChild(icon); 19361 header.appendChild(iconContainer); 19362 19363 const headingDiv = document.createElement("div"); 19364 headingDiv.classList.add("callout-title-container", "flex-fill"); 19365 // we assume heading is either a string or a span 19366 if (typeof heading === "string") { 19367 headingDiv.innerText = heading; 19368 } else { 19369 headingDiv.appendChild(heading); 19370 } 19371 header.appendChild(headingDiv); 19372 outerBlock.appendChild(header); 19373 19374 const container = document.createElement("div"); 19375 container.classList.add("callout-body-container", "callout-body"); 19376 if (typeof message === "string") { 19377 const p = document.createElement("p"); 19378 p.innerText = message; 19379 container.appendChild(p); 19380 } else { 19381 container.append(message); 19382 } 19383 outerBlock.appendChild(container); 19384 19385 if (onclick) { 19386 outerBlock.onclick = onclick; 19387 outerBlock.style.cursor = "pointer"; 19388 } 19389 19390 return outerBlock; 19391} 19392 19393const kQuartoModuleWaitClass = "ojs-in-a-box-waiting-for-module-import"; 19394 19395class QuartoOJSConnector extends OJSConnector { 19396 constructor(opts) { 19397 super(opts); 19398 } 19399 19400 //////////////////////////////////////////////////////////////////////////// 19401 // handle import module waits 19402 19403 clearImportModuleWait() { 19404 const array = Array.from( 19405 document.querySelectorAll(`.${kQuartoModuleWaitClass}`) 19406 ); 19407 for (const node of array) { 19408 node.classList.remove(kQuartoModuleWaitClass); 19409 } 19410 } 19411 19412 finishInterpreting() { 19413 return super.finishInterpreting().then(() => { 19414 if (this.mainModuleHasImports) { 19415 this.clearImportModuleWait(); 19416 } 19417 }); 19418 } 19419 19420 //////////////////////////////////////////////////////////////////////////// 19421 // Error tracking/reporting 19422 19423 locatePreDiv(cellDiv, ojsDiv) { 19424 // locate the correct pre div with the pandocDecorator 19425 // of all potential divs, we need to find the one that most 19426 // immediately precedes `ojsDiv` in the DOM. 19427 let preDiv; 19428 for (const candidate of cellDiv.querySelectorAll("pre.sourceCode")) { 19429 if ( 19430 candidate.compareDocumentPosition(ojsDiv) & 19431 ojsDiv.DOCUMENT_POSITION_FOLLOWING 19432 ) { 19433 preDiv = candidate; 19434 } else { 19435 break; 19436 } 19437 } 19438 return preDiv; 19439 } 19440
19441 findCellOutputDisplay(ojsDiv) { 19442 while (ojsDiv && !ojsDiv.classList.contains("cell-output-display")) { 19443 ojsDiv = ojsDiv.parentElement; 19444 } 19445 if (!ojsDiv) { 19446 return null; 19447 } 19448 return ojsDiv; 19449 } 19450 19451 setPreDivClasses(preDiv, hasErrors) { 19452 if (!hasErrors) { 19453 preDiv.classList.remove("numberSource"); 19454 if (preDiv._hidden === true) { 19455 const parent = preDiv.parentElement; 19456 parent.classList.add("hidden"); 19457 // when code-tools is active (that is, when pre is inside a details tag), we also need to hide the details tag. 19458 if (parent.parentElement.tagName === "DETAILS") { 19459 parent.parentElement.classList.add("hidden"); 19460 } 19461 } 19462 } else { 19463 preDiv.classList.add("numberSource"); 19464 const parent = preDiv.parentElement; 19465 if (parent.classList.contains("hidden")) { 19466 preDiv._hidden = true; // signal that we used to be hidden so that when errors go away, we're hidden again. 19467 parent.classList.remove("hidden"); 19468 19469 // when code-tools is active (that is, when pre is inside a details tag), we also need to unhide the details tag. 19470 if (parent.parentElement.tagName === "DETAILS") { 19471 parent.parentElement.classList.remove("hidden"); 19472 // open the code-tools by default when error happens. 19473 parent.parentElement.setAttribute("open", "open"); 19474 } 19475 } 19476 } 19477 } 19478 19479 clearErrorPinpoints(cellDiv, ojsDiv) { 19480 const preDiv = this.locatePreDiv(cellDiv, ojsDiv); 19481 if (preDiv === undefined) { 19482 return; 19483 } 19484 this.setPreDivClasses(preDiv, false); 19485 let startingOffset = 0; 19486 if (preDiv.parentElement.dataset.sourceOffset) { 19487 startingOffset = -Number(preDiv.parentElement.dataset.sourceOffset); 19488 } 19489 for (const entryPoint of preDiv._decorator.spanSelection( 19490 startingOffset, 19491 Infinity 19492 )) { 19493 const { node } = entryPoint; 19494 node.classList.remove("quarto-ojs-error-pinpoint"); 19495 node.onclick = null; 19496 } 19497 } 19498 19499 decorateOjsDivWithErrorPinpoint(ojsDiv, start, end, line, column) { 19500 const cellOutputDisplay = this.findCellOutputDisplay(ojsDiv); 19501 // if ojs element is inline, there's no div. 19502 if (!cellOutputDisplay) { 19503 return; 19504 } 19505 if (cellOutputDisplay._errorSpans === undefined) { 19506 cellOutputDisplay._errorSpans = []; 19507 } 19508 cellOutputDisplay._errorSpans.push({ 19509 start, 19510 end, 19511 line, 19512 column, 19513 }); 19514 } 19515 19516 decorateSource(cellDiv, ojsDiv) { 19517 if (!cellDiv) { 19518 // no div in inline spans 19519 return; 19520 } 19521 this.clearErrorPinpoints(cellDiv, ojsDiv); 19522 const preDiv = this.locatePreDiv(cellDiv, ojsDiv); 19523 // sometimes the source code is not echoed. 19524 // FIXME: should ojs source always be "hidden" so we can show it 19525 // in case of runtime errors? 19526 if (preDiv === undefined) { 19527 return; 19528 } 19529 // now find all ojsDivs that contain errors that need to be decorated 19530 // on preDiv 19531 let parent = preDiv.parentElement; 19532 if (parent.parentElement.tagName === "DETAILS") { 19533 // we're in a code-tools setting, need to go one further up 19534 parent = parent.parentElement; 19535 } 19536 let div = parent.nextElementSibling; 19537 let foundErrors = false; 19538 while (div !== null && div.classList.contains("cell-output-display")) { 19539 for (const errorSpan of div._errorSpans || []) { 19540 for (const entryPoint of preDiv._decorator.spanSelection( 19541 errorSpan.start, 19542 errorSpan.end 19543 )) { 19544 const { node } = entryPoint; 19545 node.classList.add("quarto-ojs-error-pinpoint"); 19546 node.onclick = makeDevhostErrorClickHandler( 19547 errorSpan.line, 19548 errorSpan.column 19549 ); 19550 } 19551 foundErrors = true; 19552 } 19553 div = div.nextElementSibling; 19554 } 19555 this.setPreDivClasses(preDiv, foundErrors); 19556 } 19557 19558 clearError(ojsDiv) { 19559 const cellOutputDisplay = this.findCellOutputDisplay(ojsDiv); 19560 // if ojs element is inline, there's no div. 19561 if (cellOutputDisplay) 19562 cellOutputDisplay._errorSpans = []; 19563 } 19564 19565 signalError(cellDiv, ojsDiv, ojsAst) { 19566 const buildCallout = (ojsDiv) => { 19567 let onclick; 19568 const inspectChild = ojsDiv.querySelector(".observablehq--inspect"); 19569 let [heading, message] = inspectChild.textContent.split(": "); 19570 if (heading === "RuntimeError") { 19571 heading = "OJS Runtime Error"; 19572 if (message.match(/^(.+) is not defined$/)) { 19573 const [varName, ...rest] = message.split(" "); 19574 const p = document.createElement("p"); 19575 const tt = document.createElement("tt"); 19576 tt.innerText = varName; 19577 p.appendChild(tt); 19578 p.appendChild(document.createTextNode(" " + rest.join(" "))); 19579 message = p; 19580 19581 const preDiv = this.locatePreDiv(cellDiv, ojsDiv); 19582 // preDiv might not be exist in case source isn't echoed to HTML 19583 if (preDiv !== undefined) {
19584 // force line numbers to show 19585 preDiv.classList.add("numberSource"); 19586 const missingRef = ojsAst.references.find( 19587 (n) => n.name === varName 19588 ); 19589 // TODO when missingRef === undefined, it likely means an unresolved 19590 // import reference. For now we will leave things as is, but 19591 // this needs better handling. 19592 if (missingRef !== undefined) { 19593 const { line, column } = preDiv._decorator.offsetToLineColumn( 19594 missingRef.start 19595 ); 19596 const headingSpan = document.createElement("span"); 19597 const headingTextEl = document.createTextNode( 19598 `${heading} (line ${line}, column ${column}) ` 19599 ); 19600 headingSpan.appendChild(headingTextEl); 19601 if (window.quartoDevhost) { 19602 const clicker = document.createElement("a"); 19603 clicker.href = "#"; // this forces the right CSS to apply 19604 clicker.innerText = "(source)"; 19605 onclick = makeDevhostErrorClickHandler(line, column); 19606 headingSpan.appendChild(clicker); 19607 } 19608 heading = headingSpan; 19609 this.decorateOjsDivWithErrorPinpoint( 19610 ojsDiv, 19611 missingRef.start, 19612 missingRef.end, 19613 line, 19614 column 19615 ); 19616 } 19617 } 19618 } else if ( 19619 message.match(/^(.+) could not be resolved$/) || 19620 message.match(/^(.+) is defined more than once$/) 19621 ) { 19622 const [varName, ...rest] = message.split(" "); 19623 const p = document.createElement("p"); 19624 const tt = document.createElement("tt"); 19625 tt.innerText = varName; 19626 p.appendChild(tt); 19627 p.appendChild(document.createTextNode(" " + rest.join(" "))); 19628 message = p; 19629 } else { 19630 const p = document.createElement("p"); 19631 p.appendChild(document.createTextNode(message)); 19632 message = p; 19633 } 19634 } else { 19635 heading = "OJS Error"; 19636 const p = document.createElement("p"); 19637 p.appendChild(document.createTextNode(inspectChild.textContent)); 19638 message = p; 19639 } 19640 const callout = calloutBlock({ 19641 type: "important", 19642 heading, 19643 message, 19644 onclick, 19645 }); 19646 ojsDiv.appendChild(callout); 19647 }; 19648 19649 buildCallout(ojsDiv); 19650 } 19651 19652 interpret(src, elementGetter, elementCreator) { 19653 // deno-lint-ignore no-this-alias 19654 const that = this; 19655 const observer = (targetElement, ojsAst) => { 19656 return (name) => { 19657 const element = 19658 typeof elementCreator === "function" 19659 ? elementCreator() 19660 : elementCreator; 19661 targetElement.appendChild(element); 19662 19663 // TODO the unofficial interpreter always calls viewexpression observers 19664 // twice, one with the name, and the next with 'viewof $name'. 19665 // we check for 'viewof ' here and hide the element we're creating. 19666 // this behavior appears inconsistent with OHQ's interpreter, so we 19667 // shouldn't be surprised to see this fail in the future. 19668 if ( 19669 ojsAst.id && 19670 ojsAst.id.type === "ViewExpression" && 19671 !name.startsWith("viewof ") 19672 ) { 19673 element.classList.add("quarto-ojs-hide"); 19674 } 19675 19676 // handle output:all hiding 19677 // 19678 // if every output from a cell is is not displayed, then we 19679 // must also not display the cell output display element 19680 // itself. 19681 19682 // collect the cell element as well as the cell output display 19683 // element 19684 let cellDiv = targetElement; 19685 let cellOutputDisplay; 19686 while (cellDiv !== null && !cellDiv.classList.contains("cell")) { 19687 cellDiv = cellDiv.parentElement; 19688 if (cellDiv && cellDiv.classList.contains("cell-output-display")) { 19689 cellOutputDisplay = cellDiv; 19690 } 19691 } 19692 const forceShowDeclarations = (!cellDiv) || (cellDiv.dataset.output === "all"); 19693 19694 const config = { childList: true }; 19695 const callback = function (mutationsList) { 19696 // we may fail to find a cell in inline settings; but 19697 // inline cells won't have inspectors, so in that case 19698 // we never hide 19699 for (const mutation of mutationsList) { 19700 const ojsDiv = mutation.target; 19701 19702 if (!forceShowDeclarations) { 19703 const childNodes = Array.from(mutation.target.childNodes); 19704 for (const n of childNodes) { 19705 // hide the inner inspect outputs that aren't errors or 19706 // declarations 19707 if ( 19708 n.classList.contains("observablehq--inspect") && 19709 !n.parentNode.classList.contains("observablehq--error") && 19710 n.parentNode.parentNode.dataset.nodetype !== "expression" 19711 ) { 19712 n.classList.add("quarto-ojs-hide"); 19713 } 19714 // show the inspect outputs that aren't errors and are 19715 // expressions (they might have been hidden in the past, 19716 // since errors can clear) 19717 if ( 19718 n.classList.contains("observablehq--inspect") && 19719 !n.parentNode.classList.contains("observablehq--error") && 19720 n.parentNode.parentNode.dataset.nodetype === "expression" 19721 ) { 19722 n.classList.remove("quarto-ojs-hide"); 19723 } 19724 } 19725 } 19726 19727 // if the ojsDiv shows an error, display a callout block instead of it. 19728 if (ojsDiv.classList.contains("observablehq--error")) { 19729 // we don't use quarto-ojs-hide here because that would confuse
19730 // the code which depends on that class for its logic. 19731 ojsDiv.querySelector(".observablehq--inspect").style.display = 19732 "none"; 19733 19734 if (ojsDiv.querySelectorAll(".callout-important").length === 0) { 19735 that.signalError(cellDiv, ojsDiv, ojsAst); 19736 } 19737 } else { 19738 that.clearError(ojsDiv); 19739 if ( 19740 ojsDiv.parentNode.dataset.nodetype !== "expression" && 19741 !forceShowDeclarations && 19742 Array.from(ojsDiv.childNodes).every((n) => 19743 n.classList.contains("observablehq--inspect") 19744 ) 19745 ) { 19746 // if every child is an inspect output, hide the ojsDiv 19747 ojsDiv.classList.add("quarto-ojs-hide"); 19748 } 19749 } 19750 19751 that.decorateSource(cellDiv, ojsDiv); 19752 19753 // hide import statements even if output === "all" 19754 for (const added of mutation.addedNodes) { 19755 if ( 19756 added.tagName === "FORM" && 19757 Array.from(added.classList).some( 19758 (x) => x.endsWith("table") && x.startsWith("oi-") 19759 ) 19760 ) { 19761 added.classList.add("quarto-ojs-table-fixup"); 19762 } 19763 19764 const addedButtons = added.querySelectorAll("button"); 19765 for (const button of Array.from(addedButtons)) { 19766 button.classList.add("btn"); 19767 button.classList.add("btn-quarto"); 19768 } 19769 //// Hide imports that aren't javascript code 19770 // 19771 // We search here for code.javascript and node span.hljs-... be
19771cause 19772 // at this point in the DOM, observable's runtime hasn't called 19773 // HLJS yet. if you inspect the DOM yourself, you're likely to see 19774 // HLJS, so this comment is here to prevent future confusion. 19775 const result = added.querySelectorAll("code.javascript"); 19776 if (result.length !== 1) { 19777 continue; 19778 } 19779 if (result[0].textContent.trim().startsWith("import")) { 19780 ojsDiv.classList.add("quarto-ojs-hide"); 19781 } 19782 } 19783 } 19784 19785 // cellOutputDisplay doesn't exist in inline spans, so we must check it explicitly 19786 if (cellOutputDisplay) { 19787 const children = Array.from( 19788 cellOutputDisplay.querySelectorAll("div.observablehq") 19789 ); 19790 // after all mutations are handled, we check the full cell for hiding 19791 if ( 19792 children.every((n) => { 19793 return n.classList.contains("quarto-ojs-hide"); 19794 }) 19795 ) { 19796 cellOutputDisplay.classList.add("quarto-ojs-hide"); 19797 } else { 19798 cellOutputDisplay.classList.remove("quarto-ojs-hide"); 19799 } 19800 } 19801 }; 19802 new MutationObserver(callback).observe(element, config); 19803 // 'element' is the outer div given to observable's runtime to insert their output
19804 // every quarto cell will have either one or two such divs. 19805 // The parent of these divs should always be a div corresponding to an ojs "cell" 19806 // (with ids "ojs-cell-*") 19807 19808 element.classList.add(kQuartoModuleWaitClass); 19809 19810 return new this.inspectorClass(element, ojsAst); 19811 }; 19812 }; 19813 const runCell = (cell) => { 19814 const targetElement = 19815 typeof elementGetter === "function" ? elementGetter() : elementGetter; 19816 const cellSrc = src.slice(cell.start, cell.end); 19817 const promise = this.interpreter.module( 19818 cellSrc, 19819 undefined, 19820 observer(targetElement, cell) 19821 ); 19822 return this.waitOnImports(cell, promise); 19823 }; 19824 return this.interpretWithRunner(src, runCell); 19825 } 19826} 19827 19828////////////////////////////////////////////////////////////////////////////// 19829// previously quarto-observable-shiny.js 19830 19831function createRuntime() { 19832 const quartoOjsGlobal = window._ojs; 19833 const isShiny = window.Shiny !== undefined; 19834 19835 // Are we QtWebEngine? bail 19836 if (window.navigator.userAgent.includes("QtWebEngine")) { 19837 displayQtWebEngineError(); 19838 return; 19839 } 19840 19841 // Are we file://? bail 19842 if (window.location.protocol === "file:") { 19843 displayFileProtocolError(); 19844 return; 19845 } 19846 19847 // Are we shiny? 19848 if (isShiny) { 19849 quartoOjsGlobal.hasShiny = true; 19850 initOjsShinyRuntime(); 19851 19852 const span = document.createElement("span"); 19853 window._ojs.shinyElementRoot = span; 19854 document.body.appendChild(span); 19855 } 19856 19857 // we use the trick described here to extend observable runtime's standard library 19858 // https://talk.observablehq.com/t/embedded-width/1063 19859 19860 // stdlib from our fork, which uses the safe d3-require 19861 const lib = new Library(); 19862 if (isShiny) { 19863 extendObservableStdlib(lib); 19864 } 19865 19866 function transpose(df) { 19867 const keys = Object.keys(df); 19868 return df[keys[0]] 19869 .map((v, i) => 19870 Object.fromEntries(keys.map((key) => { 19871 const v = df[key][i]; 19872 const result = v === null ? undefined : v; 19873 return [key, result]; 19874 }))) 19875 .filter((v) => !Object.values(v).every((e) => e === undefined)); 19876 } 19877 lib.transpose = () => transpose; 19878 19879 // TODO this should be user-configurable, so that we can actually 19880 // make it work in arbitrary layouts. 19881 // There's probably a slick reactive trick to make the element 19882 // user settable. 19883 // 19884 // Right now we support quarto's standard HTML formats 19885 19886 const mainEl = (document.querySelector("main") // html 19887 || document.querySelector("div.reveal") // reveal 19888 || document.querySelector("body")); // fall-through 19889 19890 function width() { 19891 if (mainEl === null) { 19892 return lib.Generators.observe((change) => { 19893 change(undefined); 19894 }); 19895 } 19896 return lib.Generators.observe(function (change) { 19897 var width = change(mainEl.clientWidth); 19898 function resized() { 19899 var w = mainEl.clientWidth; 19900 if (w !== width) change((width = w)); 19901 } 19902 window.addEventListener("resize", resized); 19903 return function () { 19904 window.removeEventListener("resize", resized); 19905 }; 19906 }); 19907 } 19908 lib.width = width; 19909 19910 // hack for "echo: fenced": remove all "//| echo: fenced" lines the hard way, but keep 19911 // the right line numbers around. 19912 Array.from(document.querySelectorAll("span.co")) 19913 .filter((n) => n.textContent === "//| echo: fenced") 19914 .forEach((n) => { 19915 const lineSpan = n.parentElement; 19916 const lineBreak = lineSpan.nextSibling; 19917 if (lineBreak) { 19918 const nextLineSpan = lineBreak.nextSibling; 19919 if (nextLineSpan) { 19920 const lineNumber = Number(nextLineSpan.id.split("-")[1]); 19921 nextLineSpan.style = `counter-reset: source-line ${lineNumber - 1}`; 19922 } 19923 } 19924 19925 // update the source offset variable with the new right amount 19926 const sourceDiv = lineSpan.parentElement.parentElement.parentElement; 19927 const oldOffset = Number(sourceDiv.dataset.sourceOffset); 19928 sourceDiv.dataset.sourceOffset = oldOffset - "//| echo: fenced\n".length; 19929 19930 lineSpan.remove(); 19931 lineBreak.remove(); 19932 }); 19933 19934 // select all elements to track: 19935 // panel elements with ids, and divs with ids and .ojs-track-layout 19936 19937 const layoutDivs = [...Array.from( 19938 document.querySelectorAll("div.quarto-layout-panel div[id]") 19939 ), 19940 ...Array.from( 19941 document.querySelectorAll('div.ojs-track-layout[id]') 19942 )]; 19943 19944 function layoutWidth() { 19945 return lib.Generators.observe(function (change) { 19946 const ourWidths = Object.fromEntries( 19947 layoutDivs.map((div) => [div.id, div.clientWidth]) 19948 ); 19949 change(ourWidths); 19950 function resized() { 19951 let changed = false;
19952 for (const div of layoutDivs) { 19953 const w = div.clientWidth; 19954 if (w !== ourWidths[div.id]) { 19955 ourWidths[div.id] = w; 19956 changed = true; 19957 } 19958 } 19959 if (changed) { 19960 change(ourWidths); 19961 } 19962 } 19963 window.addEventListener("resize", resized); 19964 return function () { 19965 window.removeEventListener("resize", resized); 19966 }; 19967 }); 19968 } 19969 lib.layoutWidth = layoutWidth; 19970 let localResolver = {}; 19971 19972 function fileAttachmentPathResolver(n) { 19973 if (localResolver[n]) { 19974 return localResolver[n]; 19975 } 19976 19977 let name; 19978 const currentPath = window.location.href.replace(/[^/]*$/, ''); 19979 19980 if (n.startsWith("/")) { 19981 // docToRoot can be empty, in which case naive concatenation creates 19982 // an absolute path. 19983 if (quartoOjsGlobal.paths.docToRoot === "") { 19984 name = `${currentPath}.${n}`; 19985 } else { 19986 name = `${currentPath}${quartoOjsGlobal.paths.docToRoot}${n}`; 19987 } 19988 } else if (n.startsWith("http")) { 19989 name = n; 19990 } else { 19991 name = `${currentPath}${n}`; 19992 } 19993 19994 const mimeType = mime.getType(name); 19995 19996 return { 19997 url: name, 19998 mimeType: mimeType, 19999 } 20000 20001 } 20002 lib.FileAttachment = () => FileAttachments(fileAttachmentPathResolver); 20003 20004 const ojsConnector = new QuartoOJSConnector({ 20005 paths: quartoOjsGlobal.paths, 20006 inspectorClass: isShiny ? ShinyInspector : QuartoInspector, 20007 library: lib, 20008 allowPendingGlobals: isShiny, 20009 }); 20010 quartoOjsGlobal.ojsConnector = ojsConnector; 20011 if (isShiny) { 20012 // When isShiny, OJSConnector is constructed with allowPendingGlobals:true. 20013 // Our guess is that most shiny-to-ojs exports will have been defined 20014 // by the time the server function finishes executing (i.e. session init 20015 // completion); so we call `killPendingGlobals()` to show errors for 20016 // variables that are still undefined. 20017 $(document).one("shiny:idle", () => { 20018 // "shiny:idle" is not late enough; it is raised before the resulting 20019 // outputs are received from the server. 20020 $(document).one("shiny:message", () => { 20021 // "shiny:message" is not late enough; it is raised after the message 20022 // is received, but before it is processed (i.e. variables are still 20023 // not actually defined). 20024 setTimeout(() => { 20025 ojsConnector.killPendingGlobals(); 20026 }, 0); 20027 }); 20028 }); 20029 } 20030 20031 const subfigIdMap = new Map(); 20032 function getSubfigId(elementId) { 20033 if (!subfigIdMap.has(elementId)) { 20034 subfigIdMap.set(elementId, 0); 20035 } 20036 let nextIx = subfigIdMap.get(elementId); 20037 nextIx++; 20038 subfigIdMap.set(elementId, nextIx); 20039 return `${elementId}-${nextIx}`; 20040 } 20041 20042 const sourceNodes = document.querySelectorAll( 20043 "pre.sourceCode code.sourceCode" 20044 ); 20045 const decorators = Array.from(sourceNodes).map((n) => { 20046 n = n.parentElement; 20047 const decorator = new PandocCodeDecorator(n); 20048 n._decorator = decorator; 20049 return decorator; 20050 }); 20051 // handle build-time syntax error 20052 decorators.forEach((n) => { 20053 if (n._node.parentElement.dataset.syntaxErrorPosition === undefined) { 20054 return; 20055 } 20056 const offset = Number(n._node.parentElement.dataset.syntaxErrorPosition); 20057 n.decorateSpan(offset, offset + 1, ["quarto-ojs-error-pinpoint"]); 20058 }); 20059 20060 const result = { 20061 setLocalResolver(obj) { 20062 localResolver = obj; 20063 ojsConnector.setLocalResolver(obj); 20064 }, 20065 finishInterpreting() { 20066 return ojsConnector.finishInterpreting(); 20067 }, 20068 20069 // return the latest value of the named reactive variable in the main module 20070 async value(name) { 20071 await this.finishInterpreting(); 20072 const result = await ojsConnector.value(name); 20073 return result; 20074 }, 20075 20076 // fixme clarify what's the expected behavior of the 'error' option 20077 // when evaluation is at client-time 20078 interpretLenient(src, targetElementId, inline) { 20079 return result.interpret(src, targetElementId, inline).catch(() => {}); 20080 }, 20081 interpret(src, targetElementId, inline) { 20082 // we capture the result here so that the error handler doesn't 20083 // grab a new id accidentally. 20084 let targetElement; 20085 const getElement = () => { 20086 targetElement = document.getElementById(targetElementId); 20087 let subFigId; 20088 if (!targetElement) { 20089 // this is a subfigure 20090 subFigId = getSubfigId(targetElementId); 20091 targetElement = document.getElementById(subFigId); 20092 if (!targetElement) { 20093 // console.error("Ran out of subfigures for element", targetElementId); 20094 // console.error("This will fail."); 20095 throw new Error("Ran out of quarto subfigures."); 20096 } 20097 } 20098 return targetElement; 20099 }; 20100 20101 const makeElement = () => { 20102 return document.createElement(inline ? "span" : "div"); 20103 }; 20104 20105 return ojsConnector.interpret(src, getElement, makeElement).catch((e) => { 20106 // to the best of our knowledge, we only get here
20107 // on import statement failures. So we report those 20108 // in a callout 20109 20110 let cellDiv = targetElement; 20111 while (cellDiv !== null && !cellDiv.classList.contains("cell")) { 20112 cellDiv = cellDiv.parentElement; 20113 } 20114 20115 const ojsDiv = targetElement.querySelector(".observablehq"); 20116 if (!ojsDiv) { 20117 // we failed to find an observablehq div inside the targetElement. 20118 // This is an internal error and we have no way to report it 20119 // except throwing the original exception. 20120 throw e; 20121 } 20122 // because this is in an exception handler, we might need 20123 // to clear some of the garbage that other pieces of code 20124 // won't have the chance to 20125 // 20126 for (const div of ojsDiv.querySelectorAll(".callout")) { 20127 div.remove(); 20128 } 20129 20130 const messagePre = document.createElement("pre"); 20131 messagePre.innerText = e.stack; 20132 20133 const callout = calloutBlock({ 20134 type: "important", 20135 heading: `${e.name}: ${e.message}`, 20136 message: messagePre, 20137 }); 20138 ojsDiv.appendChild(callout); 20139 ojsConnector.clearError(ojsDiv); 20140 ojsConnector.clearErrorPinpoints(cellDiv, ojsDiv); 20141 20142 return e; 20143 }); 20144 }, 20145 interpretQuiet(src) { 20146 return ojsConnector.interpretQuiet(src); 20147 }, 20148 interpretFromScriptTags() { 20149 // source definitions 20150 for (const el of document.querySelectorAll( 20151 "script[type='ojs-module-contents']" 20152 )) { 20153 for (const call of JSON.parse(el.text).contents) { 20154 switch (call.methodName) { 20155 case "interpret": 20156 this.interpret(call.source, call.cellName, call.inline); 20157 break; 20158 case "interpretLenient": 20159 this.interpretLenient(call.source, call.cellName, call.inline); 20160 break; 20161 case "interpretQuiet": 20162 this.interpretQuiet(call.source); 20163 break; 20164 default: 20165 throw new Error( 20166 `Don't know how to call method ${call.methodName}` 20167 ); 20168 } 20169 } 20170 } 20171 20172 // static data definitions 20173 for (const el of document.querySelectorAll("script[type='ojs-define']")) { 20174 for (const { name, value } of JSON.parse(el.text).contents) { 20175 ojsConnector.define(name)(value); 20176 } 20177 } 20178 }, 20179 }; 20180 20181 return result; 20182} 20183 20184 20185function initializeRuntime() 20186{ 20187 // TODO "obs" or "ojs"? Inconsistent naming. 20188 window._ojs = { 20189 ojsConnector: undefined, 20190 20191 paths: {}, // placeholder for per-quarto-file paths 20192 // necessary for module resolution 20193 20194 hasShiny: false, // true if we have the quarto-ojs-shiny runtime 20195 20196 shinyElementRoot: undefined, // root element for the communication with shiny 20197 // via DOM 20198 }; 20199 window._ojs.runtime = createRuntime(); 20200 window._ojs.jsx = createQuartoJsxShim(); 20201} 20202 20203initializeRuntime(); 20204// export default init;
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.