@shaxpir/duiduidui-models 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.
Files changed (211) hide show
  1. package/README.md +1 -0
  2. package/decs.d.ts +87 -0
  3. package/dist/index.d.ts +3 -0
  4. package/dist/index.js +20 -0
  5. package/dist/models/OutboundMessage.d.ts +18 -0
  6. package/dist/models/OutboundMessage.js +25 -0
  7. package/dist/models/content/Activity.d.ts +10 -0
  8. package/dist/models/content/Activity.js +2 -0
  9. package/dist/models/content/ArrayView.d.ts +26 -0
  10. package/dist/models/content/ArrayView.js +174 -0
  11. package/dist/models/content/Billing.d.ts +144 -0
  12. package/dist/models/content/Billing.js +418 -0
  13. package/dist/models/content/Book.d.ts +77 -0
  14. package/dist/models/content/Book.js +407 -0
  15. package/dist/models/content/Category.d.ts +16 -0
  16. package/dist/models/content/Category.js +20 -0
  17. package/dist/models/content/Checkpointable.d.ts +21 -0
  18. package/dist/models/content/Checkpointable.js +156 -0
  19. package/dist/models/content/Comment.d.ts +19 -0
  20. package/dist/models/content/Comment.js +53 -0
  21. package/dist/models/content/ConceptArt.d.ts +31 -0
  22. package/dist/models/content/ConceptArt.js +84 -0
  23. package/dist/models/content/Content.d.ts +52 -0
  24. package/dist/models/content/Content.js +61 -0
  25. package/dist/models/content/ContentKind.d.ts +10 -0
  26. package/dist/models/content/ContentKind.js +16 -0
  27. package/dist/models/content/Context.d.ts +28 -0
  28. package/dist/models/content/Context.js +162 -0
  29. package/dist/models/content/DevEnv.d.ts +5 -0
  30. package/dist/models/content/DevEnv.js +9 -0
  31. package/dist/models/content/Device.d.ts +24 -0
  32. package/dist/models/content/Device.js +62 -0
  33. package/dist/models/content/Dictionary.d.ts +31 -0
  34. package/dist/models/content/Dictionary.js +5 -0
  35. package/dist/models/content/DictionaryEntry.d.ts +20 -0
  36. package/dist/models/content/DictionaryEntry.js +2 -0
  37. package/dist/models/content/ElasticModel.d.ts +149 -0
  38. package/dist/models/content/ElasticModel.js +179 -0
  39. package/dist/models/content/Environment.d.ts +61 -0
  40. package/dist/models/content/Environment.js +124 -0
  41. package/dist/models/content/ExportOptions.d.ts +64 -0
  42. package/dist/models/content/ExportOptions.js +213 -0
  43. package/dist/models/content/Folder.d.ts +16 -0
  44. package/dist/models/content/Folder.js +33 -0
  45. package/dist/models/content/Fragment.d.ts +54 -0
  46. package/dist/models/content/Fragment.js +181 -0
  47. package/dist/models/content/GeoLocation.d.ts +4 -0
  48. package/dist/models/content/GeoLocation.js +2 -0
  49. package/dist/models/content/Hanzi.d.ts +21 -0
  50. package/dist/models/content/Hanzi.js +2 -0
  51. package/dist/models/content/HighlightRule.d.ts +9 -0
  52. package/dist/models/content/HighlightRule.js +2 -0
  53. package/dist/models/content/Manifest.d.ts +42 -0
  54. package/dist/models/content/Manifest.js +114 -0
  55. package/dist/models/content/Media.d.ts +32 -0
  56. package/dist/models/content/Media.js +98 -0
  57. package/dist/models/content/Metric.d.ts +46 -0
  58. package/dist/models/content/Metric.js +183 -0
  59. package/dist/models/content/Migration.d.ts +68 -0
  60. package/dist/models/content/Migration.js +155 -0
  61. package/dist/models/content/Model.d.ts +45 -0
  62. package/dist/models/content/Model.js +280 -0
  63. package/dist/models/content/Permissions.d.ts +7 -0
  64. package/dist/models/content/Permissions.js +20 -0
  65. package/dist/models/content/Phrase.d.ts +8 -0
  66. package/dist/models/content/Phrase.js +2 -0
  67. package/dist/models/content/Placeholder.d.ts +8 -0
  68. package/dist/models/content/Placeholder.js +36 -0
  69. package/dist/models/content/Profile.d.ts +30 -0
  70. package/dist/models/content/Profile.js +95 -0
  71. package/dist/models/content/RichText.d.ts +58 -0
  72. package/dist/models/content/RichText.js +79 -0
  73. package/dist/models/content/Session.d.ts +39 -0
  74. package/dist/models/content/Session.js +173 -0
  75. package/dist/models/content/Speech.d.ts +67 -0
  76. package/dist/models/content/Speech.js +97 -0
  77. package/dist/models/content/Stub.d.ts +24 -0
  78. package/dist/models/content/Stub.js +179 -0
  79. package/dist/models/content/Time.d.ts +56 -0
  80. package/dist/models/content/Time.js +295 -0
  81. package/dist/models/content/User.d.ts +36 -0
  82. package/dist/models/content/User.js +95 -0
  83. package/dist/models/content/Workspace.d.ts +71 -0
  84. package/dist/models/content/Workspace.js +237 -0
  85. package/dist/models/content/index.d.ts +36 -0
  86. package/dist/models/content/index.js +53 -0
  87. package/dist/models/index.d.ts +4 -0
  88. package/dist/models/index.js +21 -0
  89. package/dist/models/legacy/LegacyBodyFormat.d.ts +9 -0
  90. package/dist/models/legacy/LegacyBodyFormat.js +2 -0
  91. package/dist/models/legacy/LegacyComment.d.ts +12 -0
  92. package/dist/models/legacy/LegacyComment.js +2 -0
  93. package/dist/models/legacy/LegacyContent.d.ts +53 -0
  94. package/dist/models/legacy/LegacyContent.js +55 -0
  95. package/dist/models/legacy/LegacyConversion.d.ts +55 -0
  96. package/dist/models/legacy/LegacyConversion.js +401 -0
  97. package/dist/models/legacy/LegacyFragment.d.ts +21 -0
  98. package/dist/models/legacy/LegacyFragment.js +2 -0
  99. package/dist/models/legacy/LegacyLocator.d.ts +8 -0
  100. package/dist/models/legacy/LegacyLocator.js +31 -0
  101. package/dist/models/legacy/LegacyOutboundMessage.d.ts +16 -0
  102. package/dist/models/legacy/LegacyOutboundMessage.js +13 -0
  103. package/dist/models/legacy/LegacyPicture.d.ts +14 -0
  104. package/dist/models/legacy/LegacyPicture.js +2 -0
  105. package/dist/models/legacy/LegacyProfile.d.ts +9 -0
  106. package/dist/models/legacy/LegacyProfile.js +2 -0
  107. package/dist/models/legacy/LegacySession.d.ts +41 -0
  108. package/dist/models/legacy/LegacySession.js +35 -0
  109. package/dist/models/legacy/LegacyStory.d.ts +23 -0
  110. package/dist/models/legacy/LegacyStory.js +2 -0
  111. package/dist/models/legacy/LegacyStub.d.ts +15 -0
  112. package/dist/models/legacy/LegacyStub.js +2 -0
  113. package/dist/models/legacy/LegacyTransaction.d.ts +14 -0
  114. package/dist/models/legacy/LegacyTransaction.js +49 -0
  115. package/dist/models/legacy/LegacyUser.d.ts +28 -0
  116. package/dist/models/legacy/LegacyUser.js +32 -0
  117. package/dist/models/legacy/LegacyWorkspace.d.ts +23 -0
  118. package/dist/models/legacy/LegacyWorkspace.js +6 -0
  119. package/dist/models/legacy/index.d.ts +15 -0
  120. package/dist/models/legacy/index.js +32 -0
  121. package/dist/models/markup/BodyFormat.d.ts +14 -0
  122. package/dist/models/markup/BodyFormat.js +190 -0
  123. package/dist/models/markup/ChangeModel.d.ts +22 -0
  124. package/dist/models/markup/ChangeModel.js +107 -0
  125. package/dist/models/markup/DeltaOps.d.ts +5 -0
  126. package/dist/models/markup/DeltaOps.js +74 -0
  127. package/dist/models/markup/HtmlMarkup.d.ts +4 -0
  128. package/dist/models/markup/HtmlMarkup.js +21 -0
  129. package/dist/models/markup/Operation.d.ts +32 -0
  130. package/dist/models/markup/Operation.js +194 -0
  131. package/dist/models/markup/TextEditOps.d.ts +9 -0
  132. package/dist/models/markup/TextEditOps.js +50 -0
  133. package/dist/models/markup/index.d.ts +6 -0
  134. package/dist/models/markup/index.js +23 -0
  135. package/dist/repo/ConnectionListener.d.ts +9 -0
  136. package/dist/repo/ConnectionListener.js +21 -0
  137. package/dist/repo/PermissiveJson1.d.ts +58 -0
  138. package/dist/repo/PermissiveJson1.js +39 -0
  139. package/dist/repo/ShareSync.d.ts +60 -0
  140. package/dist/repo/ShareSync.js +348 -0
  141. package/dist/repo/index.d.ts +3 -0
  142. package/dist/repo/index.js +20 -0
  143. package/dist/util/Async.d.ts +8 -0
  144. package/dist/util/Async.js +18 -0
  145. package/dist/util/Base62.d.ts +6 -0
  146. package/dist/util/Base62.js +47 -0
  147. package/dist/util/BinarySearch.d.ts +7 -0
  148. package/dist/util/BinarySearch.js +46 -0
  149. package/dist/util/CachingHasher.d.ts +8 -0
  150. package/dist/util/CachingHasher.js +41 -0
  151. package/dist/util/Color.d.ts +32 -0
  152. package/dist/util/Color.js +204 -0
  153. package/dist/util/Dispatch.d.ts +15 -0
  154. package/dist/util/Dispatch.js +79 -0
  155. package/dist/util/EditDistance.d.ts +13 -0
  156. package/dist/util/EditDistance.js +184 -0
  157. package/dist/util/Encryption.d.ts +5 -0
  158. package/dist/util/Encryption.js +2 -0
  159. package/dist/util/Logging.d.ts +108 -0
  160. package/dist/util/Logging.js +412 -0
  161. package/dist/util/NumberFormat.d.ts +14 -0
  162. package/dist/util/NumberFormat.js +224 -0
  163. package/dist/util/Struct.d.ts +4 -0
  164. package/dist/util/Struct.js +15 -0
  165. package/dist/util/Template.d.ts +16 -0
  166. package/dist/util/Template.js +128 -0
  167. package/dist/util/Text.d.ts +45 -0
  168. package/dist/util/Text.js +243 -0
  169. package/dist/util/Tuples.d.ts +9 -0
  170. package/dist/util/Tuples.js +135 -0
  171. package/dist/util/Validate.d.ts +4 -0
  172. package/dist/util/Validate.js +11 -0
  173. package/dist/util/Vocabulary.d.ts +3 -0
  174. package/dist/util/Vocabulary.js +35 -0
  175. package/dist/util/index.d.ts +16 -0
  176. package/dist/util/index.js +33 -0
  177. package/lib/models/content/ArrayView.ts +203 -0
  178. package/lib/models/content/Billing.ts +558 -0
  179. package/lib/models/content/Content.ts +110 -0
  180. package/lib/models/content/ContentKind.ts +14 -0
  181. package/lib/models/content/DevEnv.ts +5 -0
  182. package/lib/models/content/Device.ts +86 -0
  183. package/lib/models/content/DictionaryEntry.ts +22 -0
  184. package/lib/models/content/GeoLocation.ts +4 -0
  185. package/lib/models/content/Hanzi.ts +25 -0
  186. package/lib/models/content/Manifest.ts +162 -0
  187. package/lib/models/content/Media.ts +126 -0
  188. package/lib/models/content/Model.ts +327 -0
  189. package/lib/models/content/Permissions.ts +21 -0
  190. package/lib/models/content/Phrase.ts +10 -0
  191. package/lib/models/content/Profile.ts +119 -0
  192. package/lib/models/content/Time.ts +328 -0
  193. package/lib/models/content/User.ts +130 -0
  194. package/lib/models/markup/ChangeModel.ts +95 -0
  195. package/lib/models/markup/DeltaOps.ts +71 -0
  196. package/lib/models/markup/Operation.ts +215 -0
  197. package/lib/models/markup/TextEditOps.ts +50 -0
  198. package/lib/repo/ConnectionListener.ts +25 -0
  199. package/lib/repo/PermissiveJson1.ts +14 -0
  200. package/lib/repo/ShareSync.ts +390 -0
  201. package/lib/util/Base62.ts +47 -0
  202. package/lib/util/CachingHasher.ts +38 -0
  203. package/lib/util/Dispatch.ts +92 -0
  204. package/lib/util/Encryption.ts +5 -0
  205. package/lib/util/Logging.ts +568 -0
  206. package/lib/util/NumberFormat.ts +194 -0
  207. package/lib/util/Struct.ts +14 -0
  208. package/lib/util/Tuples.ts +131 -0
  209. package/package.json +41 -0
  210. package/tsconfig.json +25 -0
  211. package/tslint.json +46 -0
