This commit is contained in:
Star 2024-10-11 09:57:41 +08:00
commit e4f56cbddf
7 changed files with 520 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
.*
!.gitignore
go.sum

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 apigo
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

61
README.md Normal file
View File

@ -0,0 +1,61 @@
# util for GoJS
## usage
```go
import (
"apigo.cc/gojs"
_ "apigo.cc/gojs/util"
)
func main() {
r, err := gojs.Run(`
import util from 'apigo.cc/gojs/util'
function main(args){
return util.sha512('hello 123')
}
`, "test.js")
fmt.Println(r, err, r == "27d0d415a3b14bdeb5ab5b2298ed3aed272361688927250eaef201603b84dd8bebb57cae089d6b5f1e9aee122a67917ccdf8a9ba5e499c64b35e133c7f6b007a")
}
```
## module.exports
```ts
function json(data:any): string {return ''}
function jsonP(data:any): string {return ''}
function unJson(data:string): any {return null}
function yaml(data:any): string {return ''}
function unYaml(data:string): any {return null}
function load(filename:string): any {return null}
function save(filename:string, data:any) {}
function base64(data:any): string {return ''}
function unBase64(data:string): any {return null}
function urlBase64(data:any): string {return ''}
function unUrlBase64(data:string): any {return null}
function hex(data:any): string {return ''}
function unHex(data:string): any {return null}
function aes(data:any, key:string, iv:string): string {return ''}
function unAes(data:string, key:string, iv:string): any {return null}
function gzip(data:any): string {return ''}
function gunzip(data:string): any {return null}
function id(): string {return ''}
function uniqueId(): string {return ''}
function token(size:number): string {return ''}
function md5(data:any): string {return ''}
function sha1(data:any): string {return ''}
function sha256(data:any): string {return ''}
function sha512(data:any): string {return ''}
function tpl(text:string, data:any, functions?:Object): string {return ''}
function sleep(ms:number): void {}
function setTimeout(callback:()=>void, ms?:number, ...args:any): void {}
function shell(cmd:string, ...args:string[]): string[] {return []}
function toDatetime(timestamp:number): string {return ''}
function fromDatetime(datetimeStr:string): number {return 0}
function toDate(timestamp:number): string {return ''}
function fromDate(dateStr:string): number {return 0}
```
## full api see [util.ts](http://apigo.cc/gojs/util/util.ts)

22
go.mod Normal file
View File

@ -0,0 +1,22 @@
module apigo.cc/gojs/util
go 1.18
require (
apigo.cc/gojs v0.0.1
github.com/ssgo/u v1.7.9
gopkg.in/yaml.v3 v3.0.1
)
require (
github.com/dlclark/regexp2 v1.11.4 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
github.com/google/pprof v0.0.0-20230207041349-798e818bf904 // indirect
github.com/ssgo/config v1.7.7 // indirect
github.com/ssgo/log v1.7.7 // indirect
github.com/ssgo/standard v1.7.7 // indirect
github.com/ssgo/tool v0.4.27 // indirect
golang.org/x/sys v0.26.0 // indirect
golang.org/x/text v0.19.0 // indirect
)

308
util.go Normal file
View File

