Documentation
¶
Overview ¶
Package schema is the typed model of a Norcube CMS site configuration: the root config, its collections, blocks, inputs and storages, and the field definitions they are made of. It parses the merged document the loader assembles (see package load) and offers the helpers every consumer needs: array item shapes, condition evaluation, select options.
The model mirrors the editor's schema module field for field. A knob the editor reads has a place here; a key it does not read lands in Field.Extra so a validator can report it.
Index ¶
- Constants
- Variables
- func ArrayIDKey(f Field) string
- func Canonical(t string) string
- func Eval(c Condition, s Scope) bool
- func IsArray(t string) bool
- func IsEmptyValue(v any) bool
- func IsGroup(t string) bool
- func IsMultiShape(f Field) bool
- func IsStringLike(t string) bool
- func KnownKnobs(t string) map[string]bool
- func OptionValues(opts []SelectOption) []string
- func PresenceOp(op string) bool
- func PrimitiveBucket(t string) string
- func ResolvePath(path string, s Scope) (any, bool)
- func Truthy(v any) bool
- type Block
- type Collection
- type Computed
- type Condition
- type Config
- type CustomValidator
- type Entry
- type Field
- type Preview
- type PreviewSite
- type RecommendedLength
- type Redirects
- type Resolver
- type Scope
- type SelectOption
- type Storage
- type Variables
Constants ¶
const ( TypeText = "text" TypeParagraph = "paragraph" TypeRichText = "richtext" TypeNumber = "number" TypeBoolean = "boolean" TypeDate = "date" TypeColor = "color" TypeRange = "range" TypeMultiChoice = "multichoice" TypeLink = "link" TypeImage = "image" TypeFile = "file" TypeReference = "reference" TypeSelect = "select" TypeGroup = "group" TypeArray = "array" // Legacy spellings. TypeURL = "url" // link TypeMarkdown = "markdown" // richtext TypeHTML = "html" // richtext TypeObject = "object" // group TypeBlocks = "blocks" // array of named components )
Field types the editor renders. The three legacy spellings are the names fields carried before a rename and are still accepted in content written against them.
const ( // ArrayItemTypeKey is the default discriminator of a multi-shape // array item; a field's `idKey` overrides it. ArrayItemTypeKey = "_type" // BlockComponentKey discriminates items of a legacy `blocks` field. BlockComponentKey = "_component" // CollectionKey stamps a file with the collection that owns it. CollectionKey = "_collection" // IDKey is the page-level identity the editor writes inline. IDKey = "_id" // RefKey marks a mapping that stands for a block or input. RefKey = "$ref" // BlockRefKey is the annotation the loader stamps on a resolved `$ref`. BlockRefKey = "_blockRef" )
Keys with a fixed meaning inside content files.
const ( LocaleFromPath = "path" LocaleFromNone = "none" LocaleFromFieldPrefix = "field:" ReferenceByPath = "path" ReferenceByFieldPrefix = "field:" RedirectsFormatNetlify = "netlify" RedirectsFormatVercel = "vercel" ExtraKeysShow = "show" ExtraKeysHide = "hide" ExtraKeysStrip = "strip" AreaContent = "content" AreaSite = "site" WhenHiddenKeep = "keep" WhenHiddenDrop = "drop" DefaultCollection = "pages" CurrentVersion = 1 )
Values of `localeFrom`, `by` and `redirects.format`.
const ( OpEq = "eq" OpNeq = "neq" OpIn = "in" OpNotIn = "notIn" OpTruthy = "truthy" OpFalsy = "falsy" OpEmpty = "empty" OpNonEmpty = "nonEmpty" OpGt = "gt" OpLt = "lt" OpMatches = "matches" )
Condition operators.
const ( CustomValidatorRegex = "regex" CustomValidatorExpression = "expression" )
Built-in custom validator types.
const ( StorageTypeRepo = "repo" StorageModeReadOnly = "read-only" StorageModeReadWrite = "read-write" StorageNamingOriginal = "" StorageNamingSlug = "slug" StorageNamingSlugHash = "slug+hash" StorageNamingUUID = "uuid" StorageInlineRef = "ref" StorageInlineSVG = "svg" StorageDedupHash = "hash" )
Storage knob values.
Variables ¶
var KnownOps = map[string]bool{ OpEq: true, OpNeq: true, OpIn: true, OpNotIn: true, OpTruthy: true, OpFalsy: true, OpEmpty: true, OpNonEmpty: true, OpGt: true, OpLt: true, OpMatches: true, }
KnownOps lists the condition operators.
var KnownTypes = map[string]bool{ TypeText: true, TypeParagraph: true, TypeRichText: true, TypeNumber: true, TypeBoolean: true, TypeDate: true, TypeColor: true, TypeRange: true, TypeMultiChoice: true, TypeLink: true, TypeImage: true, TypeFile: true, TypeReference: true, TypeSelect: true, TypeGroup: true, TypeArray: true, TypeURL: true, TypeMarkdown: true, TypeHTML: true, TypeObject: true, TypeBlocks: true, }
KnownTypes lists every field type this module understands, legacy spellings included.
var SupportedVersions = map[int]bool{1: true}
SupportedVersions lists the schema-language versions this module reads.
Functions ¶
func ArrayIDKey ¶
ArrayIDKey is the discriminator key the array's items carry.
func Canonical ¶
Canonical maps a legacy spelling to the current type name and returns any other name unchanged.
func IsEmptyValue ¶
IsEmptyValue is the condition evaluator's notion of empty: nil, an empty string, an empty list. Whitespace is not empty.
func IsMultiShape ¶
IsMultiShape reports whether the array accepts more than one shape.
func IsStringLike ¶
IsStringLike reports whether values of the type are strings.
func KnownKnobs ¶
KnownKnobs returns the keys a field of type t may carry.
func OptionValues ¶
func OptionValues(opts []SelectOption) []string
OptionValues returns the option values in order.
func PresenceOp ¶
PresenceOp reports whether the operator only asks whether a value is there, so a path that resolves to nothing is a legitimate answer.
func PrimitiveBucket ¶
PrimitiveBucket is the value type a primitive field type produces: "string", "number", "boolean", or "" for groups and arrays.
func ResolvePath ¶
ResolvePath reads a condition path (`key`, `$parent.key`, `$root.a.b`, `$item.k`, dotted descents, numeric array indexes) against the scope. The second result is false when any segment is missing.
Types ¶
type Block ¶
type Block struct {
Key string
Label string
Description string
Fields []Field
Preview *Preview
Raw map[string]any
}
Block is a reusable group of fields.
type Collection ¶
type Collection struct {
Key string
Label string
Description string
Path string
Match string
HasBody bool
ExtraKeysPolicy string
Area string
Preview *Preview
PreviewPath string
LocaleFrom string
SchemaVersion *int
Fields []Field
Raw map[string]any
}
Collection is one content type.
type Condition ¶
type Condition struct {
Field string
Op string
Value any
All []Condition
Any []Condition
Not *Condition
}
Condition is a `visibleIf` tree: a leaf (Field, Op, Value) or one of All, Any, Not.
type Config ¶
type Config struct {
SchemaVersion int
SiteURL string
PagesDir string
PublicDir string
DefaultStorage string
InputsFromGlob []string
// Storages in declared order.
Storages []Storage
Preview PreviewSite
Redirects Redirects
KnownPaths []string
Variables Variables
// Collections keyed by name; CollectionKeys keeps the declared order.
Collections map[string]Collection
CollectionKeys []string
// Blocks and Inputs keyed by name.
Blocks map[string]Block
BlockKeys []string
Inputs map[string]Field
InputKeys []string
// Raw is the merged document the config was parsed from.
Raw map[string]any
}
Config is a site's whole configuration after merging and `$ref` resolution.
func Parse ¶
Parse reads a merged configuration document (the shape the loader produces and the editor receives: a map with `collections`, `blocks`, `inputs`, `storages`, `preview` and the root keys) into a Config.
Parse is lenient: a malformed knob is kept in Field.Extra or ignored, never fatal, because the validators report malformed knobs with a file and a path. The only error is a document that is not a mapping.
func (*Config) DefaultStorageConfig ¶
DefaultStorageConfig returns the storage a field without `storage` uses: the declared default, else the first declared.
func (*Config) ReferenceKeys ¶
ReferenceKeys lists the field names any reference field looks entries up by (`by: field:<k>`), sorted.
func (*Config) ResolveStorage ¶
ResolveStorage returns the storage a field uses: the named one, or the default when the name is empty.
func (*Config) StorageNames ¶
StorageNames lists the declared storages in order.
type CustomValidator ¶
CustomValidator is one `customValidators` entry; Params holds every key but `type` and `message`.
type Entry ¶
Entry is one allowed shape of an array field, with the name items carry in their discriminator.
func ItemEntries ¶
ItemEntries lists an array field's shapes. The name is the entry's `name`, else its `key`, else a synthetic `__entry_<i>` that no item can match (the validator reports those).
func ResolveItemEntry ¶
ResolveItemEntry picks the shape of one item: by discriminator for mappings, by value type for primitives, the lone shape for single-shape arrays. A mapping without a discriminator falls back to the first group shape, as the editor does. Returns nil when nothing fits.
type Field ¶
type Field struct {
Key string
Type string
Label string
Description string
// Name is the discriminator of an array item shape when it differs
// from Key.
Name string
// BlockRef is the block or input a `$ref` resolved from.
BlockRef string
Required bool
RequiredMessage string
Nullable bool
Hidden bool
VisibleIf *Condition
WhenHidden string
Computed *Computed
Custom []CustomValidator
// Default is the declared default; HasDefault distinguishes an
// explicit null from no default.
Default any
HasDefault bool
// Variables is false when the field opts out of the placeholder
// paster; nil when unset.
Variables *bool
// text, paragraph, richtext, link
Regex string
RegexMessage string
MinLength *int
MinLengthMessage string
MaxLength *int
MaxLengthMessage string
RecommendedLength *RecommendedLength
Rows *int
// richtext and color
Format string
// richtext
RichTextOptions map[string]any
// number, range, multichoice
Min *float64
Max *float64
Step *float64
// select, multichoice
Options []SelectOption
Widget string
Searchable bool
SearchPlaceholder string
// image, file
Accept string
MaxSize int64
Storage string
Dir string
LockDir bool
// reference
Collection string
By string
Multiple bool
// group
Fields []Field
Preview *Preview
Inline bool
// array
Items []Field
IDKey string
MinItems *int
MinItemsMessage string
MaxItems *int
MaxItemsMessage string
UniqueOn string
UniqueOnMessage string
// Components backs the legacy `blocks` type.
Components []string
// Extra holds keys the editor does not read for this field type.
Extra map[string]any
// Raw is the field as parsed, for consumers that need a knob this
// model does not name.
Raw map[string]any
}
Field is one field definition. Every type-specific knob has a place; a nil pointer or zero value means the knob is absent.
func ItemFields ¶
ItemFields returns the fields of the shape one array item has, or nil for a primitive shape or an item no shape fits. Legacy `blocks` fields look the component up in the config's blocks.
type Preview ¶
type Preview struct {
Title []Resolver
Description []Resolver
Image []Resolver
Badges [][]Resolver
}
Preview says how an entry renders as a summary row.
type PreviewSite ¶
PreviewSite holds the site-level i18n facts of the `preview` block.
type RecommendedLength ¶
RecommendedLength is the soft length window of a text field.
type Scope ¶
type Scope struct {
Self map[string]any
Parents []map[string]any
Root map[string]any
Item map[string]any
}
Scope is what a condition path can reach: the current group's values, the chain of parents up to the root, and the nearest array item.
type SelectOption ¶
SelectOption is one option of a select or multichoice field.
func ParseOptions ¶
func ParseOptions(v any) []SelectOption
ParseOptions normalises a select's options (strings or {value, label, description} maps) to SelectOption.