@@ -0,0 +1,348 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.ShareSync = exports.ShareSyncFactory = exports.ShareSyncDisposalStrategy = void 0;
30
+ const client_1 = __importStar(require("@shaxpir/sharedb/lib/client"));
31
+ const reconnecting_websocket_1 = __importDefault(require("reconnecting-websocket"));
32
+ const Billing_1 = require("../models/content/Billing");
33
+ const Content_1 = require("../models/content/Content");
34
+ const ContentKind_1 = require("../models/content/ContentKind");
35
+ const Device_1 = require("../models/content/Device");
36
+ const Manifest_1 = require("../models/content/Manifest");
37
+ const Profile_1 = require("../models/content/Profile");
38
+ const User_1 = require("../models/content/User");
39
+ const Json1 = __importStar(require("./PermissiveJson1"));
40
+ const RichText = require('@shaxpir/rich-text');
41
+ const UnicodeText = require('ot-text-unicode');
42
+ client_1.default.types.register(Json1.type);
43
+ client_1.default.types.register(RichText.type);
44
+ client_1.default.types.register(UnicodeText.type);
45
+ Json1.type.registerSubtype(RichText.type);
46
+ Json1.type.registerSubtype(UnicodeText.type);
47
+ var ShareSyncDisposalStrategy;
48
+ (function (ShareSyncDisposalStrategy) {
49
+ ShareSyncDisposalStrategy[ShareSyncDisposalStrategy["UNSUBSCRIBE"] = 0] = "UNSUBSCRIBE";
50
+ ShareSyncDisposalStrategy[ShareSyncDisposalStrategy["DESTROY"] = 1] = "DESTROY";
51
+ ShareSyncDisposalStrategy[ShareSyncDisposalStrategy["NOTHING"] = 2] = "NOTHING";
52
+ })(ShareSyncDisposalStrategy || (exports.ShareSyncDisposalStrategy = ShareSyncDisposalStrategy = {}));
53
+ class ShareSyncFactory {
54
+ static initialize(encryption, options) {
55
+ ShareSyncFactory.INSTANCE = new ShareSync(encryption, options);
56
+ }
57
+ static get() {
58
+ return ShareSyncFactory.INSTANCE;
59
+ }
60
+ }
61
+ exports.ShareSyncFactory = ShareSyncFactory;
62
+ ShareSyncFactory.INSTANCE = null;
63
+ class ShareSync {
64
+ constructor(encryption, options) {
65
+ this._modelCache = new Map();
66
+ const shareSync = this;
67
+ shareSync._encryption = encryption;
68
+ shareSync._debug = options.debug;
69
+ shareSync._disposalStrategy = options.disposalStrategy;
70
+ shareSync._opErrorCallback = options.opErrorCallback;
71
+ shareSync._hasDurableStore = options.namespace && options.namespace.length > 0;
72
+ shareSync._useDurableStoreEncryption = options.encryptionKey && options.encryptionKey.length > 0;
73
+ shareSync._durableStoreEncryptionKey = options.encryptionKey;
74
+ // Create and configure the socket.
75
+ if (options.webSocketConstructor) {
76
+ shareSync._socket = new reconnecting_websocket_1.default(options.urlProvider, [], { WebSocket: options.webSocketConstructor });
77
+ }
78
+ else {
79
+ shareSync._socket = new reconnecting_websocket_1.default(options.urlProvider);
80
+ }
81
+ function updateSocketIsOpen() {
82
+ shareSync._socketIsOpen = shareSync._socket.readyState === reconnecting_websocket_1.default.OPEN;
83
+ }
84
+ // The listener should forward all events: open, message, close, error
85
+ shareSync._listener = options.connectionListener;
86
+ shareSync._socket.addEventListener('open', (event) => {
87
+ updateSocketIsOpen();
88
+ shareSync._listener.onSocketEvent('open', event);
89
+ });
90
+ shareSync._socket.addEventListener('message', (event) => {
91
+ updateSocketIsOpen();
92
+ shareSync._listener.onSocketEvent('message', event);
93
+ });
94
+ shareSync._socket.addEventListener('close', (event) => {
95
+ updateSocketIsOpen();
96
+ shareSync._listener.onSocketEvent('close', event);
97
+ });
98
+ shareSync._socket.addEventListener('error', (event) => {
99
+ updateSocketIsOpen();
100
+ shareSync._listener.onSocketEvent('error', event);
101
+ });
102
+ // Create the ShareDB connection from the socket
103
+ if (shareSync._hasDurableStore) {
104
+ shareSync._connection = new client_1.Connection(shareSync._socket, {
105
+ durableStore: {
106
+ namespace: options.namespace,
107
+ debug: options.debug,
108
+ useEncryption: shareSync._useDurableStoreEncryption,
109
+ encryptionCallback: (plaintext) => {
110
+ return encryption.encrypt(plaintext, shareSync._durableStoreEncryptionKey);
111
+ },
112
+ decryptionCallback: (cyphertext) => {
113
+ return encryption.decrypt(cyphertext, shareSync._durableStoreEncryptionKey);
114
+ },
115
+ onReadyCallback: options.onReadyCallback,
116
+ opErrorCallback: options.opErrorCallback,
117
+ // Use the 'docData.meta.updated_at.utc_time' field (which is universal to all Model subclasses) as the 'version'
118
+ // identifier that we use when determining if the doc in the DurableStore is up-to-date. This field won't yet
119
+ // exist when the doc is newly created (since the 'doc.data' will be undefined), so in that case, we'll return
120
+ // null as the version string, which will work correctly with the versioning semantics of the DurableStore.
121
+ extVersionDecoder: (docData) => {
122
+ if (docData &&
123
+ docData.meta &&
124
+ docData.meta.updated_at &&
125
+ docData.meta.updated_at.utc_time) {
126
+ return docData.meta.updated_at.utc_time;
127
+ }
128
+ return null;
129
+ }
130
+ }
131
+ });
132
+ }
133
+ else {
134
+ shareSync._connection = new client_1.Connection(shareSync._socket);
135
+ }
136
+ shareSync._connection.on('error', (err) => {
137
+ console.error(`ShareSync connection error: ${err}\n Error code: ${err.code}\n Error message: ${err.message}\n Error stack: ${err.stack}\n`);
138
+ });
139
+ // If the client provided a pingInterval option, then set up a periodic ping the
140
+ // connection alive. Clients who don't provide this option will send pings.
141
+ if (options.pingInterval && typeof (options.pingInterval) === 'number') {
142
+ setInterval(() => { shareSync.ping(); }, options.pingInterval);
143
+ }
144
+ if (!shareSync._hasDurableStore && !!options.onReadyCallback) {
145
+ // If there is no DurableStore, then we can call the onReadyCallback now. However,
146
+ // we have to use setTimeout to invoke it, because the callback will probably want
147
+ // to retrieve the ShareSync instance from the factory, and because the constructor
148
+ // hasn't actually finished yet, the INSTANCE pointer hasn't quite been assigned yet.
149
+ setTimeout(options.onReadyCallback, 1);
150
+ }
151
+ }
152
+ isDebug() {
153
+ return this._debug;
154
+ }
155
+ isOnline() {
156
+ return this._socketIsOpen;
157
+ }
158
+ ping() {
159
+ try {
160
+ this._connection.ping();
161
+ }
162
+ catch (error) {
163
+ // Ignore the error. We aren't directly concerned with the connection status.
164
+ // We just need to provoke the connection to attempt sending a ping message,
165
+ // so that if it fails to send that message, our normal socket-event listeners
166
+ // will notice the change in status, and trigger our downstream logic for
167
+ // displaying the offline status to the user.
168
+ }
169
+ }
170
+ makeContentId() {
171
+ return this._encryption.getRandomString(Content_1.Content.ID_LENGTH);
172
+ }
173
+ async exists(userId, kind, ref) {
174
+ // Check to see if this item exists in the model cache
175
+ const compoundKey = `${kind}/${ref}`;
176
+ if (this._modelCache.has(compoundKey)) {
177
+ const model = this._modelCache.get(compoundKey);
178
+ return model.exists();
179
+ }
180
+ // Check to see if this item exists in the durable-store inventory
181
+ const existsInDurableStore = this._connection.isDocInInventory(kind, ref);
182
+ if (existsInDurableStore) {
183
+ return true;
184
+ }
185
+ // Check to see if this item is recorded in the manifest.
186
+ const manifestId = Manifest_1.Manifest.makeManifestId(userId);
187
+ const manifest = this.load(ContentKind_1.ContentKind.MANIFEST, manifestId);
188
+ await manifest.acquire();
189
+ const existsInManifest = manifest.doesContentExist(kind, ref);
190
+ manifest.release();
191
+ if (existsInManifest) {
192
+ return true;
193
+ }
194
+ // Fetch this model from from the remote ShareDB server.
195
+ const model = this.load(kind, ref);
196
+ await model.acquire();
197
+ const exists = model.exists();
198
+ model.release();
199
+ return exists;
200
+ }
201
+ createManifest(body) {
202
+ const shareSync = this;
203
+ // Create or retrieve the doc object for this manifest model.
204
+ const manifestId = Manifest_1.Manifest.makeManifestId(body.meta.owner);
205
+ const doc = shareSync._connection.get(ContentKind_1.ContentKind.MANIFEST, manifestId);
206
+ doc.create(body, Json1.type.uri, (createErr) => {
207
+ if (createErr) {
208
+ console.log(`error creating manifest ${manifestId}: ${createErr}`);
209
+ }
210
+ });
211
+ shareSync.isDebug() && console.log(`created manifest ${manifestId}`);
212
+ const manifest = shareSync.wrap(ContentKind_1.ContentKind.MANIFEST, doc, true);
213
+ this._modelCache.set(manifest.compoundKey, manifest);
214
+ return manifest;
215
+ }
216
+ createContent(body) {
217
+ const shareSync = this;
218
+ // Create or retrieve the doc object for this content model.
219
+ const compoundKey = `${body.meta.kind}/${body.meta.ref}`;
220
+ const doc = shareSync._connection.get(body.meta.kind, body.meta.ref);
221
+ doc.create(body, Json1.type.uri, (createErr) => {
222
+ if (createErr) {
223
+ console.log(`error creating content ${compoundKey}: ${createErr}`);
224
+ }
225
+ });
226
+ shareSync.isDebug() && console.log(`created content ${compoundKey}`);
227
+ const content = shareSync.wrap(body.meta.kind, doc, true);
228
+ this._modelCache.set(compoundKey, content);
229
+ this.updateManifestForContent(content);
230
+ return content;
231
+ }
232
+ async acquire(kind, id, timestamp) {
233
+ let model = this.load(kind, id);
234
+ if (timestamp) {
235
+ model = await model.acquire(timestamp);
236
+ }
237
+ else {
238
+ model = await model.acquire();
239
+ }
240
+ return model;
241
+ }
242
+ load(kind, id) {
243
+ // First, try getting the content from the cache
244
+ const compoundKey = `${kind}/${id}`;
245
+ if (this._modelCache.has(compoundKey)) {
246
+ return this._modelCache.get(compoundKey);
247
+ }
248
+ // If not in the cache, get the model doc from the connection.
249
+ // Then wrap it and put it in the cache for future reference.
250
+ const doc = this._connection.get(kind, id);
251
+ const model = this.wrap(kind, doc, false);
252
+ this._modelCache.set(compoundKey, model);
253
+ return model;
254
+ }
255
+ async findAndAcquire(kind, query) {
256
+ const shareSync = this;
257
+ return new Promise((resolve, reject) => {
258
+ shareSync._connection.createFetchQuery(kind, query, {}, (error, results) => {
259
+ if (error) {
260
+ const message = `query error (${error.code}): ${error.message}`;
261
+ console.log(message);
262
+ reject(message);
263
+ return;
264
+ }
265
+ const contents = [];
266
+ for (let i = 0; i < results.length; i++) {
267
+ const doc = results[i];
268
+ if (doc.type) {
269
+ const compoundKey = `${doc.collection}/${doc.id}`;
270
+ if (shareSync._modelCache.has(compoundKey)) {
271
+ const content = shareSync._modelCache.get(compoundKey);
272
+ content.acquire();
273
+ contents.push(content);
274
+ }
275
+ else {
276
+ // NOTE: the wrap method calls 'acquire' on the model, so we don't need to do it here.
277
+ const content = shareSync.wrap(kind, doc, true);
278
+ shareSync._modelCache.set(compoundKey, content);
279
+ contents.push(content);
280
+ }
281
+ }
282
+ }
283
+ resolve(contents);
284
+ });
285
+ });
286
+ }
287
+ async updateManifestForContent(content) {
288
+ // TODO: how will we handle manifest updates in a sharing scenario?
289
+ // If user A owns a book, and gives B permission to edit that book, and then B makes some
290
+ // changes to the book. We want B to be able to update their own manifest, but not the
291
+ // manifest belonging to A. But then how will A know that the book has been updated?
292
+ this.isDebug() && console.log(`updating manifest for content: ${content.compoundKey}`);
293
+ content.acquire();
294
+ const manifestId = Manifest_1.Manifest.makeManifestId(content.owner);
295
+ const manifest = this.load(ContentKind_1.ContentKind.MANIFEST, manifestId);
296
+ await manifest.acquire();
297
+ manifest.update(content);
298
+ manifest.release();
299
+ content.release();
300
+ }
301
+ forEachOfflinePendingModel(callback) {
302
+ this._connection.forEachPendingDocCollectionId(callback);
303
+ }
304
+ isDocInInventory(kind, ref, minVersion) {
305
+ // Check to see if this doc is in the DurableStore inventory. And if so, does it have a `minVersion`
306
+ // greater than or equal to the supplied `minVersion`. In all shaxpir models, the `minVersion` is
307
+ // extracted from the `meta.updated_at.utc_time` field.
308
+ return this._connection.isDocInInventory(kind, ref, minVersion);
309
+ }
310
+ dispose(model) {
311
+ if (this._disposalStrategy == ShareSyncDisposalStrategy.NOTHING) {
312
+ return;
313
+ }
314
+ // Remove the model from the cache
315
+ const compoundKey = model.compoundKey;
316
+ this._modelCache.delete(compoundKey);
317
+ // Dispose of the model's doc object
318
+ if (this._disposalStrategy == ShareSyncDisposalStrategy.DESTROY) {
319
+ model.disposeAndDestroy();
320
+ }
321
+ else if (this._disposalStrategy == ShareSyncDisposalStrategy.UNSUBSCRIBE) {
322
+ model.disposeAndUnsubscribe();
323
+ }
324
+ }
325
+ onOperationError(opError) {
326
+ this._opErrorCallback && this._opErrorCallback(opError);
327
+ }
328
+ wrap(kind, doc, shouldAcquire) {
329
+ const shareSync = this;
330
+ if (kind === ContentKind_1.ContentKind.MANIFEST) {
331
+ return new Manifest_1.Manifest(doc, shouldAcquire, shareSync);
332
+ }
333
+ else if (kind === ContentKind_1.ContentKind.USER) {
334
+ return new User_1.ModernUser(doc, shouldAcquire, shareSync);
335
+ }
336
+ else if (kind === ContentKind_1.ContentKind.DEVICE) {
337
+ return new Device_1.Device(doc, shouldAcquire, shareSync);
338
+ }
339
+ else if (kind === ContentKind_1.ContentKind.BILLING) {
340
+ return new Billing_1.Billing(doc, shouldAcquire, shareSync);
341
+ }
342
+ else if (kind === ContentKind_1.ContentKind.PROFILE) {
343
+ return new Profile_1.Profile(doc, shouldAcquire, shareSync);
344
+ }
345
+ throw new Error(`can't wrap content ${kind}/${doc.id}`);
346
+ }
347
+ }
348
+ exports.ShareSync = ShareSync;
@@ -0,0 +1,3 @@
1
+ export * from './ConnectionListener';
2
+ export * from './PermissiveJson1';
3
+ export * from './ShareSync';
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ // created from 'create-ts-index'
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ __exportStar(require("./ConnectionListener"), exports);
19
+ __exportStar(require("./PermissiveJson1"), exports);
20
+ __exportStar(require("./ShareSync"), exports);
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Returns a promise that delays for the given ms before resolving.
3
+ *
4
+ * Intended to be used e.g. `await delay(1000)`
5
+ *
6
+ * @param t milliseconds to delay for
7
+ */
8
+ export declare function delay(t: number): Promise<void>;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.delay = void 0;
4
+ /**
5
+ * Returns a promise that delays for the given ms before resolving.
6
+ *
7
+ * Intended to be used e.g. `await delay(1000)`
8
+ *
9
+ * @param t milliseconds to delay for
10
+ */
11
+ function delay(t) {
12
+ return new Promise((resolve) => {
13
+ setTimeout(() => {
14
+ resolve();
15
+ }, t);
16
+ });
17
+ }
18
+ exports.delay = delay;
@@ -0,0 +1,6 @@
1
+ export declare class Base62 {
2
+ static readonly CHARS: string;
3
+ static encode(value: number, padToLength?: number): string;
4
+ static decode(value: string): number;
5
+ static fromHexHash(hex: string, length: number): string;
6
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Base62 = void 0;
4
+ class Base62 {
5
+ static encode(value, padToLength = 1) {
6
+ if (value < 0) {
7
+ throw new Error("number out of range: " + value);
8
+ }
9
+ let result = "";
10
+ while (value > 0) {
11
+ let index = value % 62;
12
+ let digit = Base62.CHARS.charAt(index);
13
+ result = digit + result;
14
+ value = Math.floor(value / 62);
15
+ }
16
+ while (result.length < padToLength) {
17
+ result = "0" + result;
18
+ }
19
+ return result;
20
+ }
21
+ static decode(value) {
22
+ let result = 0;
23
+ for (let i = 0, len = value.length; i < len; i++) {
24
+ let c = value.charAt(i);
25
+ result *= 62;
26
+ result += Base62.CHARS.indexOf(c);
27
+ }
28
+ return result;
29
+ }
30
+ static fromHexHash(hex, length) {
31
+ // NOTE: the crazy one-liner below is equivalent to this commented code...
32
+ // const b64 = Buffer.from(hex, 'hex').toString('base64');
33
+ // ...but it doesn't require Buffer class, which is only available in Node.js, not in browsers.
34
+ // This one-liner came from stackoverflow: https://stackoverflow.com/questions/23190056/hex-to-base64-converter-for-javascript
35
+ const b64 = btoa(hex.match(/\w{2}/g).map((a) => { return String.fromCharCode(parseInt(a, 16)); }).join(""));
36
+ let alphanum = b64.replace(/[^a-zA-Z0-9]/g, "");
37
+ if (alphanum.length < length) {
38
+ alphanum = alphanum.padEnd(length, "0");
39
+ }
40
+ else if (alphanum.length > length) {
41
+ alphanum = alphanum.substring(0, length);
42
+ }
43
+ return alphanum;
44
+ }
45
+ }
46
+ exports.Base62 = Base62;
47
+ Base62.CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
@@ -0,0 +1,7 @@
1
+ import { CompactDateTime } from "../models/content/Time";
2
+ import { SpeechMarkItem } from "../models/content/Speech";
3
+ export declare class BinarySearch {
4
+ static ofDateTimes(value: CompactDateTime, values: CompactDateTime[]): number;
5
+ static ofStrings(value: string, values: string[]): number;
6
+ static ofSpeechMarks(seekPoint: number, speechMarks: SpeechMarkItem[]): number;
7
+ }
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BinarySearch = void 0;
4
+ class BinarySearch {
5
+ static ofDateTimes(value, values) {
6
+ return BinarySearch.ofStrings(value, values);
7
+ }
8
+ static ofStrings(value, values) {
9
+ let low = 0;
10
+ let high = values.length - 1;
11
+ while (low <= high) {
12
+ let mid = Math.floor((low + high) / 2);
13
+ let midValue = values[mid];
14
+ let comparison = midValue.localeCompare(value);
15
+ if (comparison < 0) {
16
+ low = mid + 1;
17
+ }
18
+ else if (comparison > 0) {
19
+ high = mid - 1;
20
+ }
21
+ else {
22
+ return mid;
23
+ }
24
+ }
25
+ return -(low + 1);
26
+ }
27
+ static ofSpeechMarks(seekPoint, speechMarks) {
28
+ let low = 0;
29
+ let high = speechMarks.length - 1;
30
+ while (low <= high) {
31
+ let mid = Math.floor((low + high) / 2);
32
+ let speechMark = speechMarks[mid];
33
+ if (speechMark.time < seekPoint) {
34
+ low = mid + 1;
35
+ }
36
+ else if (speechMark.time > seekPoint) {
37
+ high = mid - 1;
38
+ }
39
+ else {
40
+ return mid;
41
+ }
42
+ }
43
+ return low - 1;
44
+ }
45
+ }
46
+ exports.BinarySearch = BinarySearch;
@@ -0,0 +1,8 @@
1
+ import { ContentId } from '../models/content/Content';
2
+ export declare class CachingHasher {
3
+ private static readonly MAX_SIZE;
4
+ private static md5HashLookup;
5
+ private static contentIdLookup;
6
+ static makeMd5Hash(text: string): string;
7
+ static makeMd5ContentId(text: string): ContentId;
8
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.CachingHasher = void 0;
7
+ const md5_1 = __importDefault(require("md5"));
8
+ const Base62_1 = require("./Base62");
9
+ class CachingHasher {
10
+ static makeMd5Hash(text) {
11
+ if (CachingHasher.md5HashLookup.size > CachingHasher.MAX_SIZE) {
12
+ CachingHasher.md5HashLookup.clear();
13
+ }
14
+ if (CachingHasher.md5HashLookup.has(text)) {
15
+ return CachingHasher.md5HashLookup.get(text);
16
+ }
17
+ else {
18
+ const rawHash = (0, md5_1.default)(text);
19
+ this.md5HashLookup.set(text, rawHash);
20
+ return rawHash;
21
+ }
22
+ }
23
+ static makeMd5ContentId(text) {
24
+ if (CachingHasher.contentIdLookup.size > CachingHasher.MAX_SIZE) {
25
+ CachingHasher.contentIdLookup.clear();
26
+ }
27
+ if (CachingHasher.contentIdLookup.has(text)) {
28
+ return CachingHasher.contentIdLookup.get(text);
29
+ }
30
+ else {
31
+ const rawHash = (0, md5_1.default)(text);
32
+ const asBase62 = Base62_1.Base62.fromHexHash(rawHash, 16);
33
+ this.contentIdLookup.set(text, asBase62);
34
+ return asBase62;
35
+ }
36
+ }
37
+ }
38
+ exports.CachingHasher = CachingHasher;
39
+ CachingHasher.MAX_SIZE = 1000;
40
+ CachingHasher.md5HashLookup = new Map();
41
+ CachingHasher.contentIdLookup = new Map();
@@ -0,0 +1,32 @@
1
+ export declare class RGB {
2
+ r: number;
3
+ g: number;
4
+ b: number;
5
+ constructor(r: number, g: number, b: number);
6
+ toHEX(): string;
7
+ toHSV(): HSV;
8
+ toHSLUV(): HSLUV;
9
+ static parse(color: string): RGB;
10
+ }
11
+ export declare class HSLUV {
12
+ h: number;
13
+ s: number;
14
+ l: number;
15
+ constructor(h: number, s: number, l: number);
16
+ toRGB(): RGB;
17
+ }
18
+ export declare class HSV {
19
+ h: number;
20
+ s: number;
21
+ v: number;
22
+ constructor(h: number, s: number, v: number);
23
+ toRGB(): RGB;
24
+ }
25
+ export declare class Color {
26
+ private static readonly EPSILON_SATURATION;
27
+ static normalize(color: string): string;
28
+ static makeShadeOf(color: string, hslOverride: {
29
+ [key: string]: number;
30
+ }): string;
31
+ static interpolate(loColor: string, hiColor: string, steps: number, percent: number): string;
32
+ }