// Package wireschema writes the conversation engine's person API v1 as // OpenAPI 3.1 schemas: the operations a device bearer calls, with the // internal/wire types their handlers encode, mirrored field by field. // docs/api/equipo-v1.openapi.json carries what it generates, and // internal/plan3test TestPersonAPIDeviceContract holds the two, the // router and the captured device answers together. package wireschema import ( "bytes" "encoding" "encoding/json" "fmt" "reflect" "regexp" "slices" "strings" "time" "amadan.net/oficina/equipo/internal/equipo/oficinaid" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/equipo/internal/wire" ) // Op is one engine operation a device bearer calls: its request body // and the body of each answer by status, as the wire types the handlers // in internal/equipo/chat encode. nil is no body; Bytes is a file. type Op struct { In any Out map[string]any } // Bytes is a body of raw bytes: an upload or a file. type Bytes struct{} // OneOf documents an operation with distinct response shapes at one status. type OneOf []any // APIError refers to the reviewed Error schema, maintained with the API's // complete copy-code inventory rather than generated from a single handler. type APIError struct{} // LegacyCard preserves the earlier person API projection on the shared URL. type LegacyCard struct{} // accepted is POST /tasks/{id}/move's 202 body, a map in the // handler: written inline. var accepted = struct { Accepted bool `json:"accepted"` }{} // Ops are the conversation engine's routes (chat.HTTP.Mount) by // "METHOD /path", the Assistant lane's apart: the Assistant keeps its // own schemas. var Ops = map[string]Op{ "GET /tasks/{id}/changes/diff": {nil, map[string]any{"200": wire.ChangeDiff{}}}, "GET /messages": {nil, map[string]any{"200": wire.MessagePage{}}}, "POST /messages": {wire.SendMessage{}, map[string]any{"200": wire.Sent{}, "201": wire.Sent{}}}, "POST /attachments": {Bytes{}, map[string]any{"201": wire.MessageAttachment{}}}, "GET /attachments/{id}": {nil, map[string]any{"200": Bytes{}}}, "GET /attachments/{id}/preview": {nil, map[string]any{"200": Bytes{}}}, "DELETE /attachments/{id}": {nil, map[string]any{"204": nil}}, "GET /turns/{id}": {nil, map[string]any{"200": wire.Turn{}}}, "POST /turns/{id}/cancel": {nil, map[string]any{"202": wire.CancelAccepted{}}}, "POST /turns/{id}/retry": {nil, map[string]any{"202": wire.Turn{}}}, "GET /cards/{id}": {nil, map[string]any{"200": OneOf{wire.Card{}, LegacyCard{}}}}, "GET /snapshot": {nil, map[string]any{"200": wire.Snapshot{}}}, "PUT /projects/{id}/star": {wire.SetProjectStar{}, map[string]any{"200": wire.Project{}}}, "DELETE /projects/{id}/names": {wire.ForgetProjectName{}, map[string]any{"204": nil}}, "PUT /projects/{id}/details": {wire.EditProject{}, map[string]any{"200": wire.Project{}}}, "GET /projects": {nil, map[string]any{"200": wire.ProjectList{}}}, "POST /projects": {wire.AddProject{}, map[string]any{"200": wire.Project{}, "201": wire.Project{}}}, "DELETE /projects/{id}": {nil, map[string]any{"200": wire.Project{}}}, "POST /cards/{id}/answer": {wire.AnswerCard{}, map[string]any{"200": wire.Answered{}, "409": OneOf{wire.CardConflict{}, APIError{}}}}, "GET /notebook": {nil, map[string]any{"200": wire.Notebook{}}}, "POST /notebook/reset": {nil, map[string]any{"202": wire.Coordinator{}}}, "DELETE /notebook/corrections/{id}": {nil, map[string]any{"204": nil}}, "GET /tasks": {nil, map[string]any{"200": wire.TaskList{}}}, "GET /tasks/{id}": {nil, map[string]any{"200": wire.Task{}}}, "POST /tasks/{id}/cancel": {nil, map[string]any{"202": wire.TaskAccepted{}}}, "POST /tasks/{id}/retry": {wire.RetryTask{}, map[string]any{"202": wire.TaskAccepted{}}}, "POST /tasks/{id}/move": {wire.MoveTask{}, map[string]any{"202": accepted}}, "PUT /tasks/{id}/priority": {wire.SetPriority{}, map[string]any{"200": wire.Task{}}}, "POST /tasks/{id}/run-now": {wire.RunNow{}, map[string]any{"202": wire.RunNowAccepted{}}}, "POST /tasks/{id}/kind": {wire.SetKind{}, map[string]any{"200": wire.Task{}}}, "POST /tasks/{id}/round": {nil, map[string]any{"202": wire.TaskAccepted{}}}, "POST /tasks/{id}/recover": {nil, map[string]any{"202": wire.TaskAccepted{}}}, "POST /tasks/{id}/duplicate": {wire.MarkDuplicate{}, map[string]any{"200": wire.Task{}}}, "POST /tasks/{id}/merge": {nil, map[string]any{"202": wire.TaskAccepted{}}}, "POST /tasks/{id}/undo-merge": {wire.UndoMerge{}, map[string]any{"201": wire.Task{}}}, "GET /projects/{id}/merge-policy": {nil, map[string]any{"200": wire.MergePolicy{}}}, "PUT /projects/{id}/merge-policy": {wire.SetMergePolicy{}, map[string]any{"200": wire.MergePolicy{}}}, "POST /tasks/{id}/uncombine": {nil, map[string]any{"200": wire.Task{}}}, "POST /tasks/{id}/thread": {wire.PostThread{}, map[string]any{"200": wire.ThreadEntry{}}}, "GET /tasks/{id}/files/{file}": {nil, map[string]any{"200": Bytes{}}}, "GET /steps/{id}/log": {nil, map[string]any{"200": wire.StepLog{}}}, "POST /tasks/{id}/questions": {wire.AskQuestion{}, map[string]any{"202": wire.Question{}}}, "GET /questions/{id}": {nil, map[string]any{"200": wire.Question{}}}, "POST /questions/{id}/cancel": {nil, map[string]any{"202": wire.TaskAccepted{}}}, "GET /needs-you": {nil, map[string]any{"200": wire.TaskList{}}}, "GET /runners": {nil, map[string]any{"200": wire.RunnerList{}}}, "GET /connections": {nil, map[string]any{"200": wire.ConnectionList{}}}, "POST /connections": {wire.Connect{}, map[string]any{"202": wire.Connection{}}}, "GET /connections/{id}": {nil, map[string]any{"200": wire.Connection{}}}, "POST /connections/{id}/cancel": {nil, map[string]any{"200": wire.Connection{}}}, "POST /connections/{id}/secret": {wire.Sealed{}, map[string]any{"202": wire.Connection{}}}, "DELETE /connections/{id}": {nil, map[string]any{"202": wire.Connection{}}}, "POST /connections/{id}/forget": {nil, map[string]any{"204": nil}}, "POST /connections/{id}/check": {nil, map[string]any{"202": nil}}, "POST /connections/{id}/model": {wire.ChooseModel{}, map[string]any{"202": wire.Connection{}}}, "PUT /connections/{id}/budget": {wire.SetBudget{}, map[string]any{"202": wire.Connection{}}}, "PUT /connections/{id}/models": {wire.SetModels{}, map[string]any{"202": wire.Connection{}}}, "POST /connections/{id}/resume": {wire.ResumeSpend{}, map[string]any{"202": nil}}, "GET /thinking": {nil, map[string]any{"200": wire.ThinkingWords{}}}, "PUT /thinking": {wire.ThinkingChoice{}, map[string]any{"200": wire.ThinkingWords{}}}, "GET /connections/preference": {nil, map[string]any{"200": wire.Preferences{}}}, "PUT /connections/preference": {wire.Preferences{}, map[string]any{"200": wire.Preferences{}}}, "PUT /time-zone": {wire.TimeZone{}, map[string]any{"200": wire.TimeZone{}}}, "GET /specialists": {nil, map[string]any{"200": wire.SpecialistList{}}}, "POST /specialists/{id}/revoke": {wire.RevokeSpecialist{}, map[string]any{"200": wire.Specialist{}}}, "GET /housekeeping": {nil, map[string]any{"200": wire.Housekeeping{}}}, "PUT /housekeeping": {wire.SetHousekeeping{}, map[string]any{"200": wire.Housekeeping{}}}, "PUT /housekeeping/detectors/{id}": {wire.SetDetector{}, map[string]any{"200": wire.Housekeeping{}}}, "GET /housekeeping/actions": {nil, map[string]any{"200": wire.HousekeepingActions{}}}, "POST /housekeeping/actions/{id}/undo": {nil, map[string]any{"200": wire.HousekeepingAction{}, "409": wire.ActionConflict{}}}, "GET /usage": {nil, map[string]any{"200": wire.UsageTotals{}}}, "GET /advice": {nil, map[string]any{"200": wire.AdviceList{}}}, "POST /advice/{id}/act": {wire.AdviceAction{}, map[string]any{"200": wire.Advice{}}}, "POST /advice/{id}/dismiss": {wire.AdviceAction{}, map[string]any{"200": wire.Advice{}}}, // Push and set aside (native slice 2). "POST /cards/{id}/visibility": {wire.SetCardVisibility{}, map[string]any{"200": wire.Card{}, "409": wire.CardConflict{}}}, "POST /push-registrations": {wire.RegisterPush{}, map[string]any{"200": wire.PushRegistration{}}}, "POST /push-registrations/activities": {wire.RegisterActivity{}, map[string]any{"204": nil}}, "GET /events": {nil, map[string]any{"200": wire.Event{}}}, } // EventData is what each kind of event on GET /events carries in // data, by type and resource (internal/equipo/chat, txn.event). var EventData = map[string]any{ "message message": wire.Message{}, "turn turn": wire.Turn{}, "delta turn": wire.Delta{}, "activity turn": wire.Activity{}, "card card": wire.Card{}, "project project": wire.Project{}, "runner runner": wire.Runner{}, "coordinator coordinator": wire.Coordinator{}, "connection connection": wire.Connection{}, "preference preference": wire.Preferences{}, "thinking thinking": wire.ThinkingChoice{}, "housekeeping housekeeping": wire.HousekeepingSummary{}, "housekeeping action": wire.HousekeepingAction{}, "task task": wire.Task{}, "step step": wire.Step{}, "activity step": wire.StepActivity{}, "question question": wire.Question{}, "delta question": wire.Delta{}, "activity question": wire.Activity{}, } // Enums are the closed sets of string fields, from the wire // constants, by schema and property. // // A card answer that starts no turn answers with a zero message and // turn: their role and state are then empty. A snapshot before the // person has a primary runner, or whose primary has not reported, has a // runner with no role. var Enums = map[string][]string{ "ChangedFile.status": {wire.ChangeFileAdded, wire.ChangeFileModified, wire.ChangeFileDeleted, wire.ChangeFileRenamed}, "Turn.state": {"", wire.TurnQueued, wire.TurnRunning, wire.TurnWaiting, wire.TurnReplied, wire.TurnFailed, wire.TurnCancelled}, "Turn.kind": {wire.TurnPerson, wire.TurnMoveIn, wire.TurnExplore, wire.TurnHousekeeping, wire.TurnSpecialistAdded}, "Message.role": {"", wire.RolePerson, wire.RoleCoordinator}, "MessageAttachment.kind": {wire.AttachmentImage, wire.AttachmentFile}, "Activity.kind": {wire.ActivityThink, wire.ActivityTool}, "ActivityLine.kind": {wire.ActivityRead, wire.ActivitySearch, wire.ActivityEdit, wire.ActivityRun, wire.ActivityOther}, "Coordinator.state": {wire.CoordinatorNew, wire.CoordinatorMovingIn, wire.CoordinatorReady}, "Project.state": {wire.ProjectActive, wire.ProjectRemoved}, "Runner.role": {"", wire.RolePrimary, wire.RoleWorker}, "Connection.state": {wire.ConnConnecting, wire.ConnHealthy, wire.ConnLimited, wire.ConnSignInAgain, wire.ConnError, wire.ConnSignedOut, wire.ConnForgotten}, "Question.state": {wire.QuestionQueued, wire.QuestionRunning, wire.QuestionAnswered, wire.QuestionFailed, wire.QuestionCancelled}, "Task.stage": {wire.StageNoted, wire.StageInvestigated, wire.StageInProgress, wire.StageInReview, wire.StageReadyToMerge, wire.StageMerging, wire.StageDone, wire.StageCancelled}, "Task.kind": {wire.KindChange, wire.KindExplore}, "Step.state": {wire.StepQueued, wire.StepRunning, wire.StepDone, wire.StepFailed, wire.StepCancelled}, "Advice.kind": {wire.AdviceBudgetNear, wire.AdvicePreferSwitch, wire.AdviceDeferTasks, wire.AdviceHeldLong}, "Advice.state": {wire.AdviceOpen, wire.AdviceActed, wire.AdviceDismissed, wire.AdviceWithdrawn}, "Specialist.state": {wire.SpecialistProposed, wire.SpecialistActive, wire.SpecialistDeclined, wire.SpecialistRevoked}, "HousekeepingAction.state": {wire.ActionClaimed, wire.ActionHeld, wire.ActionDone, wire.ActionUndone, wire.ActionRefused, wire.ActionFailed, wire.ActionVetoed, wire.ActionExpired}, "TaskPriority.priority": {wire.PriorityUrgent, wire.PriorityNormal, wire.PriorityLow}, "TaskPriority.set_by": {wire.PrioritySetByCoordinator, wire.PrioritySetByPerson}, "SetPriority.priority": {wire.PriorityUrgent, wire.PriorityNormal, wire.PriorityLow}, "UsageTotals.period": wire.UsagePeriods, "UsageTotals.by": wire.UsageGroupings, "CardConflict.code": {"card_stale", "card_answered", wire.ConflictDirectionNote}, "ActionConflict.code": {"not_undoable"}, "RegisterPush.environment": {wire.APNsProduction, wire.APNsDevelopment}, "RegisterPush.platform": {wire.PlatformIOS, wire.PlatformMacOS}, "PushRegistration.environment": {wire.APNsProduction, wire.APNsDevelopment}, "PushRegistration.platform": {wire.PlatformIOS, wire.PlatformMacOS}, "Event.type": eventKeys(0), "Event.resource": eventKeys(1), } // eventKeys are the event types (part 0) or resources (part 1) // of EventData, each once, in order. func eventKeys(part int) []string { var keys, out []string for k := range EventData { keys = append(keys, k) } slices.Sort(keys) for _, k := range keys { if v := strings.Fields(k)[part]; !slices.Contains(out, v) { out = append(out, v) } } return out } // EventName names the schema of one kind of event: MessageEvent, // or DeltaQuestionEvent where the resource is not the type. func EventName(key string) string { typ, resource, _ := strings.Cut(key, " ") title := func(s string) string { return strings.ToUpper(s[:1]) + s[1:] } if typ == resource { return title(typ) + "Event" } return title(typ) + title(resource) + "Event" } // events adds a schema for each kind of event, the event with its type, // resource and data fixed, and StreamEvent, any one of them or a ping. func (g *gen) events() { g.ref(wire.Event{}) var keys, refs []any for k := range EventData { keys = append(keys, k) } slices.SortFunc(keys, func(a, b any) int { return strings.Compare(a.(string), b.(string)) }) for _, k := range keys { key := k.(string) typ, resource, _ := strings.Cut(key, " ") name := EventName(key) g.defs[name] = obj("allOf", []any{ obj("$ref", "#/components/schemas/Event"), obj("properties", obj("type", obj("const", typ), "resource", obj("const", resource), "data", g.ref(EventData[key]))), }) refs = append(refs, obj("$ref", "#/components/schemas/"+name)) } // A ping carries only its type, every wire.PingInterval. g.defs["PingEvent"] = obj("type", "object", "properties", obj("type", obj("const", wire.EventPing)), "required", []string{"type"}, "additionalProperties", false) g.defs["StreamEvent"] = obj("oneOf", append(refs, obj("$ref", "#/components/schemas/PingEvent"))) } // ordered is a JSON object that keeps its keys in insertion order, so // a generated schema reads in its struct's field order. type ordered struct { keys []string vals map[string]any } func obj(kv ...any) *ordered { o := &ordered{vals: map[string]any{}} for i := 0; i < len(kv); i += 2 { o.set(kv[i].(string), kv[i+1]) } return o } func (o *ordered) set(k string, v any) { if _, ok := o.vals[k]; !ok { o.keys = append(o.keys, k) } o.vals[k] = v } func (o *ordered) MarshalJSON() ([]byte, error) { var b bytes.Buffer b.WriteByte('{') for i, k := range o.keys { if i > 0 { b.WriteByte(',') } key, _ := json.Marshal(k) val, err := json.Marshal(o.vals[k]) if err != nil { return nil, err } b.Write(key) b.WriteByte(':') b.Write(val) } b.WriteByte('}') return b.Bytes(), nil } // gen mirrors Go types as encoding/json writes them: every // field is always present (required) unless omitempty may drop it (a // struct value is never dropped) or omitzero; a pointer, slice or map // that is not dropped when nil may be null; a struct allows no other // properties. // // A request body is read, not written: wire.Strict rejects an unknown // field but takes any field missing. So an input schema (input set) // requires nothing; the handler's own checks are in the operation's // description. An input type that is also an answer's is named with the // suffix Input, from outputs. type gen struct { defs map[string]*ordered types map[string]reflect.Type enums map[string]bool input bool outputs map[string]reflect.Type } func newGen() *gen { return &gen{defs: map[string]*ordered{}, types: map[string]reflect.Type{}, enums: map[string]bool{}} } var ( marshaler = reflect.TypeOf((*json.Marshaler)(nil)).Elem() textMarshaler = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() ) // unsupported says why a type's JSON is not what its fields say, or "". func unsupported(t reflect.Type) string { if t == timeType || t == rawType || t.Kind() == reflect.Pointer { return "" // a pointer is its element's JSON, checked in turn } for _, m := range []reflect.Type{marshaler, textMarshaler} { if t.Implements(m) || reflect.PointerTo(t).Implements(m) { return t.String() + " writes its own JSON (" + m.String() + ")" } } if t.Kind() == reflect.Map && t.Key().Kind() != reflect.String { return t.String() + " has keys that are not strings" } return "" } var ( timeType = reflect.TypeOf(time.Time{}) rawType = reflect.TypeOf(json.RawMessage{}) ) func nullable(s *ordered) *ordered { if t, ok := s.vals["type"].(string); ok { c := obj() for _, k := range s.keys { c.set(k, s.vals[k]) } c.set("type", []string{t, "null"}) return c } return obj("anyOf", []any{s, obj("type", "null")}) } func (g *gen) ref(v any) *ordered { if _, ok := v.(LegacyCard); ok { return obj("$ref", "#/components/schemas/PersonAPICard") } if _, ok := v.(APIError); ok { return obj("$ref", "#/components/schemas/Error") } if values, ok := v.(OneOf); ok { variants := make([]*ordered, 0, len(values)) for _, value := range values { variants = append(variants, g.ref(value)) } return obj("oneOf", variants) } return g.of(reflect.TypeOf(v)) } func (g *gen) of(t reflect.Type) *ordered { if why := unsupported(t); why != "" { panic("wireschema: no schema for " + why) } switch { case t == timeType: return obj("type", "string", "format", "date-time") case t == rawType: return obj() } switch t.Kind() { case reflect.Pointer: return nullable(g.of(t.Elem())) case reflect.Slice: if t.Elem().Kind() == reflect.Uint8 { return nullable(obj("type", "string", "contentEncoding", "base64")) } return nullable(obj("type", "array", "items", g.of(t.Elem()))) case reflect.Map: return nullable(obj("type", "object", "additionalProperties", g.of(t.Elem()))) case reflect.String: return obj("type", "string") case reflect.Bool: return obj("type", "boolean") case reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint64: return obj("type", "integer", "format", "int64") case reflect.Int32, reflect.Int16, reflect.Int8, reflect.Uint32, reflect.Uint16, reflect.Uint8: return obj("type", "integer", "format", "int32") case reflect.Float64, reflect.Float32: return obj("type", "number", "format", "double") case reflect.Interface: return obj() case reflect.Struct: if t.Name() == "" { return g.object(t, "") } name := t.Name() if out, ok := g.outputs[name]; ok && g.input { if out != t { panic("two Go types named " + name + ": " + out.String() + ", " + t.String()) } name += "Input" } if seen, ok := g.types[name]; ok && seen != t { panic("two Go types named " + name + ": " + seen.String() + ", " + t.String()) } else if !ok { g.types[name] = t g.defs[name] = g.object(t, name) } return obj("$ref", "#/components/schemas/"+name) } panic("no schema for " + t.String()) } func (g *gen) object(t reflect.Type, name string) *ordered { props, required := obj(), []string{} g.fields(t, t.Name(), props, &required) if need, ok := InputRequired[name]; ok && g.input { for _, key := range need { if _, ok := props.vals[key]; !ok { panic("wireschema: " + name + " requires " + key + ", which it does not have") } } required = need } s := obj("type", "object", "properties", props) if len(required) > 0 { s.set("required", required) } s.set("additionalProperties", false) if name != "" { s.set("x-go-type", strings.TrimPrefix(t.String(), "*")) } return s } func (g *gen) fields(t reflect.Type, name string, props *ordered, required *[]string) { for i := range t.NumField() { f := t.Field(i) tag := f.Tag.Get("json") if tag == "-" || (!f.IsExported() && !f.Anonymous) { continue } key, opts, _ := strings.Cut(tag, ",") if f.Anonymous && key == "" && f.Type.Kind() == reflect.Struct { g.fields(f.Type, name, props, required) continue } if f.Anonymous && key == "" { panic("wireschema: " + t.String() + " embeds " + f.Type.String() + ", whose fields are written only when it is set") } if strings.Contains(","+opts+",", ",string,") { panic("wireschema: " + t.String() + "." + f.Name + " is written as a string (,string)") } if key == "" { key = f.Name } kind := f.Type.Kind() omit := strings.Contains(","+opts+",", ",omitzero,") || strings.Contains(","+opts+",", ",omitempty,") && kind != reflect.Struct s := g.of(f.Type) switch { case omit && kind == reflect.Pointer: // Dropped when nil, so never null. s = g.of(f.Type.Elem()) case omit && f.Type == rawType: // Dropped when empty; anything when written. case omit && (kind == reflect.Slice || kind == reflect.Map): s.set("type", s.vals["type"].([]string)[0]) } if values, ok := Enums[name+"."+key]; ok { s.set("enum", values) g.enums[name+"."+key] = true } if name == "ChangeDiff" && key == "hidden_characters" { s.set("description", "True when patch contains Unicode Cf, Default_Ignorable_Code_Point, U+2028/U+2029, or Cc except TAB and LF. FE0E/FE0F immediately after a Unicode 17 Emoji and Extended_Pictographic base are exempt, excluding bases below U+00FF and U+203C/U+2049/U+2122. Keycaps remain marked. Native shows visible code-point markers; LF remains structural and patch bytes are preserved.") } if name == "ChangeDiff" && key == "patch" { s.set("maxLength", wire.MaxFileDiffBytes) s.set("description", "Plain unified patch, at most 64 KiB UTF-8 and 2,000 complete lines, only after whole-file scanning. Not HTML.") } if name == "ChangeDiff" && key == "reason" { s.set("enum", []string{wire.DiffBinary, wire.DiffTooLarge, wire.DiffWithheld, wire.DiffUnavailable, wire.DiffExpired}) } if name == "Step" && key == "change_files" { s.set("description", "Bounded presentation facts, included only on GET /tasks/{id} detail reads. Absent from task lists, snapshots, events and Coordinator tools.") } if name == "ChangeFiles" && key == "entries" { s.set("maxItems", wire.MaxChangeEntries) s.set("description", "At most 200 entries. Totals cover the complete bounded scan; truncated is true when entries were omitted. The encoded facts are bounded to 96 KiB.") } if (name == "ChangeFiles" || name == "ChangedFile") && (key == "additions" || key == "deletions" || key == "files" || name == "ChangeFiles" && key == "binary") { s.set("minimum", 0) } props.set(key, s) if !omit && !g.input { *required = append(*required, key) } } } // InputRequired names, for the few request bodies whose handler refuses // a missing field, the fields it needs. Every other input requires // nothing (see gen). var InputRequired = map[string][]string{ "BeginDeviceInput": {"public_key", "label"}, "NativeRequest": {"assertion", "verifier"}, } // NativeOps are the native sign-in routes, with their own authentication. // The exchange overrides the document's /api/v1 server with the instance root. var NativeOps = map[string]Op{ "POST /native/oficina-id": {oficinaid.NativeRequest{}, map[string]any{"200": oficinaid.NativeSession{}, "400": oficinaid.NativeState{}, "401": oficinaid.NativeState{}, "403": oficinaid.NativeState{}, "503": oficinaid.NativeState{}}}, "POST /auth/devices/native": {personapi.BeginDeviceInput{}, map[string]any{"200": personapi.PersonCredential{}}}, } func allOps() map[string]Op { all := map[string]Op{} for k, v := range Ops { all[k] = v } for k, v := range NativeOps { all[k] = v } return all } // Generate is every schema the device operations reach, by name, as // the document writes it. It panics on an enum for a field no schema // has. func Generate() map[string]json.RawMessage { out := map[string]json.RawMessage{} for name, s := range generate() { raw, err := json.Marshal(s) if err != nil { panic(err) } out[name] = raw } return out } func generate() map[string]*ordered { out, in := build() for key := range Enums { if !out.enums[key] && !in.enums[key] { panic("Enums names no field: " + key) } } for name, s := range in.defs { out.defs[name] = s } return out.defs } // build generates the answers' schemas (out) and then the request // bodies' (in). func build() (out, in *gen) { out, in = newGen(), newGen() for _, op := range allOps() { for _, v := range op.Out { if _, bytes := v.(Bytes); v != nil && !bytes { out.ref(v) } } } out.events() in.input, in.outputs = true, out.types for _, op := range allOps() { if _, bytes := op.In.(Bytes); op.In != nil && !bytes { in.ref(op.In) } } return out, in } // RequestBody is the schema of a request body in Ops, as the document // writes it. func RequestBody(v any) json.RawMessage { if _, bytes := v.(Bytes); bytes { return Body(v) } out, _ := build() in := newGen() in.input, in.outputs = true, out.types raw, err := json.Marshal(in.ref(v)) if err != nil { panic(err) } return raw } // Body is the schema of a body in Ops, as the document writes it. func Body(v any) json.RawMessage { raw, err := json.Marshal(body(v)) if err != nil { panic(err) } return raw } func body(v any) any { switch v.(type) { case Bytes: return obj("type", "string", "contentMediaType", "application/octet-stream") case wire.Event: return obj("$ref", "#/components/schemas/StreamEvent") } return newGen().ref(v) } var dateTime = regexp.MustCompile(`^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,9})?(Z|[+-]\d\d:\d\d)$`) // Validate checks v, decoded by encoding/json into any, against s, with // defs the document's components.schemas. It takes the JSON Schema // subset the document uses: $ref, allOf, oneOf, anyOf, const, enum, // type, properties, required, additionalProperties, items and // date-time. at names v in errors. func Validate(defs map[string]any, v any, s map[string]any, at string) error { if ref, ok := s["$ref"].(string); ok { if err := Validate(defs, v, defs[strings.TrimPrefix(ref, "#/components/schemas/")].(map[string]any), at); err != nil { return err } } for _, sub := range list(s["allOf"]) { if err := Validate(defs, v, sub, at); err != nil { return err } } for _, key := range []string{"oneOf", "anyOf"} { if subs := list(s[key]); subs != nil { n, last := 0, error(nil) for _, sub := range subs { if err := Validate(defs, v, sub, at); err == nil { n++ } else { last = err } } if n == 0 || key == "oneOf" && n > 1 { return fmt.Errorf("%s: %d of %s match (%v)", at, n, key, last) } } } if c, ok := s["const"]; ok && !reflect.DeepEqual(c, v) { return fmt.Errorf("%s: %v is not %v", at, v, c) } if e, ok := s["enum"].([]any); ok && !slices.ContainsFunc(e, func(x any) bool { return reflect.DeepEqual(x, v) }) { return fmt.Errorf("%s: %v is not one of %v", at, v, e) } kind := "object" switch x := v.(type) { case nil: kind = "null" case bool: kind = "boolean" case float64: kind = "number" if x == float64(int64(x)) { kind = "integer" } case string: kind = "string" if s["format"] == "date-time" && !dateTime.MatchString(x) { return fmt.Errorf("%s: %q is not RFC 3339", at, x) } case []any: kind = "array" if items, ok := s["items"].(map[string]any); ok { for i, item := range x { if err := Validate(defs, item, items, fmt.Sprintf("%s[%d]", at, i)); err != nil { return err } } } case map[string]any: props, _ := s["properties"].(map[string]any) for _, r := range strs(s["required"]) { if _, ok := x[r]; !ok { return fmt.Errorf("%s: missing %s", at, r) } } for k, item := range x { sub, ok := props[k].(map[string]any) if !ok { if s["additionalProperties"] == false { return fmt.Errorf("%s: invented %s", at, k) } sub, _ = s["additionalProperties"].(map[string]any) } if sub != nil { if err := Validate(defs, item, sub, at+"."+k); err != nil { return err } } } } if t, ok := s["type"]; ok { types := strs(t) if !slices.Contains(types, kind) && !(kind == "integer" && slices.Contains(types, "number")) { return fmt.Errorf("%s: %s is not %v", at, kind, types) } } return nil } func list(v any) (out []map[string]any) { for _, x := range arr(v) { out = append(out, x.(map[string]any)) } return out } func strs(v any) (out []string) { if s, ok := v.(string); ok { return []string{s} } for _, x := range arr(v) { out = append(out, x.(string)) } return out } func arr(v any) []any { x, _ := v.([]any); return x }