@kaiko.io/rescript-deser 1.0.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/.dir-locals.el ADDED
@@ -0,0 +1,6 @@
1
+ ;;; Directory Local Variables
2
+ ;;; For more information see (info "(emacs) Directory Variables")
3
+
4
+ ( (rescript-mode . ((projectile-project-compilation-cmd . "make compile-rescript")
5
+ (indent-tabs-mode . nil)))
6
+ (nil . ((projectile-project-compilation-cmd . "make compile-rescript"))))
package/.gitlab-ci.yml ADDED
@@ -0,0 +1,52 @@
1
+ stages:
2
+ - compile
3
+
4
+ .x-compile: &with-compilation-script
5
+ image: node
6
+ script:
7
+ - make compile
8
+
9
+ .x-when-mr: &when-merge-request
10
+ interruptible: true
11
+ only:
12
+ - merge_requests
13
+
14
+ .x-when-stable: &when-in-stable
15
+ only:
16
+ - main
17
+
18
+ .x-when-stable-or-mr: &when-stable-or-merging
19
+ interruptible: true
20
+ only:
21
+ - main
22
+ - merge_requests
23
+
24
+ lint:
25
+ <<: *when-stable-or-merging
26
+ stage: compile
27
+ image: node
28
+ tags:
29
+ - docker
30
+ script:
31
+ - |
32
+ make format
33
+ touched=$(git status --porcelain | wc -l) || touched=0
34
+ if [ $touched -gt 0 ]; then
35
+ git status
36
+ exit 1
37
+ fi
38
+
39
+ check that we can compile the whole thing before merging:
40
+ <<: *with-compilation-script
41
+ <<: *when-merge-request
42
+ stage: compile
43
+ tags:
44
+ - docker
45
+
46
+ compile:
47
+ <<: *with-compilation-script
48
+ <<: *when-in-stable
49
+ interruptible: true
50
+ stage: compile
51
+ tags:
52
+ - docker
package/Makefile ADDED
@@ -0,0 +1,17 @@
1
+ PATH := ./node_modules/.bin/:$(PATH)
2
+
3
+ yarn.lock: bsconfig.json package.json
4
+ yarn install
5
+
6
+ compile: yarn.lock
7
+ [ -n "$(INSIDE_EMACS)" ] && (rescript build -with-deps | sed "s@ $(shell pwd)/@@") || rescript build -with-deps
8
+
9
+ format: yarn.lock
10
+ rescript format -all
11
+
12
+ .PHONY: compile format
13
+
14
+ RESCRIPT_FILES := $(shell find src -type f -name '*.res')
15
+
16
+ compile-rescript: $(RESCRIPT_FILES) yarn.lock
17
+ [ -n "$(INSIDE_EMACS)" ] && (rescript build -with-deps | sed "s@ $(shell pwd)/@@") || rescript build -with-deps
package/README.md ADDED
@@ -0,0 +1,75 @@
1
+ # bs-deser
2
+
3
+ Simple JSON deserializer for ReScript.
4
+
5
+ ## Description
6
+
7
+ This module allows you to create deserialize structures from JSON into an
8
+ internal type-safe type in ReScript. You don't (shouldn't) have to trust the
9
+ data you're getting from an API will always fit the expected shape and types.
10
+ So you might need to create a "parser" so that you can be sure the data is
11
+ type-correct.
12
+
13
+ ## Usage
14
+
15
+ You need to create a description of your data using ``JSON.Field.t``.
16
+
17
+ ```rescript
18
+ module MyData = {
19
+ @deriving(jsConverter)
20
+ type tag = [#a | #b | #c]
21
+
22
+ type t = {
23
+ id: string,
24
+ tags: array<tag>
25
+ }
26
+ }
27
+
28
+ module MyDataDeserializer = JSON.Deserializer({
29
+ type t = MyData.t
30
+ open JSON.Field
31
+
32
+ let fields = Object([
33
+ ("id", String),
34
+ ("tags", Array(variadicString(MyData.tagFromJs)))
35
+ ])
36
+ })
37
+ ```
38
+
39
+ This creates a function `MyDataDeserializer.fromJSON` with
40
+
41
+ ## Current limitations with recursive data
42
+
43
+ Currently we cannot deal with recursive data types. A type like
44
+
45
+ ```rescript
46
+ type rec Node<'t> = Leave('t) | (Branch(array<Node<'t>>)
47
+ ```
48
+
49
+ Cannot be automatically deserialized.
50
+
51
+
52
+ ## License
53
+
54
+ The MIT License
55
+
56
+ Copyright © 2022 Kaiko Systems GmbH and Collaborators
57
+
58
+ Permission is hereby granted, free of charge, to any person obtaining a copy
59
+ of this software and associated documentation files (the “Software”), to deal
60
+ in the Software without restriction, including without limitation the rights
61
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
62
+ copies of the Software, and to permit persons to whom the Software is
63
+ furnished to do so, subject to the following conditions:
64
+
65
+ The above copyright notice and this permission notice shall be included in all
66
+ copies or substantial portions of the Software.
67
+
68
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
69
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
70
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
71
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
72
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
73
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
74
+ SOFTWARE.
75
+
package/bsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "rescript-deser",
3
+ "sources": [
4
+ {
5
+ "dir": "src/",
6
+ "subdirs": true
7
+ }
8
+ ],
9
+ "suffix": ".js",
10
+ "reason": {
11
+ "react-jsx": 3
12
+ },
13
+ "bs-dependencies": [
14
+ "@kaiko.io/rescript-prelude"
15
+ ],
16
+ "package-specs": {
17
+ "module": "es6"
18
+ }
19
+ }
package/package.json ADDED
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "@kaiko.io/rescript-deser",
3
+ "version": "1.0.0",
4
+ "description": "Simple JSON deserializer for ReScript",
5
+ "repository": "https://gitlab.com/kaiko-systems/bs-deser.git",
6
+ "author": "Kaiko Systems <info@kaikosystems.com>",
7
+ "license": "MIT",
8
+ "private": false,
9
+ "dependencies": {
10
+ "@kaiko.io/rescript-prelude": "^3.0.1"
11
+ },
12
+ "devDependencies": {
13
+ "rescript": "^10.0.1"
14
+ }
15
+ }
package/src/JSON.res ADDED
@@ -0,0 +1,292 @@
1
+ open Prelude
2
+
3
+ module FieldValue = {
4
+ type t
5
+ external string: string => t = "%identity"
6
+ external int: int => t = "%identity"
7
+ external float: float => t = "%identity"
8
+ external boolean: bool => t = "%identity"
9
+ external array: array<t> => t = "%identity"
10
+ external object: Dict.t<t> => t = "%identity"
11
+ external mapping: Dict.t<t> => t = "%identity"
12
+ external any: 'a => t = "%identity"
13
+ @val external null: t = "undefined"
14
+
15
+ external asString: t => string = "%identity"
16
+ external asInt: t => int = "%identity"
17
+ external asFloat: t => float = "%identity"
18
+ external asBoolean: t => bool = "%identity"
19
+ external asArray: t => array<'a> = "%identity"
20
+ external asObject: t => 'a = "%identity"
21
+ }
22
+
23
+ exception TypeError(string)
24
+
25
+ @doc("The module type of a built deserializer which is suitable to add as a subparser.")
26
+ module type BuiltDeserializer = {
27
+ type t
28
+ let name: string
29
+ let fromJSON: Js.Json.t => result<t, string>
30
+ }
31
+
32
+ module Field = {
33
+ type rec t =
34
+ | Any
35
+ | String
36
+ | Int
37
+ | Float
38
+ | Boolean
39
+ | Array(t)
40
+ /// These SHOULD strings in ISO format, but we only validate the string
41
+ /// can be represented in Js.Date without spewing NaN all over the place;
42
+ /// Js.Date.fromString("xxx") returns an object that is mostly unusable.
43
+ ///
44
+ /// We also allow floats and then use Js.Date.fromFloat.
45
+ | Date
46
+ | Datetime // alias of Date
47
+
48
+ | Tuple(array<t>)
49
+ | Object(array<(string, t)>)
50
+ | Optional(t)
51
+ | OptionalWithDefault(t, FieldValue.t)
52
+ /// An arbitrary mapping from names to other arbitrary fields. The
53
+ /// difference with Object, is that you don't know the names of the
54
+ /// expected entries.
55
+ | Mapping(t)
56
+
57
+ | Deserializer(module(BuiltDeserializer))
58
+
59
+ /// A specialized Array of deserialized items that ignores unparsable
60
+ /// items and returns the valid collection. This saves the user from
61
+ /// writing 'Array(DefaultWhenInvalid(Optional(Deserializer(module(M)))))'
62
+ /// and then post-process the list of items with 'Array.keepSome'
63
+ | Collection(module(BuiltDeserializer))
64
+ | DefaultWhenInvalid(t, FieldValue.t)
65
+
66
+ // FIXME: this is used to add additional restrictions like variadictInt or
67
+ // variadicString; but I find it too type-unsafe. I might consider having
68
+ // a Constraints for this in the future.
69
+ | Morphism(t, FieldValue.t => FieldValue.t)
70
+
71
+ let usingString = (f: string => 'a, value) => value->FieldValue.asString->f->FieldValue.any
72
+ let usingInt = (f: int => 'a, value) => value->FieldValue.asInt->f->FieldValue.any
73
+ let usingFloat = (f: float => 'a, value) => value->FieldValue.asFloat->f->FieldValue.any
74
+ let usingBoolean = (f: bool => 'a, value) => value->FieldValue.asBoolean->f->FieldValue.any
75
+ let usingArray = (f: array<'a> => 'b, value) => value->FieldValue.asArray->f->FieldValue.any
76
+ let usingObject = (f: 'a => 'b, value) => value->FieldValue.asObject->f->FieldValue.any
77
+
78
+ let variadicInt = (hint: string, fromJs: int => option<'variadicType>) => Morphism(
79
+ Int,
80
+ usingInt(i => {
81
+ switch i->fromJs {
82
+ | Some(internalValue) => internalValue
83
+ | None =>
84
+ raise(TypeError(`This Int(${i->Int.toString}) not a valid value here. Hint: ${hint}`))
85
+ }
86
+ }),
87
+ )
88
+ let variadicString = (hint: string, fromJs: string => option<'variadicType>) => Morphism(
89
+ String,
90
+ usingString(i => {
91
+ switch i->fromJs {
92
+ | Some(internalValue) => internalValue
93
+ | None => raise(TypeError(`This String("${i}") not a valid value here. Hint: ${hint}`))
94
+ }
95
+ }),
96
+ )
97
+
98
+ let rec toString = (type_: t) =>
99
+ switch type_ {
100
+ | Any => "Any"
101
+ | String => "String"
102
+ | Int => "Integer"
103
+ | Float => "Float"
104
+ | Boolean => "Boolean"
105
+ | Datetime
106
+ | Date => "Date"
107
+ | Collection(m) => {
108
+ module M = unpack(m: BuiltDeserializer)
109
+ "Collection of " ++ M.name
110
+ }
111
+
112
+ | Array(t) => "Array of " ++ t->toString
113
+ | Tuple(bases) => `Tuple of (${bases->Array.map(toString)->Array.join(", ")})`
114
+ | Object(fields) => {
115
+ let desc = fields->Array.map(((field, t)) => `${field}: ${t->toString}`)->Array.join(", ")
116
+ `Object of {${desc}}`
117
+ }
118
+
119
+ | OptionalWithDefault(t, _)
120
+ | Optional(t) =>
121
+ "Null of " ++ t->toString
122
+ | Mapping(t) => `Mapping of ${t->toString}`
123
+ | Morphism(t, _) => t->toString ++ " to apply a morphism"
124
+ | Deserializer(m) => {
125
+ module M = unpack(m: BuiltDeserializer)
126
+ M.name
127
+ }
128
+
129
+ | DefaultWhenInvalid(t, _) => `Protected ${t->toString}`
130
+ }
131
+
132
+ let _taggedToString = (tagged: Js.Json.tagged_t) => {
133
+ switch tagged {
134
+ | Js.Json.JSONFalse => "Boolean(false)"
135
+ | Js.Json.JSONTrue => "Boolean(true)"
136
+ | Js.Json.JSONNull => "Null"
137
+ | Js.Json.JSONString(text) => `String("${text}")`
138
+ | Js.Json.JSONNumber(number) => `Number(${number->Float.toString})`
139
+ | Js.Json.JSONObject(obj) => `Object(${obj->Js.Json.stringifyAny->default("...")})`
140
+ | Js.Json.JSONArray(array) => `Array(${array->Js.Json.stringifyAny->default("...")})`
141
+ }
142
+ }
143
+
144
+ let rec extractValue = (values: Dict.t<Js.Json.t>, field: string, shape: t): FieldValue.t => {
145
+ switch values->Dict.get(field) {
146
+ | Some(value) => value->fromUntagged(shape)
147
+ | None =>
148
+ switch shape {
149
+ | DefaultWhenInvalid(_, _) => Js.Json.null->fromUntagged(shape)
150
+ | Optional(_) => Js.Json.null->fromUntagged(shape)
151
+ | OptionalWithDefault(_, default) => default
152
+ | _ => raise(TypeError(`Missing non-optional field '${field}'`))
153
+ }
154
+ }
155
+ }
156
+ and fromUntagged = (untagged: Js.Json.t, shape: t): FieldValue.t => {
157
+ switch (shape, untagged->Js.Json.classify) {
158
+ | (Any, _) => untagged->FieldValue.any
159
+ | (String, Js.Json.JSONString(text)) => FieldValue.string(text)
160
+ | (Int, Js.Json.JSONNumber(number)) => FieldValue.int(number->Float.toInt)
161
+ | (Float, Js.Json.JSONNumber(number)) => FieldValue.float(number)
162
+ | (Boolean, Js.Json.JSONTrue) => FieldValue.boolean(true)
163
+ | (Boolean, Js.Json.JSONFalse) => FieldValue.boolean(false)
164
+ | (Tuple(bases), Js.Json.JSONArray(items)) => {
165
+ let lenbases = bases->Array.length
166
+ let lenitems = items->Array.length
167
+ if lenbases == lenitems {
168
+ let values = Array.zipBy(items, bases, fromUntagged)
169
+ values->FieldValue.array
170
+ } else {
171
+ raise(
172
+ TypeError(`Expecting ${lenbases->Int.toString} items, got ${lenitems->Int.toString}`),
173
+ )
174
+ }
175
+ }
176
+
177
+ | (Datetime, Js.Json.JSONString(s))
178
+ | (Date, Js.Json.JSONString(s)) => {
179
+ let r = Js.Date.fromString(s)
180
+ if r->Js.Date.getDate->Js.Float.isNaN {
181
+ raise(TypeError(`Invalid date ${s}`))
182
+ }
183
+ r->FieldValue.any
184
+ }
185
+
186
+ | (Datetime, Js.Json.JSONNumber(f))
187
+ | (Date, Js.Json.JSONNumber(f)) => {
188
+ let r = Js.Date.fromFloat(f)
189
+ if r->Js.Date.getDate->Js.Float.isNaN {
190
+ raise(TypeError(`Invalid date ${f->Js.Float.toString}`))
191
+ }
192
+ r->FieldValue.any
193
+ }
194
+
195
+ | (Array(shape), Js.Json.JSONArray(items)) =>
196
+ FieldValue.array(items->Array.map(item => item->fromUntagged(shape)))
197
+ | (Mapping(f), Js.Json.JSONObject(values)) =>
198
+ values->Dict.mapValues(v => v->fromUntagged(f))->FieldValue.mapping
199
+ | (Object(fields), Js.Json.JSONObject(values)) =>
200
+ FieldValue.object(
201
+ fields
202
+ ->Array.map(((field, shape)) => {
203
+ let value = switch extractValue(values, field, shape) {
204
+ | value => value
205
+ | exception TypeError(msg) => raise(TypeError(`Field "${field}": ${msg}`))
206
+ }
207
+ (field, value)
208
+ })
209
+ ->Dict.fromArray,
210
+ )
211
+
212
+ | (OptionalWithDefault(_, value), Js.Json.JSONNull) => value
213
+ | (OptionalWithDefault(shape, _), _) => untagged->fromUntagged(shape)
214
+ | (Optional(_), Js.Json.JSONNull) => FieldValue.null
215
+ | (Optional(shape), _) => untagged->fromUntagged(shape)
216
+ | (Morphism(shape, f), _) => untagged->fromUntagged(shape)->f->FieldValue.any
217
+
218
+ | (Collection(m), Js.Json.JSONArray(items)) => {
219
+ module M = unpack(m: BuiltDeserializer)
220
+ items
221
+ ->Array.map(M.fromJSON)
222
+ ->Array.map(Result.warn)
223
+ ->Array.keepSome
224
+ ->Array.map(FieldValue.any)
225
+ ->FieldValue.array
226
+ }
227
+
228
+ | (Deserializer(m), _) => {
229
+ module M = unpack(m: BuiltDeserializer)
230
+ switch untagged->M.fromJSON {
231
+ | Ok(res) => res->FieldValue.any
232
+ | Error(msg) => raise(TypeError(msg))
233
+ }
234
+ }
235
+
236
+ | (DefaultWhenInvalid(t, default), _) =>
237
+ switch untagged->fromUntagged(t) {
238
+ | res => res
239
+ | exception TypeError(msg) => {
240
+ Js.Console.warn2("Detected and ignore (with default): ", msg)
241
+ default
242
+ }
243
+ }
244
+
245
+ | (expected, actual) =>
246
+ raise(TypeError(`Expected ${expected->toString}, but got ${actual->_taggedToString} instead`))
247
+ }
248
+ }
249
+ }
250
+
251
+ module type Serializable = {
252
+ type t
253
+ let fields: Field.t
254
+ }
255
+
256
+ module Deserializer = (S: Serializable) => {
257
+ type t = S.t
258
+ let fields = S.fields
259
+ %%private(let (loc, _f) = __LOC_OF__(module(S: Serializable)))
260
+ let name = `Deserializer ${__MODULE__}, ${loc}`
261
+
262
+ %%private(external _toNativeType: FieldValue.t => t = "%identity")
263
+
264
+ /// Parse a `Js.Json.t` into `result<t, string>`
265
+ let fromJSON = (json: Js.Json.t): result<t, _> => {
266
+ switch json->Field.fromUntagged(fields) {
267
+ | res => Ok(res->_toNativeType)
268
+ | exception TypeError(e) => Error(e)
269
+ }
270
+ }
271
+ }
272
+
273
+ module Test = {
274
+ type appointment = {
275
+ note: string,
276
+ date: Js.Date.t,
277
+ }
278
+ module Appointment = Deserializer({
279
+ type t = appointment
280
+ open Field
281
+
282
+ let fields = Object([("note", String), ("date", Date)])
283
+ })
284
+
285
+ type foo = array<appointment>
286
+ module Foo = Deserializer({
287
+ type t = foo
288
+ open Field
289
+
290
+ let fields = DefaultWhenInvalid(Array(Deserializer(module(Appointment))), []->FieldValue.array)
291
+ })
292
+ }