@ -0,0 +1,308 @@
package util
import (
"bytes"
_ "embed"
"encoding/hex"
"encoding/json"
"strings"
"text/template"
"time"
"apigo.cc/gojs"
"apigo.cc/gojs/goja"
"github.com/ssgo/u"
"gopkg.in/yaml.v3"
)
//go:embed util.ts
var utilTS string
//go:embed README.md
var utilMD string
func init() {
obj := map[string]any{
"json": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
if r, err := json.Marshal(args.Arguments[0].Export()); err == nil {
return vm.ToValue(string(r))
} else {
panic(vm.NewGoError(err))
}
},
"jsonP": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
if r, err := json.Marshal(args.Arguments[0].Export()); err == nil {
r1 := bytes.Buffer{}
if err2 := json.Indent(&r1, r, "", " "); err2 == nil {
return vm.ToValue(string(r))
} else {
return vm.ToValue(string(r))
}
} else {
panic(vm.NewGoError(err))
}
},
"unJson": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
var r any
if err := json.Unmarshal(u.Bytes(args.Arguments[0].Export()), &r); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"yaml": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
if r, err := yaml.Marshal(args.Arguments[0].Export()); err == nil {
return vm.ToValue(string(r))
} else {
panic(vm.NewGoError(err))
}
},
"unYaml": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
var r any
if err := yaml.Unmarshal(u.Bytes(args.Arguments[0].Export()), &r); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"save": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
filename := args.Str(0)
var data []byte
var err error
if strings.HasSuffix(filename, ".yml") || strings.HasSuffix(filename, ".yaml") {
data, err = yaml.Marshal(args.Any(1))
} else {
data, err = json.Marshal(args.Any(1))
}
if err == nil {
if err = u.WriteFileBytes(gojs.FindPath(vm, filename), data); err != nil {
panic(vm.NewGoError(err))
}
return nil
} else {
panic(vm.NewGoError(err))
}
},
"load": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
filename := args.Str(0)
if data, err := u.ReadFileBytes(gojs.FindPath(vm, filename)); err == nil {
var r any
if strings.HasSuffix(filename, ".yml") || strings.HasSuffix(filename, ".yaml") {
err = yaml.Unmarshal(data, &r)
} else {
err = json.Unmarshal(data, &r)
}
if err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
} else {
panic(vm.NewGoError(err))
}
},
"base64": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.Base64(u.Bytes(args.Arguments[0].Export())))
},
"unBase64": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.UnBase64(args.Str(0)))
},
"urlBase64": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.UrlBase64String(args.Str(0)))
},
"unUrlBase64": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.UnUrlBase64(args.Str(0)))
},
"hex": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(hex.EncodeToString(u.Bytes(args.Arguments[0].Export())))
},
"unHex": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
if r, err := hex.DecodeString(args.Str(0)); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"aes": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(3)
if r, err := u.EncryptAesBytes(u.Bytes(args.Arguments[0].Export()), u.Bytes(args.Arguments[1].Export()), u.Bytes(args.Arguments[2].Export())); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"unAes": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(3)
if r, err := u.DecryptAesBytes(u.Bytes(args.Arguments[0].Export()), u.Bytes(args.Arguments[1].Export()), u.Bytes(args.Arguments[2].Export())); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"gzip": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
if r, err := u.Gzip(u.Bytes(args.Arguments[0].Export())); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"gunzip": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
if r, err := u.Gunzip(u.Bytes(args.Arguments[0].Export())); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"id": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
return vm.ToValue(u.Id12())
},
"uniqueId": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
return vm.ToValue(u.UniqueId())
},
"token": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
size := 20
if len(argsIn.Arguments) > 0 {
size = u.Int(argsIn.Arguments[0].Export())
}
return vm.ToValue(u.MakeToken(size))
},
"md5": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.MD5(u.Bytes(args.Arguments[0].Export())))
},
"sha1": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.Sha1(u.Bytes(args.Arguments[0].Export())))
},
"sha256": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.Sha256(u.Bytes(args.Arguments[0].Export())))
},
"sha512": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(u.Sha512(u.Bytes(args.Arguments[0].Export())))
},
"tpl": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(2)
var functions = map[string]any{}
if len(argsIn.Arguments) > 2 {
obj := argsIn.Arguments[2].ToObject(vm)
for _, k := range obj.Keys() {
v := obj.Get(k)
if cb, ok := goja.AssertFunction(v); ok {
functions[k] = func(in string) string {
if r, err := cb(argsIn.This, vm.ToValue(in)); err == nil {
return r.String()
}
return ""
}
}
}
}
buf := bytes.NewBuffer(make([]byte, 0))
var err error
tpl := template.New("tpl")
if len(functions) > 0 {
tpl.Funcs(functions)
}
if tpl, err = tpl.Parse(args.Str(0)); err == nil {
err = tpl.Execute(buf, args.Arguments[1].Export())
}
if err != nil {
panic(vm.NewGoError(err))
}
return vm.ToValue(buf.String())
},
"sleep": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
time.Sleep(time.Duration(args.Int64(0)) * time.Millisecond)
return nil
},
"setTimeout": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
callback := args.Func(0)
timeout := time.Duration(args.Int64(1)) * time.Millisecond
if callback != nil {
go func() {
if timeout > 0 {
time.Sleep(timeout)
}
if _, err := callback(args.This, args.Arguments[2:]...); err != nil {
args.Logger.Error(err.Error())
}
}()
}
return nil
},
"shell": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
a := make([]string, len(args.Arguments)-1)
for i := 1; i < len(args.Arguments); i++ {
a[i-1] = args.Str(i)
}
if r, err := u.RunCommand(args.Str(0), a...); err == nil {
return vm.ToValue(r)
} else {
panic(vm.NewGoError(err))
}
},
"toDatetime": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(time.UnixMilli(args.Int64(0)).Format("2006-01-02 15:04:05"))
},
"fromDatetime": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
timeStr := args.Str(0)
if len(timeStr) > 19 {
timeStr = timeStr[0:19]
}
if strings.ContainsRune(timeStr, 'T') {
timeStr = strings.ReplaceAll(timeStr, "T", " ")
}
if tm, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, time.Local); err == nil {
return vm.ToValue(tm.UnixMilli())
} else {
panic(vm.NewGoError(err))
}
},
"toDate": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
return vm.ToValue(time.UnixMilli(args.Int64(0)).Format("2006-01-02"))
},
"fromDate": func(argsIn goja.FunctionCall, vm *goja.Runtime) goja.Value {
args := gojs.MakeArgs(&argsIn, vm).Check(1)
timeStr := args.Str(0)
if len(timeStr) > 10 {
timeStr = timeStr[0:10]
}
if tm, err := time.ParseInLocation("2006-01-02", timeStr, time.Local); err == nil {
return vm.ToValue(tm.UnixMilli())
} else {
panic(vm.NewGoError(err))
}
},
}
gojs.Register("apigo.cc/gojs/util", gojs.Module{
Object: obj,
TsCode: utilTS,
Example: utilMD,
})
}

