Comparing version 0.1.4 to 0.2.0
/// <reference types="web" /> | ||
import type { IParseError, File, ShOptions } from './types.js'; | ||
import { IParseError, File, ShOptions } from './types.js'; | ||
export declare class ParseError extends Error implements IParseError { | ||
@@ -4,0 +4,0 @@ Filename: string; |
import { __awaiter } from "tslib"; | ||
/* eslint-disable @typescript-eslint/restrict-plus-operands */ | ||
import { nanoid } from 'nanoid/async'; | ||
import { LangVariant } from './types.js'; | ||
export class ParseError extends Error { | ||
@@ -16,4 +15,5 @@ constructor({ Filename, Incomplete, Text, Pos }) { | ||
let wasmFilePromise; | ||
// eslint-disable-next-line sonarjs/cognitive-complexity | ||
function processor(textOrAst, { filepath, originalText, keepComments = true, stopAt, variant, useTabs = false, tabWidth = 2, indent = useTabs ? 0 : tabWidth, binaryNextLine = true, switchCaseIndent = true, spaceRedirects = true, keepPadding = false, minify = false, functionNextLine = false, } = {}) { | ||
const encoder = new TextEncoder(); | ||
const decoder = new TextDecoder(); | ||
function processor(textOrAst, { filepath, originalText, keepComments = true, stopAt = '', variant = LangVariant.LangBash, useTabs = false, tabWidth = 2, indent = useTabs ? 0 : tabWidth, binaryNextLine = true, switchCaseIndent = true, spaceRedirects = true, keepPadding = false, minify = false, functionNextLine = false, } = {}) { | ||
return __awaiter(this, void 0, void 0, function* () { | ||
@@ -26,23 +26,5 @@ if (!wasmFile) { | ||
} | ||
const go = new Go(); | ||
const uid = yield nanoid(); | ||
const argv = [ | ||
'js', | ||
'-uid=' + uid, | ||
'-keepComments=' + keepComments, | ||
'-indent=' + indent, | ||
'-binaryNextLine=' + binaryNextLine, | ||
'-switchCaseIndent=' + switchCaseIndent, | ||
'-spaceRedirects=' + spaceRedirects, | ||
'-keepPadding=' + keepPadding, | ||
'-minify=' + minify, | ||
'-functionNextLine=' + functionNextLine, | ||
]; | ||
if (filepath != null) { | ||
argv.push('-filepath=' + filepath); | ||
} | ||
let isAst = false; | ||
if (typeof textOrAst !== 'string') { | ||
isAst = true; | ||
argv.push('-ast=ast'); | ||
if (originalText == null) { | ||
@@ -52,29 +34,34 @@ console.warn('`originalText` is required for now, hope we will find better solution later'); | ||
} | ||
if (stopAt != null) { | ||
argv.push('-stopAt=' + stopAt); | ||
} | ||
if (variant != null) { | ||
argv.push('-variant=' + variant); | ||
} | ||
go.argv = argv; | ||
const result = yield WebAssembly.instantiate(wasmFile, go.importObject); | ||
const wasm = result.instance; | ||
if (!Go.__shProcessing) { | ||
Go.__shProcessing = {}; | ||
} | ||
Go.__shProcessing[uid] = { | ||
Text: isAst ? originalText : textOrAst, | ||
Data: null, | ||
Error: null, | ||
}; | ||
yield go.run(wasm); | ||
const processed = Go.__shProcessing[uid]; | ||
delete Go.__shProcessing[uid]; | ||
if ('Error' in processed && processed.Error != null) { | ||
const go = new Go(); | ||
const wasm = yield WebAssembly.instantiate(wasmFile, go.importObject); | ||
// Do not await this promise, because it only resolves once the go main() | ||
// function has exited. But we need the main function to stay alive to be | ||
// able to call the `parse` and `print` function. | ||
// eslint-disable-next-line no-void | ||
void go.run(wasm.instance); | ||
const { memory, wasmAlloc, wasmFree, process } = wasm.instance.exports; | ||
const filePath = encoder.encode(filepath); | ||
const text = encoder.encode(isAst ? originalText : textOrAst); | ||
const uStopAt = encoder.encode(stopAt); | ||
const filePathPointer = wasmAlloc(filePath.byteLength); | ||
new Uint8Array(memory.buffer).set(filePath, filePathPointer); | ||
const textPointer = wasmAlloc(text.byteLength); | ||
new Uint8Array(memory.buffer).set(text, textPointer); | ||
const stopAtPointer = wasmAlloc(uStopAt.byteLength); | ||
new Uint8Array(memory.buffer).set(uStopAt, stopAtPointer); | ||
const resultPointer = process(filePathPointer, filePath.byteLength, filePath.byteLength, textPointer, text.byteLength, text.byteLength, isAst, keepComments, stopAtPointer, uStopAt.byteLength, uStopAt.byteLength, variant, indent, binaryNextLine, switchCaseIndent, spaceRedirects, keepPadding, minify, functionNextLine); | ||
wasmFree(filePathPointer); | ||
wasmFree(textPointer); | ||
wasmFree(stopAtPointer); | ||
const result = new Uint8Array(memory.buffer).subarray(resultPointer); | ||
const end = result.indexOf(0); | ||
const string = decoder.decode(result.subarray(0, end)); | ||
const { file, text: processedText, parseError, message, } = JSON.parse(string); | ||
if (parseError || message) { | ||
/* istanbul ignore next */ | ||
throw typeof processed.Error === 'string' | ||
? new SyntaxError(processed.Error) | ||
: new ParseError(processed.Error); | ||
throw parseError == null | ||
? new SyntaxError(message) | ||
: new ParseError(parseError); | ||
} | ||
return processed.Data; | ||
return isAst ? processedText : file; | ||
}); | ||
@@ -81,0 +68,0 @@ } |
@@ -7,10 +7,8 @@ export declare enum LangVariant { | ||
} | ||
export interface ShOptions { | ||
filepath?: string; | ||
originalText?: string; | ||
useTabs?: boolean; | ||
tabWidth?: number; | ||
export interface ShParserOptions { | ||
keepComments?: boolean; | ||
stopAt?: string; | ||
variant?: LangVariant; | ||
} | ||
export interface ShPrinterOptions { | ||
indent?: number; | ||
@@ -24,2 +22,10 @@ binaryNextLine?: boolean; | ||
} | ||
export interface ShSyntaxOptions extends ShParserOptions, ShPrinterOptions { | ||
} | ||
export interface ShOptions extends ShSyntaxOptions { | ||
filepath?: string; | ||
originalText?: string; | ||
useTabs?: boolean; | ||
tabWidth?: number; | ||
} | ||
export interface Pos { | ||
@@ -73,6 +79,1 @@ Col: number; | ||
} | ||
export interface ShProcessing { | ||
Text: string | null; | ||
Data: File | string | null; | ||
Error: IParseError | string | null; | ||
} |
{ | ||
"name": "sh-syntax", | ||
"version": "0.1.4", | ||
"version": "0.2.0", | ||
"type": "module", | ||
@@ -33,15 +33,15 @@ "description": "A WASM shell parser and formatter with bash support, based on mvdan/sh", | ||
"dependencies": { | ||
"nanoid": "^3.3.2", | ||
"tslib": "^2.3.1" | ||
"tslib": "^2.4.0" | ||
}, | ||
"devDependencies": { | ||
"@1stg/lib-config": "^5.5.0", | ||
"@1stg/lib-config": "^6.0.0", | ||
"@changesets/changelog-github": "^0.4.4", | ||
"@changesets/cli": "^2.22.0", | ||
"@types/jest": "^27.4.1", | ||
"@types/node": "^17.0.23", | ||
"@types/web": "^0.0.61", | ||
"ts-jest": "^27.1.4", | ||
"@types/golang-wasm-exec": "^1.15.0", | ||
"@types/jest": "^27.5.0", | ||
"@types/node": "^17.0.31", | ||
"@types/web": "^0.0.64", | ||
"ts-jest": "^28.0.2", | ||
"type-coverage": "^2.21.1", | ||
"typescript": "^4.6.3" | ||
"typescript": "^4.6.4" | ||
}, | ||
@@ -92,5 +92,4 @@ "jest": { | ||
"typecov": "type-coverage", | ||
"wasm": "GOOS=js GOARCH=wasm go build -o main.wasm" | ||
}, | ||
"readme": "# sh-syntax\n\n[![GitHub Actions](https://github.com/rx-ts/sh-syntax/workflows/CI/badge.svg)](https://github.com/rx-ts/sh-syntax/actions/workflows/ci.yml)\n[![Codecov](https://img.shields.io/codecov/c/github/rx-ts/sh-syntax.svg)](https://codecov.io/gh/rx-ts/sh-syntax)\n[![Codacy Grade](https://img.shields.io/codacy/grade/1d00ac27c99d4412bb70211e258706ab)](https://app.codacy.com/gh/rx-ts/sh-syntax)\n[![type-coverage](https://img.shields.io/badge/dynamic/json.svg?label=type-coverage&prefix=%E2%89%A5&suffix=%&query=$.typeCoverage.atLeast&uri=https%3A%2F%2Fraw.githubusercontent.com%2Frx-ts%2Fsh-syntax%2Fmain%2Fpackage.json)](https://github.com/plantain-00/type-coverage)\n[![npm](https://img.shields.io/npm/v/sh-syntax.svg)](https://www.npmjs.com/package/sh-syntax)\n[![GitHub Release](https://img.shields.io/github/release/rx-ts/sh-syntax)](https://github.com/rx-ts/sh-syntax/releases)\n\n[![David Peer](https://img.shields.io/david/peer/rx-ts/sh-syntax.svg)](https://david-dm.org/rx-ts/sh-syntax?type=peer)\n[![David](https://img.shields.io/david/rx-ts/sh-syntax.svg)](https://david-dm.org/rx-ts/sh-syntax)\n[![David Dev](https://img.shields.io/david/dev/rx-ts/sh-syntax.svg)](https://david-dm.org/rx-ts/sh-syntax?type=dev)\n\n[![Conventional Commits](https://img.shields.io/badge/conventional%20commits-1.0.0-yellow.svg)](https://conventionalcommits.org)\n[![Renovate enabled](https://img.shields.io/badge/renovate-enabled-brightgreen.svg)](https://renovatebot.com)\n[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)\n[![Code Style: Prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)\n[![changesets](https://img.shields.io/badge/maintained%20with-changesets-176de3.svg)](https://github.com/atlassian/changesets)\n\nA WASM shell parser and formatter with bash support, based on mvdan/sh\n\n## TOC <!-- omit in toc -->\n\n- [Usage](#usage)\n - [Install](#install)\n - [API](#api)\n- [Changelog](#changelog)\n- [License](#license)\n\n## Usage\n\n### Install\n\n```sh\n# yarn\nyarn add sh-syntax\n\n# npm\nnpm i sh-syntax\n```\n\n### API\n\n```js\n// node\nimport { parse, print } from 'sh-syntax'\n\nconst text = \"echo 'Hello World!'\"\nconst ast = await parse(text)\nconst newText = await print(ast, {\n // `originalText` is required for now, hope we will find better solution later\n originalText: text,\n})\n```\n\n```js\n// browser\nimport { getProcessor } from 'sh-syntax'\n\nconst processor = getProcessor(() =>\n fetch('path/to/main.wasm').then(res => res.arrayBuffer()),\n)\n\nconst parse = (text, options) => processor(text, options)\n\nconst print = (ast, options) => processor(ast, options)\n\n// just like node again\nconst text = \"echo 'Hello World!'\"\nconst ast = await parse(text)\nconst newText = await print(ast, { originalText: text })\n```\n\n## Changelog\n\nDetailed changes for each release are documented in [CHANGELOG.md](./CHANGELOG.md).\n\n## License\n\n[MIT][] © [JounQin][]@[1stG.me][]\n\n[1stg.me]: https://www.1stg.me\n[jounqin]: https://GitHub.com/JounQin\n[mit]: http://opensource.org/licenses/MIT\n" | ||
"wasm": "tinygo build -o main.wasm -target wasm --no-debug" | ||
} | ||
} |
/* eslint-disable unicorn/filename-case */ | ||
import _fs from 'fs' | ||
import type { IParseError, ShProcessing } from 'sh-syntax' | ||
declare global { | ||
@@ -10,19 +8,3 @@ namespace globalThis { | ||
var fs: typeof _fs | ||
class Go { | ||
static __shProcessing?: Record<string, ShProcessing> | ||
_pendingEvent: { id: number } | ||
argv: string[] | ||
env: NodeJS.ProcessEnv | ||
importObject: WebAssembly.Imports | ||
exited: boolean | ||
_resume(): void | ||
exit(code?: number): void | ||
run(instance: WebAssembly.Instance): Promise<void> | ||
} | ||
} | ||
} |
// Copyright 2018 The Go Authors. All rights reserved. | ||
// Use of this source code is governed by a BSD-style | ||
// license that can be found in the LICENSE file. | ||
// | ||
// This file has been modified for use by the TinyGo compiler. | ||
"use strict"; | ||
(() => { | ||
// Map multiple JavaScript environments to a single common API, | ||
// preferring web standards over Node.js API. | ||
// | ||
// Environments considered: | ||
// - Browsers | ||
// - Node.js | ||
// - Electron | ||
// - Parcel | ||
(() => { | ||
if (typeof global !== "undefined") { | ||
// global already exists | ||
} else if (typeof window !== "undefined") { | ||
window.global = window; | ||
} else if (typeof self !== "undefined") { | ||
self.global = self; | ||
} else { | ||
throw new Error("cannot export Go (neither global, window nor self is defined)"); | ||
} | ||
if (!global.require && typeof require !== "undefined") { | ||
global.require = require; | ||
} | ||
if (!global.fs && global.require) { | ||
global.fs = require("fs"); | ||
} | ||
const enosys = () => { | ||
@@ -14,5 +41,5 @@ const err = new Error("not implemented"); | ||
if (!globalThis.fs) { | ||
if (!global.fs) { | ||
let outputBuf = ""; | ||
globalThis.fs = { | ||
global.fs = { | ||
constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 }, // unused | ||
@@ -62,4 +89,4 @@ writeSync(fd, buf) { | ||
if (!globalThis.process) { | ||
globalThis.process = { | ||
if (!global.process) { | ||
global.process = { | ||
getuid() { return -1; }, | ||
@@ -78,45 +105,52 @@ getgid() { return -1; }, | ||
if (!globalThis.crypto) { | ||
throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)"); | ||
if (!global.crypto) { | ||
const nodeCrypto = require("crypto"); | ||
global.crypto = { | ||
getRandomValues(b) { | ||
nodeCrypto.randomFillSync(b); | ||
}, | ||
}; | ||
} | ||
if (!globalThis.performance) { | ||
throw new Error("globalThis.performance is not available, polyfill required (performance.now only)"); | ||
if (!global.performance) { | ||
global.performance = { | ||
now() { | ||
const [sec, nsec] = process.hrtime(); | ||
return sec * 1000 + nsec / 1000000; | ||
}, | ||
}; | ||
} | ||
if (!globalThis.TextEncoder) { | ||
throw new Error("globalThis.TextEncoder is not available, polyfill required"); | ||
if (!global.TextEncoder) { | ||
global.TextEncoder = require("util").TextEncoder; | ||
} | ||
if (!globalThis.TextDecoder) { | ||
throw new Error("globalThis.TextDecoder is not available, polyfill required"); | ||
if (!global.TextDecoder) { | ||
global.TextDecoder = require("util").TextDecoder; | ||
} | ||
// End of polyfills for common API. | ||
const encoder = new TextEncoder("utf-8"); | ||
const decoder = new TextDecoder("utf-8"); | ||
var logLine = []; | ||
globalThis.Go = class { | ||
global.Go = class { | ||
constructor() { | ||
this.argv = ["js"]; | ||
this.env = {}; | ||
this.exit = (code) => { | ||
if (code !== 0) { | ||
console.warn("exit code:", code); | ||
} | ||
}; | ||
this._exitPromise = new Promise((resolve) => { | ||
this._resolveExitPromise = resolve; | ||
}); | ||
this._pendingEvent = null; | ||
this._scheduledTimeouts = new Map(); | ||
this._callbackTimeouts = new Map(); | ||
this._nextCallbackTimeoutID = 1; | ||
const mem = () => { | ||
// The buffer may change when requesting more memory. | ||
return new DataView(this._inst.exports.memory.buffer); | ||
} | ||
const setInt64 = (addr, v) => { | ||
this.mem.setUint32(addr + 0, v, true); | ||
this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true); | ||
mem().setUint32(addr + 0, v, true); | ||
mem().setUint32(addr + 4, Math.floor(v / 4294967296), true); | ||
} | ||
const getInt64 = (addr) => { | ||
const low = this.mem.getUint32(addr + 0, true); | ||
const high = this.mem.getInt32(addr + 4, true); | ||
const low = mem().getUint32(addr + 0, true); | ||
const high = mem().getInt32(addr + 4, true); | ||
return low + high * 4294967296; | ||
@@ -126,3 +160,3 @@ } | ||
const loadValue = (addr) => { | ||
const f = this.mem.getFloat64(addr, true); | ||
const f = mem().getFloat64(addr, true); | ||
if (f === 0) { | ||
@@ -135,3 +169,3 @@ return undefined; | ||
const id = this.mem.getUint32(addr, true); | ||
const id = mem().getUint32(addr, true); | ||
return this._values[id]; | ||
@@ -143,15 +177,33 @@ } | ||
if (typeof v === "number" && v !== 0) { | ||
if (typeof v === "number") { | ||
if (isNaN(v)) { | ||
this.mem.setUint32(addr + 4, nanHead, true); | ||
this.mem.setUint32(addr, 0, true); | ||
mem().setUint32(addr + 4, nanHead, true); | ||
mem().setUint32(addr, 0, true); | ||
return; | ||
} | ||
this.mem.setFloat64(addr, v, true); | ||
if (v === 0) { | ||
mem().setUint32(addr + 4, nanHead, true); | ||
mem().setUint32(addr, 1, true); | ||
return; | ||
} | ||
mem().setFloat64(addr, v, true); | ||
return; | ||
} | ||
if (v === undefined) { | ||
this.mem.setFloat64(addr, 0, true); | ||
return; | ||
switch (v) { | ||
case undefined: | ||
mem().setFloat64(addr, 0, true); | ||
return; | ||
case null: | ||
mem().setUint32(addr + 4, nanHead, true); | ||
mem().setUint32(addr, 2, true); | ||
return; | ||
case true: | ||
mem().setUint32(addr + 4, nanHead, true); | ||
mem().setUint32(addr, 3, true); | ||
return; | ||
case false: | ||
mem().setUint32(addr + 4, nanHead, true); | ||
mem().setUint32(addr, 4, true); | ||
return; | ||
} | ||
@@ -170,9 +222,4 @@ | ||
this._goRefCounts[id]++; | ||
let typeFlag = 0; | ||
let typeFlag = 1; | ||
switch (typeof v) { | ||
case "object": | ||
if (v !== null) { | ||
typeFlag = 1; | ||
} | ||
break; | ||
case "string": | ||
@@ -188,15 +235,11 @@ typeFlag = 2; | ||
} | ||
this.mem.setUint32(addr + 4, nanHead | typeFlag, true); | ||
this.mem.setUint32(addr, id, true); | ||
mem().setUint32(addr + 4, nanHead | typeFlag, true); | ||
mem().setUint32(addr, id, true); | ||
} | ||
const loadSlice = (addr) => { | ||
const array = getInt64(addr + 0); | ||
const len = getInt64(addr + 8); | ||
return new Uint8Array(this._inst.exports.mem.buffer, array, len); | ||
const loadSlice = (array, len, cap) => { | ||
return new Uint8Array(this._inst.exports.memory.buffer, array, len); | ||
} | ||
const loadSliceOfValues = (addr) => { | ||
const array = getInt64(addr + 0); | ||
const len = getInt64(addr + 8); | ||
const loadSliceOfValues = (array, len, cap) => { | ||
const a = new Array(len); | ||
@@ -209,6 +252,4 @@ for (let i = 0; i < len; i++) { | ||
const loadString = (addr) => { | ||
const saddr = getInt64(addr + 0); | ||
const len = getInt64(addr + 8); | ||
return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len)); | ||
const loadString = (ptr, len) => { | ||
return decoder.decode(new DataView(this._inst.exports.memory.buffer, ptr, len)); | ||
} | ||
@@ -218,150 +259,119 @@ | ||
this.importObject = { | ||
go: { | ||
// Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters) | ||
// may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported | ||
// function. A goroutine can switch to a new stack if the current stack is too small (see morestack function). | ||
// This changes the SP, thus we have to update the SP used by the imported function. | ||
// func wasmExit(code int32) | ||
"runtime.wasmExit": (sp) => { | ||
sp >>>= 0; | ||
const code = this.mem.getInt32(sp + 8, true); | ||
this.exited = true; | ||
delete this._inst; | ||
delete this._values; | ||
delete this._goRefCounts; | ||
delete this._ids; | ||
delete this._idPool; | ||
this.exit(code); | ||
wasi_snapshot_preview1: { | ||
// https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#fd_write | ||
fd_write: function(fd, iovs_ptr, iovs_len, nwritten_ptr) { | ||
let nwritten = 0; | ||
if (fd == 1) { | ||
for (let iovs_i=0; iovs_i<iovs_len;iovs_i++) { | ||
let iov_ptr = iovs_ptr+iovs_i*8; // assuming wasm32 | ||
let ptr = mem().getUint32(iov_ptr + 0, true); | ||
let len = mem().getUint32(iov_ptr + 4, true); | ||
nwritten += len; | ||
for (let i=0; i<len; i++) { | ||
let c = mem().getUint8(ptr+i); | ||
if (c == 13) { // CR | ||
// ignore | ||
} else if (c == 10) { // LF | ||
// write line | ||
let line = decoder.decode(new Uint8Array(logLine)); | ||
logLine = []; | ||
console.log(line); | ||
} else { | ||
logLine.push(c); | ||
} | ||
} | ||
} | ||
} else { | ||
console.error('invalid file descriptor:', fd); | ||
} | ||
mem().setUint32(nwritten_ptr, nwritten, true); | ||
return 0; | ||
}, | ||
// func wasmWrite(fd uintptr, p unsafe.Pointer, n int32) | ||
"runtime.wasmWrite": (sp) => { | ||
sp >>>= 0; | ||
const fd = getInt64(sp + 8); | ||
const p = getInt64(sp + 16); | ||
const n = this.mem.getInt32(sp + 24, true); | ||
fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n)); | ||
fd_close: () => 0, // dummy | ||
fd_fdstat_get: () => 0, // dummy | ||
fd_seek: () => 0, // dummy | ||
"proc_exit": (code) => { | ||
if (global.process) { | ||
// Node.js | ||
process.exit(code); | ||
} else { | ||
// Can't exit in a browser. | ||
throw 'trying to exit with code ' + code; | ||
} | ||
}, | ||
// func resetMemoryDataView() | ||
"runtime.resetMemoryDataView": (sp) => { | ||
sp >>>= 0; | ||
this.mem = new DataView(this._inst.exports.mem.buffer); | ||
random_get: (bufPtr, bufLen) => { | ||
crypto.getRandomValues(loadSlice(bufPtr, bufLen)); | ||
return 0; | ||
}, | ||
// func nanotime1() int64 | ||
"runtime.nanotime1": (sp) => { | ||
sp >>>= 0; | ||
setInt64(sp + 8, (timeOrigin + performance.now()) * 1000000); | ||
}, | ||
env: { | ||
// func ticks() float64 | ||
"runtime.ticks": () => { | ||
return timeOrigin + performance.now(); | ||
}, | ||
// func walltime() (sec int64, nsec int32) | ||
"runtime.walltime": (sp) => { | ||
sp >>>= 0; | ||
const msec = (new Date).getTime(); | ||
setInt64(sp + 8, msec / 1000); | ||
this.mem.setInt32(sp + 16, (msec % 1000) * 1000000, true); | ||
// func sleepTicks(timeout float64) | ||
"runtime.sleepTicks": (timeout) => { | ||
// Do not sleep, only reactivate scheduler after the given timeout. | ||
setTimeout(this._inst.exports.go_scheduler, timeout); | ||
}, | ||
// func scheduleTimeoutEvent(delay int64) int32 | ||
"runtime.scheduleTimeoutEvent": (sp) => { | ||
sp >>>= 0; | ||
const id = this._nextCallbackTimeoutID; | ||
this._nextCallbackTimeoutID++; | ||
this._scheduledTimeouts.set(id, setTimeout( | ||
() => { | ||
this._resume(); | ||
while (this._scheduledTimeouts.has(id)) { | ||
// for some reason Go failed to register the timeout event, log and try again | ||
// (temporary workaround for https://github.com/golang/go/issues/28975) | ||
console.warn("scheduleTimeoutEvent: missed timeout event"); | ||
this._resume(); | ||
} | ||
}, | ||
getInt64(sp + 8) + 1, // setTimeout has been seen to fire up to 1 millisecond early | ||
)); | ||
this.mem.setInt32(sp + 16, id, true); | ||
}, | ||
// func clearTimeoutEvent(id int32) | ||
"runtime.clearTimeoutEvent": (sp) => { | ||
sp >>>= 0; | ||
const id = this.mem.getInt32(sp + 8, true); | ||
clearTimeout(this._scheduledTimeouts.get(id)); | ||
this._scheduledTimeouts.delete(id); | ||
}, | ||
// func getRandomData(r []byte) | ||
"runtime.getRandomData": (sp) => { | ||
sp >>>= 0; | ||
crypto.getRandomValues(loadSlice(sp + 8)); | ||
}, | ||
// func finalizeRef(v ref) | ||
"syscall/js.finalizeRef": (sp) => { | ||
sp >>>= 0; | ||
const id = this.mem.getUint32(sp + 8, true); | ||
this._goRefCounts[id]--; | ||
if (this._goRefCounts[id] === 0) { | ||
const v = this._values[id]; | ||
this._values[id] = null; | ||
this._ids.delete(v); | ||
this._idPool.push(id); | ||
} | ||
// Note: TinyGo does not support finalizers so this should never be | ||
// called. | ||
console.error('syscall/js.finalizeRef not implemented'); | ||
}, | ||
// func stringVal(value string) ref | ||
"syscall/js.stringVal": (sp) => { | ||
sp >>>= 0; | ||
storeValue(sp + 24, loadString(sp + 8)); | ||
"syscall/js.stringVal": (ret_ptr, value_ptr, value_len) => { | ||
const s = loadString(value_ptr, value_len); | ||
storeValue(ret_ptr, s); | ||
}, | ||
// func valueGet(v ref, p string) ref | ||
"syscall/js.valueGet": (sp) => { | ||
sp >>>= 0; | ||
const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16)); | ||
sp = this._inst.exports.getsp() >>> 0; // see comment above | ||
storeValue(sp + 32, result); | ||
"syscall/js.valueGet": (retval, v_addr, p_ptr, p_len) => { | ||
let prop = loadString(p_ptr, p_len); | ||
let value = loadValue(v_addr); | ||
let result = Reflect.get(value, prop); | ||
storeValue(retval, result); | ||
}, | ||
// func valueSet(v ref, p string, x ref) | ||
"syscall/js.valueSet": (sp) => { | ||
sp >>>= 0; | ||
Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32)); | ||
"syscall/js.valueSet": (v_addr, p_ptr, p_len, x_addr) => { | ||
const v = loadValue(v_addr); | ||
const p = loadString(p_ptr, p_len); | ||
const x = loadValue(x_addr); | ||
Reflect.set(v, p, x); | ||
}, | ||
// func valueDelete(v ref, p string) | ||
"syscall/js.valueDelete": (sp) => { | ||
sp >>>= 0; | ||
Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16)); | ||
"syscall/js.valueDelete": (v_addr, p_ptr, p_len) => { | ||
const v = loadValue(v_addr); | ||
const p = loadString(p_ptr, p_len); | ||
Reflect.deleteProperty(v, p); | ||
}, | ||
// func valueIndex(v ref, i int) ref | ||
"syscall/js.valueIndex": (sp) => { | ||
sp >>>= 0; | ||
storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16))); | ||
"syscall/js.valueIndex": (ret_addr, v_addr, i) => { | ||
storeValue(ret_addr, Reflect.get(loadValue(v_addr), i)); | ||
}, | ||
// valueSetIndex(v ref, i int, x ref) | ||
"syscall/js.valueSetIndex": (sp) => { | ||
sp >>>= 0; | ||
Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24)); | ||
"syscall/js.valueSetIndex": (v_addr, i, x_addr) => { | ||
Reflect.set(loadValue(v_addr), i, loadValue(x_addr)); | ||
}, | ||
// func valueCall(v ref, m string, args []ref) (ref, bool) | ||
"syscall/js.valueCall": (sp) => { | ||
sp >>>= 0; | ||
"syscall/js.valueCall": (ret_addr, v_addr, m_ptr, m_len, args_ptr, args_len, args_cap) => { | ||
const v = loadValue(v_addr); | ||
const name = loadString(m_ptr, m_len); | ||
const args = loadSliceOfValues(args_ptr, args_len, args_cap); | ||
try { | ||
const v = loadValue(sp + 8); | ||
const m = Reflect.get(v, loadString(sp + 16)); | ||
const args = loadSliceOfValues(sp + 32); | ||
const result = Reflect.apply(m, v, args); | ||
sp = this._inst.exports.getsp() >>> 0; // see comment above | ||
storeValue(sp + 56, result); | ||
this.mem.setUint8(sp + 64, 1); | ||
const m = Reflect.get(v, name); | ||
storeValue(ret_addr, Reflect.apply(m, v, args)); | ||
mem().setUint8(ret_addr + 8, 1); | ||
} catch (err) { | ||
sp = this._inst.exports.getsp() >>> 0; // see comment above | ||
storeValue(sp + 56, err); | ||
this.mem.setUint8(sp + 64, 0); | ||
storeValue(ret_addr, err); | ||
mem().setUint8(ret_addr + 8, 0); | ||
} | ||
@@ -371,15 +381,11 @@ }, | ||
// func valueInvoke(v ref, args []ref) (ref, bool) | ||
"syscall/js.valueInvoke": (sp) => { | ||
sp >>>= 0; | ||
"syscall/js.valueInvoke": (ret_addr, v_addr, args_ptr, args_len, args_cap) => { | ||
try { | ||
const v = loadValue(sp + 8); | ||
const args = loadSliceOfValues(sp + 16); | ||
const result = Reflect.apply(v, undefined, args); | ||
sp = this._inst.exports.getsp() >>> 0; // see comment above | ||
storeValue(sp + 40, result); | ||
this.mem.setUint8(sp + 48, 1); | ||
const v = loadValue(v_addr); | ||
const args = loadSliceOfValues(args_ptr, args_len, args_cap); | ||
storeValue(ret_addr, Reflect.apply(v, undefined, args)); | ||
mem().setUint8(ret_addr + 8, 1); | ||
} catch (err) { | ||
sp = this._inst.exports.getsp() >>> 0; // see comment above | ||
storeValue(sp + 40, err); | ||
this.mem.setUint8(sp + 48, 0); | ||
storeValue(ret_addr, err); | ||
mem().setUint8(ret_addr + 8, 0); | ||
} | ||
@@ -389,15 +395,11 @@ }, | ||
// func valueNew(v ref, args []ref) (ref, bool) | ||
"syscall/js.valueNew": (sp) => { | ||
sp >>>= 0; | ||
"syscall/js.valueNew": (ret_addr, v_addr, args_ptr, args_len, args_cap) => { | ||
const v = loadValue(v_addr); | ||
const args = loadSliceOfValues(args_ptr, args_len, args_cap); | ||
try { | ||
const v = loadValue(sp + 8); | ||
const args = loadSliceOfValues(sp + 16); | ||
const result = Reflect.construct(v, args); | ||
sp = this._inst.exports.getsp() >>> 0; // see comment above | ||
storeValue(sp + 40, result); | ||
this.mem.setUint8(sp + 48, 1); | ||
storeValue(ret_addr, Reflect.construct(v, args)); | ||
mem().setUint8(ret_addr + 8, 1); | ||
} catch (err) { | ||
sp = this._inst.exports.getsp() >>> 0; // see comment above | ||
storeValue(sp + 40, err); | ||
this.mem.setUint8(sp + 48, 0); | ||
storeValue(ret_addr, err); | ||
mem().setUint8(ret_addr+ 8, 0); | ||
} | ||
@@ -407,35 +409,34 @@ }, | ||
// func valueLength(v ref) int | ||
"syscall/js.valueLength": (sp) => { | ||
sp >>>= 0; | ||
setInt64(sp + 16, parseInt(loadValue(sp + 8).length)); | ||
"syscall/js.valueLength": (v_addr) => { | ||
return loadValue(v_addr).length; | ||
}, | ||
// valuePrepareString(v ref) (ref, int) | ||
"syscall/js.valuePrepareString": (sp) => { | ||
sp >>>= 0; | ||
const str = encoder.encode(String(loadValue(sp + 8))); | ||
storeValue(sp + 16, str); | ||
setInt64(sp + 24, str.length); | ||
"syscall/js.valuePrepareString": (ret_addr, v_addr) => { | ||
const s = String(loadValue(v_addr)); | ||
const str = encoder.encode(s); | ||
storeValue(ret_addr, str); | ||
setInt64(ret_addr + 8, str.length); | ||
}, | ||
// valueLoadString(v ref, b []byte) | ||
"syscall/js.valueLoadString": (sp) => { | ||
sp >>>= 0; | ||
const str = loadValue(sp + 8); | ||
loadSlice(sp + 16).set(str); | ||
"syscall/js.valueLoadString": (v_addr, slice_ptr, slice_len, slice_cap) => { | ||
const str = loadValue(v_addr); | ||
loadSlice(slice_ptr, slice_len, slice_cap).set(str); | ||
}, | ||
// func valueInstanceOf(v ref, t ref) bool | ||
"syscall/js.valueInstanceOf": (sp) => { | ||
sp >>>= 0; | ||
this.mem.setUint8(sp + 24, (loadValue(sp + 8) instanceof loadValue(sp + 16)) ? 1 : 0); | ||
"syscall/js.valueInstanceOf": (v_addr, t_addr) => { | ||
return loadValue(v_addr) instanceof loadValue(t_addr); | ||
}, | ||
// func copyBytesToGo(dst []byte, src ref) (int, bool) | ||
"syscall/js.copyBytesToGo": (sp) => { | ||
sp >>>= 0; | ||
const dst = loadSlice(sp + 8); | ||
const src = loadValue(sp + 32); | ||
"syscall/js.copyBytesToGo": (ret_addr, dest_addr, dest_len, dest_cap, source_addr) => { | ||
let num_bytes_copied_addr = ret_addr; | ||
let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable | ||
const dst = loadSlice(dest_addr, dest_len); | ||
const src = loadValue(source_addr); | ||
if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) { | ||
this.mem.setUint8(sp + 48, 0); | ||
mem().setUint8(returned_status_addr, 0); // Return "not ok" status | ||
return; | ||
@@ -445,13 +446,17 @@ } | ||
dst.set(toCopy); | ||
setInt64(sp + 40, toCopy.length); | ||
this.mem.setUint8(sp + 48, 1); | ||
setInt64(num_bytes_copied_addr, toCopy.length); | ||
mem().setUint8(returned_status_addr, 1); // Return "ok" status | ||
}, | ||
// func copyBytesToJS(dst ref, src []byte) (int, bool) | ||
"syscall/js.copyBytesToJS": (sp) => { | ||
sp >>>= 0; | ||
const dst = loadValue(sp + 8); | ||
const src = loadSlice(sp + 16); | ||
// copyBytesToJS(dst ref, src []byte) (int, bool) | ||
// Originally copied from upstream Go project, then modified: | ||
// https://github.com/golang/go/blob/3f995c3f3b43033013013e6c7ccc93a9b1411ca9/misc/wasm/wasm_exec.js#L404-L416 | ||
"syscall/js.copyBytesToJS": (ret_addr, dest_addr, source_addr, source_len, source_cap) => { | ||
let num_bytes_copied_addr = ret_addr; | ||
let returned_status_addr = ret_addr + 4; // Address of returned boolean status variable | ||
const dst = loadValue(dest_addr); | ||
const src = loadSlice(source_addr, source_len); | ||
if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) { | ||
this.mem.setUint8(sp + 48, 0); | ||
mem().setUint8(returned_status_addr, 0); // Return "not ok" status | ||
return; | ||
@@ -461,9 +466,5 @@ } | ||
dst.set(toCopy); | ||
setInt64(sp + 40, toCopy.length); | ||
this.mem.setUint8(sp + 48, 1); | ||
setInt64(num_bytes_copied_addr, toCopy.length); | ||
mem().setUint8(returned_status_addr, 1); // Return "ok" status | ||
}, | ||
"debug": (value) => { | ||
console.log(value); | ||
}, | ||
} | ||
@@ -474,7 +475,3 @@ }; | ||
async run(instance) { | ||
if (!(instance instanceof WebAssembly.Instance)) { | ||
throw new Error("Go.run: WebAssembly.Instance expected"); | ||
} | ||
this._inst = instance; | ||
this.mem = new DataView(this._inst.exports.mem.buffer); | ||
this._values = [ // JS values that Go currently has references to, indexed by reference id | ||
@@ -486,64 +483,27 @@ NaN, | ||
false, | ||
globalThis, | ||
global, | ||
this, | ||
]; | ||
this._goRefCounts = new Array(this._values.length).fill(Infinity); // number of references that Go has to a JS value, indexed by reference id | ||
this._ids = new Map([ // mapping from JS values to reference ids | ||
[0, 1], | ||
[null, 2], | ||
[true, 3], | ||
[false, 4], | ||
[globalThis, 5], | ||
[this, 6], | ||
]); | ||
this._idPool = []; // unused ids that have been garbage collected | ||
this.exited = false; // whether the Go program has exited | ||
this._goRefCounts = []; // number of references that Go has to a JS value, indexed by reference id | ||
this._ids = new Map(); // mapping from JS values to reference ids | ||
this._idPool = []; // unused ids that have been garbage collected | ||
this.exited = false; // whether the Go program has exited | ||
// Pass command line arguments and environment variables to WebAssembly by writing them to the linear memory. | ||
let offset = 4096; | ||
const mem = new DataView(this._inst.exports.memory.buffer) | ||
const strPtr = (str) => { | ||
const ptr = offset; | ||
const bytes = encoder.encode(str + "\0"); | ||
new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes); | ||
offset += bytes.length; | ||
if (offset % 8 !== 0) { | ||
offset += 8 - (offset % 8); | ||
while (true) { | ||
const callbackPromise = new Promise((resolve) => { | ||
this._resolveCallbackPromise = () => { | ||
if (this.exited) { | ||
throw new Error("bad callback: Go program has already exited"); | ||
} | ||
setTimeout(resolve, 0); // make sure it is asynchronous | ||
}; | ||
}); | ||
this._inst.exports._start(); | ||
if (this.exited) { | ||
break; | ||
} | ||
return ptr; | ||
}; | ||
const argc = this.argv.length; | ||
const argvPtrs = []; | ||
this.argv.forEach((arg) => { | ||
argvPtrs.push(strPtr(arg)); | ||
}); | ||
argvPtrs.push(0); | ||
const keys = Object.keys(this.env).sort(); | ||
keys.forEach((key) => { | ||
argvPtrs.push(strPtr(`${key}=${this.env[key]}`)); | ||
}); | ||
argvPtrs.push(0); | ||
const argv = offset; | ||
argvPtrs.forEach((ptr) => { | ||
this.mem.setUint32(offset, ptr, true); | ||
this.mem.setUint32(offset + 4, 0, true); | ||
offset += 8; | ||
}); | ||
// The linker guarantees global data starts from at least wasmMinDataAddr. | ||
// Keep in sync with cmd/link/internal/ld/data.go:wasmMinDataAddr. | ||
const wasmMinDataAddr = 4096 + 8192; | ||
if (offset >= wasmMinDataAddr) { | ||
throw new Error("total length of command line and environment variables exceeds limit"); | ||
await callbackPromise; | ||
} | ||
this._inst.exports.run(argc, argv); | ||
if (this.exited) { | ||
this._resolveExitPromise(); | ||
} | ||
await this._exitPromise; | ||
} | ||
@@ -571,2 +531,23 @@ | ||
} | ||
if ( | ||
global.require && | ||
global.require.main === module && | ||
global.process && | ||
global.process.versions && | ||
!global.process.versions.electron | ||
) { | ||
if (process.argv.length != 3) { | ||
console.error("usage: go_js_wasm_exec [wasm binary] [arguments]"); | ||
process.exit(1); | ||
} | ||
const go = new Go(); | ||
WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject).then((result) => { | ||
return go.run(result.instance); | ||
}).catch((err) => { | ||
console.error(err); | ||
process.exit(1); | ||
}); | ||
} | ||
})(); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
1
578084
10
1353
8
- Removednanoid@^3.3.2
- Removednanoid@3.3.8(transitive)
Updatedtslib@^2.4.0