Help us shape the future of Go! Take the 2026 Go Developer Survey

generate

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

Overview

Package generate turns a livewire registry into its artifacts (D19): the TypeScript client (types.ts, filters.ts, api.ts and the copied runtime.ts and vue.ts), the OpenAPI 3.0.3 document, the Go client package on livewire/client (D67) and the command-line client on github.com/urfave/cli/v3 (D68). Write is the entry point; everything it writes is deterministic, byte for byte, for one registry and one Options value, gofmt'ed where it is Go, and carries the header `Code generated by livewire. DO NOT EDIT.`.

The runtime/ directory holds the TypeScript runtime sources the generator copies; they are tested there under bun. The Go client's runtime is the package livewire/client, which the generated code imports. The generator itself stays on the standard library: the generated CLI imports urfave/cli, the generator only writes its source.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Write

func Write(registry *livewire.Registry, options *Options) error

Write generates the artifacts of the registry into the files the options name. It validates and copies the options (DES-001), renders every file before it writes the first, so a registry the generator cannot describe writes nothing, and creates the TypeScript directory and the OpenAPI file's directory as needed. It fails on a Go type encoding/json cannot marshal (a channel, a function, a complex number, a map with keys of another kind than string, integer or encoding.TextMarshaler), on two generated TypeScript identifiers that collide (two declaration names that differ only in the case of their first letter, say) or that are reserved words, and on invalid options. Two DTOs with the same Go name from different packages never collide: both are qualified with their package's name, deterministically. With a Go client it also fails on a type the client cannot import from GoClient.ImportPath (D67), on a ClientID create whose body's id it cannot fill in, and on two Go identifiers that collide; with a CLI on two commands or flags of one command that share a name (D68).

Example

ExampleWrite generates the TypeScript client and the OpenAPI document of a registry, the way an application's `go generate` step or a test (livewiretest.GeneratedIsCurrent) does.

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/govengers/auth/authorization"

	"github.com/govengers/livewire"
	"github.com/govengers/livewire/generate"
)

type exampleNote struct {
	ID   string `json:"id"`
	Text string `json:"text"`
}

func main() {
	registry, err := livewire.NewRegistry(&livewire.RegistryOptions{BasePath: "/api/v1"})
	if err != nil {
		panic(err)
	}
	err = registry.Add(livewire.NewList("notes", "/notes", &livewire.ListOptions[exampleNote, livewire.NoParameters]{
		Tables: []string{"notes"}, Read: authorization.IsUser(),
		Load: func(context.Context, *livewire.NoParameters) ([]exampleNote, error) { return nil, nil },
	}))
	if err != nil {
		panic(err)
	}
	directory, err := os.MkdirTemp("", "livewire-example")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(directory)
	err = generate.Write(registry, &generate.Options{
		TypeScriptDirectory: filepath.Join(directory, "ui", "src", "api"),
		OpenAPIFile:         filepath.Join(directory, "openapi.yaml"),
		OpenAPI: generate.OpenAPIOptions{
			Title: "Notes", Version: "1.0.0",
			SecuritySchemes: []generate.SecurityScheme{{Name: "apiKey", Type: "http", Scheme: "bearer"}},
		},
	})
	if err != nil {
		panic(err)
	}
	written, err := filepath.Glob(filepath.Join(directory, "ui", "src", "api", "*.ts"))
	if err != nil {
		panic(err)
	}
	for _, path := range written {
		fmt.Println(filepath.Base(path))
	}
}
Output:
api.ts
filters.ts
runtime.ts
types.ts
vue.ts
Example (GoClient)

ExampleWrite_goClient generates the Go client package and the command-line client of a registry: the client imports the DTO package (here the generator's fixture), so ImportPath says where the client lives (D67).

package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"

	"github.com/govengers/auth/authorization"

	"github.com/govengers/livewire"
	"github.com/govengers/livewire/generate"
	"github.com/govengers/livewire/generate/internal/fixture"
)

func main() {
	registry, err := livewire.NewRegistry(&livewire.RegistryOptions{BasePath: "/api/v1"})
	if err != nil {
		panic(err)
	}
	err = registry.Add(livewire.NewList("notes", "/notes", &livewire.ListOptions[fixture.Note, livewire.NoParameters]{
		Tables: []string{"notes"}, Read: authorization.IsUser(),
		Load: func(context.Context, *livewire.NoParameters) ([]fixture.Note, error) { return nil, nil },
	}))
	if err != nil {
		panic(err)
	}
	directory, err := os.MkdirTemp("", "livewire-example")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(directory)
	err = generate.Write(registry, &generate.Options{
		GoClient:    generate.GoClientOptions{Directory: filepath.Join(directory, "notesclient"), ImportPath: "github.com/govengers/livewire/generate/internal/notesclient"},
		CommandLine: generate.CommandLineOptions{Directory: filepath.Join(directory, "notescommand"), Name: "notes"},
	})
	if err != nil {
		panic(err)
	}
	written, err := filepath.Glob(filepath.Join(directory, "*", "*.go"))
	if err != nil {
		panic(err)
	}
	for _, path := range written {
		fmt.Println(filepath.Base(filepath.Dir(path)) + "/" + filepath.Base(path))
	}
}
Output:
notesclient/client.go
notesclient/filters.go
notescommand/command.go

Types

type CommandLineOptions

type CommandLineOptions struct {
	Directory         string
	Package           string
	Name              string
	EnvironmentPrefix string
}

