Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions examples/experimental/encoding.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { TextDecoder, TextEncoder } from "k6/experimental/encoding";

export default function () {
const decoder = new TextDecoder("utf-8");
const encoder = new TextEncoder();

const decoded = decoder.decode(encoder.encode("hello world"));
console.log(decoded);
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ require (
github.com/tidwall/pretty v1.2.1 // indirect
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
golang.org/x/text v0.31.0
google.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 // indirect
gopkg.in/cenkalti/backoff.v1 v1.1.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions internal/js/jsmodules.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"go.k6.io/k6/internal/js/modules/k6/encoding"
"go.k6.io/k6/internal/js/modules/k6/execution"
"go.k6.io/k6/internal/js/modules/k6/experimental/csv"
expencoding "go.k6.io/k6/internal/js/modules/k6/experimental/encoding"
"go.k6.io/k6/internal/js/modules/k6/experimental/fs"
"go.k6.io/k6/internal/js/modules/k6/experimental/streams"
expws "go.k6.io/k6/internal/js/modules/k6/experimental/websockets"
Expand Down Expand Up @@ -48,6 +49,7 @@ func getInternalJSModules() map[string]interface{} {

// Experimental modules
"k6/experimental/csv": csv.New(),
"k6/experimental/encoding": expencoding.New(),
"k6/experimental/fs": fs.New(),
"k6/experimental/redis": redis.New(),
"k6/experimental/streams": streams.New(),
Expand Down
70 changes: 70 additions & 0 deletions internal/js/modules/k6/experimental/encoding/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package encoding

import (
"fmt"

"github.com/grafana/sobek"
)

// ErrorName is a type alias for the name of an encoding error.
//
// Note that it is a type alias, and not a binding, so that it
// is not interpreted as an object by sobek.
type ErrorName = string

const (
// RangeError is thrown if the value of label is unknown, or
// is one of the values leading to a 'replacement' decoding
// algorithm ("iso-2022-cn" or "iso-2022-cn-ext").
RangeError ErrorName = "RangeError"

// TypeError is thrown if the value if the Decoder fatal option
// is set and the input data cannot be decoded.
TypeError ErrorName = "TypeError"
)

// Error represents an encoding error.
type Error struct {
// Name contains one of the strings associated with an error name.
Name ErrorName `json:"name"`

// Message represents message or description associated with the given error name.
Message string `json:"message"`
}

// JSError creates a JavaScript error object that can be thrown
func (e *Error) JSError(rt *sobek.Runtime) *sobek.Object {
var constructor *sobek.Object

switch e.Name {
case TypeError:
constructor = rt.Get("TypeError").ToObject(rt)
case RangeError:
constructor = rt.Get("RangeError").ToObject(rt)
default:
constructor = rt.Get("Error").ToObject(rt)
}

errorObj, err := rt.New(constructor, rt.ToValue(e.Message))
if err != nil {
// Fallback to generic error
errorObj = rt.ToValue(fmt.Errorf("%s: %s", e.Name, e.Message)).ToObject(rt)
}

return errorObj
}

// Error implements the `error` interface.
func (e *Error) Error() string {
return fmt.Sprintf("%s: %s", e.Name, e.Message)
}

// NewError returns a new Error instance.
func NewError(name, message string) *Error {
return &Error{
Name: name,
Message: message,
}
}

var _ error = (*Error)(nil)
228 changes: 228 additions & 0 deletions internal/js/modules/k6/experimental/encoding/module.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
// Package encoding provides a k6 JS module that implements the TextEncoder and
// TextDecoder interfaces.
package encoding

import (
"errors"

"github.com/grafana/sobek"
"go.k6.io/k6/js/common"
"go.k6.io/k6/js/modules"
)

type (
// RootModule is the global module instance that will create Client
// instances for each VU.
RootModule struct{}

// ModuleInstance represents an instance of the JS module.
ModuleInstance struct {
vu modules.VU

*TextDecoder
*TextEncoder
}
)

// Ensure the interfaces are implemented correctly
var (
_ modules.Instance = &ModuleInstance{}
_ modules.Module = &RootModule{}
)

// New returns a pointer to a new RootModule instance
func New() *RootModule {
return &RootModule{}
}

// NewModuleInstance implements the modules.Module interface and returns
// a new instance for each VU.
func (*RootModule) NewModuleInstance(vu modules.VU) modules.Instance {
return &ModuleInstance{
vu: vu,
TextDecoder: &TextDecoder{},
TextEncoder: &TextEncoder{},
}
}

// Exports implements the modules.Instance interface and returns
// the exports of the JS module.
func (mi *ModuleInstance) Exports() modules.Exports {
return modules.Exports{Named: map[string]interface{}{
"TextDecoder": mi.NewTextDecoder,
"TextEncoder": mi.NewTextEncoder,
}}
}

// NewTextDecoder is the JS constructor for the TextDecoder object.
func (mi *ModuleInstance) NewTextDecoder(call sobek.ConstructorCall) *sobek.Object {
rt := mi.vu.Runtime()

// Parse the label parameter - default to "utf-8" if undefined
var label string
if call.Argument(0) != nil && !sobek.IsUndefined(call.Argument(0)) {
err := rt.ExportTo(call.Argument(0), &label)
if err != nil {
common.Throw(rt, NewError(RangeError, "unable to extract label from the first argument; reason: "+err.Error()))
}
}
if label == "" {
label = "utf-8"
}

// Parse the options parameter
var options TextDecoderOptions
if call.Argument(1) != nil && !sobek.IsUndefined(call.Argument(1)) {
err := rt.ExportTo(call.Argument(1), &options)
if err != nil {
common.Throw(rt, err)
}
}

td, err := NewTextDecoder(rt, label, options)
if err != nil {
common.Throw(rt, err)
}

return newTextDecoderObject(rt, td)
}

// NewTextEncoder is the JS constructor for the TextEncoder object.
func (mi *ModuleInstance) NewTextEncoder(_ sobek.ConstructorCall) *sobek.Object {
return newTextEncoderObject(mi.vu.Runtime(), NewTextEncoder())
}

// newTextDecoderObject converts the given TextDecoder instance into a JS object.
//
// It is used by the TextDecoder constructor to convert the Go instance into a JS,
// and will also set the relevant properties as read-only as per the spec.
//
// In the event setting the properties on the object where to fail, the function
// will throw a JS exception.
func newTextDecoderObject(rt *sobek.Runtime, td *TextDecoder) *sobek.Object {
obj := rt.NewObject()

// Wrap the Go TextDecoder.Decode method in a JS function
decodeMethod := func(call sobek.FunctionCall) sobek.Value {
// Handle variable arguments - buffer can be undefined/missing
var buffer sobek.Value
if len(call.Arguments) > 0 {
buffer = call.Arguments[0]
}

// Handle options parameter
var options TextDecodeOptions
if len(call.Arguments) > 1 && !sobek.IsUndefined(call.Arguments[1]) {
err := rt.ExportTo(call.Arguments[1], &options)
if err != nil {
common.Throw(rt, err)
}
}

data, err := exportArrayBuffer(rt, buffer)
if err != nil {
common.Throw(rt, err)
}

decoded, err := td.Decode(data, options)
if err != nil {
// Check if it's our custom error type for proper JavaScript error throwing
var encErr *Error
if errors.As(err, &encErr) {
// Throw the specific JavaScript error type
switch encErr.Name {
case TypeError:
panic(rt.NewTypeError(encErr.Message))
case RangeError:
// Create a RangeError using the constructor
rangeErrorConstructor := rt.Get("RangeError")
rangeError, _ := rt.New(rangeErrorConstructor, rt.ToValue(encErr.Message))
panic(rangeError)
}
}
common.Throw(rt, err)
}

return rt.ToValue(decoded)
}

// Set the decode method to the wrapper function we just created
if err := setReadOnlyPropertyOf(obj, "decode", rt.ToValue(decodeMethod)); err != nil {
common.Throw(
rt,
errors.New("unable to define decode read-only property on TextDecoder object; reason: "+err.Error()),
)
}

// Set the encoding property
if err := setReadOnlyPropertyOf(obj, "encoding", rt.ToValue(td.Encoding)); err != nil {
common.Throw(
rt,
errors.New("unable to define encoding read-only property on TextDecoder object; reason: "+err.Error()),
)
}

// Set the fatal property
if err := setReadOnlyPropertyOf(obj, "fatal", rt.ToValue(td.Fatal)); err != nil {
common.Throw(
rt,
errors.New("unable to define fatal read-only property on TextDecoder object; reason: "+err.Error()),
)
}

// Set the ignoreBOM property
if err := setReadOnlyPropertyOf(obj, "ignoreBOM", rt.ToValue(td.IgnoreBOM)); err != nil {
common.Throw(
rt,
errors.New("unable to define ignoreBOM read-only property on TextDecoder object; reason: "+err.Error()),
)
}

return obj
}

func newTextEncoderObject(rt *sobek.Runtime, te *TextEncoder) *sobek.Object {
obj := rt.NewObject()

// Wrap the Go TextEncoder.Encode method in a JS function
encodeMethod := func(s sobek.Value) *sobek.Object {
// Handle undefined/null values by defaulting to empty string
var text string
if s == nil || sobek.IsUndefined(s) {
text = ""
} else {
text = s.String()
}

buffer, err := te.Encode(text)
if err != nil {
common.Throw(rt, err)
}

// Create a new Uint8Array from the buffer
u, err := rt.New(rt.Get("Uint8Array"), rt.ToValue(rt.NewArrayBuffer(buffer)))
if err != nil {
common.Throw(rt, err)
}

return u
}

// Set the encode property by wrapping the Go function in a JS function
if err := setReadOnlyPropertyOf(obj, "encode", rt.ToValue(encodeMethod)); err != nil {
common.Throw(
rt,
errors.New("unable to define encode read-only method on TextEncoder object; reason: "+err.Error()),
)
}

// Set the encoding property
if err := setReadOnlyPropertyOf(obj, "encoding", rt.ToValue(te.Encoding)); err != nil {
common.Throw(
rt,
errors.New("unable to define encoding read-only property on TextEncoder object; reason: "+err.Error()),
)
}

return obj
}
23 changes: 23 additions & 0 deletions internal/js/modules/k6/experimental/encoding/module_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package encoding

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestModuleTextDecoder(t *testing.T) {
t.Parallel()

t.Run("TextDecoder.Decode", func(t *testing.T) {
t.Parallel()

ts := newTestSetup(t)

_, err := ts.rt.RunOnEventLoop(`
new TextDecoder().decode(undefined)
`)

assert.NoError(t, err)
})
}
Loading
Loading