68
util.ts Normal file
View File

@ -0,0 +1,68 @@
// just for develop
export default {
json,
jsonP,
unJson,
yaml,
unYaml,
load,
save,
base64,
unBase64,
urlBase64,
unUrlBase64,
hex,
unHex,
aes,
unAes,
gzip,
gunzip,
id,
uniqueId,
token,
md5,
sha1,
sha256,
sha512,
tpl,
sleep,
shell,
toDatetime,
fromDatetime,
toDate,
fromDate
}
function json(data:any): string {return ''}
function jsonP(data:any): string {return ''}
function unJson(data:string): any {return null}
function yaml(data:any): string {return ''}
function unYaml(data:string): any {return null}
function load(filename:string): any {return null}
function save(filename:string, data:any) {}
function base64(data:any): string {return ''}
function unBase64(data:string): any {return null}
function urlBase64(data:any): string {return ''}
function unUrlBase64(data:string): any {return null}
function hex(data:any): string {return ''}
function unHex(data:string): any {return null}
function aes(data:any, key:string, iv:string): string {return ''}
function unAes(data:string, key:string, iv:string): any {return null}
function gzip(data:any): string {return ''}
function gunzip(data:string): any {return null}
function id(): string {return ''}
function uniqueId(): string {return ''}
function token(size:number): string {return ''}
function md5(data:any): string {return ''}
function sha1(data:any): string {return ''}
function sha256(data:any): string {return ''}
function sha512(data:any): string {return ''}
function tpl(text:string, data:any, functions?:Object): string {return ''}
function sleep(ms:number): void {}
function setTimeout(callback:()=>void, ms?:number, ...args:any): void {}
function shell(cmd:string, ...args:string[]): string[] {return []}
function toDatetime(timestamp:number): string {return ''}
function fromDatetime(datetimeStr:string): number {return 0}
function toDate(timestamp:number): string {return ''}
function fromDate(dateStr:string): number {return 0}

49
util_test.go Normal file
View File

@ -0,0 +1,49 @@
package util_test
import (
"bytes"
"fmt"
"testing"
"time"
"apigo.cc/gojs"
_ "apigo.cc/gojs/util"
"github.com/ssgo/u"
)
func TestHash(t *testing.T) {
vm := gojs.New()
vm.RunCode("import util from 'apigo.cc/gojs/util'")
testIsSame(vm, t, "util.md5('hello 123')", u.MD5([]byte("hello 123")))
testIsSame(vm, t, "util.base64(util.md5('hello 123'))", u.MD5Base64("hello 123"))
testIsSame(vm, t, "util.hex(util.md5('hello 123'))", u.MD5String("hello 123"))
testIsSame(vm, t, "util.sha1('hello 123')", u.Sha1([]byte("hello 123")))
testIsSame(vm, t, "util.sha256('hello 123')", u.Sha256([]byte("hello 123")))
testIsSame(vm, t, "util.sha512('hello 123')", u.Sha512([]byte("hello 123")))
testIsSame(vm, t, "util.json('hello 123')", u.Json("hello 123"))
testIsSame(vm, t, "util.yaml('hello 123')", u.Yaml("hello 123"))
testIsSame(vm, t, "util.aes('hello 123','12345678901234567','12345678901234567')", u.EncryptAes("hello 123", []byte("12345678901234567"), []byte("12345678901234567")))
testIsSame(vm, t, "util.gzip('hello 123')", u.GzipN([]byte("hello 123")))
tm, _ := time.ParseInLocation("2006-01-02 15:04:05", "2024-01-01 00:00:00", time.Local)
testIsSame(vm, t, "util.fromDatetime('2024-01-01 00:00:00')", tm.UnixMilli())
}
func testIsSame(vm *gojs.Runtime, t *testing.T, code string, checkValue any) {
r, err := vm.RunCode(code)
if err != nil {
t.Fatal(code, err)
return
}
if data, ok := r.([]byte); ok {
if !bytes.Equal(data, u.Bytes(r)) {
t.Fatal(code, r)
return
}
} else {
if r != checkValue {
t.Fatal(code, r, checkValue)
return
}
}
fmt.Println(u.Green(code))
}