CommandLineOptions configures the command-line client on github.com/urfave/cli/v3 (D19, D20), written into Directory as command.go ("" writes none): a package whose Command is the root command and whose Run is a binary's main. Name is the command's name (required, lower-case letters, digits and dashes); EnvironmentPrefix prefixes its environment variables <PREFIX>_BASE_URL, <PREFIX>_API_KEY and <PREFIX>_SOCKET_URL (default: Name upper-cased with dashes as underscores); Package is the package name, by default the last element of Directory. The CLI imports no DTO package: it passes the JSON through.

type Enum

type Enum struct {
	Type   reflect.Type
	Values []string
}

Enum lists the values of a named string type; build it with EnumOf.

func EnumOf

func EnumOf[Value ~string](values ...Value) Enum

EnumOf lists the values of the named string type Value, in the order the generated union and the OpenAPI enum show them.

type File

type File struct {
	Path    string
	Content []byte
}

File is one artifact as Render renders it: the path the options give it and its content.

func Render

func Render(registry *livewire.Registry, options *Options) ([]File, error)

Render renders every file Write would write, with the same validation and refusals, and writes nothing: the paths are the ones the options name, so a test compares each with the committed file at that path (livewiretest.GeneratedIsCurrent, D70).

type GoClientOptions

type GoClientOptions struct {
	Directory  string
	ImportPath string
	Package    string
}

GoClientOptions configures the Go client package (D19, D67), written into Directory as client.go and filters.go ("" writes none). ImportPath is that directory's import path, required with it: the client imports the application's DTO packages, so Write refuses a type the package could not import from there (an unexported one, one of a main or test package, one behind an internal directory whose parent does not contain ImportPath). Package is the package name, by default the last element of ImportPath ("partsclient").

type OpenAPIOptions

type OpenAPIOptions struct {
	Title           string
	Version         string
	Description     string
	Servers         []Server
	SecuritySchemes []SecurityScheme
}

OpenAPIOptions describes the OpenAPI document: its info (Title and Version are required), its servers, whose URLs stop before the registry's BasePath (the paths carry it), and the security schemes every operation accepts, any one of them (D20: an API key for the CLI and the Go client next to the browser's session, for instance).

type Options

type Options struct {
	TypeScriptDirectory string
	OpenAPIFile         string
	OpenAPI             OpenAPIOptions
	GoClient            GoClientOptions
	CommandLine         CommandLineOptions
	Enums               []Enum
	Presence            bool
}

Options configures Write. TypeScriptDirectory receives types.ts, filters.ts, api.ts, runtime.ts and vue.ts ("" writes no TypeScript); OpenAPIFile is the path of the OpenAPI 3.0.3 document ("" writes none), a YAML file whose content is JSON under the generated header (YAML reads JSON, and a JSON file could not carry the header), so it must not end in ".json". GoClient configures the Go client package and CommandLine the command-line client (each written only with its Directory). At least one output is required. OpenAPI describes the document and is required with OpenAPIFile.

Enums names the values of named string types: reflection cannot list a Go type's constants, and an `enum:"a,b"` tag on every field repeats the list, so a named string type listed here is a union of its values in TypeScript and an enum in OpenAPI wherever it appears; an `enum` tag on a field still wins for that field. Presence says that the engine serves presence (EngineOptions.PresenceStore is set, D37): only then are the presence reads, their routes and joins generated, as only then does the REST adapter mount them.

type SecurityScheme

type SecurityScheme struct {
	Name             string
	Type             string
	Description      string
	Scheme           string
	BearerFormat     string
	In               string
	ParameterName    string
	OpenIDConnectURL string
}

SecurityScheme is one entry of components.securitySchemes: Name is its key, Type one of "http" (with Scheme, "bearer" or "basic", and an optional BearerFormat), "apiKey" (with In, "header", "query" or "cookie", and ParameterName) or "openIdConnect" (with OpenIDConnectURL).

type Server

type Server struct {
	URL         string
	Description string
}

Server is one entry of the document's servers.

Directories

Path Synopsis
internal
fixture
Package fixture holds the DTOs of the generator's test registry: every mapping case of encoding/json the generator follows.
Package fixture holds the DTOs of the generator's test registry: every mapping case of encoding/json the generator follows.
fixture/billing
Package billing holds DTOs whose Go names repeat the fixture package's: the generator qualifies both with their package's name.
Package billing holds DTOs whose Go names repeat the fixture package's: the generator qualifies both with their package's name.
fixture/fixtureclient
Package fixtureclient is the Go client of the API at /api/v1 (D19, D67), generated from its livewire registry: build a Client with New and call one method per read, mutation, upload and export.
Package fixtureclient is the Go client of the API at /api/v1 (D19, D67), generated from its livewire registry: build a Client with New and call one method per read, mutation, upload and export.
fixture/fixturecommand
Package fixturecommand is the command-line client fixture of the API at /api/v1 (D19, D20), on github.com/urfave/cli/v3, generated from its livewire registry: one command per declaration and read kind, the parameters as flags, a body as --body or on stdin, the answers as JSON on stdout and the diagnostics on stderr.
Package fixturecommand is the command-line client fixture of the API at /api/v1 (D19, D20), on github.com/urfave/cli/v3, generated from its livewire registry: one command per declaration and read kind, the parameters as flags, a body as --body or on stdin, the answers as JSON on stdout and the diagnostics on stderr.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL