cbc

package
v0.502.2 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2026 License: Apache-2.0 Imports: 18 Imported by: 16

Documentation

Overview

Package cbc provides a set of Common Basic Components.

Name is take from the similar namespace used in UBL.

Index

Constants

View Source
const (
	KeyPattern           = `^(?:[a-z]|[a-z0-9][a-z0-9-+]*[a-z0-9])$`
	KeyPatternWord       = `([a-z]([a-z0-9-]*[a-z0-9])?)`
	KeyPatternExtensions = `(\+` + KeyPatternWord + `)`
	KeyPatternWordOnly   = `^` + KeyPatternWord + `$`
	KeyPatternFull       = `^` + KeyPatternWord + KeyPatternExtensions + `*$`
)

Key Pattern constants for validation and parsing.

Variables

View Source
var (
	CodeSeparators           = `.\-:/,_& ` // only escape dash for JS compatibility
	CodeDigits               = `A-ZÑa-z0-9`
	CodePattern              = `^[` + CodeDigits + `]+([` + CodeSeparators + `]?[` + CodeDigits + `]+)*$`
	CodePatternRegexp        = regexp.MustCompile(CodePattern)
	CodeMinLength     uint64 = 1
	CodeMaxLength     uint64 = 128

	// CodePatternLenient is the default code validation pattern. It rejects
	// leading or trailing whitespace and any control character (C0, DEL, and
	// C1), leaving the contents otherwise unconstrained. Use CodePattern (via
	// StrictCode) for the stricter canonical format.
	CodePatternLenient       = `^[^\s\x00-\x1f\x7f-\x9f]([^\x00-\x1f\x7f-\x9f]*[^\s\x00-\x1f\x7f-\x9f])?$`
	CodePatternLenientRegexp = regexp.MustCompile(CodePatternLenient)
)

Basic code constants.

View Source
var (
	// KeyValidationRegexp is used for key validation
	KeyValidationRegexp = regexp.MustCompile(KeyPattern)
	// KeySeparator is used to separate keys join using the "With"
	// method.
	KeySeparator = "+"
)
View Source
var (
	// KeyMinLength defines the minimum key length
	KeyMinLength uint64 = 1
	// KeyMaxLength defines the maximum key length
	KeyMaxLength uint64 = 64
)

StrictCode is a validation test that ensures a code matches the strict canonical pattern (letters, numbers, and single separators). Use it on the fields of machine-readable identifiers that require the stricter format; the default code validation only rejects leading or trailing whitespace.

View Source
var URIMaxLength uint64 = 2048

URIMaxLength is the maximum number of characters allowed in a URI.

Functions

func CodeMapHas added in v0.55.0

func CodeMapHas(keys ...Key) rules.Test

CodeMapHas returns a validation rule that ensures the code set contains the provided keys.

func CodeStrings added in v0.302.0

func CodeStrings(codes []Code) []string

CodeStrings is a convenience method to convert a list of codes into a list of strings.

func InCodeDefs added in v0.207.0

func InCodeDefs(list []*Definition) rules.Test

InCodeDefs prepares a validation to provide a rule that will determine if the codes are in the provided set.

func InCodes added in v0.400.0

func InCodes(codes ...Code) rules.Test

InCodes provides a rules test that checks if a code's value is one of the provided codes.

func InKeyDefs added in v0.69.0

func InKeyDefs(list []*Definition) rules.Test

InKeyDefs prepares a validation to provide a rule that will determine if the keys are in the provided set.

func KeyStrings added in v0.81.0

func KeyStrings(keys []Key) []string

KeyStrings is a convenience method to convert a list of keys into a list of strings.

func NormalizeString added in v0.300.0

func NormalizeString(in string) string

NormalizeString will attempt to clean a string by removing any potentially invalid UTF-8 characters (replaced with ?), trimming whitespace, and removing nil characters.

Types

type Code

type Code string

Code represents a string used to uniquely identify the data we're looking at. We use "code" instead of "id", to re-enforce the fact that codes should be more easily set and used by humans within definitions than IDs or UUIDs.

By default codes are treated leniently so that values coming from other systems and formats can be preserved as-is: normalization applies Unicode NFC, removes control and other non-printable characters, and trims surrounding whitespace (see NormalizeCode), while validation only requires that the code be no longer than 128 characters and contain no control characters or leading or trailing whitespace.

Fields that need a stricter, canonical format (letters, numbers, and single `.`, `-`, `:`, `/`, `,`, `_`, `&`, or space separators between blocks) can opt in using NormalizeStrictCode for normalization and the StrictCode test for validation.

