PyLD 2.0.4__py3-none-any.whl

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.
c14n/Canonicalize.py ADDED
@@ -0,0 +1,474 @@
1
+ ##############################################################################
2
+ # #
3
+ # Copyright 2006-2019 WebPKI.org (http://webpki.org). #
4
+ # #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); #
6
+ # you may not use this file except in compliance with the License. #
7
+ # You may obtain a copy of the License at #
8
+ # #
9
+ # https://www.apache.org/licenses/LICENSE-2.0 #
10
+ # #
11
+ # Unless required by applicable law or agreed to in writing, software #
12
+ # distributed under the License is distributed on an "AS IS" BASIS, #
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
14
+ # See the License for the specific language governing permissions and #
15
+ # limitations under the License. #
16
+ # #
17
+ ##############################################################################
18
+
19
+ #################################################
20
+ # JCS compatible JSON serializer for Python 3.x #
21
+ #################################################
22
+
23
+ import re
24
+
25
+ from c14n.NumberToJson import convert2Es6Format
26
+
27
+ try:
28
+ from _json import encode_basestring_ascii as c_encode_basestring_ascii
29
+ except ImportError:
30
+ c_encode_basestring_ascii = None
31
+ try:
32
+ from _json import encode_basestring as c_encode_basestring
33
+ except ImportError:
34
+ c_encode_basestring = None
35
+ try:
36
+ from _json import make_encoder as c_make_encoder
37
+ except ImportError:
38
+ c_make_encoder = None
39
+
40
+ ESCAPE = re.compile(r'[\x00-\x1f\\"\b\f\n\r\t]')
41
+ ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
42
+ HAS_UTF8 = re.compile(b'[\x80-\xff]')
43
+ ESCAPE_DCT = {
44
+ '\\': '\\\\',
45
+ '"': '\\"',
46
+ '\b': '\\b',
47
+ '\f': '\\f',
48
+ '\n': '\\n',
49
+ '\r': '\\r',
50
+ '\t': '\\t',
51
+ }
52
+ for i in range(0x20):
53
+ ESCAPE_DCT.setdefault(chr(i), '\\u{0:04x}'.format(i))
54
+ #ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
55
+
56
+ INFINITY = float('inf')
57
+
58
+ def py_encode_basestring(s):
59
+ """Return a JSON representation of a Python string
60
+
61
+ """
62
+ def replace(match):
63
+ return ESCAPE_DCT[match.group(0)]
64
+ return '"' + ESCAPE.sub(replace, s) + '"'
65
+
66
+
67
+ encode_basestring = (c_encode_basestring or py_encode_basestring)
68
+
69
+ def py_encode_basestring_ascii(s):
70
+ """Return an ASCII-only JSON representation of a Python string
71
+
72
+ """
73
+ def replace(match):
74
+ s = match.group(0)
75
+ try:
76
+ return ESCAPE_DCT[s]
77
+ except KeyError:
78
+ n = ord(s)
79
+ if n < 0x10000:
80
+ return '\\u{0:04x}'.format(n)
81
+ #return '\\u%04x' % (n,)
82
+ else:
83
+ # surrogate pair
84
+ n -= 0x10000
85
+ s1 = 0xd800 | ((n >> 10) & 0x3ff)
86
+ s2 = 0xdc00 | (n & 0x3ff)
87
+ return '\\u{0:04x}\\u{1:04x}'.format(s1, s2)
88
+ return '"' + ESCAPE_ASCII.sub(replace, s) + '"'
89
+
90
+
91
+ encode_basestring_ascii = (
92
+ c_encode_basestring_ascii or py_encode_basestring_ascii)
93
+
94
+ class JSONEncoder(object):
95
+ """Extensible JSON <http://json.org> encoder for Python data structures.
96
+
97
+ Supports the following objects and types by default:
98
+
99
+ +-------------------+---------------+
100
+ | Python | JSON |
101
+ +===================+===============+
102
+ | dict | object |
103
+ +-------------------+---------------+
104
+ | list, tuple | array |
105
+ +-------------------+---------------+
106
+ | str | string |
107
+ +-------------------+---------------+
108
+ | int, float | number |
109
+ +-------------------+---------------+
110
+ | True | true |
111
+ +-------------------+---------------+
112
+ | False | false |
113
+ +-------------------+---------------+
114
+ | None | null |
115
+ +-------------------+---------------+
116
+
117
+ To extend this to recognize other objects, subclass and implement a
118
+ ``.default()`` method with another method that returns a serializable
119
+ object for ``o`` if possible, otherwise it should call the superclass
120
+ implementation (to raise ``TypeError``).
121
+
122
+ """
123
+ item_separator = ', '
124
+ key_separator = ': '
125
+ def __init__(self, *, skipkeys=False, ensure_ascii=False,
126
+ check_circular=True, allow_nan=True, sort_keys=True,
127
+ indent=None, separators=(',', ':'), default=None):
128
+ """Constructor for JSONEncoder, with sensible defaults.
129
+
130
+ If skipkeys is false, then it is a TypeError to attempt
131
+ encoding of keys that are not str, int, float or None. If
132
+ skipkeys is True, such items are simply skipped.
133
+
134
+ If ensure_ascii is true, the output is guaranteed to be str
135
+ objects with all incoming non-ASCII characters escaped. If
136
+ ensure_ascii is false, the output can contain non-ASCII characters.
137
+
138
+ If check_circular is true, then lists, dicts, and custom encoded
139
+ objects will be checked for circular references during encoding to
140
+ prevent an infinite recursion (which would cause an OverflowError).
141
+ Otherwise, no such check takes place.
142
+
143
+ If allow_nan is true, then NaN, Infinity, and -Infinity will be
144
+ encoded as such. This behavior is not JSON specification compliant,
145
+ but is consistent with most JavaScript based encoders and decoders.
146
+ Otherwise, it will be a ValueError to encode such floats.
147
+
148
+ If sort_keys is true, then the output of dictionaries will be
149
+ sorted by key; this is useful for regression tests to ensure
150
+ that JSON serializations can be compared on a day-to-day basis.
151
+
152
+ If indent is a non-negative integer, then JSON array
153
+ elements and object members will be pretty-printed with that
154
+ indent level. An indent level of 0 will only insert newlines.
155
+ None is the most compact representation.
156
+
157
+ If specified, separators should be an (item_separator, key_separator)
158
+ tuple. The default is (', ', ': ') if *indent* is ``None`` and
159
+ (',', ': ') otherwise. To get the most compact JSON representation,
160
+ you should specify (',', ':') to eliminate whitespace.
161
+
162
+ If specified, default is a function that gets called for objects
163
+ that can't otherwise be serialized. It should return a JSON encodable
164
+ version of the object or raise a ``TypeError``.
165
+
166
+ """
167
+
168
+ self.skipkeys = skipkeys
169
+ self.ensure_ascii = ensure_ascii
170
+ self.check_circular = check_circular
171
+ self.allow_nan = allow_nan
172
+ self.sort_keys = sort_keys
173
+ self.indent = indent
174
+ if separators is not None:
175
+ self.item_separator, self.key_separator = separators
176
+ elif indent is not None:
177
+ self.item_separator = ','
178
+ if default is not None:
179
+ self.default = default
180
+
181
+ def default(self, o):
182
+ """Implement this method in a subclass such that it returns
183
+ a serializable object for ``o``, or calls the base implementation
184
+ (to raise a ``TypeError``).
185
+
186
+ For example, to support arbitrary iterators, you could
187
+ implement default like this::
188
+
189
+ def default(self, o):
190
+ try:
191
+ iterable = iter(o)
192
+ except TypeError:
193
+ pass
194
+ else:
195
+ return list(iterable)
196
+ # Let the base class default method raise the TypeError
197
+ return JSONEncoder.default(self, o)
198
+
199
+ """
200
+ raise TypeError("Object of type '%s' is not JSON serializable" %
201
+ o.__class__.__name__)
202
+
203
+ def encode(self, o):
204
+ """Return a JSON string representation of a Python data structure.
205
+
206
+ >>> from json.encoder import JSONEncoder
207
+ >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
208
+ '{"foo": ["bar", "baz"]}'
209
+
210
+ """
211
+ # This is for extremely simple cases and benchmarks.
212
+ if isinstance(o, str):
213
+ if self.ensure_ascii:
214
+ return encode_basestring_ascii(o)
215
+ else:
216
+ return encode_basestring(o)
217
+ # This doesn't pass the iterator directly to ''.join() because the
218
+ # exceptions aren't as detailed. The list call should be roughly
219
+ # equivalent to the PySequence_Fast that ''.join() would do.
220
+ chunks = self.iterencode(o, _one_shot=False)
221
+ if not isinstance(chunks, (list, tuple)):
222
+ chunks = list(chunks)
223
+ return ''.join(chunks)
224
+
225
+ def iterencode(self, o, _one_shot=False):
226
+ """Encode the given object and yield each string
227
+ representation as available.
228
+
229
+ For example::
230
+
231
+ for chunk in JSONEncoder().iterencode(bigobject):
232
+ mysocket.write(chunk)
233
+
234
+ """
235
+ if self.check_circular:
236
+ markers = {}
237
+ else:
238
+ markers = None
239
+ if self.ensure_ascii:
240
+ _encoder = encode_basestring_ascii
241
+ else:
242
+ _encoder = encode_basestring
243
+
244
+ def floatstr(o, allow_nan=self.allow_nan,
245
+ _repr=float.__repr__, _inf=INFINITY, _neginf=-INFINITY):
246
+ # Check for specials. Note that this type of test is processor
247
+ # and/or platform-specific, so do tests which don't depend on the
248
+ # internals.
249
+
250
+ if o != o:
251
+ text = 'NaN'
252
+ elif o == _inf:
253
+ text = 'Infinity'
254
+ elif o == _neginf:
255
+ text = '-Infinity'
256
+ else:
257
+ return _repr(o)
258
+
259
+ if not allow_nan:
260
+ raise ValueError(
261
+ "Out of range float values are not JSON compliant: " +
262
+ repr(o))
263
+
264
+ return text
265
+
266
+
267
+ if (_one_shot and c_make_encoder is not None
268
+ and self.indent is None):
269
+ _iterencode = c_make_encoder(
270
+ markers, self.default, _encoder, self.indent,
271
+ self.key_separator, self.item_separator, self.sort_keys,
272
+ self.skipkeys, self.allow_nan)
273
+ else:
274
+ _iterencode = _make_iterencode(
275
+ markers, self.default, _encoder, self.indent, floatstr,
276
+ self.key_separator, self.item_separator, self.sort_keys,
277
+ self.skipkeys, _one_shot)
278
+ return _iterencode(o, 0)
279
+
280
+ def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
281
+ _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
282
+ ## HACK: hand-optimized bytecode; turn globals into locals
283
+ ValueError=ValueError,
284
+ dict=dict,
285
+ float=float,
286
+ id=id,
287
+ int=int,
288
+ isinstance=isinstance,
289
+ list=list,
290
+ str=str,
291
+ tuple=tuple,
292
+ _intstr=int.__str__,
293
+ ):
294
+
295
+ if _indent is not None and not isinstance(_indent, str):
296
+ _indent = ' ' * _indent
297
+
298
+ def _iterencode_list(lst, _current_indent_level):
299
+ if not lst:
300
+ yield '[]'
301
+ return
302
+ if markers is not None:
303
+ markerid = id(lst)
304
+ if markerid in markers:
305
+ raise ValueError("Circular reference detected")
306
+ markers[markerid] = lst
307
+ buf = '['
308
+ if _indent is not None:
309
+ _current_indent_level += 1
310
+ newline_indent = '\n' + _indent * _current_indent_level
311
+ separator = _item_separator + newline_indent
312
+ buf += newline_indent
313
+ else:
314
+ newline_indent = None
315
+ separator = _item_separator
316
+ first = True
317
+ for value in lst:
318
+ if first:
319
+ first = False
320
+ else:
321
+ buf = separator
322
+ if isinstance(value, str):
323
+ yield buf + _encoder(value)
324
+ elif value is None:
325
+ yield buf + 'null'
326
+ elif value is True:
327
+ yield buf + 'true'
328
+ elif value is False:
329
+ yield buf + 'false'
330
+ elif isinstance(value, int):
331
+ # Subclasses of int/float may override __str__, but we still
332
+ # want to encode them as integers/floats in JSON. One example
333
+ # within the standard library is IntEnum.
334
+ yield buf + convert2Es6Format(value)
335
+ elif isinstance(value, float):
336
+ # see comment above for int
337
+ yield buf + convert2Es6Format(value)
338
+ else:
339
+ yield buf
340
+ if isinstance(value, (list, tuple)):
341
+ chunks = _iterencode_list(value, _current_indent_level)
342
+ elif isinstance(value, dict):
343
+ chunks = _iterencode_dict(value, _current_indent_level)
344
+ else:
345
+ chunks = _iterencode(value, _current_indent_level)
346
+ yield from chunks
347
+ if newline_indent is not None:
348
+ _current_indent_level -= 1
349
+ yield '\n' + _indent * _current_indent_level
350
+ yield ']'
351
+ if markers is not None:
352
+ del markers[markerid]
353
+
354
+ def _iterencode_dict(dct, _current_indent_level):
355
+ if not dct:
356
+ yield '{}'
357
+ return
358
+ if markers is not None:
359
+ markerid = id(dct)
360
+ if markerid in markers:
361
+ raise ValueError("Circular reference detected")
362
+ markers[markerid] = dct
363
+ yield '{'
364
+ if _indent is not None:
365
+ _current_indent_level += 1
366
+ newline_indent = '\n' + _indent * _current_indent_level
367
+ item_separator = _item_separator + newline_indent
368
+ yield newline_indent
369
+ else:
370
+ newline_indent = None
371
+ item_separator = _item_separator
372
+ first = True
373
+ if _sort_keys:
374
+ items = sorted(dct.items(), key=lambda kv: kv[0].encode('utf-16_be'))
375
+ else:
376
+ items = dct.items()
377
+ for key, value in items:
378
+ if isinstance(key, str):
379
+ pass
380
+ # JavaScript is weakly typed for these, so it makes sense to
381
+ # also allow them. Many encoders seem to do something like this.
382
+ elif isinstance(key, float):
383
+ # see comment for int/float in _make_iterencode
384
+ key = convert2Es6Format(key)
385
+ elif key is True:
386
+ key = 'true'
387
+ elif key is False:
388
+ key = 'false'
389
+ elif key is None:
390
+ key = 'null'
391
+ elif isinstance(key, int):
392
+ # see comment for int/float in _make_iterencode
393
+ key = convert2Es6Format(key)
394
+ elif _skipkeys:
395
+ continue
396
+ else:
397
+ raise TypeError("key " + repr(key) + " is not a string")
398
+ if first:
399
+ first = False
400
+ else:
401
+ yield item_separator
402
+ yield _encoder(key)
403
+ yield _key_separator
404
+ if isinstance(value, str):
405
+ yield _encoder(value)
406
+ elif value is None:
407
+ yield 'null'
408
+ elif value is True:
409
+ yield 'true'
410
+ elif value is False:
411
+ yield 'false'
412
+ elif isinstance(value, int):
413
+ # see comment for int/float in _make_iterencode
414
+ yield convert2Es6Format(value)
415
+ elif isinstance(value, float):
416
+ # see comment for int/float in _make_iterencode
417
+ yield convert2Es6Format(value)
418
+ else:
419
+ if isinstance(value, (list, tuple)):
420
+ chunks = _iterencode_list(value, _current_indent_level)
421
+ elif isinstance(value, dict):
422
+ chunks = _iterencode_dict(value, _current_indent_level)
423
+ else:
424
+ chunks = _iterencode(value, _current_indent_level)
425
+ yield from chunks
426
+ if newline_indent is not None:
427
+ _current_indent_level -= 1
428
+ yield '\n' + _indent * _current_indent_level
429
+ yield '}'
430
+ if markers is not None:
431
+ del markers[markerid]
432
+
433
+ def _iterencode(o, _current_indent_level):
434
+ if isinstance(o, str):
435
+ yield _encoder(o)
436
+ elif o is None:
437
+ yield 'null'
438
+ elif o is True:
439
+ yield 'true'
440
+ elif o is False:
441
+ yield 'false'
442
+ elif isinstance(o, int):
443
+ # see comment for int/float in _make_iterencode
444
+ yield convert2Es6Format(o)
445
+ elif isinstance(o, float):
446
+ # see comment for int/float in _make_iterencode
447
+ yield convert2Es6Format(o)
448
+ elif isinstance(o, (list, tuple)):
449
+ yield from _iterencode_list(o, _current_indent_level)
450
+ elif isinstance(o, dict):
451
+ yield from _iterencode_dict(o, _current_indent_level)
452
+ else:
453
+ if markers is not None:
454
+ markerid = id(o)
455
+ if markerid in markers:
456
+ raise ValueError("Circular reference detected")
457
+ markers[markerid] = o
458
+ o = _default(o)
459
+ yield from _iterencode(o, _current_indent_level)
460
+ if markers is not None:
461
+ del markers[markerid]
462
+ return _iterencode
463
+
464
+ def canonicalize(obj,utf8=True):
465
+ textVal = JSONEncoder(sort_keys=True).encode(obj)
466
+ if utf8:
467
+ return textVal.encode()
468
+ return textVal
469
+
470
+ def serialize(obj,utf8=True):
471
+ textVal = JSONEncoder(sort_keys=False).encode(obj)
472
+ if utf8:
473
+ return textVal.encode()
474
+ return textVal
c14n/NumberToJson.py ADDED
@@ -0,0 +1,112 @@
1
+ ##############################################################################
2
+ # #
3
+ # Copyright 2006-2019 WebPKI.org (http://webpki.org). #
4
+ # #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); #
6
+ # you may not use this file except in compliance with the License. #
7
+ # You may obtain a copy of the License at #
8
+ # #
9
+ # https://www.apache.org/licenses/LICENSE-2.0 #
10
+ # #
11
+ # Unless required by applicable law or agreed to in writing, software #
12
+ # distributed under the License is distributed on an "AS IS" BASIS, #
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
14
+ # See the License for the specific language governing permissions and #
15
+ # limitations under the License. #
16
+ # #
17
+ ##############################################################################
18
+
19
+
20
+ ##################################################################
21
+ # Convert a Python double/float into an ES6/V8 compatible string #
22
+ ##################################################################
23
+ def convert2Es6Format(value):
24
+ # Convert double/float to str using the native Python formatter
25
+ fvalue = float(value)
26
+ #
27
+ # Zero is a special case. The following line takes "-0" case as well
28
+ #
29
+ if fvalue == 0:
30
+ return '0'
31
+ #
32
+ # The rest of the algorithm works on the textual representation only
33
+ #
34
+ pyDouble = str(fvalue)
35
+ #
36
+ # The following line catches the "inf" and "nan" values returned by str(fvalue)
37
+ #
38
+ if pyDouble.find('n') >= 0:
39
+ raise ValueError("Invalid JSON number: " + pyDouble)
40
+ #
41
+ # Save sign separately, it doesn't have any role in the algorithm
42
+ #
43
+ pySign = ''
44
+ if pyDouble.find('-') == 0:
45
+ pySign = '-'
46
+ pyDouble = pyDouble[1:]
47
+ #
48
+ # Now we should only have valid non-zero values
49
+ #
50
+ pyExpStr = ''
51
+ pyExpVal = 0
52
+ q = pyDouble.find('e')
53
+ if q > 0:
54
+ #
55
+ # Grab the exponent and remove it from the number
56
+ #
57
+ pyExpStr = pyDouble[q:]
58
+ if pyExpStr[2:3] == '0':
59
+ #
60
+ # Supress leading zero on exponents
61
+ #
62
+ pyExpStr = pyExpStr[:2] + pyExpStr[3:]
63
+ pyDouble = pyDouble[0:q]
64
+ pyExpVal = int(pyExpStr[1:])
65
+ #
66
+ # Split number in pyFirst + pyDot + pyLast
67
+ #
68
+ pyFirst = pyDouble
69
+ pyDot = ''
70
+ pyLast = ''
71
+ q = pyDouble.find('.')
72
+ if q > 0:
73
+ pyDot = '.'
74
+ pyFirst = pyDouble[:q]
75
+ pyLast = pyDouble[q + 1:]
76
+ #
77
+ # Now the string is split into: pySign + pyFirst + pyDot + pyLast + pyExpStr
78
+ #
79
+ if pyLast == '0':
80
+ #
81
+ # Always remove trailing .0
82
+ #
83
+ pyDot = ''
84
+ pyLast = ''
85
+ if pyExpVal > 0 and pyExpVal < 21:
86
+ #
87
+ # Integers are shown as is with up to 21 digits
88
+ #
89
+ pyFirst += pyLast
90
+ pyLast = ''
91
+ pyDot = ''
92
+ pyExpStr = ''
93
+ q = pyExpVal - len(pyFirst)
94
+ while q >= 0:
95
+ q -= 1;
96
+ pyFirst += '0'
97
+ elif pyExpVal < 0 and pyExpVal > -7:
98
+ #
99
+ # Small numbers are shown as 0.etc with e-6 as lower limit
100
+ #
101
+ pyLast = pyFirst + pyLast
102
+ pyFirst = '0'
103
+ pyDot = '.'
104
+ pyExpStr = ''
105
+ q = pyExpVal
106
+ while q < -1:
107
+ q += 1;
108
+ pyLast = '0' + pyLast
109
+ #
110
+ # The resulting sub-strings are concatenated
111
+ #
112
+ return pySign + pyFirst + pyDot + pyLast + pyExpStr
c14n/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """ JSON Canonicalization. """
2
+ from .Canonicalize import canonicalize
3
+
4
+ __all__ = ['canonicalize']
pyld/__about__.py ADDED
@@ -0,0 +1,9 @@
1
+ # PyLD JSON-LD meta data
2
+
3
+ __all__ = [
4
+ '__copyright__', '__license__', '__version__'
5
+ ]
6
+
7
+ __copyright__ = 'Copyright (c) 2011-2024 Digital Bazaar, Inc.'
8
+ __license__ = 'New BSD license'
9
+ __version__ = '2.0.4'
pyld/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """ The PyLD module is used to process JSON-LD. """
2
+ from . import jsonld
3
+ from .context_resolver import ContextResolver
4
+
5
+ __all__ = ['jsonld', 'ContextResolver']