diff --git a/src/drawingToolkit/Turtle.js b/src/drawingToolkit/Turtle.js index 3136995f5..a26837f1f 100644 --- a/src/drawingToolkit/Turtle.js +++ b/src/drawingToolkit/Turtle.js @@ -1,13 +1,10 @@ import { translatePt, rotatePt } from "./affineTransformations.js"; -import { assertArgs } from './assert.js' const copy = obj => JSON.parse(JSON.stringify(obj)) export class Turtle { constructor() { - assertArgs(arguments, [], 'new bt.Turtle') - this.drawing = true this.position = [ 0, 0 ] this.angle = 0 @@ -18,8 +15,6 @@ export class Turtle { } up() { - assertArgs(arguments, [], 'turtle.up') - if (!this.drawing) return this this.drawing = false this.path.push([[...this.position]]) @@ -27,15 +22,11 @@ export class Turtle { } down() { - assertArgs(arguments, [], 'turtle.down') - this.drawing = true return this } goTo([x, y]) { - assertArgs(arguments, ['point'], 'turtle.goTo') - const lastPath = this.path.at(-1) if (this.drawing) { const [lastX, lastY] = this.position @@ -51,9 +42,7 @@ export class Turtle { return this } - step([dx, dy]) { - assertArgs(arguments, ['point'], 'turtle.step') - + step([dx, dy]) { // document this const [x, y] = this.position; this.goTo([ @@ -65,8 +54,6 @@ export class Turtle { } jump(pt) { - assertArgs(arguments, ['point'], 'turtle.jump') - const [x, y] = pt; const lastPath = this.path.at(-1); if (lastPath.length === 1) { @@ -82,8 +69,6 @@ export class Turtle { } forward(distance) { - assertArgs(arguments, ['number'], 'turtle.forward') - const last = this.position const a = (this.angle / 180) * Math.PI const x = last[0] + distance * Math.cos(a) @@ -95,8 +80,6 @@ export class Turtle { } arc(angle, radius) { - assertArgs(arguments, ['number', 'number'], 'turtle.arc') - if (angle === 0 || radius === 0) return this; const n = 64; @@ -135,8 +118,6 @@ export class Turtle { // setHeading? setAngle(theta) { - assertArgs(arguments, ['number'], 'turtle.setAngle') - this.angle = theta return this @@ -147,24 +128,18 @@ export class Turtle { // } right(theta) { - assertArgs(arguments, ['number'], 'turtle.right') - this.angle -= theta return this } left(theta) { - assertArgs(arguments, ['number'], 'turtle.left') - this.angle += theta return this } lines() { // could be called polylines - assertArgs(arguments, [], 'turtle.lines') - const pls = copy(this.path); return pls.filter(pl => pl.length > 1); @@ -172,8 +147,6 @@ export class Turtle { copy() { - assertArgs(arguments, [], 'turtle.copy') - const t = new Turtle() t.path = copy(this.path) @@ -185,16 +158,12 @@ export class Turtle { } applyToPath(fn) { - assertArgs(arguments, ['function'], 'turtle.applyToPath') - fn(this.path); return this; } // undoced apply(fn) { - assertArgs(arguments, ['function'], 'turtle.apply') - fn(this); return this; } diff --git a/src/drawingToolkit/affineTransformations.js b/src/drawingToolkit/affineTransformations.js index 73a8aab2c..cab14337d 100644 --- a/src/drawingToolkit/affineTransformations.js +++ b/src/drawingToolkit/affineTransformations.js @@ -1,9 +1,6 @@ -import { assertArgs } from "./assert.js"; import { bounds } from "./bounds.js"; -export function translate(polylines, to, origin = [0, 0]) { - assertArgs(arguments, ['polylines', 'point', 'point?'], 'bt.translate') - +export const translate = (polylines, to, origin = [0, 0]) => { polylines.flat().forEach(pt => { const [x, y] = translatePt(pt, to, origin); pt[0] = x; @@ -13,9 +10,7 @@ export function translate(polylines, to, origin = [0, 0]) { return polylines; } -export function rotate(polylines, angle, origin) { - assertArgs(arguments, ['polylines', 'number', 'point?'], 'bt.rotate') - +export const rotate = (polylines, angle, origin) => { if (!origin) origin = bounds(polylines).cc polylines.flat().forEach(pt => { @@ -27,9 +22,7 @@ export function rotate(polylines, angle, origin) { return polylines } -export function scale(polylines, factor, origin) { - assertArgs(arguments, ['polylines', ['number', 'point'], 'point?'], 'bt.scale') - +export const scale = (polylines, factor, origin) => { if (!origin) origin = bounds(polylines).cc polylines.flat().forEach(pt => { diff --git a/src/drawingToolkit/assert.js b/src/drawingToolkit/assert.js deleted file mode 100644 index 315f64c8a..000000000 --- a/src/drawingToolkit/assert.js +++ /dev/null @@ -1,113 +0,0 @@ -/* -Type strings: -- number -- point: [x, y] -- polyline: point[] -- polylines: polyline[] -- function -- boolean -- undefined - -You can append a "?" to any type to make it optional, -but optional arguments must be at the end of your type -list. An array of strings allows for multiple types. - -special: -- any (function accepts any type) (use this for options - objects) -- unknown (function given unexpected type) -- emptyArray (function given an empty array, which - satisfies both polyline and polylines) -*/ -function getType(value) { - if (typeof value === "number") return "number"; - if (Array.isArray(value)) { - if (value.length === 0) return "emptyArray"; - if (value.length === 2 && value.every(v => typeof v === "number")) return "point"; - if (value.every(v => getType(v) === "point")) return "polyline"; - if (value.every(v => getType(v) === "polyline")) return "polylines"; - } - if (typeof value === "function") return "function"; - if (typeof value === "boolean") return "boolean"; - if (value === undefined) return "undefined"; - return "unknown"; -} - -const typeStrings = { - number: "a number", - point: "a point", - polyline: "a single polyline", - polylines: "an array of polylines", - emptyArray: "an empty array", - function: "a function", - boolean: "a boolean", - undefined: "undefined", - unknown: "an unknown type", - any: "any type" -} -function getTypeString(type) { - if (typeof type === "string" && type.endsWith("?")) { - return `${getTypeString(type.replace(/\?$/, ""))} (optional)`; - } - if (Array.isArray(type)) { - return type.map(getTypeString).join(" or "); - } - if (type in typeStrings) { - return typeStrings[type]; - } - console.warn(`No name for type ${type}`); - return String(type); -} - -function typeMatches(type, expected) { - if (Array.isArray(expected)) { - return expected.some(t => typeMatches(t, type)); - } - if (expected.endsWith("?") && type === "undefined") return true; - - const expectedType = expected.replace(/\?$/, ""); - if (expectedType === "any") return true; - if ( - type === "emptyArray" && - ["polyline", "polylines"].includes(expectedType) - ) return true; - - return type === expectedType; -} - -/** - * @typedef {'number' | 'point' | 'polyline' | 'polylines' | 'function' | 'boolean' | 'undefined' | 'any'} ExpectedTypeString - * @typedef {ExpectedTypeString | ExpectedTypeString[]} ExpectedType - * - * @param {any[]} args - * @param {ExpectedType[]} expected - * @param {string} name - */ -export function assertArgs(args, expected, name) { - const maxExpectedCount = expected.length; - const minExpectedCount = expected.filter(e => ( - !(typeof e === "string" && e.endsWith("?")) - )).length; - - if ( - args.length < minExpectedCount || args.length > maxExpectedCount - ) { - const expectedCountString = minExpectedCount === maxExpectedCount - ? `${minExpectedCount} argument${minExpectedCount !== 1 ? "s" : ""}` - : `${minExpectedCount} to ${maxExpectedCount} arguments`; - throw new Error(`${name} expects ${expectedCountString}, but got ${args.length}`) - } - - for (let i = 0; i < expected.length; i++) { - const arg = args[i]; - const expectedType = expected[i]; - const argType = getType(arg); - const matches = typeMatches(argType, expectedType); - if (!matches) { - console.warn(`Expected type ${expectedType}, but got ${argType}`); - throw new Error( - `${name} expects argument ${i + 1} to be ${getTypeString(expectedType)}, but got ${getTypeString(argType)}` - ); - } - } -} \ No newline at end of file diff --git a/src/drawingToolkit/bounds.js b/src/drawingToolkit/bounds.js index f97b13663..762e09e30 100644 --- a/src/drawingToolkit/bounds.js +++ b/src/drawingToolkit/bounds.js @@ -1,8 +1,5 @@ -import { assertArgs } from './assert' export function bounds(polylines) { - assertArgs(arguments, ['polylines'], 'bt.bounds'); - const { xMin, xMax, yMin, yMax } = extrema(polylines.flat()); const width = xMax - xMin; diff --git a/src/drawingToolkit/catmullRom.js b/src/drawingToolkit/catmullRom.js index 73d6b53af..5f4a256e4 100644 --- a/src/drawingToolkit/catmullRom.js +++ b/src/drawingToolkit/catmullRom.js @@ -1,8 +1,4 @@ -import { assertArgs } from './assert' - export function catmullRom(controlPoints, segments = 100) { - assertArgs(arguments, ['polyline', 'number?'], 'bt.catmullRom'); - const isClosed = (points) => { const start = points[0]; const end = points[points.length - 1]; diff --git a/src/drawingToolkit/cutCover.js b/src/drawingToolkit/cutCover.js index f12e97040..7979b9ab8 100644 --- a/src/drawingToolkit/cutCover.js +++ b/src/drawingToolkit/cutCover.js @@ -1,11 +1,8 @@ import { bounds } from "./bounds.js"; import { pointInPolylines } from "./pointInPolylines.js" import { mergePolylines } from "./mergePolylines.js"; -import { assertArgs } from "./assert.js"; - -export function cut(polylines0, polylines1, assumeClosed = true) { - assertArgs(arguments, ['polylines', 'polylines', 'boolean?'], 'bt.cut'); +export const cut = (polylines0, polylines1, assumeClosed = true) => { if (assumeClosed) polylines1.forEach(poly => { const [x, y] = poly.at(0); poly.push([x, y]); @@ -28,9 +25,7 @@ export function cut(polylines0, polylines1, assumeClosed = true) { return polylines0; }; -export function cover(polylines0, polylines1, assumeClosed = true) { - assertArgs(arguments, ['polylines', 'polylines', 'boolean?'], 'bt.cover'); - +export const cover = (polylines0, polylines1, assumeClosed = true) => { if (assumeClosed) polylines1.forEach(poly => { const [x, y] = poly.at(0); poly.push([x, y]); diff --git a/src/drawingToolkit/getAngleAtT.js b/src/drawingToolkit/getAngleAtT.js index 558ce2da8..1d7eed0e9 100644 --- a/src/drawingToolkit/getAngleAtT.js +++ b/src/drawingToolkit/getAngleAtT.js @@ -1,8 +1,4 @@ -import { assertArgs } from './assert' - export function getAngleAtT(polylines, t) { - assertArgs(arguments, ['polylines', 'number'], 'bt.getAngle') - // Calculate the total length of all polylines let totalLength = 0 let lengths = polylines.map(polyline => { diff --git a/src/drawingToolkit/getNormalAtT.js b/src/drawingToolkit/getNormalAtT.js index b7847996f..a8a23ff92 100644 --- a/src/drawingToolkit/getNormalAtT.js +++ b/src/drawingToolkit/getNormalAtT.js @@ -1,8 +1,4 @@ -import { assertArgs } from './assert' - export function getNormalAtT(polylines, t) { - assertArgs(arguments, ['polylines', 'number'], 'bt.getNormal') - // Calculate the total length of all polylines let totalLength = 0 let lengths = polylines.map(polyline => { diff --git a/src/drawingToolkit/getPointAtT.js b/src/drawingToolkit/getPointAtT.js index e8ccea09b..ab554c267 100644 --- a/src/drawingToolkit/getPointAtT.js +++ b/src/drawingToolkit/getPointAtT.js @@ -1,8 +1,4 @@ -import { assertArgs } from './assert' - export function getPointAtT(polylines, t) { - assertArgs(arguments, ['polylines', 'number'], 'bt.getPoint') - t = Math.max(t, 0) t = Math.min(t, 1) diff --git a/src/drawingToolkit/iteratePolylines.js b/src/drawingToolkit/iteratePolylines.js index 0b8215a74..d92d24db4 100644 --- a/src/drawingToolkit/iteratePolylines.js +++ b/src/drawingToolkit/iteratePolylines.js @@ -1,8 +1,4 @@ -import { assertArgs } from './assert' - export function iteratePolylines(polylines, fn) { - assertArgs(arguments, ['polylines', 'function'], 'bt.iteratePoints') - const toRemove = new Set() const toBreak = new Set() diff --git a/src/drawingToolkit/mergePolylines.js b/src/drawingToolkit/mergePolylines.js index df41cbc2b..fd66a5215 100644 --- a/src/drawingToolkit/mergePolylines.js +++ b/src/drawingToolkit/mergePolylines.js @@ -1,8 +1,4 @@ -import { assertArgs } from './assert' - export function mergePolylines(polylines) { - assertArgs(arguments, ['polylines'], 'bt.merge'); - let merged = true; while (merged) { diff --git a/src/drawingToolkit/noise.js b/src/drawingToolkit/noise.js index 1a48ee9da..3d7ce3d5d 100644 --- a/src/drawingToolkit/noise.js +++ b/src/drawingToolkit/noise.js @@ -1,4 +1,3 @@ -import { assertArgs } from './assert.js' import { rand } from './rand.js' let PERLIN_YWRAPB = 4 @@ -14,7 +13,6 @@ let scaled_cosine = function (i) { let perlin// will be initialized lazily by noise() or noiseSeed() export function noise( vector, options = {}) { - assertArgs(arguments, ['point', 'any?'], 'bt.noise') if (typeof vector === 'number') vector = [vector, 0, 0] let [x, y, z] = vector y = y || 0 diff --git a/src/drawingToolkit/offset.js b/src/drawingToolkit/offset.js index df2514e90..0efad31d3 100644 --- a/src/drawingToolkit/offset.js +++ b/src/drawingToolkit/offset.js @@ -1,4 +1,3 @@ -import { assertArgs } from './assert.js' import { ClipperLib } from "./clipper_unminified.js"; const overlap = (p0, p1) => 0.00000001 > Math.abs(p0[0] - p1[0]) + Math.abs(p0[1] - p1[1]); @@ -11,8 +10,6 @@ const isClosed = shape => { } export function offset(polylines, delta, ops = {}) { - assertArgs(arguments, ['polylines', 'number', 'any?'], 'bt.offset') - const ogPolylines = polylines; if (typeof polylines.at(0)?.at(0) === "number") polylines = [polylines]; diff --git a/src/drawingToolkit/pointInPolylines.js b/src/drawingToolkit/pointInPolylines.js index 0426753d3..53fa65c60 100644 --- a/src/drawingToolkit/pointInPolylines.js +++ b/src/drawingToolkit/pointInPolylines.js @@ -1,7 +1,4 @@ -import { assertArgs } from './assert' - export function pointInPolylines(polylines, point, ops = {}) { - assertArgs(arguments, ['polylines', 'point'], 'bt.pointInside'); const insides = polylines .map(poly => pointInPolyline(point, poly, ops)) diff --git a/src/drawingToolkit/rand.js b/src/drawingToolkit/rand.js index 54e237289..ce9254612 100644 --- a/src/drawingToolkit/rand.js +++ b/src/drawingToolkit/rand.js @@ -1,10 +1,6 @@ -import { assertArgs } from './assert' - let jsr = 69 export function rand() { - assertArgs(arguments, [], 'bt.rand') - const max = 4294967295 jsr ^= jsr << 17 jsr ^= jsr >>> 13 @@ -13,20 +9,14 @@ export function rand() { } export function setRandSeed(seed) { - assertArgs(arguments, ['number'], 'bt.setRandSeed') - jsr = seed } export function randInRange(min, max) { - assertArgs(arguments, ['number', 'number'], 'bt.randInRange') - return rand() * (max - min) + min } export function randIntInRange(min, max) { - assertArgs(arguments, ['number', 'number'], 'bt.randIntInRange') - min = Math.ceil(min) max = Math.floor(max) return Math.floor(rand() * (max - min + 1) + min) diff --git a/src/drawingToolkit/resamplePolylines.js b/src/drawingToolkit/resamplePolylines.js index 90a5f3f38..9771347bf 100644 --- a/src/drawingToolkit/resamplePolylines.js +++ b/src/drawingToolkit/resamplePolylines.js @@ -1,5 +1,3 @@ -import { assertArgs } from './assert' - function isect_circ_line( cx, cy, @@ -108,8 +106,6 @@ function resamplePolyline(polyline, step) { } export function resamplePolylines(polylines, resolution) { - assertArgs(arguments, ['polylines', 'number'], 'bt.resample') - polylines.forEach(pl => { const newPl = resamplePolyline(pl, resolution) while (pl.length > 0) pl.pop() diff --git a/src/drawingToolkit/toolkit.js b/src/drawingToolkit/toolkit.js index 1fbdabb54..e8a923a9d 100644 --- a/src/drawingToolkit/toolkit.js +++ b/src/drawingToolkit/toolkit.js @@ -19,7 +19,6 @@ import { bounds } from "./bounds.js"; import { catmullRom } from "./catmullRom.js"; import { nurbs } from "./nurbs.js"; import { offset } from "./offset.js" -import { assertArgs } from "./assert.js"; // import * as polyclip from 'polyclip-ts'; // import polygonClipping from "polygon-clipping"; @@ -27,18 +26,10 @@ import { assertArgs } from "./assert.js"; // import { bezierEasing } from "./bezierEasing.js"; export const toolkit = { - union(polylines0, polylines1, ops = {}) { - assertArgs(arguments, ['polylines', 'polylines', 'any?'], 'bt.union'); - return boolean(polylines0, polylines1, "union", ops); - }, - intersection(polylines0, polylines1, ops = {}) { - assertArgs(arguments, ['polylines', 'polylines', 'any?'], 'bt.intersection'); - return boolean(polylines0, polylines1, "intersection", ops); - }, - difference(polylines0, polylines1, ops = {}) { - assertArgs(arguments, ['polylines', 'polylines', 'any?'], 'bt.difference'); - return boolean(polylines0, polylines1, "difference", ops); - }, + union: (polylines0, polylines1, ops = {}) => boolean(polylines0, polylines1, "union", ops), + intersection: (polylines0, polylines1, ops = {}) => boolean(polylines0, polylines1, "intersection", ops), + difference: (polylines0, polylines1, ops = {}) => boolean(polylines0, polylines1, "difference", ops), + xor: (polylines0, polylines1, ops = {}) => boolean(polylines0, polylines1, "xor", ops), offset, iteratePoints: iteratePolylines, transform, @@ -56,8 +47,6 @@ export const toolkit = { // bezierEasing, // used to be in catmullRom, nurbs(points, ops = {}) { - assertArgs(arguments, ['polyline', 'any?'], 'bt.nurbs') - const degree = ops.degree ?? 2; const steps = ops.steps ?? 100; const boundary = isClosed(points) ? "closed" : "clamped"; @@ -103,8 +92,6 @@ export const toolkit = { } }, originate(polylines) { - assertArgs(arguments, ['polylines'], 'bt.originate') - const cc = bounds(polylines).cc; translate(polylines, [0, 0], cc); return polylines; @@ -119,8 +106,6 @@ export const toolkit = { getNormal: getNormalAtT, resample: resamplePolylines, simplify(polylines, tolerance, hq = true) { - assertArgs(arguments, ['polylines', 'number', 'boolean?'], 'bt.simplify') - polylines.forEach(pl => { const newPl = simplifyPolyline(pl, tolerance, hq) while (pl.length > 0) pl.pop() @@ -135,8 +120,6 @@ export const toolkit = { trim: trimPolylines, merge: mergePolylines, svgToPolylines(svgString) { // undoced - assertArgs(arguments, ['string'], 'bt.svgToPolylines') - try { const parser = new DOMParser(); const doc = parser.parseFromString(svgString, 'image/svg+xml'); @@ -179,11 +162,7 @@ export const toolkit = { return first; }, - copy(obj) { - assertArgs(arguments, ['any'], 'bt.copy') - - return JSON.parse(JSON.stringify(obj)); - } + copy: obj => JSON.parse(JSON.stringify(obj)) } diff --git a/src/drawingToolkit/trimPolylines.js b/src/drawingToolkit/trimPolylines.js index 0a71aa159..9f03ff68a 100644 --- a/src/drawingToolkit/trimPolylines.js +++ b/src/drawingToolkit/trimPolylines.js @@ -1,8 +1,4 @@ -import { assertArgs } from './assert' - export function trimPolylines(polylines, t1, t2) { - assertArgs(arguments, ['polylines', 'number', 'number'], 'bt.trims'); - t1 = Math.max(0, Math.min(1, t1)); t2 = Math.max(0, Math.min(1, t2)); diff --git a/src/getPosFromErr.js b/src/getPosFromErr.js index 317c6cf3e..a688a87c3 100644 --- a/src/getPosFromErr.js +++ b/src/getPosFromErr.js @@ -1,89 +1,16 @@ -Error.stackTraceLimit = Infinity; -Error.prepareStackTrace = (_err, stack) => stack; - -// Error.stack is an unstandardized string, so we use -// a regex based on the format of the stack trace, as -// seen in the source code of the JavaScript engines -// SpiderMonkey (Firefox): https://searchfox.org/mozilla-central/rev/87630817796aae3cbceb369a1b642da3e4741745/js/src/vm/SavedStacks.cpp#1007-1022 -// JavaScriptCore (Safari): https://github.com/WebKit/WebKit/blob/f087a1892ee65f63fc511d500f59c8ecd31b7e0b/Source/JavaScriptCore/runtime/StackFrame.cpp#L152-L164 - -const frameRegex = /^ *(?:(?.*?)\*)?(?.*?)@(?.*?)(?::(?\d+):(?\d+))?$/ - -export const traceFormat = (function () { - const stack = (0, eval)('new Error()').stack - - if (Array.isArray(stack)) { - return 'V8' - } - - const matches = stack.trim().split('\n').map(l => l.match(frameRegex)) - if (!matches.every(m => m)) { - console.error("Unable to parse this browser's stack trace:", stack) - return 'unknown' - } - - const topHasLineNumber = matches[0].groups.line !== undefined - if (topHasLineNumber) { - return 'SpiderMonkey' - } else { - return 'JavaScriptCore' - } -})() - export function getPosFromErr(err) { try { - if (!(err instanceof Error)) { - // Cannot get the position from a non-error - return { line: 0, column: 0 } - } - - const stack = err.stack - - if (Array.isArray(stack)) { - // V8 (Chrome)-specific internal stack representation - // https://v8.dev/docs/stack-trace-api - // Frames with isEval() are within user code, the - // topmost one is the error location - const frame = stack.find(f => f.isEval()) - console.log(frame, frame.getLineNumber(), frame.getColumnNumber()) - return { line: frame.getLineNumber() - 3, column: frame.getColumnNumber() - 1 } - } - - const lines = stack.trim().split('\n') + const match = err.stack.match(/:(\d+):(\d+)/); - const frameMatches = lines.map(l => l.match(frameRegex)) - if (frameMatches.every(m => m)) { - // The regex matched all lines, so it is probably correct + const pos = { line: Number(match[1]), column: Number(match[2]) } - // This frame is the one constructed by us, an AsyncFunction - // always has the name of "anonymous" and our hack for Safari - // uses a function named "__blotUserCodeFunction" - const ourFrame = frameMatches.findLast(m => ( - // SpiderMonkey - (m.groups.func === 'anonymous' && m.groups.source.endsWith(' > AsyncFunction')) || - // JavaScriptCore - (m.groups.func === '__blotUserCodeFunction' && m.groups.source.startsWith('data:')) - )) + pos.line -= 2; // why? - if (!ourFrame) { - // No frame that we recognize - return { line: 0, column: 0 } - } + // to account for "use strict\n" + pos.line -= 1 + pos.column -= 1 - // All frames with the same source are part of the user's code - const entry = frameMatches.find(m => m.groups.source === ourFrame.groups.source) - - // Used the importScripts trick, so we need to offset the line differently - const usedImportScripts = ourFrame.groups.func === '__blotUserCodeFunction' - - return { - line: Number(entry.groups.line) - (usedImportScripts ? 2 : 3), - column: Number(entry.groups.column) - 1 - } - } - - console.error('Unable to parse stack trace:', stack) - return { line: 0, column: 0 } + return pos } catch (e) { // An error in the error handler?! // that's embarassing. diff --git a/src/makeIncluded.js b/src/makeIncluded.js index 2774bcc88..11e3673cc 100644 --- a/src/makeIncluded.js +++ b/src/makeIncluded.js @@ -1,4 +1,3 @@ -import { assertArgs } from './drawingToolkit/assert.js' import { toolkit } from "./drawingToolkit/toolkit.js"; import { Turtle } from './drawingToolkit/Turtle.js' import { getPosFromErr } from "./getPosFromErr.js"; @@ -63,14 +62,10 @@ https://github.com/hackclub/blot/issues/161`); console: patchedConsole, setDocDimensions(w, h) { - assertArgs(arguments, ['number', 'number'], 'setDocDimensions'); - docDimensions.width = w; docDimensions.height = h; }, - drawLines(polylines = [], style = {}) { - assertArgs(arguments, ['polylines', 'any?'], 'drawLines'); - + drawLines: (polylines = [], style = {}) => { if (polylines.length === 0) return; const temp = {}; diff --git a/src/runCodeInner.js b/src/runCodeInner.js index 4b9447a42..9374d4eea 100644 --- a/src/runCodeInner.js +++ b/src/runCodeInner.js @@ -1,27 +1,10 @@ -import { traceFormat } from "./getPosFromErr.js" -const AsyncFunction = async function () {}.constructor - -function createFunction(str, globalKeys) { - const useAsyncFunction = traceFormat !== 'JavaScriptCore' - if (useAsyncFunction) { - return new AsyncFunction(...globalKeys, str) - } else { - // stupid hack for Safari - // build a Data URL from the code and use importScripts - // this is needed to get line numbers for errors - const code = - `globalThis.__blotUserCodeFunction = (async function __blotUserCodeFunction(${globalKeys.join(", ")}) {\n${str}\n})` - const dataURL = `data:text/javascript;base64,${btoa(code)}` - importScripts(dataURL) - return globalThis.__blotUserCodeFunction - } -} - -export async function runCodeInner(str, globalScope, basePath) { +export async function runCodeInner(str, globalScope, basePath) { + const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor + str = subDynamicImports(str); str = `"use strict"\n${str}` - const fn = createFunction(str, Object.keys(globalScope)) + const fn = new AsyncFunction(...Object.keys(globalScope), str) await fn(...Object.values(globalScope)).catch(err => { throw err