93 lines
2.4 KiB
Go
93 lines
2.4 KiB
Go
// Package tsconvert provides utilities for converting Go types to TypeScript definitions.
|
|
package tsconvert
|
|
|
|
import (
|
|
"fmt"
|
|
"regexp"
|
|
)
|
|
|
|
// TypeDecl represents a TypeScript type declaration.
|
|
type TypeDecl struct {
|
|
Name string // e.g., "UserConfig"
|
|
Definition string // e.g., "interface UserConfig { name: string }"
|
|
}
|
|
|
|
// TypeSet manages a collection of type declarations with deduplication support.
|
|
type TypeSet struct {
|
|
types map[string]string // name -> definition
|
|
}
|
|
|
|
// NewTypeSet creates a new empty TypeSet.
|
|
func NewTypeSet() *TypeSet {
|
|
return &TypeSet{
|
|
types: make(map[string]string),
|
|
}
|
|
}
|
|
|
|
// Add adds a type declaration to the set.
|
|
// Returns an error if a type with the same name but different definition already exists.
|
|
func (ts *TypeSet) Add(name, definition string) error {
|
|
if existing, ok := ts.types[name]; ok {
|
|
if existing != definition {
|
|
return fmt.Errorf("type conflict: %s has conflicting definitions", name)
|
|
}
|
|
// Same name and definition, no conflict
|
|
return nil
|
|
}
|
|
ts.types[name] = definition
|
|
return nil
|
|
}
|
|
|
|
// Get retrieves a type definition by name.
|
|
func (ts *TypeSet) Get(name string) (string, bool) {
|
|
def, ok := ts.types[name]
|
|
return def, ok
|
|
}
|
|
|
|
// All returns all type declarations as a map.
|
|
func (ts *TypeSet) All() map[string]string {
|
|
result := make(map[string]string, len(ts.types))
|
|
for k, v := range ts.types {
|
|
result[k] = v
|
|
}
|
|
return result
|
|
}
|
|
|
|
// Names returns all type names in the set.
|
|
func (ts *TypeSet) Names() []string {
|
|
names := make([]string, 0, len(ts.types))
|
|
for name := range ts.types {
|
|
names = append(names, name)
|
|
}
|
|
return names
|
|
}
|
|
|
|
// Merge merges another TypeSet into this one.
|
|
// Returns an error if there are conflicting definitions.
|
|
func (ts *TypeSet) Merge(other *TypeSet) error {
|
|
for name, def := range other.types {
|
|
if err := ts.Add(name, def); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ExtractName extracts the type name from a TypeScript declaration.
|
|
// Supports "interface Name {...}" and "type Name = ..." patterns.
|
|
func ExtractName(definition string) string {
|
|
// Try interface pattern: "interface Name { ... }"
|
|
interfaceRe := regexp.MustCompile(`^interface\s+(\w+)`)
|
|
if matches := interfaceRe.FindStringSubmatch(definition); len(matches) > 1 {
|
|
return matches[1]
|
|
}
|
|
|
|
// Try type alias pattern: "type Name = ..."
|
|
typeRe := regexp.MustCompile(`^type\s+(\w+)`)
|
|
if matches := typeRe.FindStringSubmatch(definition); len(matches) > 1 {
|
|
return matches[1]
|
|
}
|
|
|
|
return ""
|
|
}
|