@skillstech/thunderlang 1.7.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +75 -0
- package/README.md +10 -3
- package/dist/core.cjs +234 -20
- package/dist/index.cjs +8853 -1045
- package/dist/learn.cjs +1339 -69
- package/package.json +1 -1
- package/src/cli-main.mjs +312 -115
- package/src/core/check.mjs +312 -6
- package/src/core/cli.mjs +60 -8
- package/src/core/csharp-run.mjs +2 -2
- package/src/core/diagnostics.mjs +9 -0
- package/src/core/engine-core.mjs +141 -19
- package/src/core/engine-values.mjs +1 -0
- package/src/core/engine.mjs +131 -7
- package/src/core/go-run.mjs +2 -2
- package/src/core/index.mjs +6 -2
- package/src/core/java-run.mjs +2 -2
- package/src/core/kind.mjs +3 -0
- package/src/core/lexer.mjs +16 -2
- package/src/core/parser.mjs +200 -15
- package/src/core/project-root.mjs +18 -0
- package/src/core/project.mjs +15 -18
- package/src/core/react-run.mjs +2 -2
- package/src/core/runtime-go/thunder_runtime.go +269 -1
- package/src/core/runtime-python.mjs +365 -3
- package/src/core/runtime-typescript.mjs +150 -5
- package/src/core/rust-run.mjs +2 -2
- package/src/core/serving.mjs +12 -0
- package/src/core/store-format.mjs +110 -0
- package/src/core/target-go.mjs +10 -3
- package/src/core/target-python.mjs +38 -5
- package/src/core/target-typescript.mjs +62 -6
- package/src/core/typescript-run.mjs +6 -4
- package/src/core-changes-fs.mjs +28 -0
- package/src/core-changes.d.mts +67 -0
- package/src/core-changes.mjs +603 -0
- package/src/core-rules.mjs +146 -0
- package/src/core-services.d.mts +4 -0
- package/src/core-services.mjs +49 -0
- package/src/emit.mjs +1 -1
- package/src/evidence.mjs +28 -0
- package/src/examples.d.mts +21 -0
- package/src/examples.mjs +175 -0
- package/src/index.d.ts +4 -0
- package/src/index.mjs +4 -0
- package/src/mcp.mjs +42 -3
- package/src/program.d.mts +4 -0
- package/src/program.mjs +4 -0
- package/src/read-repo-fs.mjs +2 -1
- package/src/review.mjs +69 -3
- package/src/system.mjs +1 -1
- package/src/trace-cli.mjs +8 -3
- package/src/trace-fs.mjs +29 -3
- package/src/trace.mjs +23 -7
|
@@ -12,6 +12,8 @@ package thunder
|
|
|
12
12
|
|
|
13
13
|
import (
|
|
14
14
|
"bufio"
|
|
15
|
+
"bytes"
|
|
16
|
+
"encoding/json"
|
|
15
17
|
"fmt"
|
|
16
18
|
"math/big"
|
|
17
19
|
"os"
|
|
@@ -2978,7 +2980,271 @@ func Init(file string, fn func(F *Frame)) {
|
|
|
2978
2980
|
}()
|
|
2979
2981
|
}
|
|
2980
2982
|
|
|
2981
|
-
//
|
|
2983
|
+
// ── Stored lists (Store habits as a list of Habit): data/<name>.json, the format of store-format.mjs ─────────────
|
|
2984
|
+
// Each field is written by its kind: whole number -> a JSON integer (text when too large for one), number and money
|
|
2985
|
+
// -> exact text, date -> "2026-11-27", yes/no -> true/false, nothing -> null. The bytes are JavaScript's
|
|
2986
|
+
// JSON.stringify(rows, null, 2), so Go, Python, TypeScript, and the Thunder engine take turns on one file.
|
|
2987
|
+
|
|
2988
|
+
// StoreField is a stored record's field and its kind ("money", or "?money" for an optional one).
|
|
2989
|
+
type StoreField struct {
|
|
2990
|
+
Py string
|
|
2991
|
+
Kind string
|
|
2992
|
+
}
|
|
2993
|
+
|
|
2994
|
+
type store struct {
|
|
2995
|
+
file string
|
|
2996
|
+
line int
|
|
2997
|
+
name string
|
|
2998
|
+
cls *RecordKind
|
|
2999
|
+
fields []StoreField
|
|
3000
|
+
items *List
|
|
3001
|
+
}
|
|
3002
|
+
|
|
3003
|
+
var stores []*store
|
|
3004
|
+
|
|
3005
|
+
// NewStore is a stored list: empty until the program runs (Run fills it), saved when the program finishes well.
|
|
3006
|
+
func NewStore(file string, line int, name string, cls *RecordKind, fields []StoreField) V {
|
|
3007
|
+
items := &List{[]V{}}
|
|
3008
|
+
stores = append(stores, &store{file, line, name, cls, fields, items})
|
|
3009
|
+
return items
|
|
3010
|
+
}
|
|
3011
|
+
|
|
3012
|
+
var storeKinds = map[string]string{"whole": "a whole number", "number": "a number", "money": "money", "text": "text", "bool": "yes or no", "date": "a date"}
|
|
3013
|
+
var wholeText = regexp.MustCompile(`^-?\d+$`)
|
|
3014
|
+
var maxSafe = big.NewInt(9007199254740991)
|
|
3015
|
+
|
|
3016
|
+
// storeJSONText is a JSON string the way JavaScript writes one: only ", \, and control characters escaped.
|
|
3017
|
+
func storeJSONText(b *strings.Builder, t string) {
|
|
3018
|
+
b.WriteByte('"')
|
|
3019
|
+
for _, r := range t {
|
|
3020
|
+
switch r {
|
|
3021
|
+
case '"':
|
|
3022
|
+
b.WriteString(`\"`)
|
|
3023
|
+
case '\\':
|
|
3024
|
+
b.WriteString(`\\`)
|
|
3025
|
+
case '\b':
|
|
3026
|
+
b.WriteString(`\b`)
|
|
3027
|
+
case '\f':
|
|
3028
|
+
b.WriteString(`\f`)
|
|
3029
|
+
case '\n':
|
|
3030
|
+
b.WriteString(`\n`)
|
|
3031
|
+
case '\r':
|
|
3032
|
+
b.WriteString(`\r`)
|
|
3033
|
+
case '\t':
|
|
3034
|
+
b.WriteString(`\t`)
|
|
3035
|
+
default:
|
|
3036
|
+
if r < 0x20 {
|
|
3037
|
+
fmt.Fprintf(b, `\u%04x`, r)
|
|
3038
|
+
} else {
|
|
3039
|
+
b.WriteRune(r)
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
}
|
|
3043
|
+
b.WriteByte('"')
|
|
3044
|
+
}
|
|
3045
|
+
|
|
3046
|
+
func storeEncode(b *strings.Builder, v V, kind string) {
|
|
3047
|
+
if strings.HasPrefix(kind, "?") {
|
|
3048
|
+
kind = kind[1:]
|
|
3049
|
+
}
|
|
3050
|
+
if v == nil {
|
|
3051
|
+
b.WriteString("null")
|
|
3052
|
+
return
|
|
3053
|
+
}
|
|
3054
|
+
switch kind {
|
|
3055
|
+
case "whole":
|
|
3056
|
+
n, ok := v.(*big.Int)
|
|
3057
|
+
if ok && new(big.Int).Abs(n).Cmp(maxSafe) <= 0 {
|
|
3058
|
+
b.WriteString(n.String())
|
|
3059
|
+
} else {
|
|
3060
|
+
storeJSONText(b, PyStr(v))
|
|
3061
|
+
}
|
|
3062
|
+
case "number":
|
|
3063
|
+
storeJSONText(b, PyStr(v))
|
|
3064
|
+
case "money":
|
|
3065
|
+
storeJSONText(b, strings.Replace(PyStr(v), "$", "", 1))
|
|
3066
|
+
case "date":
|
|
3067
|
+
if d, ok := v.(*Date); ok {
|
|
3068
|
+
storeJSONText(b, d.iso())
|
|
3069
|
+
} else {
|
|
3070
|
+
storeJSONText(b, PyStr(v))
|
|
3071
|
+
}
|
|
3072
|
+
case "bool":
|
|
3073
|
+
if v == true {
|
|
3074
|
+
b.WriteString("true")
|
|
3075
|
+
} else {
|
|
3076
|
+
b.WriteString("false")
|
|
3077
|
+
}
|
|
3078
|
+
default:
|
|
3079
|
+
storeJSONText(b, PyStr(v))
|
|
3080
|
+
}
|
|
3081
|
+
}
|
|
3082
|
+
|
|
3083
|
+
func storeText(st *store) string {
|
|
3084
|
+
if len(st.items.Items) == 0 {
|
|
3085
|
+
return "[]\n"
|
|
3086
|
+
}
|
|
3087
|
+
var b strings.Builder
|
|
3088
|
+
b.WriteString("[\n")
|
|
3089
|
+
for i, item := range st.items.Items {
|
|
3090
|
+
rec := item.(*Record)
|
|
3091
|
+
b.WriteString(" {\n")
|
|
3092
|
+
for j, f := range st.fields {
|
|
3093
|
+
b.WriteString(" ")
|
|
3094
|
+
storeJSONText(&b, f.Py)
|
|
3095
|
+
b.WriteString(": ")
|
|
3096
|
+
storeEncode(&b, rec.F[f.Py], f.Kind)
|
|
3097
|
+
if j < len(st.fields)-1 {
|
|
3098
|
+
b.WriteByte(',')
|
|
3099
|
+
}
|
|
3100
|
+
b.WriteByte('\n')
|
|
3101
|
+
}
|
|
3102
|
+
b.WriteString(" }")
|
|
3103
|
+
if i < len(st.items.Items)-1 {
|
|
3104
|
+
b.WriteByte(',')
|
|
3105
|
+
}
|
|
3106
|
+
b.WriteByte('\n')
|
|
3107
|
+
}
|
|
3108
|
+
b.WriteString("]\n")
|
|
3109
|
+
return b.String()
|
|
3110
|
+
}
|
|
3111
|
+
|
|
3112
|
+
func storeDecode(x any, kind, where string) V {
|
|
3113
|
+
if strings.HasPrefix(kind, "?") {
|
|
3114
|
+
if x == nil {
|
|
3115
|
+
return nil
|
|
3116
|
+
}
|
|
3117
|
+
kind = kind[1:]
|
|
3118
|
+
}
|
|
3119
|
+
bad := func() V {
|
|
3120
|
+
shown, _ := json.Marshal(x)
|
|
3121
|
+
panic(ConversionFailed(fmt.Sprintf("%s should be %s, but the file has %s.", where, storeKinds[kind], shown)))
|
|
3122
|
+
}
|
|
3123
|
+
num, isNum := x.(json.Number)
|
|
3124
|
+
str, isStr := x.(string)
|
|
3125
|
+
switch kind {
|
|
3126
|
+
case "whole":
|
|
3127
|
+
if isNum && wholeText.MatchString(string(num)) {
|
|
3128
|
+
n, _ := new(big.Int).SetString(string(num), 10)
|
|
3129
|
+
return n
|
|
3130
|
+
}
|
|
3131
|
+
if isStr && wholeText.MatchString(str) {
|
|
3132
|
+
n, _ := new(big.Int).SetString(str, 10)
|
|
3133
|
+
return n
|
|
3134
|
+
}
|
|
3135
|
+
case "number":
|
|
3136
|
+
if isNum && wholeText.MatchString(string(num)) {
|
|
3137
|
+
n, _ := new(big.Int).SetString(string(num), 10)
|
|
3138
|
+
return n
|
|
3139
|
+
}
|
|
3140
|
+
if isStr {
|
|
3141
|
+
if wholeText.MatchString(str) {
|
|
3142
|
+
n, _ := new(big.Int).SetString(str, 10)
|
|
3143
|
+
return n
|
|
3144
|
+
}
|
|
3145
|
+
if d := ParseDec(str); d != nil {
|
|
3146
|
+
return d
|
|
3147
|
+
}
|
|
3148
|
+
}
|
|
3149
|
+
case "money":
|
|
3150
|
+
text := str
|
|
3151
|
+
if isNum {
|
|
3152
|
+
text = string(num)
|
|
3153
|
+
}
|
|
3154
|
+
if isNum || isStr {
|
|
3155
|
+
if d := ParseDec(text); d != nil {
|
|
3156
|
+
return &Money{d}
|
|
3157
|
+
}
|
|
3158
|
+
}
|
|
3159
|
+
case "text":
|
|
3160
|
+
if isStr {
|
|
3161
|
+
return str
|
|
3162
|
+
}
|
|
3163
|
+
case "bool":
|
|
3164
|
+
if v, ok := x.(bool); ok {
|
|
3165
|
+
return v
|
|
3166
|
+
}
|
|
3167
|
+
case "date":
|
|
3168
|
+
if isStr {
|
|
3169
|
+
if d := parseDate(str); d != nil {
|
|
3170
|
+
return d
|
|
3171
|
+
}
|
|
3172
|
+
}
|
|
3173
|
+
default:
|
|
3174
|
+
return x
|
|
3175
|
+
}
|
|
3176
|
+
return bad()
|
|
3177
|
+
}
|
|
3178
|
+
|
|
3179
|
+
func storeRead(st *store, path, text string) []V {
|
|
3180
|
+
dec := json.NewDecoder(bytes.NewReader([]byte(text)))
|
|
3181
|
+
dec.UseNumber()
|
|
3182
|
+
var raw any
|
|
3183
|
+
if err := dec.Decode(&raw); err != nil {
|
|
3184
|
+
panic(ConversionFailed(fmt.Sprintf("%s is not a list Thunder can read (%s).", path, err.Error())))
|
|
3185
|
+
}
|
|
3186
|
+
rows, ok := raw.([]any)
|
|
3187
|
+
if !ok {
|
|
3188
|
+
panic(ConversionFailed(path + " should hold a list, written [ … ]."))
|
|
3189
|
+
}
|
|
3190
|
+
out := []V{}
|
|
3191
|
+
for i, r := range rows {
|
|
3192
|
+
row, ok := r.(map[string]any)
|
|
3193
|
+
if !ok {
|
|
3194
|
+
panic(ConversionFailed(fmt.Sprintf("%s, item %d should be a record, written { … }.", path, i+1)))
|
|
3195
|
+
}
|
|
3196
|
+
given := []Pair{}
|
|
3197
|
+
for _, f := range st.fields {
|
|
3198
|
+
x, has := row[f.Py]
|
|
3199
|
+
if !has {
|
|
3200
|
+
if strings.HasPrefix(f.Kind, "?") {
|
|
3201
|
+
given = append(given, Pair{f.Py, nil})
|
|
3202
|
+
continue
|
|
3203
|
+
}
|
|
3204
|
+
panic(ConversionFailed(fmt.Sprintf("%s, item %d has no \"%s\".", path, i+1, f.Py)))
|
|
3205
|
+
}
|
|
3206
|
+
given = append(given, Pair{f.Py, storeDecode(x, f.Kind, fmt.Sprintf("%s, item %d, \"%s\"", path, i+1, f.Py))})
|
|
3207
|
+
}
|
|
3208
|
+
out = append(out, NewRecord(st.cls, given...))
|
|
3209
|
+
}
|
|
3210
|
+
return out
|
|
3211
|
+
}
|
|
3212
|
+
|
|
3213
|
+
// fillStores fills each stored list from its file (a missing file is an empty list); a problem is reported at the
|
|
3214
|
+
// Store line.
|
|
3215
|
+
func fillStores() {
|
|
3216
|
+
for _, st := range stores {
|
|
3217
|
+
path := "data/" + st.name + ".json"
|
|
3218
|
+
data, err := os.ReadFile(path)
|
|
3219
|
+
if err != nil {
|
|
3220
|
+
if os.IsNotExist(err) {
|
|
3221
|
+
continue
|
|
3222
|
+
}
|
|
3223
|
+
panic(PyErr("OSError", err.Error()))
|
|
3224
|
+
}
|
|
3225
|
+
withFrame(&Frame{st.file, st.line}, func() V { st.items.Items = storeRead(st, path, string(data)); return nil })
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
|
|
3229
|
+
// saveStores writes each stored list to a new file next to the old one, then renames it, so a file is never left
|
|
3230
|
+
// half written.
|
|
3231
|
+
func saveStores() {
|
|
3232
|
+
for _, st := range stores {
|
|
3233
|
+
path := filepath.Join("data", st.name+".json")
|
|
3234
|
+
if err := os.MkdirAll("data", 0o755); err != nil {
|
|
3235
|
+
panic(PyErr("OSError", err.Error()))
|
|
3236
|
+
}
|
|
3237
|
+
if err := os.WriteFile(path+".saving", []byte(storeText(st)), 0o644); err != nil {
|
|
3238
|
+
panic(PyErr("OSError", err.Error()))
|
|
3239
|
+
}
|
|
3240
|
+
if err := os.Rename(path+".saving", path); err != nil {
|
|
3241
|
+
panic(PyErr("OSError", err.Error()))
|
|
3242
|
+
}
|
|
3243
|
+
}
|
|
3244
|
+
}
|
|
3245
|
+
|
|
3246
|
+
// Run runs a program's main part, then ends the process with Python's exit status. Stored lists are filled first
|
|
3247
|
+
// and saved only when it finishes well.
|
|
2982
3248
|
func Run(main func()) {
|
|
2983
3249
|
if !aborted {
|
|
2984
3250
|
func() {
|
|
@@ -2987,7 +3253,9 @@ func Run(main func()) {
|
|
|
2987
3253
|
report(r)
|
|
2988
3254
|
}
|
|
2989
3255
|
}()
|
|
3256
|
+
fillStores()
|
|
2990
3257
|
main()
|
|
3258
|
+
saveStores()
|
|
2991
3259
|
}()
|
|
2992
3260
|
}
|
|
2993
3261
|
out.Flush()
|
|
@@ -754,7 +754,8 @@ def _callers(tb):
|
|
|
754
754
|
|
|
755
755
|
|
|
756
756
|
def describe_error(error):
|
|
757
|
-
|
|
757
|
+
placed = getattr(error, "thunder_where", None) # a stored list's file: its Store line
|
|
758
|
+
src, line, from_python = (*placed, False) if placed else thunder_place(error.__traceback__)
|
|
758
759
|
message = explain(error)
|
|
759
760
|
code = _code(error)
|
|
760
761
|
# Any error Thunder has no words for came from Python code reached through "Use" (TC508), even when that
|
|
@@ -769,15 +770,376 @@ def describe_error(error):
|
|
|
769
770
|
return "%s: %s [%s]" % (where, message, code)
|
|
770
771
|
|
|
771
772
|
|
|
772
|
-
|
|
773
|
-
|
|
773
|
+
# ── Stored lists (Store habits as a list of Habit): data/<name>.json, the format of store-format.mjs ─────────────
|
|
774
|
+
_STORES = []
|
|
775
|
+
_STORE_KINDS = {"whole": "a whole number", "number": "a number", "money": "money", "text": "text", "bool": "yes or no", "date": "a date"}
|
|
776
|
+
|
|
777
|
+
|
|
778
|
+
def new_store(source, line, name, cls, kinds):
|
|
779
|
+
"""A stored list: empty until the program starts (run fills it), saved when the program finishes well.
|
|
780
|
+
A file it can't read is reported at its Store line (source, line), as on the Thunder engine and TypeScript."""
|
|
781
|
+
items = []
|
|
782
|
+
_STORES.append((source, line, name, cls, kinds, items))
|
|
783
|
+
return items
|
|
784
|
+
|
|
785
|
+
|
|
786
|
+
def _store_encode(v, kind):
|
|
787
|
+
if kind.startswith("?"):
|
|
788
|
+
return None if v is None else _store_encode(v, kind[1:])
|
|
789
|
+
if v is None:
|
|
790
|
+
return None
|
|
791
|
+
if kind == "whole":
|
|
792
|
+
return v if -(2 ** 53 - 1) <= v <= 2 ** 53 - 1 else str(v)
|
|
793
|
+
if kind == "number":
|
|
794
|
+
return str(v)
|
|
795
|
+
if kind == "money":
|
|
796
|
+
return str(v).replace("$", "")
|
|
797
|
+
if kind == "date":
|
|
798
|
+
return v.isoformat()
|
|
799
|
+
return v
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def _store_decode(x, kind, where, has="the file has"):
|
|
803
|
+
if kind.startswith("?"):
|
|
804
|
+
return None if x is None else _store_decode(x, kind[1:], where, has)
|
|
805
|
+
def bad():
|
|
806
|
+
return ConversionFailed("%s should be %s, but %s %s." % (where, _STORE_KINDS.get(kind, "a value"), has, json.dumps(x)))
|
|
807
|
+
if kind == "whole":
|
|
808
|
+
if isinstance(x, int) and not isinstance(x, bool):
|
|
809
|
+
return x
|
|
810
|
+
if isinstance(x, str) and re.fullmatch(r"-?\d+", x):
|
|
811
|
+
return int(x)
|
|
812
|
+
raise bad()
|
|
813
|
+
if kind == "number":
|
|
814
|
+
if isinstance(x, int) and not isinstance(x, bool):
|
|
815
|
+
return x
|
|
816
|
+
if isinstance(x, str):
|
|
817
|
+
if re.fullmatch(r"-?\d+", x):
|
|
818
|
+
return int(x)
|
|
819
|
+
try:
|
|
820
|
+
return Decimal(x)
|
|
821
|
+
except InvalidOperation:
|
|
822
|
+
raise bad()
|
|
823
|
+
raise bad()
|
|
824
|
+
if kind == "money":
|
|
825
|
+
try:
|
|
826
|
+
return Money(Decimal(str(x)))
|
|
827
|
+
except (InvalidOperation, ValueError):
|
|
828
|
+
raise bad()
|
|
829
|
+
if kind == "text":
|
|
830
|
+
if isinstance(x, str):
|
|
831
|
+
return x
|
|
832
|
+
raise bad()
|
|
833
|
+
if kind == "bool":
|
|
834
|
+
if isinstance(x, bool):
|
|
835
|
+
return x
|
|
836
|
+
raise bad()
|
|
837
|
+
if kind == "date":
|
|
838
|
+
try:
|
|
839
|
+
return date.fromisoformat(x)
|
|
840
|
+
except (TypeError, ValueError):
|
|
841
|
+
raise bad()
|
|
842
|
+
return x
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
def _store_file(name):
|
|
846
|
+
return "data/%s.json" % name
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def _fill_stores():
|
|
850
|
+
import os
|
|
851
|
+
for source, line, name, cls, kinds, items in _STORES:
|
|
852
|
+
path = _store_file(name)
|
|
853
|
+
if not os.path.exists(path):
|
|
854
|
+
continue
|
|
855
|
+
try:
|
|
856
|
+
items[:] = _read_store(path, cls, kinds)
|
|
857
|
+
except Exception as error: # noqa: BLE001 - reported at the Store line
|
|
858
|
+
error.thunder_where = (source, line)
|
|
859
|
+
raise
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
def _read_store(path, cls, kinds):
|
|
863
|
+
"""The records in a store's file; a problem names the item and field."""
|
|
864
|
+
with open(path, encoding="utf-8") as fh:
|
|
865
|
+
text = fh.read()
|
|
866
|
+
try:
|
|
867
|
+
rows = json.loads(text)
|
|
868
|
+
except ValueError as error:
|
|
869
|
+
raise ConversionFailed("%s is not a list Thunder can read (%s)." % (path, error))
|
|
870
|
+
if not isinstance(rows, list):
|
|
871
|
+
raise ConversionFailed("%s should hold a list, written [ … ]." % path)
|
|
872
|
+
return [_record_from(row, cls, kinds, "%s, item %d" % (path, i + 1)) for i, row in enumerate(rows)]
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
def _record_from(row, cls, kinds, where, has="the file has"):
|
|
876
|
+
"""A record from a JSON object, each field read by its kind; a problem names where it is and the field."""
|
|
877
|
+
if not isinstance(row, dict):
|
|
878
|
+
raise ConversionFailed("%s should be a record, written { … }." % where)
|
|
879
|
+
given = {}
|
|
880
|
+
for field_name, kind in kinds.items():
|
|
881
|
+
if field_name not in row:
|
|
882
|
+
if kind.startswith("?"):
|
|
883
|
+
given[field_name] = None
|
|
884
|
+
continue
|
|
885
|
+
raise ConversionFailed('%s has no "%s".' % (where, field_name))
|
|
886
|
+
given[field_name] = _store_decode(row[field_name], kind, '%s, "%s"' % (where, field_name), has)
|
|
887
|
+
return cls(**given)
|
|
888
|
+
|
|
889
|
+
|
|
890
|
+
def _save_stores():
|
|
891
|
+
import os
|
|
892
|
+
for source, line, name, cls, kinds, items in _STORES:
|
|
893
|
+
path = _store_file(name)
|
|
894
|
+
rows = [{f: _store_encode(getattr(item, f), kind) for f, kind in kinds.items()} for item in items]
|
|
895
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
896
|
+
with open(path + ".saving", "w", encoding="utf-8") as fh:
|
|
897
|
+
fh.write(json.dumps(rows, indent=2, ensure_ascii=False) + "\n")
|
|
898
|
+
os.replace(path + ".saving", path)
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
# ── HTTP (When someone calls GET /habits: and the answer from GET "…"): data in the stored-list format ──────────
|
|
902
|
+
class CallFailed(ThunderError):
|
|
903
|
+
code = "TC510"
|
|
904
|
+
|
|
905
|
+
|
|
906
|
+
_ANSWER_STATUS = [None]
|
|
907
|
+
|
|
908
|
+
|
|
909
|
+
def answer_status(status):
|
|
910
|
+
"""Give … with status 201: the status this request answers with (a direct call in a test ignores it)."""
|
|
911
|
+
_ANSWER_STATUS[0] = status
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
def stop_with(message, status):
|
|
915
|
+
"""Stop with "…" and status 404: a Stop that an endpoint answers with that status."""
|
|
916
|
+
error = Stop(message)
|
|
917
|
+
error.status = status
|
|
918
|
+
return error
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
def _data_ready(v):
|
|
922
|
+
"""A value as JSON data, written by its kind: whole numbers as numbers (text when too large), numbers and money as
|
|
923
|
+
exact text, dates as "2026-11-28", records as objects. The same on every target."""
|
|
924
|
+
if v is None or isinstance(v, (bool, str)):
|
|
925
|
+
return v
|
|
926
|
+
if isinstance(v, int):
|
|
927
|
+
return v if -(2 ** 53 - 1) <= v <= 2 ** 53 - 1 else str(v)
|
|
928
|
+
if isinstance(v, Decimal):
|
|
929
|
+
return str(v)
|
|
930
|
+
if isinstance(v, Money):
|
|
931
|
+
return str(v).replace("$", "", 1)
|
|
932
|
+
if isinstance(v, date):
|
|
933
|
+
return v.isoformat()
|
|
934
|
+
if isinstance(v, (list, tuple)):
|
|
935
|
+
return [_data_ready(x) for x in v]
|
|
936
|
+
if isinstance(v, dict):
|
|
937
|
+
out = {}
|
|
938
|
+
for k, x in v.items():
|
|
939
|
+
if not isinstance(k, str):
|
|
940
|
+
raise KindMismatch("A JSON object's keys are text, but one is %s." % show(k))
|
|
941
|
+
out[k] = _data_ready(x)
|
|
942
|
+
return out
|
|
943
|
+
if is_dataclass(v):
|
|
944
|
+
alts = getattr(type(v), "__thunder_alts__", None)
|
|
945
|
+
if alts is not None: # an alternative of a data type: "which" and the fields it has
|
|
946
|
+
keep = ("which",) + tuple(alts.get(v.which, ()))
|
|
947
|
+
return {name: _data_ready(getattr(v, name)) for name in keep}
|
|
948
|
+
return {f.name: _data_ready(getattr(v, f.name)) for f in fields(v)}
|
|
949
|
+
raise KindMismatch("%s can't be sent as JSON." % show(v))
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
def data_json(v):
|
|
953
|
+
return json.dumps(_data_ready(v), ensure_ascii=False, separators=(",", ":"))
|
|
954
|
+
|
|
955
|
+
|
|
956
|
+
def _unreachable_reason(error):
|
|
957
|
+
"""Why a service could not be reached, in words that are the same on every target."""
|
|
958
|
+
import socket
|
|
959
|
+
reason = getattr(error, "reason", error)
|
|
960
|
+
if isinstance(reason, (TimeoutError, socket.timeout)):
|
|
961
|
+
return "no answer within 30 seconds"
|
|
962
|
+
if isinstance(reason, ConnectionRefusedError):
|
|
963
|
+
return "nothing is answering there"
|
|
964
|
+
if isinstance(reason, socket.gaierror):
|
|
965
|
+
return "the address could not be found"
|
|
966
|
+
return str(reason)
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def http_call(method, url, body, read_as):
|
|
970
|
+
"""the answer from GET "…": the answer's text, or records read from it (read_as = (record, kinds, many))."""
|
|
971
|
+
import urllib.error
|
|
972
|
+
import urllib.request
|
|
973
|
+
where = "The answer from %s %s" % (method, url)
|
|
974
|
+
data = data_json(body).encode("utf-8") if body is not None else None
|
|
975
|
+
headers = {"Accept": "application/json"}
|
|
976
|
+
if data is not None:
|
|
977
|
+
headers["Content-Type"] = "application/json"
|
|
978
|
+
request = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
979
|
+
try:
|
|
980
|
+
with urllib.request.urlopen(request, timeout=30) as reply:
|
|
981
|
+
text = reply.read().decode("utf-8")
|
|
982
|
+
except urllib.error.HTTPError as error:
|
|
983
|
+
raise CallFailed("%s %s answered %d: %s" % (method, url, error.code, error.read().decode("utf-8", "replace").strip()[:300]))
|
|
984
|
+
except (urllib.error.URLError, OSError, ValueError) as error:
|
|
985
|
+
raise CallFailed("%s %s could not be reached (%s)." % (method, url, _unreachable_reason(error)))
|
|
986
|
+
if read_as is None:
|
|
987
|
+
return text
|
|
988
|
+
cls, kinds, many = read_as
|
|
989
|
+
try:
|
|
990
|
+
answer = json.loads(text)
|
|
991
|
+
except ValueError:
|
|
992
|
+
raise ConversionFailed("%s is not JSON Thunder can read." % where)
|
|
993
|
+
if many:
|
|
994
|
+
if not isinstance(answer, list):
|
|
995
|
+
raise ConversionFailed("%s should be a list, written [ … ]." % where)
|
|
996
|
+
return [_record_from(row, cls, kinds, "%s, item %d" % (where, i + 1), "it has") for i, row in enumerate(answer)]
|
|
997
|
+
return _record_from(answer, cls, kinds, where, "it has")
|
|
998
|
+
|
|
999
|
+
|
|
1000
|
+
def _input_value(raw, kind, where, from_text):
|
|
1001
|
+
"""A request's input read by its kind. Path and query parts are text, so yes/no is written yes, no, true, or false."""
|
|
1002
|
+
plain = kind.lstrip("?")
|
|
1003
|
+
if from_text and plain == "bool" and isinstance(raw, str) and raw.lower() in ("yes", "no", "true", "false"):
|
|
1004
|
+
raw = raw.lower() in ("yes", "true")
|
|
1005
|
+
return _store_decode(raw, kind, where, "the request has")
|
|
1006
|
+
|
|
1007
|
+
|
|
1008
|
+
def _serve(routes):
|
|
1009
|
+
"""Answer requests on this machine, one at a time, until stopped (Ctrl+C). Stored lists are saved after each
|
|
1010
|
+
request that finishes well."""
|
|
1011
|
+
import os
|
|
1012
|
+
import urllib.parse
|
|
1013
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
1014
|
+
|
|
1015
|
+
host = os.environ.get("THUNDER_HOST", "127.0.0.1")
|
|
1016
|
+
port = int(os.environ.get("THUNDER_PORT", "8080"))
|
|
1017
|
+
table = []
|
|
1018
|
+
for method, path, handler, inputs in routes:
|
|
1019
|
+
parts = [p for p in path.split("/") if p]
|
|
1020
|
+
table.append((method, path, parts, handler, inputs))
|
|
1021
|
+
|
|
1022
|
+
def match(parts, request_parts):
|
|
1023
|
+
if len(parts) != len(request_parts):
|
|
1024
|
+
return None
|
|
1025
|
+
found = {}
|
|
1026
|
+
for want, got in zip(parts, request_parts):
|
|
1027
|
+
if want.startswith("{") and want.endswith("}"):
|
|
1028
|
+
found[want[1:-1].strip().lower()] = urllib.parse.unquote(got)
|
|
1029
|
+
elif want != got:
|
|
1030
|
+
return None
|
|
1031
|
+
return found
|
|
1032
|
+
|
|
1033
|
+
class Handler(BaseHTTPRequestHandler):
|
|
1034
|
+
server_version = "Thunder"
|
|
1035
|
+
|
|
1036
|
+
def answer(self, status, value):
|
|
1037
|
+
data = data_json(value).encode("utf-8")
|
|
1038
|
+
self.send_response(status)
|
|
1039
|
+
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
1040
|
+
self.send_header("Content-Length", str(len(data)))
|
|
1041
|
+
self.end_headers()
|
|
1042
|
+
self.wfile.write(data)
|
|
1043
|
+
print("%s %s -> %d" % (self.command, self.path, status), flush=True)
|
|
1044
|
+
|
|
1045
|
+
def handle_any(self):
|
|
1046
|
+
url = urllib.parse.urlsplit(self.path)
|
|
1047
|
+
request_parts = [p for p in url.path.split("/") if p]
|
|
1048
|
+
query = {k: v[-1] for k, v in urllib.parse.parse_qs(url.query).items()}
|
|
1049
|
+
chosen, methods = None, []
|
|
1050
|
+
for method, path, parts, handler, inputs in table:
|
|
1051
|
+
found = match(parts, request_parts)
|
|
1052
|
+
if found is None:
|
|
1053
|
+
continue
|
|
1054
|
+
methods.append(method)
|
|
1055
|
+
if method == self.command:
|
|
1056
|
+
chosen = (method, path, handler, inputs, found)
|
|
1057
|
+
if chosen is None:
|
|
1058
|
+
if methods:
|
|
1059
|
+
return self.answer(405, {"problem": "%s answers only %s." % (url.path, ", ".join(methods))})
|
|
1060
|
+
return self.answer(404, {"problem": "Nothing here answers %s %s." % (self.command, url.path)})
|
|
1061
|
+
method, path, handler, inputs, found = chosen
|
|
1062
|
+
body = {}
|
|
1063
|
+
length = int(self.headers.get("Content-Length") or 0)
|
|
1064
|
+
if length:
|
|
1065
|
+
try:
|
|
1066
|
+
body = json.loads(self.rfile.read(length).decode("utf-8"))
|
|
1067
|
+
except ValueError:
|
|
1068
|
+
return self.answer(400, {"problem": "The request's body is not JSON Thunder can read."})
|
|
1069
|
+
if not isinstance(body, dict):
|
|
1070
|
+
return self.answer(400, {"problem": "The request's body should be a JSON object, written { … }."})
|
|
1071
|
+
args = {}
|
|
1072
|
+
try:
|
|
1073
|
+
for text, py_name, kind, source, has_default in inputs:
|
|
1074
|
+
key = text.lower()
|
|
1075
|
+
if source == "path":
|
|
1076
|
+
args[py_name] = _input_value(found[key], kind, '"%s"' % text, True)
|
|
1077
|
+
elif key in query:
|
|
1078
|
+
args[py_name] = _input_value(query[key], kind, '"%s"' % text, True)
|
|
1079
|
+
elif py_name in query:
|
|
1080
|
+
args[py_name] = _input_value(query[py_name], kind, '"%s"' % text, True)
|
|
1081
|
+
elif text in body or key in body or py_name in body:
|
|
1082
|
+
raw = body[text] if text in body else body[key] if key in body else body[py_name]
|
|
1083
|
+
args[py_name] = _input_value(raw, kind, '"%s"' % text, False)
|
|
1084
|
+
elif not has_default:
|
|
1085
|
+
if kind.startswith("?"):
|
|
1086
|
+
args[py_name] = None
|
|
1087
|
+
else:
|
|
1088
|
+
return self.answer(400, {"problem": "%s %s needs %s (%s)." % (method, path, text, _STORE_KINDS.get(kind, kind))})
|
|
1089
|
+
except ThunderError as error:
|
|
1090
|
+
return self.answer(400, {"problem": explain(error)})
|
|
1091
|
+
_ANSWER_STATUS[0] = None
|
|
1092
|
+
try:
|
|
1093
|
+
value = handler(**args)
|
|
1094
|
+
except Stop as error:
|
|
1095
|
+
return self.answer(getattr(error, "status", 400), {"problem": explain(error)})
|
|
1096
|
+
except RuleBroken as error:
|
|
1097
|
+
return self.answer(422, {"problem": explain(error)})
|
|
1098
|
+
except Exception as error: # noqa: BLE001 - reported in Thunder words, the server keeps answering
|
|
1099
|
+
print(describe_error(error), file=sys.stderr, flush=True)
|
|
1100
|
+
return self.answer(500, {"problem": explain(error)})
|
|
1101
|
+
status = _ANSWER_STATUS[0] or 200
|
|
1102
|
+
try:
|
|
1103
|
+
_save_stores()
|
|
1104
|
+
data = data_json(value)
|
|
1105
|
+
except Exception as error: # noqa: BLE001
|
|
1106
|
+
print(describe_error(error), file=sys.stderr, flush=True)
|
|
1107
|
+
return self.answer(500, {"problem": explain(error)})
|
|
1108
|
+
self.answer(status, json.loads(data) if data != "null" else None)
|
|
1109
|
+
|
|
1110
|
+
do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = handle_any
|
|
1111
|
+
|
|
1112
|
+
def log_message(self, *args):
|
|
1113
|
+
pass
|
|
1114
|
+
|
|
1115
|
+
server = HTTPServer((host, port), Handler)
|
|
1116
|
+
print("Thunder is answering on http://%s:%d" % (host, port), flush=True)
|
|
1117
|
+
for method, path, handler, inputs in routes:
|
|
1118
|
+
print(" %s %s" % (method, path), flush=True)
|
|
1119
|
+
print("Press Ctrl+C to stop.", flush=True)
|
|
1120
|
+
try:
|
|
1121
|
+
server.serve_forever()
|
|
1122
|
+
except KeyboardInterrupt:
|
|
1123
|
+
print("Stopped answering.", flush=True)
|
|
1124
|
+
finally:
|
|
1125
|
+
server.server_close()
|
|
1126
|
+
|
|
1127
|
+
|
|
1128
|
+
def run(main, file=None, routes=None):
|
|
1129
|
+
"""Runs a generated program; an error is reported against the Thunder line, then the program exits with 1.
|
|
1130
|
+
Stored lists are filled first and saved only when the program finishes well. With endpoints, it then answers
|
|
1131
|
+
requests until stopped."""
|
|
774
1132
|
try:
|
|
1133
|
+
_fill_stores()
|
|
775
1134
|
main()
|
|
1135
|
+
_save_stores()
|
|
776
1136
|
except KeyboardInterrupt:
|
|
777
1137
|
raise
|
|
778
1138
|
except Exception as error: # noqa: BLE001 - every error is reported in Thunder words
|
|
779
1139
|
print(describe_error(error), file=sys.stderr)
|
|
780
1140
|
sys.exit(1)
|
|
1141
|
+
if routes:
|
|
1142
|
+
_serve(routes)
|
|
781
1143
|
|
|
782
1144
|
|
|
783
1145
|
def run_tests(modules):
|