const CodeEmpty Code = ""

CodeEmpty is used when no code is defined.

const (
	// DefaultCodeSeparator is the default separator used to join codes.
	DefaultCodeSeparator Code = "-"
)

func DefinitionCodes added in v0.207.0

func DefinitionCodes(list []*Definition) []Code

DefinitionCodes helps extract the codes from a list of key definitions.

func NormalizeAlphanumericalCode added in v0.204.0

func NormalizeAlphanumericalCode(c Code) Code

NormalizeAlphanumericalCode cleans and normalizes the code to its strict form, ensuring all letters are uppercase while also removing non-alphanumerical characters.

func NormalizeCode added in v0.200.0

func NormalizeCode(c Code) Code

NormalizeCode applies the default, lenient normalization to a code: it applies Unicode NFC normalization (so canonically-equivalent codes compare equal), removes any control or non-printable characters, and trims leading and trailing whitespace, but otherwise leaves the contents untouched. This is the normalization applied automatically to every cbc.Code in a document. Use NormalizeStrictCode for the stricter cleaning required by machine-readable identifiers.

func NormalizeNumericalCode added in v0.204.0

func NormalizeNumericalCode(c Code) Code

NormalizeNumericalCode cleans and normalizes the code to its strict form, while also removing non-numerical characters.

func NormalizeStrictCode added in v0.500.0

func NormalizeStrictCode(c Code) Code

NormalizeStrictCode cleans the code into its canonical strict form: leading and trailing whitespace is trimmed, repeated separators are collapsed, and any character outside the permitted set is removed.

func NormalizeUpperCode added in v0.309.0

func NormalizeUpperCode(c Code) Code

NormalizeUpperCode cleans and normalizes the code to its strict form, ensuring all letters are uppercase while preserving valid separators.

func (Code) HasPrefix added in v0.501.0

func (c Code) HasPrefix(prefix Code) bool

HasPrefix reports whether the code starts with prefix.

func (Code) HasSuffix added in v0.501.0

func (c Code) HasSuffix(suffix Code) bool

HasSuffix reports whether the code ends with suffix.

func (Code) In

func (c Code) In(ary ...Code) bool

In returns true if the code's value matches one of those in the provided list.

func (Code) IsEmpty

func (c Code) IsEmpty() bool

IsEmpty returns true if no code is specified.

func (Code) JSONSchema

func (Code) JSONSchema() *jsonschema.Schema

JSONSchema provides a representation of the struct for usage in Schema.

func (Code) Join added in v0.202.0

func (c Code) Join(c2 Code) Code

Join returns a new code that is the result of joining the provided code with the current one using a default separator.

func (Code) JoinWith added in v0.202.0

func (c Code) JoinWith(separator Code, c2 Code) Code

JoinWith returns a new code that is the result of joining the provided code with the current one using the provided separator. If any of the codes are empty, no separator will be added.

func (Code) String

func (c Code) String() string

String returns string representation of code.

func (Code) TrimPrefix added in v0.501.0

func (c Code) TrimPrefix(prefix Code) Code

TrimPrefix returns the code with the leading prefix removed.

func (Code) TrimSuffix added in v0.501.0

func (c Code) TrimSuffix(suffix Code) Code

TrimSuffix returns the code with the trailing suffix removed.

func (Code) Validate

func (c Code) Validate() error

Validate ensures that the code complies with the expected rules.

type CodeMap added in v0.55.0

type CodeMap map[Key]Code

CodeMap is a map of keys to specific codes, useful to determine regime specific codes from their key counterparts.

func (CodeMap) Equals added in v0.55.0

func (cs CodeMap) Equals(other CodeMap) bool

Equals returns true if the code map has the same keys and values as the provided map.

func (CodeMap) Has added in v0.55.0

func (cs CodeMap) Has(keys ...Key) bool

Has returns true if the code map has values for all the provided keys.

func (CodeMap) JSONSchemaExtend added in v0.55.0

func (CodeMap) JSONSchemaExtend(schema *jsonschema.Schema)

JSONSchemaExtend ensures the pattern property is set correctly.

func (CodeMap) Lookup added in v0.403.0

func (cs CodeMap) Lookup(k Key) Code

Lookup returns the code matching the provided key, falling back to less specific keys by progressively popping the last subkey.

type Definition added in v0.207.0

