-
Notifications
You must be signed in to change notification settings - Fork 10
/
transit.cljs
425 lines (371 loc) · 12.7 KB
/
transit.cljs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
;; Vendored copy of as of yet unreleased transit-cljs, with support for :default tag handlers
;; https://github.com/lambdaisland/transit-cljs/blob/37e25db4eade6b92c95f1319d93d3447de2ade22/src/cognitect/transit.cljs
;; Arne - 2018-11-30
;; Copyright 2014-2018 Cognitect. All Rights Reserved.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS-IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns kaocha.cljs.cognitect.transit
(:refer-clojure :exclude [integer? uuid uuid? uri?])
(:require [com.cognitect.transit :as t]
[com.cognitect.transit.types :as ty]
[com.cognitect.transit.eq :as eq])
(:import [goog.math Long]))
;; patch cljs.core/UUID IEquiv
(extend-type UUID
IEquiv
(-equiv [this other]
(cond
(instance? UUID other)
(identical? (.-uuid this) (.-uuid other))
(instance? ty/UUID other)
(identical? (.-uuid this) (.toString other))
:else false)))
(extend-protocol IComparable
UUID
(-compare [this other]
(if (or (instance? UUID other)
(instance? ty/UUID other))
(compare (.toString this) (.toString other))
(throw (js/Error. (str "Cannot compare " this " to " other)))))
ty/UUID
(-compare [this other]
(if (or (instance? UUID other)
(instance? ty/UUID other))
(compare (.toString this) (.toString other))
(throw (js/Error. (str "Cannot compare " this " to " other))))))
(extend-protocol IEquiv
Long
(-equiv [this other]
(.equiv this other))
ty/UUID
(-equiv [this other]
(if (instance? UUID other)
(-equiv other this)
(.equiv this other)))
ty/TaggedValue
(-equiv [this other]
(.equiv this other)))
(extend-protocol IHash
Long
(-hash [this]
(eq/hashCode this))
ty/UUID
(-hash [this]
(hash (.toString this)))
ty/TaggedValue
(-hash [this]
(eq/hashCode this)))
(extend-type ty/UUID
IPrintWithWriter
(-pr-writer [uuid writer _]
(-write writer (str "#uuid \"" (.toString uuid) "\""))))
(defn ^:no-doc opts-merge [a b]
(doseq [k (js-keys b)]
(let [v (aget b k)]
(aset a k v)))
a)
(deftype ^:no-doc MapBuilder []
Object
(init [_ node] (transient {}))
(add [_ m k v node] (assoc! m k v))
(finalize [_ m node] (persistent! m))
(fromArray [_ arr node] (cljs.core/PersistentArrayMap.fromArray arr true true)))
(deftype ^:no-doc VectorBuilder []
Object
(init [_ node] (transient []))
(add [_ v x node] (conj! v x))
(finalize [_ v node] (persistent! v))
(fromArray [_ arr node] (cljs.core/PersistentVector.fromArray arr true)))
(defn reader
"Return a transit reader. type may be either :json or :json-verbose.
opts may be a map optionally containing a :handlers entry. The value
of :handlers should be map from string tag to a decoder function of one
argument which returns the in-memory representation of the semantic transit
value. If a :default handler is provided, it will be used when no matching
read handler can be found."
([type] (reader type nil))
([type opts]
(t/reader (name type)
(opts-merge
#js {:handlers
(clj->js
(merge
{"$" (fn [v] (symbol v))
":" (fn [v] (keyword v))
"set" (fn [v] (into #{} v))
"list" (fn [v] (into () (.reverse v)))
"cmap" (fn [v]
(loop [i 0 ret (transient {})]
(if (< i (alength v))
(recur (+ i 2)
(assoc! ret (aget v i) (aget v (inc i))))
(persistent! ret))))
"with-meta"
(fn [v] (with-meta (aget v 0) (aget v 1)))}
(dissoc (:handlers opts) :default)))
:defaultHandler (-> opts :handlers :default)
:mapBuilder (MapBuilder.)
:arrayBuilder (VectorBuilder.)
:prefersStrings false}
(clj->js (dissoc opts :handlers))))))
(defn read
"Read a transit encoded string into ClojureScript values given a
transit reader."
[r str]
(.read r str))
(deftype ^:no-doc KeywordHandler []
Object
(tag [_ v] ":")
(rep [_ v] (.-fqn v))
(stringRep [_ v] (.-fqn v)))
(deftype ^:no-doc SymbolHandler []
Object
(tag [_ v] "$")
(rep [_ v] (.-str v))
(stringRep [_ v] (.-str v)))
(deftype ^:no-doc ListHandler []
Object
(tag [_ v] "list")
(rep [_ v]
(let [ret #js []]
(doseq [x v] (.push ret x))
(t/tagged "array" ret)))
(stringRep [_ v] nil))
(deftype ^:no-doc MapHandler []
Object
(tag [_ v] "map")
(rep [_ v] v)
(stringRep [_ v] nil))
(deftype ^:no-doc SetHandler []
Object
(tag [_ v] "set")
(rep [_ v]
(let [ret #js []]
(doseq [x v] (.push ret x))
(t/tagged "array" ret)))
(stringRep [v] nil))
(deftype ^:no-doc VectorHandler []
Object
(tag [_ v] "array")
(rep [_ v]
(let [ret #js []]
(doseq [x v] (.push ret x))
ret))
(stringRep [_ v] nil))
(deftype ^:no-doc UUIDHandler []
Object
(tag [_ v] "u")
(rep [_ v] (.-uuid v))
(stringRep [this v] (.rep this v)))
(deftype ^:no-doc WithMeta [value meta])
(deftype ^:no-doc WithMetaHandler []
Object
(tag [_ v] "with-meta")
(rep [_ v]
(t/tagged "array" #js [(.-value v) (.-meta v)]))
(stringRep [_ v] nil))
(defn writer
"Return a transit writer. type maybe either :json or :json-verbose.
opts is a map with the following optional keys:
:handlers - a map of type constructors to handler instances. Can optionally
provide a :default write handler which will be used if no
matching handler can be found.
:transform - a function of one argument returning a transformed value. Will
be invoked on a value before it is written."
([type] (writer type nil))
([type opts]
(let [keyword-handler (KeywordHandler.)
symbol-handler (SymbolHandler.)
list-handler (ListHandler.)
map-handler (MapHandler.)
set-handler (SetHandler.)
vector-handler (VectorHandler.)
uuid-handler (UUIDHandler.)
meta-handler (WithMetaHandler.)
handlers
(merge
{cljs.core/Keyword keyword-handler
cljs.core/Symbol symbol-handler
cljs.core/Range list-handler
cljs.core/List list-handler
cljs.core/Cons list-handler
cljs.core/EmptyList list-handler
cljs.core/LazySeq list-handler
cljs.core/RSeq list-handler
cljs.core/IndexedSeq list-handler
cljs.core/ChunkedCons list-handler
cljs.core/ChunkedSeq list-handler
cljs.core/PersistentQueueSeq list-handler
cljs.core/PersistentQueue list-handler
cljs.core/PersistentArrayMapSeq list-handler
cljs.core/PersistentTreeMapSeq list-handler
cljs.core/NodeSeq list-handler
cljs.core/ArrayNodeSeq list-handler
cljs.core/KeySeq list-handler
cljs.core/ValSeq list-handler
cljs.core/PersistentArrayMap map-handler
cljs.core/PersistentHashMap map-handler
cljs.core/PersistentTreeMap map-handler
cljs.core/PersistentHashSet set-handler
cljs.core/PersistentTreeSet set-handler
cljs.core/PersistentVector vector-handler
cljs.core/Subvec vector-handler
cljs.core/UUID uuid-handler
WithMeta meta-handler}
(when (exists? cljs.core/Eduction)
{^:cljs.analyzer/no-resolve cljs.core/Eduction list-handler})
(when (exists? cljs.core/Repeat)
{^:cljs.analyzer/no-resolve cljs.core/Repeat list-handler})
(when (exists? cljs.core/MapEntry)
{^:cljs.analyzer/no-resolve cljs.core/MapEntry vector-handler})
(:handlers opts))]
(t/writer (name type)
(opts-merge
#js {:objectBuilder
(fn [m kfn vfn]
(reduce-kv
(fn [obj k v]
(doto obj (.push (kfn k) (vfn v))))
#js ["^ "] m))
:handlers
(specify handlers
Object
(forEach
([coll f]
(doseq [[k v] coll]
(if (= :default k)
(f v "default")
(f v k))))))
:unpack
(fn [x]
(if (instance? cljs.core/PersistentArrayMap x)
(.-arr x)
false))}
(clj->js (dissoc opts :handlers)))))))
(defn write
"Encode an object into a transit string given a transit writer."
[w o]
(.write w o))
(defn read-handler
"Construct a read handler. Implemented as identity, exists primarily
for API compatiblity with transit-clj"
[from-rep]
from-rep)
(defn write-handler
"Creates a transit write handler whose tag, rep,
stringRep, and verboseWriteHandler methods
invoke the provided fns."
([tag-fn rep-fn]
(write-handler tag-fn rep-fn nil nil))
([tag-fn rep-fn str-rep-fn]
(write-handler tag-fn rep-fn str-rep-fn nil))
([tag-fn rep-fn str-rep-fn verbose-handler-fn]
(reify
Object
(tag [_ o] (tag-fn o))
(rep [_ o] (rep-fn o))
(stringRep [_ o] (when str-rep-fn (str-rep-fn o)))
(getVerboseHandler [_] (when verbose-handler-fn (verbose-handler-fn))))))
;; =============================================================================
;; Constructors & Predicates
(defn tagged-value
"Construct a tagged value. tag must be a string and rep can
be any transit encodeable value."
[tag rep]
(ty/taggedValue tag rep))
(defn tagged-value?
"Returns true if x is a transit tagged value, false otherwise."
[x]
(ty/isTaggedValue x))
(defn integer
"Construct a transit integer value. Returns JavaScript number if
in the 53bit integer range, a goog.math.Long instance if above. s
may be a string or a JavaScript number."
[s]
(ty/intValue s))
(defn integer?
"Returns true if x is an integer value between the 53bit and 64bit
range, false otherwise."
[x]
(ty/isInteger x))
(defn bigint
"Construct a big integer from a string."
[s]
(ty/bigInteger s))
(defn bigint?
"Returns true if x is a transit big integer value, false otherwise."
[x]
(ty/isBigInteger x))
(defn bigdec
"Construct a big decimal from a string."
[s]
(ty/bigDecimalValue s))
(defn bigdec?
"Returns true if x is a transit big decimal value, false otherwise."
[x]
(ty/isBigDecimal x))
(defn uri
"Construct a URI from a string."
[s]
(ty/uri s))
(defn uri?
"Returns true if x is a transit URI value, false otherwise."
[x]
(ty/isURI x))
(defn uuid
"Construct a UUID from a string."
[s]
(ty/uuid s))
(defn uuid?
"Returns true if x is a transit UUID value, false otherwise."
[x]
(or (ty/isUUID x) (instance? UUID x)))
(defn binary
"Construct a transit binary value. s should be base64 encoded
string."
[s]
(ty/binary s))
(defn binary?
"Returns true if x is a transit binary value, false otherwise."
[x]
(ty/isBinary x))
(defn quoted
"Construct a quoted transit value. x should be a transit
encodeable value."
[x]
(ty/quoted x))
(defn quoted?
"Returns true if x is a transit quoted value, false otherwise."
[x]
(ty/isQuoted x))
(defn link
"Construct a transit link value. x should be an IMap instance
containing at a minimum the following keys: :href, :rel. It
may optionall include :name, :render, and :prompt. :href must
be a transit URI, all other values are strings, and :render must
be either :image or :link."
[x]
(ty/link x))
(defn link?
"Returns true if x a transit link value, false if otherwise."
[x]
(ty/isLink x))
(defn write-meta
"For :transform. Will write any metadata present on the value."
[x]
(if (implements? IMeta x)
(let [m (-meta ^not-native x)]
(if-not (nil? m)
(WithMeta. (-with-meta ^not-native x nil) m)
x))
x))