@mikrojs/native 0.18.3-next.20260829153835 → 0.19.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/src/mikrojs.cpp CHANGED
@@ -312,6 +312,7 @@ MIKRuntime* MIK_NewRuntimeInternal(MIKRunOptions* options) {
312
312
  * distinguish "unset" from "set to some object". */
313
313
  mik_rt->result_proto = JS_UNDEFINED;
314
314
  mik_rt->result_ok_void_singleton = JS_UNDEFINED;
315
+ mik_rt->http_body_consumed_ctor = JS_UNDEFINED;
315
316
 
316
317
  /* Default fs read cap: 64 KiB. Large enough for typical config/JSON
317
318
  * payloads on MCU; small enough that a runaway readFile() can't
@@ -361,7 +362,13 @@ MIKRuntime* MIK_NewRuntimeInternal(MIKRunOptions* options) {
361
362
  mik__udp_init(ctx);
362
363
  mik__observable_init(ctx);
363
364
 
364
- /* Native mikrojs modules (replace bytecode builtins) */
365
+ /* Native mikrojs modules (replace bytecode builtins). The http client
366
+ * modules are NOT registered here: they load lazily through the C-module
367
+ * table in modules.cpp so virtual modules keep precedence. Schema takes
368
+ * the other lazy route, putting a descriptor on the native: registry,
369
+ * because mikro/schema keeps a small facade for its Result-returning
370
+ * parse(); both are resolved after the virtual-module check. */
371
+ mik__schema_register();
365
372
  mik__inspect_register(ctx);
366
373
  mik__pub_fs_register(ctx);
367
374
 
@@ -432,6 +439,8 @@ void MIK_FreeRuntime(MIKRuntime* mik_rt) {
432
439
  mik_rt->env_obj = JS_UNDEFINED;
433
440
  JS_FreeValue(mik_rt->ctx, mik_rt->result_ok_void_singleton);
434
441
  mik_rt->result_ok_void_singleton = JS_UNDEFINED;
442
+ JS_FreeValue(mik_rt->ctx, mik_rt->http_body_consumed_ctor);
443
+ mik_rt->http_body_consumed_ctor = JS_UNDEFINED;
435
444
  JS_FreeValue(mik_rt->ctx, mik_rt->result_proto);
436
445
  mik_rt->result_proto = JS_UNDEFINED;
437
446
  JS_FreeContext(mik_rt->ctx);
@@ -911,15 +920,32 @@ static void mik__check_pre_eval_headroom(JSContext* ctx, const char* filename) {
911
920
  if (mem.malloc_limit <= 0) return; /* No limit configured — nothing to warn about. */
912
921
 
913
922
  long headroom = (long)mem.malloc_limit - (long)mem.malloc_size;
923
+ /* The malloc limit is fixed at runtime creation, but the physical heap
924
+ * moves underneath it — the real budget is whichever ceiling is nearer.
925
+ * 0 means the platform can't report system memory (desktop builds). */
926
+ const MIKPlatform* platform = MIK_GetPlatform();
927
+ size_t sys_free = platform->get_free_system_mem();
928
+ bool sys_bound = sys_free > 0 && (long)sys_free < headroom;
929
+ if (sys_bound) {
930
+ headroom = (long)sys_free;
931
+ }
914
932
  if (headroom >= MIK__PRE_EVAL_HEADROOM_WARN) return;
915
933
 
916
- const MIKPlatform* platform = MIK_GetPlatform();
917
- platform->log(MIK_LOG_WARN, "mikrojs",
918
- "Low QuickJS heap headroom before evaluating '%s': %ld bytes left "
919
- "(%ld / %ld used). Module evaluation may fail with OOM. Lower "
920
- "`memReserved` in mikro.config.ts or split the module graph with "
921
- "dynamic imports.",
922
- filename, headroom, (long)mem.malloc_size, (long)mem.malloc_limit);
934
+ if (sys_bound) {
935
+ platform->log(MIK_LOG_WARN, "mikrojs",
936
+ "Low system heap before evaluating '%s': %ld bytes free "
937
+ "(QuickJS %ld / %ld used has room, but native subsystems have "
938
+ "overrun the reserve). Module evaluation may fail with OOM. Raise "
939
+ "`memReserved` in mikro.config.ts or free native resources.",
940
+ filename, headroom, (long)mem.malloc_size, (long)mem.malloc_limit);
941
+ } else {
942
+ platform->log(MIK_LOG_WARN, "mikrojs",
943
+ "Low QuickJS heap headroom before evaluating '%s': %ld bytes left "
944
+ "(%ld / %ld used). Module evaluation may fail with OOM. Lower "
945
+ "`memReserved` in mikro.config.ts or split the module graph with "
946
+ "dynamic imports.",
947
+ filename, headroom, (long)mem.malloc_size, (long)mem.malloc_limit);
948
+ }
923
949
 
924
950
  /* Signal the host so it can take application-level action (flash LED,
925
951
  * log metric, trigger reset, forward to telemetry). Operates on C state
package/src/modules.cpp CHANGED
@@ -240,6 +240,21 @@ static JSModuleDef* mik_module_loader_inner(JSContext* ctx, const char* module_n
240
240
  }
241
241
 
242
242
  if (strncmp(mikro_prefix, module_name, strlen(mikro_prefix)) == 0) {
243
+ /* C-backed mikro-prefixed modules (ported from bytecode builtins). Resolved
244
+ * here — after the virtual-module check, before bytecode builtins —
245
+ * so MIK_RegisterVirtualModule keeps documented precedence and
246
+ * runtimes that never import them pay nothing. */
247
+ static const struct {
248
+ const char* name;
249
+ JSModuleDef* (*load)(JSContext* ctx);
250
+ } c_modules[] = {
251
+ {"mikro/http/helpers", mik__http_helpers_load},
252
+ {"mikro/http/request", mik__http_request_load},
253
+ {"mikro/wifi", mik__wifi_client_load},
254
+ };
255
+ for (const auto& cm : c_modules) {
256
+ if (strcmp(cm.name, module_name) == 0) return cm.load(ctx);
257
+ }
243
258
  JSModuleDef* builtin_m = mik__load_builtin(ctx, module_name);
244
259
  if (builtin_m) return builtin_m;
245
260
  /* mik__load_builtin returns NULL either because the module isn't in
@@ -960,3 +975,54 @@ bool mik__is_unloadable_namespace(JSContext* ctx, JSValueConst ns) {
960
975
  JS_FreeCString(ctx, name);
961
976
  return ok;
962
977
  }
978
+
979
+ /* Load `specifier` through the module loader on behalf of `importer` and
980
+ * return its namespace. Goes through the loader (not the C-module table
981
+ * directly) so virtual-module overrides keep documented precedence.
982
+ *
983
+ * A PENDING evaluation promise is normal even for fully synchronous modules:
984
+ * quickjs-ng settles it through the job queue when this runs inside an outer
985
+ * module graph. Two invariants, picked by `require_evaluated`:
986
+ * - false: the caller only stores the namespace or reads hoisted function
987
+ * exports, which are safe from instantiation onward.
988
+ * - true: the caller immediately reads or invokes const/class exports, so
989
+ * the module body must have finished running (status EVALUATED); a module
990
+ * parked in top-level await fails with a clear error instead of TDZ. */
991
+ JSValue mik__load_module_ns(JSContext* ctx, const char* importer, const char* specifier,
992
+ bool require_evaluated) {
993
+ JSAtom name = JS_NewAtom(ctx, specifier);
994
+ JSModuleDef* m = JS_FindLoadedModule(ctx, name);
995
+ if (!m) {
996
+ JSValue p = JS_LoadModule(ctx, importer, specifier);
997
+ if (JS_IsException(p)) {
998
+ /* Propagate the loader's real error (e.g. a syntax error in a
999
+ * virtual stub), not a generic not-available message. */
1000
+ JS_FreeAtom(ctx, name);
1001
+ return p;
1002
+ }
1003
+ if (JS_PromiseState(ctx, p) == JS_PROMISE_REJECTED) {
1004
+ JSValue reason = JS_PromiseResult(ctx, p);
1005
+ JS_PromiseMarkAsHandled(ctx, p);
1006
+ JS_FreeValue(ctx, p);
1007
+ JS_FreeAtom(ctx, name);
1008
+ return JS_Throw(ctx, reason);
1009
+ }
1010
+ /* A PENDING promise (top-level-await stub) may still reject later;
1011
+ * mark it handled so that surfaces as a load error, not as an
1012
+ * unhandled-rejection report. Harmless for the fulfilled case. */
1013
+ JS_PromiseMarkAsHandled(ctx, p);
1014
+ JS_FreeValue(ctx, p);
1015
+ m = JS_FindLoadedModule(ctx, name);
1016
+ }
1017
+ JS_FreeAtom(ctx, name);
1018
+ if (!m) {
1019
+ return JS_ThrowReferenceError(ctx, "Native module '%s' is not available", specifier);
1020
+ }
1021
+ /* 5 == EVALUATED; quickjs.h documents the numbering but exports no enum. */
1022
+ if (require_evaluated && JS_GetModuleStatus(ctx, m) != 5) {
1023
+ return JS_ThrowReferenceError(
1024
+ ctx, "Module '%s' has not finished evaluating (top-level await is not supported here)",
1025
+ specifier);
1026
+ }
1027
+ return JS_GetModuleNamespace(ctx, m);
1028
+ }
@@ -1,163 +0,0 @@
1
- declare function err<E>(error: E): {
2
- ok: false;
3
- error: E;
4
- };
5
- export type SchemaError = {
6
- name: 'ValidationFailed';
7
- message: string;
8
- path: string;
9
- };
10
- export declare const SchemaError: {
11
- ValidationFailed: (message: string, path: string) => SchemaError;
12
- };
13
- type Primitive = string | number | boolean;
14
- export type Format = 'url' | 'hostname' | 'ipv4' | 'mac' | 'email';
15
- export type Unit = 'm' | 'kg' | 's' | 'A' | 'K' | 'cd' | 'mol' | 'Hz' | 'rad' | 'sr' | 'N' | 'Pa' | 'J' | 'W' | 'C' | 'V' | 'F' | 'Ohm' | 'S' | 'Wb' | 'T' | 'H' | 'Cel' | 'lm' | 'lx' | 'Bq' | 'Gy' | 'Sv' | 'kat' | 'm2' | 'm3' | 'm/s' | 'm/s2' | 'm3/s' | 'W/m2' | 'cd/m2' | 'bit' | 'bit/s' | 'lat' | 'lon' | 'pH' | 'dB' | 'dBW' | 'count' | '/' | '%RH' | '%EL' | 'EL' | '1/s' | 'S/m' | 'B' | 'VA' | 'VAs' | 'var' | 'vars' | 'J/m' | 'kg/m3' | 'deg' | 'NTU' | 'ms' | 'min' | 'h' | 'MHz' | 'kW' | 'kVA' | 'kvar' | 'Ah' | 'Wh' | 'kWh' | 'varh' | 'kvarh' | 'kVAh' | 'Wh/km' | 'KiB' | 'GB' | 'Mbit/s' | 'B/s' | 'MB/s' | 'mV' | 'mA' | 'dBm' | 'ug/m3' | 'mm/h' | 'm/h' | 'ppm' | '/100' | '/1000' | 'hPa' | 'mm' | 'cm' | 'km' | 'km/h' | 'ppb' | 'ppt' | 'VAh' | 'mg/l' | 'ug/l' | 'g/l' | 'us' | 'kHz' | 'GHz' | 'mW' | 'uA' | 'uV' | 'mAh' | 'MiB' | 'kB' | 'MB' | 'kbit/s' | 'KiB/s' | 'kohm' | 'Mohm' | 'kPa' | 'bar' | 'Bd';
16
- interface Annotated {
17
- readonly title?: string;
18
- readonly description?: string;
19
- }
20
- export interface StringSchema extends Annotated {
21
- readonly kind: 'string';
22
- readonly default?: string;
23
- readonly mask?: boolean;
24
- readonly minLength?: number;
25
- readonly maxLength?: number;
26
- readonly format?: Format;
27
- }
28
- export interface NumberSchema extends Annotated {
29
- readonly kind: 'number';
30
- readonly default?: number;
31
- readonly mask?: boolean;
32
- readonly min?: number;
33
- readonly max?: number;
34
- readonly integer?: boolean;
35
- readonly unit?: Unit;
36
- }
37
- export interface BooleanSchema extends Annotated {
38
- readonly kind: 'boolean';
39
- readonly default?: boolean;
40
- }
41
- export interface UnknownSchema {
42
- readonly kind: 'unknown';
43
- }
44
- export interface LiteralSchema<T extends Primitive = Primitive> extends Annotated {
45
- readonly kind: 'literal';
46
- readonly value: T;
47
- readonly default?: T;
48
- }
49
- export interface ArraySchema<S extends Schema = Schema> extends Annotated {
50
- readonly kind: 'array';
51
- readonly element: S;
52
- readonly default?: unknown;
53
- readonly minItems?: number;
54
- readonly maxItems?: number;
55
- }
56
- export interface ObjectSchema<Shape extends Record<string, Schema> = Record<string, Schema>> extends Annotated {
57
- readonly kind: 'object';
58
- readonly shape: Shape;
59
- }
60
- export interface OptionalSchema<S extends Schema = Schema> {
61
- readonly kind: 'optional';
62
- readonly inner: S;
63
- }
64
- export interface TupleSchema<Elements extends readonly Schema[] = readonly Schema[]> extends Annotated {
65
- readonly kind: 'tuple';
66
- readonly elements: Elements;
67
- readonly default?: unknown;
68
- }
69
- export interface UnionSchema<Members extends readonly Schema[] = readonly Schema[]> extends Annotated {
70
- readonly kind: 'union';
71
- readonly members: Members;
72
- readonly default?: unknown;
73
- }
74
- export interface TaggedUnionSchema<Key extends string = string, Branches extends Record<string, ObjectSchema> = Record<string, ObjectSchema>> extends Annotated {
75
- readonly kind: 'taggedUnion';
76
- readonly key: Key;
77
- readonly branches: Branches;
78
- readonly default?: unknown;
79
- }
80
- export type Schema = StringSchema | NumberSchema | BooleanSchema | UnknownSchema | LiteralSchema | ArraySchema | ObjectSchema | OptionalSchema | TupleSchema | UnionSchema | TaggedUnionSchema;
81
- type Simplify<T> = {
82
- [K in keyof T]: T[K];
83
- } & {};
84
- export type Infer<S> = S extends StringSchema ? string : S extends NumberSchema ? number : S extends BooleanSchema ? boolean : S extends UnknownSchema ? unknown : S extends LiteralSchema<infer T> ? T : S extends ArraySchema<infer E> ? ArraySchema extends S ? [] : Infer<E>[] : S extends ObjectSchema<infer Shape> ? ObjectSchema extends S ? object : Simplify<InferObject<Shape>> : S extends TupleSchema<infer Elements> ? InferTuple<Elements> : S extends OptionalSchema<infer Inner> ? OptionalSchema extends S ? OptionalSchema : Infer<Inner> | undefined : S extends UnionSchema<infer Members> ? InferUnion<Members> : S extends TaggedUnionSchema<infer Key, infer Branches> ? InferTaggedUnion<Key, Branches> : never;
85
- type InferObject<Shape> = {
86
- [K in keyof Shape as Shape[K] extends OptionalSchema ? never : K]: Infer<Shape[K]>;
87
- } & {
88
- [K in keyof Shape as Shape[K] extends OptionalSchema ? K : never]?: Infer<Shape[K]>;
89
- };
90
- type InferTuple<Elements> = Elements extends readonly [infer Head, ...infer Tail] ? [Infer<Head>, ...InferTuple<Tail>] : [];
91
- type InferUnion<Members> = Members extends readonly [infer Head, ...infer Tail] ? Infer<Head> | InferUnion<Tail> : never;
92
- type InferTaggedUnion<Key extends string, Branches> = {
93
- [Tag in keyof Branches & string]: {
94
- [K in Key]: Tag;
95
- } & Infer<Branches[Tag]>;
96
- }[keyof Branches & string];
97
- export type InferRead<S> = S extends ObjectSchema<infer Shape> ? ObjectSchema extends S ? object : Simplify<InferReadObject<Shape>> : Infer<S>;
98
- type Filled<S> = S extends {
99
- default: unknown;
100
- } ? true : S extends OptionalSchema ? false : S extends ObjectSchema<infer Shape> ? ObjectSchema extends S ? false : AllFilled<Shape> : false;
101
- type AllFilled<Shape> = false extends {
102
- [K in keyof Shape]: Shape[K] extends OptionalSchema ? true : Filled<Shape[K]>;
103
- }[keyof Shape] ? false : true;
104
- type InferReadObject<Shape> = {
105
- [K in keyof Shape as Filled<Shape[K]> extends true ? K : never]: InferRead<Shape[K]>;
106
- } & {
107
- [K in keyof Shape as Filled<Shape[K]> extends true ? never : K]?: InferRead<Shape[K]>;
108
- };
109
- export interface DisplayOptions {
110
- readonly title?: string;
111
- readonly description?: string;
112
- }
113
- export interface ScalarOptions<T> extends DisplayOptions {
114
- readonly default?: T;
115
- }
116
- export interface DefaultOption<T> extends DisplayOptions {
117
- readonly default?: T;
118
- }
119
- export interface MaskableOptions<T> extends ScalarOptions<T> {
120
- readonly mask?: boolean;
121
- }
122
- export interface StringOptions<T> extends MaskableOptions<T> {
123
- readonly minLength?: number;
124
- readonly maxLength?: number;
125
- readonly format?: Format;
126
- }
127
- export interface NumberOptions<T> extends MaskableOptions<T> {
128
- readonly min?: number;
129
- readonly max?: number;
130
- readonly integer?: boolean;
131
- readonly unit?: Unit;
132
- }
133
- export interface ArrayOptions<T> extends DefaultOption<T> {
134
- readonly minItems?: number;
135
- readonly maxItems?: number;
136
- }
137
- type Defaulted<S, D> = [D] extends [undefined] ? S : S & {
138
- readonly default: unknown;
139
- };
140
- export declare function string<D extends string | undefined = undefined>(options?: StringOptions<D>): Defaulted<StringSchema, D>;
141
- export declare function number<D extends number | undefined = undefined>(options?: NumberOptions<D>): Defaulted<NumberSchema, D>;
142
- export declare function boolean<D extends boolean | undefined = undefined>(options?: ScalarOptions<D>): Defaulted<BooleanSchema, D>;
143
- export declare function unknown(): UnknownSchema;
144
- export declare function literal<T extends Primitive, D extends T | undefined = undefined>(value: T, options?: ScalarOptions<D>): Defaulted<LiteralSchema<T>, D>;
145
- export declare function array<S extends Schema, D extends NoInfer<Infer<S>>[] | undefined = undefined>(element: S, options?: ArrayOptions<D>): Defaulted<ArraySchema<S>, D>;
146
- export declare function object<Shape extends Record<string, Schema>>(shape: Shape, options?: DefaultOption<never>): ObjectSchema<Shape>;
147
- export declare function tuple<Elements extends readonly Schema[], D extends NoInfer<Infer<TupleSchema<Elements>>> | undefined = undefined>(elements: [...Elements], options?: DefaultOption<D>): Defaulted<TupleSchema<Elements>, D>;
148
- export declare function optional<S extends Schema>(inner: S): OptionalSchema<S>;
149
- export declare function union<Members extends readonly Schema[], D extends NoInfer<Infer<UnionSchema<Members>>> | undefined = undefined>(members: [...Members], options?: DefaultOption<D>): Defaulted<UnionSchema<Members>, D>;
150
- export interface EnumEntry<T extends Primitive> {
151
- readonly value: T;
152
- readonly title?: string;
153
- readonly description?: string;
154
- }
155
- type EnumMembers<Entries extends readonly EnumEntry<Primitive>[]> = {
156
- [K in keyof Entries]: LiteralSchema<Entries[K]['value']>;
157
- };
158
- export declare function enumOf<const Entries extends readonly EnumEntry<Primitive>[], D extends Entries[number]['value'] | undefined = undefined>(entries: Entries, options?: DefaultOption<D>): Defaulted<UnionSchema<EnumMembers<Entries>>, D>;
159
- export declare function taggedUnion<Key extends string, Branches extends Record<string, ObjectSchema>, D extends NoInfer<Infer<TaggedUnionSchema<Key, Branches>>> | undefined = undefined>(key: Key, branches: Branches, options?: DefaultOption<D>): Defaulted<TaggedUnionSchema<Key, Branches>, D>;
160
- export declare function applyDefaults(schema: Schema, value: unknown): unknown;
161
- export declare function validate(schema: Schema, value: unknown, path: string): ReturnType<typeof err<SchemaError>> | null;
162
- export {};
163
- //# sourceMappingURL=core.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../../../runtime/schema/core.ts"],"names":[],"mappings":"AAKA,iBAAS,GAAG,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC;;;EAEvB;AAOD,MAAM,MAAM,WAAW,GAAG;IAAC,IAAI,EAAE,kBAAkB,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAC,CAAA;AACnF,eAAO,MAAM,WAAW;gCACM,MAAM,QAAQ,MAAM,KAAG,WAAW;CAK/D,CAAA;AAID,KAAK,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAA;AAa1C,MAAM,MAAM,MAAM,GAAG,KAAK,GAAG,UAAU,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,CAAA;AAsBlE,MAAM,MAAM,IAAI,GACZ,GAAG,GACH,IAAI,GACJ,GAAG,GACH,GAAG,GACH,GAAG,GACH,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,KAAK,GACL,IAAI,GACJ,GAAG,GACH,IAAI,GACJ,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,GAAG,GACH,KAAK,G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GAAG,SAAS,GAAG,SAAS,EAC1D,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,WAAW,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC,CAQ/F;AAED,wBAAgB,WAAW,CACzB,GAAG,SAAS,MAAM,EAClB,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,EAC7C,CAAC,SAAS,OAAO,CAAC,KAAK,CAAC,iBAAiB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,SAAS,GAAG,SAAS,EAElF,GAAG,EAAE,GAAG,EACR,QAAQ,EAAE,QAAQ,EAClB,OAAO,CAAC,EAAE,aAAa,CAAC,CAAC,CAAC,GACzB,SAAS,CAAC,iBAAiB,CAAC,GAAG,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC,CAShD;AAUD,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAuCrE;AAuBD,wBAAgB,QAAQ,CACtB,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,OAAO,EACd,IAAI,EAAE,MAAM,GACX,UAAU,CAAC,OAAO,GAAG,CAAC,WAAW,CAAC,CAAC,GAAG,IAAI,CAgI5C"}
@@ -1,306 +0,0 @@
1
- /* Core schema machinery: types, constructors, the validator, and
2
- * applyDefaults. Dependency-free so hosts (CLI, registries) can import it via
3
- * shared.ts without resolving mikro/* builtins; mikro/schema re-exports it and
4
- * adds the Result-returning parse(). */
5
- function err(error) {
6
- return { ok: false, error };
7
- }
8
- export const SchemaError = {
9
- ValidationFailed: (message, path) => ({
10
- name: 'ValidationFailed',
11
- message,
12
- path,
13
- }),
14
- };
15
- /* Defaults below a wholesale unit never fill: applyDefaults replaces the unit
16
- * whole, so only a unit-level default applies. Rejected where they are written
17
- * rather than at the validation that later misses the field. The walk stops at
18
- * a nested unit's own default, since that unit's constructor already cleared
19
- * everything under it. */
20
- function rejectInnerDefaults(node, path, unit, self) {
21
- if (node.default !== undefined) {
22
- throw new TypeError(`a default under ${unit} never applies; give ${self} itself a whole-value ` +
23
- `default instead (found at ${path})`);
24
- }
25
- if (node.kind === 'object') {
26
- const keys = Object.keys(node.shape);
27
- for (let i = 0; i < keys.length; i++) {
28
- rejectInnerDefaults(node.shape[keys[i]], `${path}.${keys[i]}`, unit, self);
29
- }
30
- }
31
- else if (node.kind === 'optional') {
32
- // optional() rejects an inner default itself, so this only reaches what it
33
- // wraps without reporting the same node twice.
34
- rejectInnerDefaults(node.inner, path, unit, self);
35
- }
36
- }
37
- /* Copies the annotations onto the node and rejects a `default` whose *shape*
38
- * the node would not accept, so an obviously wrong default fails where it is
39
- * written. Annotations live on the node so a schema serializes to JSON as-is.
40
- *
41
- * Constraints are deliberately not checked here, because validate() below does
42
- * not carry them: see its comment. A default that breaks its own bound is
43
- * caught by parseConfigSchema in shared.ts, which runs when the config is
44
- * packed, moments after this. */
45
- const ANNOTATION_KEYS = [
46
- 'title',
47
- 'description',
48
- 'mask',
49
- 'minLength',
50
- 'maxLength',
51
- 'min',
52
- 'max',
53
- 'integer',
54
- 'minItems',
55
- 'maxItems',
56
- 'format',
57
- 'unit',
58
- ];
59
- function annotate(node, options) {
60
- if (options === undefined)
61
- return node;
62
- const out = node;
63
- const src = options;
64
- for (let i = 0; i < ANNOTATION_KEYS.length; i++) {
65
- const key = ANNOTATION_KEYS[i];
66
- if (src[key] !== undefined)
67
- out[key] = src[key];
68
- }
69
- if (options.default !== undefined) {
70
- out.default = options.default;
71
- const result = validate(node, options.default, '');
72
- if (result !== null) {
73
- throw new TypeError(`schema default does not match the schema: ${result.error.message}`);
74
- }
75
- }
76
- return node;
77
- }
78
- export function string(options) {
79
- return annotate({ kind: 'string' }, options);
80
- }
81
- export function number(options) {
82
- return annotate({ kind: 'number' }, options);
83
- }
84
- export function boolean(options) {
85
- return annotate({ kind: 'boolean' }, options);
86
- }
87
- export function unknown() {
88
- return { kind: 'unknown' };
89
- }
90
- export function literal(value, options) {
91
- return annotate({ kind: 'literal', value }, options);
92
- }
93
- export function array(element, options) {
94
- rejectInnerDefaults(element, '[]', 'an array', 'the array');
95
- return annotate({ kind: 'array', element }, options);
96
- }
97
- export function object(shape, options) {
98
- if (options?.default !== undefined) {
99
- throw new TypeError("an object's defaults compose from its fields; declare defaults on the fields");
100
- }
101
- return annotate({ kind: 'object', shape }, options);
102
- }
103
- export function tuple(elements, options) {
104
- for (let i = 0; i < elements.length; i++) {
105
- rejectInnerDefaults(elements[i], `[${i}]`, 'a tuple', 'the tuple');
106
- }
107
- return annotate({ kind: 'tuple', elements }, options);
108
- }
109
- export function optional(inner) {
110
- if (inner.default !== undefined) {
111
- throw new TypeError('optional() cannot wrap a schema with a default');
112
- }
113
- return { kind: 'optional', inner };
114
- }
115
- export function union(members, options) {
116
- for (let i = 0; i < members.length; i++) {
117
- rejectInnerDefaults(members[i], `[${i}]`, 'a union', 'the union');
118
- }
119
- return annotate({ kind: 'union', members }, options);
120
- }
121
- export function enumOf(entries, options) {
122
- const members = entries.map((entry) => literal(entry.value, { title: entry.title, description: entry.description }));
123
- return annotate({ kind: 'union', members }, options);
124
- }
125
- export function taggedUnion(key, branches, options) {
126
- const tags = Object.keys(branches);
127
- for (let i = 0; i < tags.length; i++) {
128
- rejectInnerDefaults(branches[tags[i]], `.${tags[i]}`, 'a taggedUnion', 'the union');
129
- }
130
- return annotate({ kind: 'taggedUnion', key, branches }, options);
131
- }
132
- // ── Defaults ────────────────────────────────────────────────────────
133
- /* Builds the effective value: schema defaults with `value` layered over them.
134
- * Objects are structure and always materialize (recursing per field, unknown
135
- * keys dropped); every other node is replaced wholesale by a present value, so
136
- * defaults inside array elements or union branches are form hints, not fills.
137
- * The result is unvalidated — a missing required field stays missing for
138
- * parse() to report. */
139
- export function applyDefaults(schema, value) {
140
- switch (schema.kind) {
141
- case 'object': {
142
- // A present non-object stays as-is so validation rejects it; replacing
143
- // it with {} here would make `{mqtt: 42}` validate clean and never
144
- // record a configError.
145
- if (value !== undefined &&
146
- (typeof value !== 'object' || value === null || Array.isArray(value))) {
147
- return value;
148
- }
149
- const src = value === undefined ? {} : value;
150
- const out = {};
151
- const keys = Object.keys(schema.shape);
152
- for (let i = 0; i < keys.length; i++) {
153
- const key = keys[i];
154
- const field = schema.shape[key];
155
- // hasOwn, not indexing: a shape key like "constructor" must read as
156
- // absent, not as the inherited prototype member.
157
- const raw = Object.hasOwn(src, key) ? src[key] : undefined;
158
- if (field.kind === 'optional') {
159
- if (raw !== undefined)
160
- out[key] = raw;
161
- }
162
- else {
163
- const child = applyDefaults(field, raw);
164
- if (child !== undefined)
165
- out[key] = child;
166
- }
167
- }
168
- return out;
169
- }
170
- case 'array':
171
- if (value !== undefined)
172
- return value;
173
- return schema.default !== undefined ? schema.default : [];
174
- case 'unknown':
175
- case 'optional':
176
- return value;
177
- default:
178
- return value !== undefined ? value : schema.default;
179
- }
180
- }
181
- // ── Parse ───────────────────────────────────────────────────────────
182
- function typeOf(value) {
183
- if (value === null)
184
- return 'null';
185
- if (Array.isArray(value))
186
- return 'array';
187
- return typeof value;
188
- }
189
- /* Structure only: the shape of a value, never a constraint on it.
190
- *
191
- * Constraints (min, max, integer, minLength, maxLength, minItems, maxItems,
192
- * format) are enforced host-side in shared.ts, not here. This module is bundled
193
- * into the device, and a config schema never reaches a device: it is validated
194
- * where the registry runs and where the CLI packs. Carrying the checks here
195
- * charged every app that imports mikro/schema for enforcement it could not use,
196
- * measured at about 4 KB of heap on the `+ schema` bench checkpoint, most of it
197
- * the format expressions.
198
- *
199
- * The cost of that split, stated plainly: parse() on the device checks that a
200
- * number is a number, not that it is within its declared bounds. Constraints in
201
- * a schema are a config-authoring feature. */
202
- export function validate(schema, value, path) {
203
- switch (schema.kind) {
204
- case 'string':
205
- if (typeof value !== 'string')
206
- return err(SchemaError.ValidationFailed(`expected string, got ${typeOf(value)}`, path));
207
- return null;
208
- case 'number':
209
- if (typeof value !== 'number' || Number.isNaN(value))
210
- return err(SchemaError.ValidationFailed(`expected number, got ${typeOf(value)}`, path));
211
- return null;
212
- case 'boolean':
213
- if (typeof value !== 'boolean')
214
- return err(SchemaError.ValidationFailed(`expected boolean, got ${typeOf(value)}`, path));
215
- return null;
216
- case 'unknown':
217
- return null;
218
- case 'literal':
219
- if (value !== schema.value)
220
- return err(SchemaError.ValidationFailed(`expected ${JSON.stringify(schema.value)}, got ${JSON.stringify(value)}`, path));
221
- return null;
222
- case 'array': {
223
- if (!Array.isArray(value))
224
- return err(SchemaError.ValidationFailed(`expected array, got ${typeOf(value)}`, path));
225
- for (let i = 0; i < value.length; i++) {
226
- const result = validate(schema.element, value[i], `${path}[${i}]`);
227
- if (result !== null)
228
- return result;
229
- }
230
- return null;
231
- }
232
- case 'object': {
233
- if (typeof value !== 'object' || value === null || Array.isArray(value))
234
- return err(SchemaError.ValidationFailed(`expected object, got ${typeOf(value)}`, path));
235
- const obj = value;
236
- const keys = Object.keys(schema.shape);
237
- for (let i = 0; i < keys.length; i++) {
238
- const key = keys[i];
239
- const fieldSchema = schema.shape[key];
240
- const fieldPath = `${path}.${key}`;
241
- // hasOwn, like the taggedUnion dispatch: an inherited "constructor"
242
- // must not stand in for a field.
243
- if (fieldSchema.kind === 'optional') {
244
- if (Object.hasOwn(obj, key)) {
245
- const result = validate(fieldSchema, obj[key], fieldPath);
246
- if (result !== null)
247
- return result;
248
- }
249
- }
250
- else {
251
- if (!Object.hasOwn(obj, key))
252
- return err(SchemaError.ValidationFailed(`missing required field`, fieldPath));
253
- const result = validate(fieldSchema, obj[key], fieldPath);
254
- if (result !== null)
255
- return result;
256
- }
257
- }
258
- return null;
259
- }
260
- case 'tuple': {
261
- if (!Array.isArray(value))
262
- return err(SchemaError.ValidationFailed(`expected array, got ${typeOf(value)}`, path));
263
- if (value.length !== schema.elements.length)
264
- return err(SchemaError.ValidationFailed(`expected ${schema.elements.length} elements, got ${value.length}`, path));
265
- for (let i = 0; i < schema.elements.length; i++) {
266
- const result = validate(schema.elements[i], value[i], `${path}[${i}]`);
267
- if (result !== null)
268
- return result;
269
- }
270
- return null;
271
- }
272
- case 'optional': {
273
- if (value === undefined)
274
- return null;
275
- return validate(schema.inner, value, path);
276
- }
277
- case 'union': {
278
- for (let i = 0; i < schema.members.length; i++) {
279
- const result = validate(schema.members[i], value, path);
280
- if (result === null)
281
- return null;
282
- }
283
- return err(SchemaError.ValidationFailed(`value did not match any union member`, path));
284
- }
285
- case 'taggedUnion': {
286
- if (typeof value !== 'object' || value === null || Array.isArray(value))
287
- return err(SchemaError.ValidationFailed(`expected object, got ${typeOf(value)}`, path));
288
- const obj = value;
289
- const tag = obj[schema.key];
290
- if (tag === undefined)
291
- return err(SchemaError.ValidationFailed(`missing discriminator field`, `${path}.${schema.key}`));
292
- if (typeof tag !== 'string' && typeof tag !== 'number' && typeof tag !== 'boolean')
293
- return err(SchemaError.ValidationFailed(`expected primitive discriminator, got ${typeOf(tag)}`, `${path}.${schema.key}`));
294
- // hasOwn, not indexing: a tag like "constructor" must not resolve to
295
- // an inherited property and validate against garbage.
296
- const branch = Object.hasOwn(schema.branches, tag)
297
- ? schema.branches[tag]
298
- : undefined;
299
- if (branch === undefined)
300
- return err(SchemaError.ValidationFailed(`unknown tag ${JSON.stringify(tag)}`, `${path}.${schema.key}`));
301
- return validate(branch, value, path);
302
- }
303
- }
304
- return err(SchemaError.ValidationFailed(`unknown schema kind: ${schema.kind}`, path));
305
- }
306
- //# sourceMappingURL=core.js.map