type Definition struct {
	// Key being defined.
	Key Key `json:"key,omitempty" jsonschema:"title=Key"`
	// Code this definition represents.
	Code Code `json:"code,omitempty" jsonschema:"title=Code"`

	// Short name for the key.
	Name i18n.String `json:"name" jsonschema:"title=Name"`
	// Description offering more details about when the key should be used.
	Desc i18n.String `json:"desc,omitempty" jsonschema:"title=Description"`
	// Meta defines any additional details that may be useful or associated
	// with the key.
	Meta Meta `json:"meta,omitempty" jsonschema:"title=Meta"`

	// Where the information was sourced from and where it can be reviewed for updates in the future.
	Sources []*Source `json:"sources,omitempty" jsonschema:"title=Sources"`

	// Values defines the possible values associated with the key, which themselves will
	// either be keys or codes depending on the context.
	Values []*Definition `json:"values,omitempty" jsonschema:"title=Values"`

	// Pattern is used to validate the key value instead of using a fixed value
	// from the code or key definitions.
	Pattern string `json:"pattern,omitempty" jsonschema:"title=Pattern"`

	// Map helps map local keys to specific codes, useful for converting the
	// described key into a local code.
	Map CodeMap `json:"map,omitempty" jsonschema:"title=Code Map"`
}

Definition defines properties of a key, code, or other value that has a specific meaning or utility.

func GetCodeDefinition added in v0.207.0

func GetCodeDefinition(code Code, list []*Definition) *Definition

GetCodeDefinition helps fetch the code definition instance from a list.

func GetKeyDefinition added in v0.69.0

func GetKeyDefinition(key Key, list []*Definition) *Definition

GetKeyDefinition helps fetch the key definition instance from a list.

func (*Definition) CodeDef added in v0.207.0

func (d *Definition) CodeDef(code Code) *Definition

CodeDef searches the list of values and provides the matching definition.

func (*Definition) HasCode added in v0.207.0

func (d *Definition) HasCode(code Code) bool

HasCode loops through values and determines if there is a match for the code.

func (*Definition) HasKey added in v0.207.0

func (d *Definition) HasKey(key Key) bool

HasKey loops through values and determines if there is a match for the key.

func (*Definition) KeyDef added in v0.207.0

func (d *Definition) KeyDef(key Key) *Definition

KeyDef searches the list of values and provides the matching definition.

type HasKeyRule added in v0.400.0

type HasKeyRule struct {
	// contains filtered or unexported fields
}

HasKeyRule defines a test that will check for the presence of keys.

func HasValidKeyIn added in v0.50.0

func HasValidKeyIn(keys ...Key) HasKeyRule

HasValidKeyIn provides a validator to check the Key's value is within the provided known set.

func (HasKeyRule) Check added in v0.400.0

func (r HasKeyRule) Check(value any) bool

Check returns true if the value satisfies the rule.

func (HasKeyRule) String added in v0.400.0

func (r HasKeyRule) String() string

String provides a string representation of the test.

func (HasKeyRule) Validate added in v0.400.0

func (r HasKeyRule) Validate(v interface{}) error

Validate will provide an error if the value is not defined inside the set of keys provided to the rule.

type Key

type Key string

Key is used to define an ID or code that more closely represents a human name. The objective is to make it easier to define constants that can be re-used more easily.

const KeyEmpty Key = ""

KeyEmpty is used when no key is available.

func AppendUniqueKeys added in v0.204.0

func AppendUniqueKeys(keys []Key, key ...Key) []Key

AppendUniqueKeys is a convenience method to append keys to a list ensuring that any existing keys are not re-added.

func DefinitionKeys added in v0.81.0

func DefinitionKeys(list []*Definition) []Key

DefinitionKeys helps extract the keys from a list of key definitions.

func StringsToKeys added in v0.303.0

func StringsToKeys(strs []string) []Key

StringsToKeys is a convenience method to convert a list of strings into a list of keys.

func (Key) Has added in v0.50.0

func (k Key) Has(ke Key) bool

Has returns true if the key contains the provided key.

func (Key) HasPrefix added in v0.50.0

func (k Key) HasPrefix(ke Key) bool

HasPrefix checks to see if the key starts with the provided key. As per `Has`, only the complete key between `+` symbols are matched.

func (Key) In

func (k Key) In(set ...Key) bool

In returns true if the key's value matches one of those in the provided list.

func (Key) IsEmpty added in v0.50.0

func (k Key) IsEmpty() bool

IsEmpty returns true if the key has no value.

func (Key) JSONSchema

func (Key) JSONSchema() *jsonschema.Schema

