| 1 | // Package wireschema writes the conversation engine's person API v1 as |
| 2 | // OpenAPI 3.1 schemas: the operations a device bearer calls, with the |
| 3 | // internal/wire types their handlers encode, mirrored field by field. |
| 4 | // docs/api/equipo-v1.openapi.json carries what it generates, and |
| 5 | // internal/plan3test TestPersonAPIDeviceContract holds the two, the |
| 6 | // router and the captured device answers together. |
| 7 | package wireschema |
| 8 | |
| 9 | import ( |
| 10 | "bytes" |
| 11 | "encoding" |
| 12 | "encoding/json" |
| 13 | "fmt" |
| 14 | "reflect" |
| 15 | "regexp" |
| 16 | "slices" |
| 17 | "strings" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/equipo/internal/equipo/oficinaid" |
| 21 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 22 | "amadan.net/oficina/equipo/internal/wire" |
| 23 | ) |
| 24 | |
| 25 | // Op is one engine operation a device bearer calls: its request body |
| 26 | // and the body of each answer by status, as the wire types the handlers |
| 27 | // in internal/equipo/chat encode. nil is no body; Bytes is a file. |
| 28 | type Op struct { |
| 29 | In any |
| 30 | Out map[string]any |
| 31 | } |
| 32 | |
| 33 | // Bytes is a body of raw bytes: an upload or a file. |
| 34 | type Bytes struct{} |
| 35 | |
| 36 | // OneOf documents an operation with distinct response shapes at one status. |
| 37 | type OneOf []any |
| 38 | |
| 39 | // APIError refers to the reviewed Error schema, maintained with the API's |
| 40 | // complete copy-code inventory rather than generated from a single handler. |
| 41 | type APIError struct{} |
| 42 | |
| 43 | // LegacyCard preserves the earlier person API projection on the shared URL. |
| 44 | type LegacyCard struct{} |
| 45 | |
| 46 | // accepted is POST /tasks/{id}/move's 202 body, a map in the |
| 47 | // handler: written inline. |
| 48 | var accepted = struct { |
| 49 | Accepted bool `json:"accepted"` |
| 50 | }{} |
| 51 | |
| 52 | // Ops are the conversation engine's routes (chat.HTTP.Mount) by |
| 53 | // "METHOD /path", the Assistant lane's apart: the Assistant keeps its |
| 54 | // own schemas. |
| 55 | var Ops = map[string]Op{ |
| 56 | "GET /tasks/{id}/changes/diff": {nil, map[string]any{"200": wire.ChangeDiff{}}}, |
| 57 | "GET /messages": {nil, map[string]any{"200": wire.MessagePage{}}}, |
| 58 | "POST /messages": {wire.SendMessage{}, map[string]any{"200": wire.Sent{}, "201": wire.Sent{}}}, |
| 59 | "POST /attachments": {Bytes{}, map[string]any{"201": wire.MessageAttachment{}}}, |
| 60 | "GET /attachments/{id}": {nil, map[string]any{"200": Bytes{}}}, |
| 61 | "GET /attachments/{id}/preview": {nil, map[string]any{"200": Bytes{}}}, |
| 62 | "DELETE /attachments/{id}": {nil, map[string]any{"204": nil}}, |
| 63 | "GET /turns/{id}": {nil, map[string]any{"200": wire.Turn{}}}, |
| 64 | "POST /turns/{id}/cancel": {nil, map[string]any{"202": wire.CancelAccepted{}}}, |
| 65 | "POST /turns/{id}/retry": {nil, map[string]any{"202": wire.Turn{}}}, |
| 66 | "GET /cards/{id}": {nil, map[string]any{"200": OneOf{wire.Card{}, LegacyCard{}}}}, |
| 67 | "GET /snapshot": {nil, map[string]any{"200": wire.Snapshot{}}}, |
| 68 | "PUT /projects/{id}/star": {wire.SetProjectStar{}, map[string]any{"200": wire.Project{}}}, |
| 69 | "DELETE /projects/{id}/names": {wire.ForgetProjectName{}, map[string]any{"204": nil}}, |
| 70 | "PUT /projects/{id}/details": {wire.EditProject{}, map[string]any{"200": wire.Project{}}}, |
| 71 | "GET /projects": {nil, map[string]any{"200": wire.ProjectList{}}}, |
| 72 | "POST /projects": {wire.AddProject{}, map[string]any{"200": wire.Project{}, "201": wire.Project{}}}, |
| 73 | "DELETE /projects/{id}": {nil, map[string]any{"200": wire.Project{}}}, |
| 74 | "POST /cards/{id}/answer": {wire.AnswerCard{}, map[string]any{"200": wire.Answered{}, "409": OneOf{wire.CardConflict{}, APIError{}}}}, |
| 75 | "GET /notebook": {nil, map[string]any{"200": wire.Notebook{}}}, |
| 76 | "POST /notebook/reset": {nil, map[string]any{"202": wire.Coordinator{}}}, |
| 77 | "DELETE /notebook/corrections/{id}": {nil, map[string]any{"204": nil}}, |
| 78 | "GET /tasks": {nil, map[string]any{"200": wire.TaskList{}}}, |
| 79 | "GET /tasks/{id}": {nil, map[string]any{"200": wire.Task{}}}, |
| 80 | "POST /tasks/{id}/cancel": {nil, map[string]any{"202": wire.TaskAccepted{}}}, |
| 81 | "POST /tasks/{id}/retry": {wire.RetryTask{}, map[string]any{"202": wire.TaskAccepted{}}}, |
| 82 | "POST /tasks/{id}/move": {wire.MoveTask{}, map[string]any{"202": accepted}}, |
| 83 | "PUT /tasks/{id}/priority": {wire.SetPriority{}, map[string]any{"200": wire.Task{}}}, |
| 84 | "POST /tasks/{id}/run-now": {wire.RunNow{}, map[string]any{"202": wire.RunNowAccepted{}}}, |
| 85 | "POST /tasks/{id}/kind": {wire.SetKind{}, map[string]any{"200": wire.Task{}}}, |
| 86 | "POST /tasks/{id}/round": {nil, map[string]any{"202": wire.TaskAccepted{}}}, |
| 87 | "POST /tasks/{id}/recover": {nil, map[string]any{"202": wire.TaskAccepted{}}}, |
| 88 | "POST /tasks/{id}/duplicate": {wire.MarkDuplicate{}, map[string]any{"200": wire.Task{}}}, |
| 89 | "POST /tasks/{id}/merge": {nil, map[string]any{"202": wire.TaskAccepted{}}}, |
| 90 | "POST /tasks/{id}/undo-merge": {wire.UndoMerge{}, map[string]any{"201": wire.Task{}}}, |
| 91 | "GET /projects/{id}/merge-policy": {nil, map[string]any{"200": wire.MergePolicy{}}}, |
| 92 | "PUT /projects/{id}/merge-policy": {wire.SetMergePolicy{}, map[string]any{"200": wire.MergePolicy{}}}, |
| 93 | "POST /tasks/{id}/uncombine": {nil, map[string]any{"200": wire.Task{}}}, |
| 94 | "POST /tasks/{id}/thread": {wire.PostThread{}, map[string]any{"200": wire.ThreadEntry{}}}, |
| 95 | "GET /tasks/{id}/files/{file}": {nil, map[string]any{"200": Bytes{}}}, |
| 96 | "GET /steps/{id}/log": {nil, map[string]any{"200": wire.StepLog{}}}, |
| 97 | "POST /tasks/{id}/questions": {wire.AskQuestion{}, map[string]any{"202": wire.Question{}}}, |
| 98 | "GET /questions/{id}": {nil, map[string]any{"200": wire.Question{}}}, |
| 99 | "POST /questions/{id}/cancel": {nil, map[string]any{"202": wire.TaskAccepted{}}}, |
| 100 | "GET /needs-you": {nil, map[string]any{"200": wire.TaskList{}}}, |
| 101 | "GET /runners": {nil, map[string]any{"200": wire.RunnerList{}}}, |
| 102 | "GET /connections": {nil, map[string]any{"200": wire.ConnectionList{}}}, |
| 103 | "POST /connections": {wire.Connect{}, map[string]any{"202": wire.Connection{}}}, |
| 104 | "GET /connections/{id}": {nil, map[string]any{"200": wire.Connection{}}}, |
| 105 | "POST /connections/{id}/cancel": {nil, map[string]any{"200": wire.Connection{}}}, |
| 106 | "POST /connections/{id}/secret": {wire.Sealed{}, map[string]any{"202": wire.Connection{}}}, |
| 107 | "DELETE /connections/{id}": {nil, map[string]any{"202": wire.Connection{}}}, |
| 108 | "POST /connections/{id}/forget": {nil, map[string]any{"204": nil}}, |
| 109 | "POST /connections/{id}/check": {nil, map[string]any{"202": nil}}, |
| 110 | "POST /connections/{id}/model": {wire.ChooseModel{}, map[string]any{"202": wire.Connection{}}}, |
| 111 | "PUT /connections/{id}/budget": {wire.SetBudget{}, map[string]any{"202": wire.Connection{}}}, |
| 112 | "PUT /connections/{id}/models": {wire.SetModels{}, map[string]any{"202": wire.Connection{}}}, |
| 113 | "POST /connections/{id}/resume": {wire.ResumeSpend{}, map[string]any{"202": nil}}, |
| 114 | "GET /thinking": {nil, map[string]any{"200": wire.ThinkingWords{}}}, |
| 115 | "PUT /thinking": {wire.ThinkingChoice{}, map[string]any{"200": wire.ThinkingWords{}}}, |
| 116 | "GET /connections/preference": {nil, map[string]any{"200": wire.Preferences{}}}, |
| 117 | "PUT /connections/preference": {wire.Preferences{}, map[string]any{"200": wire.Preferences{}}}, |
| 118 | "PUT /time-zone": {wire.TimeZone{}, map[string]any{"200": wire.TimeZone{}}}, |
| 119 | "GET /specialists": {nil, map[string]any{"200": wire.SpecialistList{}}}, |
| 120 | "POST /specialists/{id}/revoke": {wire.RevokeSpecialist{}, map[string]any{"200": wire.Specialist{}}}, |
| 121 | "GET /housekeeping": {nil, map[string]any{"200": wire.Housekeeping{}}}, |
| 122 | "PUT /housekeeping": {wire.SetHousekeeping{}, map[string]any{"200": wire.Housekeeping{}}}, |
| 123 | "PUT /housekeeping/detectors/{id}": {wire.SetDetector{}, map[string]any{"200": wire.Housekeeping{}}}, |
| 124 | "GET /housekeeping/actions": {nil, map[string]any{"200": wire.HousekeepingActions{}}}, |
| 125 | "POST /housekeeping/actions/{id}/undo": {nil, map[string]any{"200": wire.HousekeepingAction{}, "409": wire.ActionConflict{}}}, |
| 126 | "GET /usage": {nil, map[string]any{"200": wire.UsageTotals{}}}, |
| 127 | "GET /advice": {nil, map[string]any{"200": wire.AdviceList{}}}, |
| 128 | "POST /advice/{id}/act": {wire.AdviceAction{}, map[string]any{"200": wire.Advice{}}}, |
| 129 | "POST /advice/{id}/dismiss": {wire.AdviceAction{}, map[string]any{"200": wire.Advice{}}}, |
| 130 | |
| 131 | // Push and set aside (native slice 2). |
| 132 | "POST /cards/{id}/visibility": {wire.SetCardVisibility{}, map[string]any{"200": wire.Card{}, "409": wire.CardConflict{}}}, |
| 133 | "POST /push-registrations": {wire.RegisterPush{}, map[string]any{"200": wire.PushRegistration{}}}, |
| 134 | "POST /push-registrations/activities": {wire.RegisterActivity{}, map[string]any{"204": nil}}, |
| 135 | |
| 136 | "GET /events": {nil, map[string]any{"200": wire.Event{}}}, |
| 137 | } |
| 138 | |
| 139 | // EventData is what each kind of event on GET /events carries in |
| 140 | // data, by type and resource (internal/equipo/chat, txn.event). |
| 141 | var EventData = map[string]any{ |
| 142 | "message message": wire.Message{}, |
| 143 | "turn turn": wire.Turn{}, |
| 144 | "delta turn": wire.Delta{}, |
| 145 | "activity turn": wire.Activity{}, |
| 146 | "card card": wire.Card{}, |
| 147 | "project project": wire.Project{}, |
| 148 | "runner runner": wire.Runner{}, |
| 149 | "coordinator coordinator": wire.Coordinator{}, |
| 150 | "connection connection": wire.Connection{}, |
| 151 | "preference preference": wire.Preferences{}, |
| 152 | "thinking thinking": wire.ThinkingChoice{}, |
| 153 | "housekeeping housekeeping": wire.HousekeepingSummary{}, |
| 154 | "housekeeping action": wire.HousekeepingAction{}, |
| 155 | "task task": wire.Task{}, |
| 156 | "step step": wire.Step{}, |
| 157 | "activity step": wire.StepActivity{}, |
| 158 | "question question": wire.Question{}, |
| 159 | "delta question": wire.Delta{}, |
| 160 | "activity question": wire.Activity{}, |
| 161 | } |
| 162 | |
| 163 | // Enums are the closed sets of string fields, from the wire |
| 164 | // constants, by schema and property. |
| 165 | // |
| 166 | // A card answer that starts no turn answers with a zero message and |
| 167 | // turn: their role and state are then empty. A snapshot before the |
| 168 | // person has a primary runner, or whose primary has not reported, has a |
| 169 | // runner with no role. |
| 170 | var Enums = map[string][]string{ |
| 171 | "ChangedFile.status": {wire.ChangeFileAdded, wire.ChangeFileModified, wire.ChangeFileDeleted, wire.ChangeFileRenamed}, |
| 172 | "Turn.state": {"", wire.TurnQueued, wire.TurnRunning, wire.TurnWaiting, wire.TurnReplied, wire.TurnFailed, wire.TurnCancelled}, |
| 173 | "Turn.kind": {wire.TurnPerson, wire.TurnMoveIn, wire.TurnExplore, wire.TurnHousekeeping, wire.TurnSpecialistAdded}, |
| 174 | "Message.role": {"", wire.RolePerson, wire.RoleCoordinator}, |
| 175 | "MessageAttachment.kind": {wire.AttachmentImage, wire.AttachmentFile}, |
| 176 | "Activity.kind": {wire.ActivityThink, wire.ActivityTool}, |
| 177 | "ActivityLine.kind": {wire.ActivityRead, wire.ActivitySearch, wire.ActivityEdit, wire.ActivityRun, wire.ActivityOther}, |
| 178 | "Coordinator.state": {wire.CoordinatorNew, wire.CoordinatorMovingIn, wire.CoordinatorReady}, |
| 179 | "Project.state": {wire.ProjectActive, wire.ProjectRemoved}, |
| 180 | "Runner.role": {"", wire.RolePrimary, wire.RoleWorker}, |
| 181 | "Connection.state": {wire.ConnConnecting, wire.ConnHealthy, wire.ConnLimited, wire.ConnSignInAgain, wire.ConnError, wire.ConnSignedOut, wire.ConnForgotten}, |
| 182 | "Question.state": {wire.QuestionQueued, wire.QuestionRunning, wire.QuestionAnswered, wire.QuestionFailed, wire.QuestionCancelled}, |
| 183 | "Task.stage": {wire.StageNoted, wire.StageInvestigated, wire.StageInProgress, wire.StageInReview, wire.StageReadyToMerge, wire.StageMerging, wire.StageDone, wire.StageCancelled}, |
| 184 | "Task.kind": {wire.KindChange, wire.KindExplore}, |
| 185 | "Step.state": {wire.StepQueued, wire.StepRunning, wire.StepDone, wire.StepFailed, wire.StepCancelled}, |
| 186 | "Advice.kind": {wire.AdviceBudgetNear, wire.AdvicePreferSwitch, wire.AdviceDeferTasks, wire.AdviceHeldLong}, |
| 187 | "Advice.state": {wire.AdviceOpen, wire.AdviceActed, wire.AdviceDismissed, wire.AdviceWithdrawn}, |
| 188 | "Specialist.state": {wire.SpecialistProposed, wire.SpecialistActive, wire.SpecialistDeclined, wire.SpecialistRevoked}, |
| 189 | "HousekeepingAction.state": {wire.ActionClaimed, wire.ActionHeld, wire.ActionDone, wire.ActionUndone, wire.ActionRefused, wire.ActionFailed, wire.ActionVetoed, wire.ActionExpired}, |
| 190 | "TaskPriority.priority": {wire.PriorityUrgent, wire.PriorityNormal, wire.PriorityLow}, |
| 191 | "TaskPriority.set_by": {wire.PrioritySetByCoordinator, wire.PrioritySetByPerson}, |
| 192 | "SetPriority.priority": {wire.PriorityUrgent, wire.PriorityNormal, wire.PriorityLow}, |
| 193 | "UsageTotals.period": wire.UsagePeriods, |
| 194 | "UsageTotals.by": wire.UsageGroupings, |
| 195 | "CardConflict.code": {"card_stale", "card_answered", wire.ConflictDirectionNote}, |
| 196 | "ActionConflict.code": {"not_undoable"}, |
| 197 | |
| 198 | "RegisterPush.environment": {wire.APNsProduction, wire.APNsDevelopment}, |
| 199 | "RegisterPush.platform": {wire.PlatformIOS, wire.PlatformMacOS}, |
| 200 | "PushRegistration.environment": {wire.APNsProduction, wire.APNsDevelopment}, |
| 201 | "PushRegistration.platform": {wire.PlatformIOS, wire.PlatformMacOS}, |
| 202 | |
| 203 | "Event.type": eventKeys(0), |
| 204 | "Event.resource": eventKeys(1), |
| 205 | } |
| 206 | |
| 207 | // eventKeys are the event types (part 0) or resources (part 1) |
| 208 | // of EventData, each once, in order. |
| 209 | func eventKeys(part int) []string { |
| 210 | var keys, out []string |
| 211 | for k := range EventData { |
| 212 | keys = append(keys, k) |
| 213 | } |
| 214 | slices.Sort(keys) |
| 215 | for _, k := range keys { |
| 216 | if v := strings.Fields(k)[part]; !slices.Contains(out, v) { |
| 217 | out = append(out, v) |
| 218 | } |
| 219 | } |
| 220 | return out |
| 221 | } |
| 222 | |
| 223 | // EventName names the schema of one kind of event: MessageEvent, |
| 224 | // or DeltaQuestionEvent where the resource is not the type. |
| 225 | func EventName(key string) string { |
| 226 | typ, resource, _ := strings.Cut(key, " ") |
| 227 | title := func(s string) string { return strings.ToUpper(s[:1]) + s[1:] } |
| 228 | if typ == resource { |
| 229 | return title(typ) + "Event" |
| 230 | } |
| 231 | return title(typ) + title(resource) + "Event" |
| 232 | } |
| 233 | |
| 234 | // events adds a schema for each kind of event, the event with its type, |
| 235 | // resource and data fixed, and StreamEvent, any one of them or a ping. |
| 236 | func (g *gen) events() { |
| 237 | g.ref(wire.Event{}) |
| 238 | var keys, refs []any |
| 239 | for k := range EventData { |
| 240 | keys = append(keys, k) |
| 241 | } |
| 242 | slices.SortFunc(keys, func(a, b any) int { return strings.Compare(a.(string), b.(string)) }) |
| 243 | for _, k := range keys { |
| 244 | key := k.(string) |
| 245 | typ, resource, _ := strings.Cut(key, " ") |
| 246 | name := EventName(key) |
| 247 | g.defs[name] = obj("allOf", []any{ |
| 248 | obj("$ref", "#/components/schemas/Event"), |
| 249 | obj("properties", obj("type", obj("const", typ), "resource", obj("const", resource), "data", g.ref(EventData[key]))), |
| 250 | }) |
| 251 | refs = append(refs, obj("$ref", "#/components/schemas/"+name)) |
| 252 | } |
| 253 | // A ping carries only its type, every wire.PingInterval. |
| 254 | g.defs["PingEvent"] = obj("type", "object", "properties", obj("type", obj("const", wire.EventPing)), "required", []string{"type"}, "additionalProperties", false) |
| 255 | g.defs["StreamEvent"] = obj("oneOf", append(refs, obj("$ref", "#/components/schemas/PingEvent"))) |
| 256 | } |
| 257 | |
| 258 | // ordered is a JSON object that keeps its keys in insertion order, so |
| 259 | // a generated schema reads in its struct's field order. |
| 260 | type ordered struct { |
| 261 | keys []string |
| 262 | vals map[string]any |
| 263 | } |
| 264 | |
| 265 | func obj(kv ...any) *ordered { |
| 266 | o := &ordered{vals: map[string]any{}} |
| 267 | for i := 0; i < len(kv); i += 2 { |
| 268 | o.set(kv[i].(string), kv[i+1]) |
| 269 | } |
| 270 | return o |
| 271 | } |
| 272 | |
| 273 | func (o *ordered) set(k string, v any) { |
| 274 | if _, ok := o.vals[k]; !ok { |
| 275 | o.keys = append(o.keys, k) |
| 276 | } |
| 277 | o.vals[k] = v |
| 278 | } |
| 279 | |
| 280 | func (o *ordered) MarshalJSON() ([]byte, error) { |
| 281 | var b bytes.Buffer |
| 282 | b.WriteByte('{') |
| 283 | for i, k := range o.keys { |
| 284 | if i > 0 { |
| 285 | b.WriteByte(',') |
| 286 | } |
| 287 | key, _ := json.Marshal(k) |
| 288 | val, err := json.Marshal(o.vals[k]) |
| 289 | if err != nil { |
| 290 | return nil, err |
| 291 | } |
| 292 | b.Write(key) |
| 293 | b.WriteByte(':') |
| 294 | b.Write(val) |
| 295 | } |
| 296 | b.WriteByte('}') |
| 297 | return b.Bytes(), nil |
| 298 | } |
| 299 | |
| 300 | // gen mirrors Go types as encoding/json writes them: every |
| 301 | // field is always present (required) unless omitempty may drop it (a |
| 302 | // struct value is never dropped) or omitzero; a pointer, slice or map |
| 303 | // that is not dropped when nil may be null; a struct allows no other |
| 304 | // properties. |
| 305 | // |
| 306 | // A request body is read, not written: wire.Strict rejects an unknown |
| 307 | // field but takes any field missing. So an input schema (input set) |
| 308 | // requires nothing; the handler's own checks are in the operation's |
| 309 | // description. An input type that is also an answer's is named with the |
| 310 | // suffix Input, from outputs. |
| 311 | type gen struct { |
| 312 | defs map[string]*ordered |
| 313 | types map[string]reflect.Type |
| 314 | enums map[string]bool |
| 315 | input bool |
| 316 | outputs map[string]reflect.Type |
| 317 | } |
| 318 | |
| 319 | func newGen() *gen { |
| 320 | return &gen{defs: map[string]*ordered{}, types: map[string]reflect.Type{}, enums: map[string]bool{}} |
| 321 | } |
| 322 | |
| 323 | var ( |
| 324 | marshaler = reflect.TypeOf((*json.Marshaler)(nil)).Elem() |
| 325 | textMarshaler = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() |
| 326 | ) |
| 327 | |
| 328 | // unsupported says why a type's JSON is not what its fields say, or "". |
| 329 | func unsupported(t reflect.Type) string { |
| 330 | if t == timeType || t == rawType || t.Kind() == reflect.Pointer { |
| 331 | return "" // a pointer is its element's JSON, checked in turn |
| 332 | } |
| 333 | for _, m := range []reflect.Type{marshaler, textMarshaler} { |
| 334 | if t.Implements(m) || reflect.PointerTo(t).Implements(m) { |
| 335 | return t.String() + " writes its own JSON (" + m.String() + ")" |
| 336 | } |
| 337 | } |
| 338 | if t.Kind() == reflect.Map && t.Key().Kind() != reflect.String { |
| 339 | return t.String() + " has keys that are not strings" |
| 340 | } |
| 341 | return "" |
| 342 | } |
| 343 | |
| 344 | var ( |
| 345 | timeType = reflect.TypeOf(time.Time{}) |
| 346 | rawType = reflect.TypeOf(json.RawMessage{}) |
| 347 | ) |
| 348 | |
| 349 | func nullable(s *ordered) *ordered { |
| 350 | if t, ok := s.vals["type"].(string); ok { |
| 351 | c := obj() |
| 352 | for _, k := range s.keys { |
| 353 | c.set(k, s.vals[k]) |
| 354 | } |
| 355 | c.set("type", []string{t, "null"}) |
| 356 | return c |
| 357 | } |
| 358 | return obj("anyOf", []any{s, obj("type", "null")}) |
| 359 | } |
| 360 | |
| 361 | func (g *gen) ref(v any) *ordered { |
| 362 | if _, ok := v.(LegacyCard); ok { |
| 363 | return obj("$ref", "#/components/schemas/PersonAPICard") |
| 364 | } |
| 365 | if _, ok := v.(APIError); ok { |
| 366 | return obj("$ref", "#/components/schemas/Error") |
| 367 | } |
| 368 | if values, ok := v.(OneOf); ok { |
| 369 | variants := make([]*ordered, 0, len(values)) |
| 370 | for _, value := range values { |
| 371 | variants = append(variants, g.ref(value)) |
| 372 | } |
| 373 | return obj("oneOf", variants) |
| 374 | } |
| 375 | return g.of(reflect.TypeOf(v)) |
| 376 | } |
| 377 | |
| 378 | func (g *gen) of(t reflect.Type) *ordered { |
| 379 | if why := unsupported(t); why != "" { |
| 380 | panic("wireschema: no schema for " + why) |
| 381 | } |
| 382 | switch { |
| 383 | case t == timeType: |
| 384 | return obj("type", "string", "format", "date-time") |
| 385 | case t == rawType: |
| 386 | return obj() |
| 387 | } |
| 388 | switch t.Kind() { |
| 389 | case reflect.Pointer: |
| 390 | return nullable(g.of(t.Elem())) |
| 391 | case reflect.Slice: |
| 392 | if t.Elem().Kind() == reflect.Uint8 { |
| 393 | return nullable(obj("type", "string", "contentEncoding", "base64")) |
| 394 | } |
| 395 | return nullable(obj("type", "array", "items", g.of(t.Elem()))) |
| 396 | case reflect.Map: |
| 397 | return nullable(obj("type", "object", "additionalProperties", g.of(t.Elem()))) |
| 398 | case reflect.String: |
| 399 | return obj("type", "string") |
| 400 | case reflect.Bool: |
| 401 | return obj("type", "boolean") |
| 402 | case reflect.Int, reflect.Int64, reflect.Uint, reflect.Uint64: |
| 403 | return obj("type", "integer", "format", "int64") |
| 404 | case reflect.Int32, reflect.Int16, reflect.Int8, reflect.Uint32, reflect.Uint16, reflect.Uint8: |
| 405 | return obj("type", "integer", "format", "int32") |
| 406 | case reflect.Float64, reflect.Float32: |
| 407 | return obj("type", "number", "format", "double") |
| 408 | case reflect.Interface: |
| 409 | return obj() |
| 410 | case reflect.Struct: |
| 411 | if t.Name() == "" { |
| 412 | return g.object(t, "") |
| 413 | } |
| 414 | name := t.Name() |
| 415 | if out, ok := g.outputs[name]; ok && g.input { |
| 416 | if out != t { |
| 417 | panic("two Go types named " + name + ": " + out.String() + ", " + t.String()) |
| 418 | } |
| 419 | name += "Input" |
| 420 | } |
| 421 | if seen, ok := g.types[name]; ok && seen != t { |
| 422 | panic("two Go types named " + name + ": " + seen.String() + ", " + t.String()) |
| 423 | } else if !ok { |
| 424 | g.types[name] = t |
| 425 | g.defs[name] = g.object(t, name) |
| 426 | } |
| 427 | return obj("$ref", "#/components/schemas/"+name) |
| 428 | } |
| 429 | panic("no schema for " + t.String()) |
| 430 | } |
| 431 | |
| 432 | func (g *gen) object(t reflect.Type, name string) *ordered { |
| 433 | props, required := obj(), []string{} |
| 434 | g.fields(t, t.Name(), props, &required) |
| 435 | if need, ok := InputRequired[name]; ok && g.input { |
| 436 | for _, key := range need { |
| 437 | if _, ok := props.vals[key]; !ok { |
| 438 | panic("wireschema: " + name + " requires " + key + ", which it does not have") |
| 439 | } |
| 440 | } |
| 441 | required = need |
| 442 | } |
| 443 | s := obj("type", "object", "properties", props) |
| 444 | if len(required) > 0 { |
| 445 | s.set("required", required) |
| 446 | } |
| 447 | s.set("additionalProperties", false) |
| 448 | if name != "" { |
| 449 | s.set("x-go-type", strings.TrimPrefix(t.String(), "*")) |
| 450 | } |
| 451 | return s |
| 452 | } |
| 453 | |
| 454 | func (g *gen) fields(t reflect.Type, name string, props *ordered, required *[]string) { |
| 455 | for i := range t.NumField() { |
| 456 | f := t.Field(i) |
| 457 | tag := f.Tag.Get("json") |
| 458 | if tag == "-" || (!f.IsExported() && !f.Anonymous) { |
| 459 | continue |
| 460 | } |
| 461 | key, opts, _ := strings.Cut(tag, ",") |
| 462 | if f.Anonymous && key == "" && f.Type.Kind() == reflect.Struct { |
| 463 | g.fields(f.Type, name, props, required) |
| 464 | continue |
| 465 | } |
| 466 | if f.Anonymous && key == "" { |
| 467 | panic("wireschema: " + t.String() + " embeds " + f.Type.String() + ", whose fields are written only when it is set") |
| 468 | } |
| 469 | if strings.Contains(","+opts+",", ",string,") { |
| 470 | panic("wireschema: " + t.String() + "." + f.Name + " is written as a string (,string)") |
| 471 | } |
| 472 | if key == "" { |
| 473 | key = f.Name |
| 474 | } |
| 475 | kind := f.Type.Kind() |
| 476 | omit := strings.Contains(","+opts+",", ",omitzero,") || |
| 477 | strings.Contains(","+opts+",", ",omitempty,") && kind != reflect.Struct |
| 478 | s := g.of(f.Type) |
| 479 | switch { |
| 480 | case omit && kind == reflect.Pointer: |
| 481 | // Dropped when nil, so never null. |
| 482 | s = g.of(f.Type.Elem()) |
| 483 | case omit && f.Type == rawType: |
| 484 | // Dropped when empty; anything when written. |
| 485 | case omit && (kind == reflect.Slice || kind == reflect.Map): |
| 486 | s.set("type", s.vals["type"].([]string)[0]) |
| 487 | } |
| 488 | if values, ok := Enums[name+"."+key]; ok { |
| 489 | s.set("enum", values) |
| 490 | g.enums[name+"."+key] = true |
| 491 | } |
| 492 | if name == "ChangeDiff" && key == "hidden_characters" { |
| 493 | 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.") |
| 494 | } |
| 495 | if name == "ChangeDiff" && key == "patch" { |
| 496 | s.set("maxLength", wire.MaxFileDiffBytes) |
| 497 | s.set("description", "Plain unified patch, at most 64 KiB UTF-8 and 2,000 complete lines, only after whole-file scanning. Not HTML.") |
| 498 | } |
| 499 | if name == "ChangeDiff" && key == "reason" { |
| 500 | s.set("enum", []string{wire.DiffBinary, wire.DiffTooLarge, wire.DiffWithheld, wire.DiffUnavailable, wire.DiffExpired}) |
| 501 | } |
| 502 | if name == "Step" && key == "change_files" { |
| 503 | s.set("description", "Bounded presentation facts, included only on GET /tasks/{id} detail reads. Absent from task lists, snapshots, events and Coordinator tools.") |
| 504 | } |
| 505 | if name == "ChangeFiles" && key == "entries" { |
| 506 | s.set("maxItems", wire.MaxChangeEntries) |
| 507 | 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.") |
| 508 | } |
| 509 | if (name == "ChangeFiles" || name == "ChangedFile") && (key == "additions" || key == "deletions" || key == "files" || name == "ChangeFiles" && key == "binary") { |
| 510 | s.set("minimum", 0) |
| 511 | } |
| 512 | props.set(key, s) |
| 513 | if !omit && !g.input { |
| 514 | *required = append(*required, key) |
| 515 | } |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | // InputRequired names, for the few request bodies whose handler refuses |
| 520 | // a missing field, the fields it needs. Every other input requires |
| 521 | // nothing (see gen). |
| 522 | var InputRequired = map[string][]string{ |
| 523 | "BeginDeviceInput": {"public_key", "label"}, |
| 524 | "NativeRequest": {"assertion", "verifier"}, |
| 525 | } |
| 526 | |
| 527 | // NativeOps are the native sign-in routes, with their own authentication. |
| 528 | // The exchange overrides the document's /api/v1 server with the instance root. |
| 529 | var NativeOps = map[string]Op{ |
| 530 | "POST /native/oficina-id": {oficinaid.NativeRequest{}, map[string]any{"200": oficinaid.NativeSession{}, "400": oficinaid.NativeState{}, "401": oficinaid.NativeState{}, "403": oficinaid.NativeState{}, "503": oficinaid.NativeState{}}}, |
| 531 | "POST /auth/devices/native": {personapi.BeginDeviceInput{}, map[string]any{"200": personapi.PersonCredential{}}}, |
| 532 | } |
| 533 | |
| 534 | func allOps() map[string]Op { |
| 535 | all := map[string]Op{} |
| 536 | for k, v := range Ops { |
| 537 | all[k] = v |
| 538 | } |
| 539 | for k, v := range NativeOps { |
| 540 | all[k] = v |
| 541 | } |
| 542 | return all |
| 543 | } |
| 544 | |
| 545 | // Generate is every schema the device operations reach, by name, as |
| 546 | // the document writes it. It panics on an enum for a field no schema |
| 547 | // has. |
| 548 | func Generate() map[string]json.RawMessage { |
| 549 | out := map[string]json.RawMessage{} |
| 550 | for name, s := range generate() { |
| 551 | raw, err := json.Marshal(s) |
| 552 | if err != nil { |
| 553 | panic(err) |
| 554 | } |
| 555 | out[name] = raw |
| 556 | } |
| 557 | return out |
| 558 | } |
| 559 | |
| 560 | func generate() map[string]*ordered { |
| 561 | out, in := build() |
| 562 | for key := range Enums { |
| 563 | if !out.enums[key] && !in.enums[key] { |
| 564 | panic("Enums names no field: " + key) |
| 565 | } |
| 566 | } |
| 567 | for name, s := range in.defs { |
| 568 | out.defs[name] = s |
| 569 | } |
| 570 | return out.defs |
| 571 | } |
| 572 | |
| 573 | // build generates the answers' schemas (out) and then the request |
| 574 | // bodies' (in). |
| 575 | func build() (out, in *gen) { |
| 576 | out, in = newGen(), newGen() |
| 577 | for _, op := range allOps() { |
| 578 | for _, v := range op.Out { |
| 579 | if _, bytes := v.(Bytes); v != nil && !bytes { |
| 580 | out.ref(v) |
| 581 | } |
| 582 | } |
| 583 | } |
| 584 | out.events() |
| 585 | in.input, in.outputs = true, out.types |
| 586 | for _, op := range allOps() { |
| 587 | if _, bytes := op.In.(Bytes); op.In != nil && !bytes { |
| 588 | in.ref(op.In) |
| 589 | } |
| 590 | } |
| 591 | return out, in |
| 592 | } |
| 593 | |
| 594 | // RequestBody is the schema of a request body in Ops, as the document |
| 595 | // writes it. |
| 596 | func RequestBody(v any) json.RawMessage { |
| 597 | if _, bytes := v.(Bytes); bytes { |
| 598 | return Body(v) |
| 599 | } |
| 600 | out, _ := build() |
| 601 | in := newGen() |
| 602 | in.input, in.outputs = true, out.types |
| 603 | raw, err := json.Marshal(in.ref(v)) |
| 604 | if err != nil { |
| 605 | panic(err) |
| 606 | } |
| 607 | return raw |
| 608 | } |
| 609 | |
| 610 | // Body is the schema of a body in Ops, as the document writes it. |
| 611 | func Body(v any) json.RawMessage { |
| 612 | raw, err := json.Marshal(body(v)) |
| 613 | if err != nil { |
| 614 | panic(err) |
| 615 | } |
| 616 | return raw |
| 617 | } |
| 618 | |
| 619 | func body(v any) any { |
| 620 | switch v.(type) { |
| 621 | case Bytes: |
| 622 | return obj("type", "string", "contentMediaType", "application/octet-stream") |
| 623 | case wire.Event: |
| 624 | return obj("$ref", "#/components/schemas/StreamEvent") |
| 625 | } |
| 626 | return newGen().ref(v) |
| 627 | } |
| 628 | |
| 629 | var dateTime = regexp.MustCompile(`^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,9})?(Z|[+-]\d\d:\d\d)$`) |
| 630 | |
| 631 | // Validate checks v, decoded by encoding/json into any, against s, with |
| 632 | // defs the document's components.schemas. It takes the JSON Schema |
| 633 | // subset the document uses: $ref, allOf, oneOf, anyOf, const, enum, |
| 634 | // type, properties, required, additionalProperties, items and |
| 635 | // date-time. at names v in errors. |
| 636 | func Validate(defs map[string]any, v any, s map[string]any, at string) error { |
| 637 | if ref, ok := s["$ref"].(string); ok { |
| 638 | if err := Validate(defs, v, defs[strings.TrimPrefix(ref, "#/components/schemas/")].(map[string]any), at); err != nil { |
| 639 | return err |
| 640 | } |
| 641 | } |
| 642 | for _, sub := range list(s["allOf"]) { |
| 643 | if err := Validate(defs, v, sub, at); err != nil { |
| 644 | return err |
| 645 | } |
| 646 | } |
| 647 | for _, key := range []string{"oneOf", "anyOf"} { |
| 648 | if subs := list(s[key]); subs != nil { |
| 649 | n, last := 0, error(nil) |
| 650 | for _, sub := range subs { |
| 651 | if err := Validate(defs, v, sub, at); err == nil { |
| 652 | n++ |
| 653 | } else { |
| 654 | last = err |
| 655 | } |
| 656 | } |
| 657 | if n == 0 || key == "oneOf" && n > 1 { |
| 658 | return fmt.Errorf("%s: %d of %s match (%v)", at, n, key, last) |
| 659 | } |
| 660 | } |
| 661 | } |
| 662 | if c, ok := s["const"]; ok && !reflect.DeepEqual(c, v) { |
| 663 | return fmt.Errorf("%s: %v is not %v", at, v, c) |
| 664 | } |
| 665 | if e, ok := s["enum"].([]any); ok && !slices.ContainsFunc(e, func(x any) bool { return reflect.DeepEqual(x, v) }) { |
| 666 | return fmt.Errorf("%s: %v is not one of %v", at, v, e) |
| 667 | } |
| 668 | kind := "object" |
| 669 | switch x := v.(type) { |
| 670 | case nil: |
| 671 | kind = "null" |
| 672 | case bool: |
| 673 | kind = "boolean" |
| 674 | case float64: |
| 675 | kind = "number" |
| 676 | if x == float64(int64(x)) { |
| 677 | kind = "integer" |
| 678 | } |
| 679 | case string: |
| 680 | kind = "string" |
| 681 | if s["format"] == "date-time" && !dateTime.MatchString(x) { |
| 682 | return fmt.Errorf("%s: %q is not RFC 3339", at, x) |
| 683 | } |
| 684 | case []any: |
| 685 | kind = "array" |
| 686 | if items, ok := s["items"].(map[string]any); ok { |
| 687 | for i, item := range x { |
| 688 | if err := Validate(defs, item, items, fmt.Sprintf("%s[%d]", at, i)); err != nil { |
| 689 | return err |
| 690 | } |
| 691 | } |
| 692 | } |
| 693 | case map[string]any: |
| 694 | props, _ := s["properties"].(map[string]any) |
| 695 | for _, r := range strs(s["required"]) { |
| 696 | if _, ok := x[r]; !ok { |
| 697 | return fmt.Errorf("%s: missing %s", at, r) |
| 698 | } |
| 699 | } |
| 700 | for k, item := range x { |
| 701 | sub, ok := props[k].(map[string]any) |
| 702 | if !ok { |
| 703 | if s["additionalProperties"] == false { |
| 704 | return fmt.Errorf("%s: invented %s", at, k) |
| 705 | } |
| 706 | sub, _ = s["additionalProperties"].(map[string]any) |
| 707 | } |
| 708 | if sub != nil { |
| 709 | if err := Validate(defs, item, sub, at+"."+k); err != nil { |
| 710 | return err |
| 711 | } |
| 712 | } |
| 713 | } |
| 714 | } |
| 715 | if t, ok := s["type"]; ok { |
| 716 | types := strs(t) |
| 717 | if !slices.Contains(types, kind) && !(kind == "integer" && slices.Contains(types, "number")) { |
| 718 | return fmt.Errorf("%s: %s is not %v", at, kind, types) |
| 719 | } |
| 720 | } |
| 721 | return nil |
| 722 | } |
| 723 | |
| 724 | func list(v any) (out []map[string]any) { |
| 725 | for _, x := range arr(v) { |
| 726 | out = append(out, x.(map[string]any)) |
| 727 | } |
| 728 | return out |
| 729 | } |
| 730 | |
| 731 | func strs(v any) (out []string) { |
| 732 | if s, ok := v.(string); ok { |
| 733 | return []string{s} |
| 734 | } |
| 735 | for _, x := range arr(v) { |
| 736 | out = append(out, x.(string)) |
| 737 | } |
| 738 | return out |
| 739 | } |
| 740 | |
| 741 | func arr(v any) []any { x, _ := v.([]any); return x } |
| 742 | |