JSONSchema provides a representation of the struct for usage in Schema.

func (Key) Pop added in v0.207.0

func (k Key) Pop() Key

Pop removes the last key from a list and returns the remaining base, or an empty key if there is nothing left.

Example:

Key("a+b+c").Pop() => Key("a+b")

func (Key) String

func (k Key) String() string

String provides string representation of key

func (Key) With

func (k Key) With(ke Key) Key

With provides a new key that combines another joining them together with a `+` symbol.

type Meta

type Meta map[Key]string

Meta defines a structure for data about the data being defined. Typically would be used for adding additional IDs or specifications not already defined or required by the base structure.

GOBL is focussed on ensuring the recipient has everything they need, as such, meta should only be used for data that may be used by intermediary conversion processes that should not be needed by the end-user.

We need to always use strings for values so that meta-data is easy to convert into other formats, such as protobuf which has strict type requirements.

func (Meta) All added in v0.402.0

func (m Meta) All() iter.Seq2[Key, string]

All returns an iterator over the Meta entries in alphabetical order of the keys. Intended for use with Go 1.23+ range-over-func:

for k, v := range m.All() {
    // ...
}

func (Meta) Equals added in v0.112.0

func (m Meta) Equals(m2 Meta) bool

Equals checks if the meta data is the same.

func (Meta) JSONSchemaExtend added in v0.50.0

func (Meta) JSONSchemaExtend(schema *jsonschema.Schema)

JSONSchemaExtend ensures the meta keys are valid.

func (Meta) Keys added in v0.402.0

func (m Meta) Keys() []Key

Keys returns all the keys of the Meta sorted alphabetically.

func (Meta) MarshalJSON added in v0.402.0

func (m Meta) MarshalJSON() ([]byte, error)

MarshalJSON emits the Meta as a JSON object with keys sorted alphabetically for deterministic output. An empty or nil Meta marshals to "null", which combines with `json:"meta,omitempty"` on map fields to omit the field from the encoded parent object.

func (Meta) Values added in v0.402.0

func (m Meta) Values() []string

Values returns all the values of the Meta in the order of their keys' alphabetical sorting.

type Source added in v0.209.0

type Source struct {
	// Title stores the name of the source of information.
	Title i18n.String `json:"title,omitempty" jsonschema:"title=Title"`

	// URL is the location of the source of information.
	URL string `json:"url" jsonschema:"title=URL,format=uri"`

	// ContentType of the information expected at the URL.
	ContentType string `json:"content_type,omitempty" jsonschema:"title=Content Type"`

	// At is the date and time the information was retrieved.
	At *cal.DateTime `json:"at,omitempty" jsonschema:"title=At"`
}

Source is used to identify a specific source of data. Typically this is used as part of other structures to identify where the data came from.

type URI added in v0.500.0

type URI string

URI is a Uniform Resource Identifier in `scheme:opaque` form, used to identify a resource or address. Examples include "gobl:acme.example.com", "iso6523-actorid-upis::9920:b123123123" (a Peppol participant identifier), and "mailto:billing@example.com". The scheme names the namespace; its interpretation is left to consumers.

func (URI) Host added in v0.500.0

func (u URI) Host() string

Host returns the URI's host component (for hierarchical URIs like "https://acme.example/x"), or an empty string if the URI cannot be parsed or carries no host (e.g. opaque URIs such as "mailto:a@b").

func (URI) JSONSchema added in v0.500.0

func (URI) JSONSchema() *jsonschema.Schema

JSONSchema provides a representation of the type for usage in schemas.

func (URI) Opaque added in v0.500.0

func (u URI) Opaque() string

Opaque returns the URI's scheme-specific part, excluding any query component, or an empty string if the URI cannot be parsed.

func (URI) Parse added in v0.500.0

func (u URI) Parse() (*url.URL, error)

Parse parses the URI using the standard library.

func (URI) Path added in v0.500.0

func (u URI) Path() string

Path returns the URI's path component (for hierarchical URIs), or an empty string if the URI cannot be parsed or carries no path.

func (URI) Scheme added in v0.500.0

func (u URI) Scheme() string

Scheme returns the URI's scheme (the part before the first colon), or an empty string if the URI cannot be parsed.

func (URI) String added in v0.500.0

func (u URI) String() string

String provides the string representation of the URI.

func (URI) Validate added in v0.500.0

func (u URI) Validate() error

Validate ensures the URI is well-formed.

Jump to

Keyboard shortcuts

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