@itwin/core-backend 3.7.4 → 3.7.6

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 (246) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/lib/cjs/AliCloudStorageService.d.ts +23 -23
  3. package/lib/cjs/AliCloudStorageService.js +71 -71
  4. package/lib/cjs/AliCloudStorageService.js.map +1 -1
  5. package/lib/cjs/BackendHubAccess.d.ts +224 -224
  6. package/lib/cjs/BackendHubAccess.js +41 -41
  7. package/lib/cjs/BackendHubAccess.js.map +1 -1
  8. package/lib/cjs/BackendLoggerCategory.d.ts +91 -91
  9. package/lib/cjs/BackendLoggerCategory.js +99 -99
  10. package/lib/cjs/BackendLoggerCategory.js.map +1 -1
  11. package/lib/cjs/BisCoreSchema.d.ts +21 -21
  12. package/lib/cjs/BisCoreSchema.js +60 -60
  13. package/lib/cjs/BisCoreSchema.js.map +1 -1
  14. package/lib/cjs/BriefcaseManager.d.ts +170 -170
  15. package/lib/cjs/BriefcaseManager.js +414 -414
  16. package/lib/cjs/BriefcaseManager.js.map +1 -1
  17. package/lib/cjs/Category.d.ts +153 -153
  18. package/lib/cjs/Category.js +243 -243
  19. package/lib/cjs/Category.js.map +1 -1
  20. package/lib/cjs/ChangeSummaryManager.d.ts +187 -187
  21. package/lib/cjs/ChangeSummaryManager.js +447 -447
  22. package/lib/cjs/ChangeSummaryManager.js.map +1 -1
  23. package/lib/cjs/ChangedElementsDb.d.ts +99 -99
  24. package/lib/cjs/ChangedElementsDb.js +165 -165
  25. package/lib/cjs/ChangedElementsDb.js.map +1 -1
  26. package/lib/cjs/ChangedElementsManager.d.ts +39 -39
  27. package/lib/cjs/ChangedElementsManager.js +88 -88
  28. package/lib/cjs/ChangedElementsManager.js.map +1 -1
  29. package/lib/cjs/CheckpointManager.d.ts +121 -121
  30. package/lib/cjs/CheckpointManager.d.ts.map +1 -1
  31. package/lib/cjs/CheckpointManager.js +352 -349
  32. package/lib/cjs/CheckpointManager.js.map +1 -1
  33. package/lib/cjs/ClassRegistry.d.ts +79 -79
  34. package/lib/cjs/ClassRegistry.js +250 -250
  35. package/lib/cjs/ClassRegistry.js.map +1 -1
  36. package/lib/cjs/CloudSqlite.d.ts +350 -350
  37. package/lib/cjs/CloudSqlite.js +153 -153
  38. package/lib/cjs/CloudSqlite.js.map +1 -1
  39. package/lib/cjs/CloudStorageBackend.d.ts +58 -58
  40. package/lib/cjs/CloudStorageBackend.js +173 -173
  41. package/lib/cjs/CloudStorageBackend.js.map +1 -1
  42. package/lib/cjs/CodeService.d.ts +396 -396
  43. package/lib/cjs/CodeService.js +63 -63
  44. package/lib/cjs/CodeService.js.map +1 -1
  45. package/lib/cjs/CodeSpecs.d.ts +55 -55
  46. package/lib/cjs/CodeSpecs.js +124 -124
  47. package/lib/cjs/CodeSpecs.js.map +1 -1
  48. package/lib/cjs/ConcurrentQuery.d.ts +13 -13
  49. package/lib/cjs/ConcurrentQuery.js +36 -36
  50. package/lib/cjs/ConcurrentQuery.js.map +1 -1
  51. package/lib/cjs/CustomViewState3dCreator.d.ts +21 -21
  52. package/lib/cjs/CustomViewState3dCreator.js +82 -82
  53. package/lib/cjs/CustomViewState3dCreator.js.map +1 -1
  54. package/lib/cjs/DevTools.d.ts +71 -71
  55. package/lib/cjs/DevTools.js +154 -154
  56. package/lib/cjs/DevTools.js.map +1 -1
  57. package/lib/cjs/DisplayStyle.d.ts +106 -106
  58. package/lib/cjs/DisplayStyle.js +256 -256
  59. package/lib/cjs/DisplayStyle.js.map +1 -1
  60. package/lib/cjs/ECDb.d.ts +194 -194
  61. package/lib/cjs/ECDb.js +355 -355
  62. package/lib/cjs/ECDb.js.map +1 -1
  63. package/lib/cjs/ECSchemaXmlContext.d.ts +18 -18
  64. package/lib/cjs/ECSchemaXmlContext.js +41 -41
  65. package/lib/cjs/ECSchemaXmlContext.js.map +1 -1
  66. package/lib/cjs/ECSqlStatement.d.ts +473 -473
  67. package/lib/cjs/ECSqlStatement.js +791 -791
  68. package/lib/cjs/ECSqlStatement.js.map +1 -1
  69. package/lib/cjs/Element.d.ts +1109 -1109
  70. package/lib/cjs/Element.js +1427 -1427
  71. package/lib/cjs/Element.js.map +1 -1
  72. package/lib/cjs/ElementAspect.d.ts +179 -179
  73. package/lib/cjs/ElementAspect.js +211 -211
  74. package/lib/cjs/ElementAspect.js.map +1 -1
  75. package/lib/cjs/ElementGraphics.d.ts +9 -9
  76. package/lib/cjs/ElementGraphics.js +41 -41
  77. package/lib/cjs/ElementGraphics.js.map +1 -1
  78. package/lib/cjs/ElementTreeWalker.d.ts +162 -162
  79. package/lib/cjs/ElementTreeWalker.js +409 -409
  80. package/lib/cjs/ElementTreeWalker.js.map +1 -1
  81. package/lib/cjs/Entity.d.ts +106 -106
  82. package/lib/cjs/Entity.js +134 -134
  83. package/lib/cjs/Entity.js.map +1 -1
  84. package/lib/cjs/EntityReferences.d.ts +49 -49
  85. package/lib/cjs/EntityReferences.js +95 -95
  86. package/lib/cjs/EntityReferences.js.map +1 -1
  87. package/lib/cjs/ExportGraphics.d.ts +317 -317
  88. package/lib/cjs/ExportGraphics.js +208 -208
  89. package/lib/cjs/ExportGraphics.js.map +1 -1
  90. package/lib/cjs/ExternalSource.d.ts +96 -96
  91. package/lib/cjs/ExternalSource.js +131 -131
  92. package/lib/cjs/ExternalSource.js.map +1 -1
  93. package/lib/cjs/GeoCoordConfig.d.ts +19 -19
  94. package/lib/cjs/GeoCoordConfig.js +85 -85
  95. package/lib/cjs/GeoCoordConfig.js.map +1 -1
  96. package/lib/cjs/GeometrySummary.d.ts +4 -4
  97. package/lib/cjs/GeometrySummary.js +380 -380
  98. package/lib/cjs/GeometrySummary.js.map +1 -1
  99. package/lib/cjs/HubMock.d.ts +94 -94
  100. package/lib/cjs/HubMock.js +222 -222
  101. package/lib/cjs/HubMock.js.map +1 -1
  102. package/lib/cjs/IModelCloneContext.d.ts +8 -8
  103. package/lib/cjs/IModelCloneContext.js +15 -15
  104. package/lib/cjs/IModelCloneContext.js.map +1 -1
  105. package/lib/cjs/IModelDb.d.ts +1213 -1213
  106. package/lib/cjs/IModelDb.js +2392 -2392
  107. package/lib/cjs/IModelDb.js.map +1 -1
  108. package/lib/cjs/IModelElementCloneContext.d.ts +89 -89
  109. package/lib/cjs/IModelElementCloneContext.js +159 -159
  110. package/lib/cjs/IModelElementCloneContext.js.map +1 -1
  111. package/lib/cjs/IModelHost.d.ts +369 -369
  112. package/lib/cjs/IModelHost.js +496 -496
  113. package/lib/cjs/IModelHost.js.map +1 -1
  114. package/lib/cjs/IModelJsFs.d.ts +62 -62
  115. package/lib/cjs/IModelJsFs.js +140 -140
  116. package/lib/cjs/IModelJsFs.js.map +1 -1
  117. package/lib/cjs/IpcHost.d.ts +104 -104
  118. package/lib/cjs/IpcHost.js +278 -278
  119. package/lib/cjs/IpcHost.js.map +1 -1
  120. package/lib/cjs/LineStyle.d.ts +311 -311
  121. package/lib/cjs/LineStyle.js +295 -295
  122. package/lib/cjs/LineStyle.js.map +1 -1
  123. package/lib/cjs/LocalHub.d.ts +162 -162
  124. package/lib/cjs/LocalHub.js +585 -585
  125. package/lib/cjs/LocalHub.js.map +1 -1
  126. package/lib/cjs/LocalhostIpcHost.d.ts +21 -21
  127. package/lib/cjs/LocalhostIpcHost.js +81 -81
  128. package/lib/cjs/LocalhostIpcHost.js.map +1 -1
  129. package/lib/cjs/Material.d.ts +131 -131
  130. package/lib/cjs/Material.js +181 -181
  131. package/lib/cjs/Material.js.map +1 -1
  132. package/lib/cjs/Model.d.ts +392 -392
  133. package/lib/cjs/Model.js +485 -485
  134. package/lib/cjs/Model.js.map +1 -1
  135. package/lib/cjs/NativeAppStorage.d.ts +51 -51
  136. package/lib/cjs/NativeAppStorage.js +202 -202
  137. package/lib/cjs/NativeAppStorage.js.map +1 -1
  138. package/lib/cjs/NativeHost.d.ts +52 -52
  139. package/lib/cjs/NativeHost.js +163 -163
  140. package/lib/cjs/NativeHost.js.map +1 -1
  141. package/lib/cjs/NavigationRelationship.d.ts +156 -156
  142. package/lib/cjs/NavigationRelationship.js +225 -225
  143. package/lib/cjs/NavigationRelationship.js.map +1 -1
  144. package/lib/cjs/PromiseMemoizer.d.ts +51 -51
  145. package/lib/cjs/PromiseMemoizer.js +101 -101
  146. package/lib/cjs/PromiseMemoizer.js.map +1 -1
  147. package/lib/cjs/PropertyStore.d.ts +132 -132
  148. package/lib/cjs/PropertyStore.js +11 -11
  149. package/lib/cjs/PropertyStore.js.map +1 -1
  150. package/lib/cjs/Relationship.d.ts +416 -416
  151. package/lib/cjs/Relationship.js +494 -494
  152. package/lib/cjs/Relationship.js.map +1 -1
  153. package/lib/cjs/RpcBackend.d.ts +5 -5
  154. package/lib/cjs/RpcBackend.js +32 -32
  155. package/lib/cjs/RpcBackend.js.map +1 -1
  156. package/lib/cjs/SQLiteDb.d.ts +219 -219
  157. package/lib/cjs/SQLiteDb.js +214 -214
  158. package/lib/cjs/SQLiteDb.js.map +1 -1
  159. package/lib/cjs/Schema.d.ts +55 -55
  160. package/lib/cjs/Schema.js +83 -83
  161. package/lib/cjs/Schema.js.map +1 -1
  162. package/lib/cjs/ServerBasedLocks.d.ts +57 -57
  163. package/lib/cjs/ServerBasedLocks.js +168 -168
  164. package/lib/cjs/ServerBasedLocks.js.map +1 -1
  165. package/lib/cjs/SqliteStatement.d.ts +360 -360
  166. package/lib/cjs/SqliteStatement.js +586 -586
  167. package/lib/cjs/SqliteStatement.js.map +1 -1
  168. package/lib/cjs/Texture.d.ts +58 -58
  169. package/lib/cjs/Texture.js +82 -82
  170. package/lib/cjs/Texture.js.map +1 -1
  171. package/lib/cjs/TileStorage.d.ts +18 -18
  172. package/lib/cjs/TileStorage.js +90 -90
  173. package/lib/cjs/TileStorage.js.map +1 -1
  174. package/lib/cjs/TxnManager.d.ts +202 -202
  175. package/lib/cjs/TxnManager.js +356 -356
  176. package/lib/cjs/TxnManager.js.map +1 -1
  177. package/lib/cjs/ViewDefinition.d.ts +439 -439
  178. package/lib/cjs/ViewDefinition.js +646 -646
  179. package/lib/cjs/ViewDefinition.js.map +1 -1
  180. package/lib/cjs/ViewStateHydrator.d.ts +13 -13
  181. package/lib/cjs/ViewStateHydrator.js +103 -103
  182. package/lib/cjs/ViewStateHydrator.js.map +1 -1
  183. package/lib/cjs/assets/IModelChange.02.00.00.ecschema.xml +90 -90
  184. package/lib/cjs/assets/Settings/Schemas/Cloud.Schema.json +67 -67
  185. package/lib/cjs/assets/Settings/Schemas/Gcs.schema.json +31 -31
  186. package/lib/cjs/assets/Settings/Schemas/Workspace.Schema.json +52 -52
  187. package/lib/cjs/assets/Settings/backend.setting.json5 +138 -138
  188. package/lib/cjs/core-backend.d.ts +184 -184
  189. package/lib/cjs/core-backend.js +204 -204
  190. package/lib/cjs/core-backend.js.map +1 -1
  191. package/lib/cjs/domains/FunctionalElements.d.ts +101 -101
  192. package/lib/cjs/domains/FunctionalElements.js +145 -145
  193. package/lib/cjs/domains/FunctionalElements.js.map +1 -1
  194. package/lib/cjs/domains/FunctionalSchema.d.ts +13 -13
  195. package/lib/cjs/domains/FunctionalSchema.js +40 -40
  196. package/lib/cjs/domains/FunctionalSchema.js.map +1 -1
  197. package/lib/cjs/domains/GenericElements.d.ts +177 -177
  198. package/lib/cjs/domains/GenericElements.js +263 -263
  199. package/lib/cjs/domains/GenericElements.js.map +1 -1
  200. package/lib/cjs/domains/GenericSchema.d.ts +10 -10
  201. package/lib/cjs/domains/GenericSchema.js +28 -28
  202. package/lib/cjs/domains/GenericSchema.js.map +1 -1
  203. package/lib/cjs/rpc/multipart.d.ts +11 -11
  204. package/lib/cjs/rpc/multipart.js +71 -71
  205. package/lib/cjs/rpc/multipart.js.map +1 -1
  206. package/lib/cjs/rpc/tracing.d.ts +28 -28
  207. package/lib/cjs/rpc/tracing.js +74 -74
  208. package/lib/cjs/rpc/tracing.js.map +1 -1
  209. package/lib/cjs/rpc/web/logging.d.ts +9 -9
  210. package/lib/cjs/rpc/web/logging.js +43 -43
  211. package/lib/cjs/rpc/web/logging.js.map +1 -1
  212. package/lib/cjs/rpc/web/request.d.ts +6 -6
  213. package/lib/cjs/rpc/web/request.js +74 -74
  214. package/lib/cjs/rpc/web/request.js.map +1 -1
  215. package/lib/cjs/rpc/web/response.d.ts +6 -6
  216. package/lib/cjs/rpc/web/response.js +106 -106
  217. package/lib/cjs/rpc/web/response.js.map +1 -1
  218. package/lib/cjs/rpc-impl/DevToolsRpcImpl.d.ts +15 -15
  219. package/lib/cjs/rpc-impl/DevToolsRpcImpl.js +32 -32
  220. package/lib/cjs/rpc-impl/DevToolsRpcImpl.js.map +1 -1
  221. package/lib/cjs/rpc-impl/IModelReadRpcImpl.d.ts +47 -47
  222. package/lib/cjs/rpc-impl/IModelReadRpcImpl.js +294 -294
  223. package/lib/cjs/rpc-impl/IModelReadRpcImpl.js.map +1 -1
  224. package/lib/cjs/rpc-impl/IModelTileRpcImpl.d.ts +22 -22
  225. package/lib/cjs/rpc-impl/IModelTileRpcImpl.d.ts.map +1 -1
  226. package/lib/cjs/rpc-impl/IModelTileRpcImpl.js +211 -208
  227. package/lib/cjs/rpc-impl/IModelTileRpcImpl.js.map +1 -1
  228. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.d.ts +36 -36
  229. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js +168 -168
  230. package/lib/cjs/rpc-impl/RpcBriefcaseUtility.js.map +1 -1
  231. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.d.ts +16 -16
  232. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js +43 -43
  233. package/lib/cjs/rpc-impl/SnapshotIModelRpcImpl.js.map +1 -1
  234. package/lib/cjs/rpc-impl/WipRpcImpl.d.ts +15 -15
  235. package/lib/cjs/rpc-impl/WipRpcImpl.js +37 -37
  236. package/lib/cjs/rpc-impl/WipRpcImpl.js.map +1 -1
  237. package/lib/cjs/workspace/Settings.d.ts +186 -186
  238. package/lib/cjs/workspace/Settings.js +155 -155
  239. package/lib/cjs/workspace/Settings.js.map +1 -1
  240. package/lib/cjs/workspace/SettingsSchemas.d.ts +75 -75
  241. package/lib/cjs/workspace/SettingsSchemas.js +191 -191
  242. package/lib/cjs/workspace/SettingsSchemas.js.map +1 -1
  243. package/lib/cjs/workspace/Workspace.d.ts +414 -414
  244. package/lib/cjs/workspace/Workspace.js +543 -543
  245. package/lib/cjs/workspace/Workspace.js.map +1 -1
  246. package/package.json +12 -12
@@ -1,415 +1,415 @@
1
- "use strict";
2
- /*---------------------------------------------------------------------------------------------
3
- * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
- * See LICENSE.md in the project root for license terms and full copyright notice.
5
- *--------------------------------------------------------------------------------------------*/
6
- /** @packageDocumentation
7
- * @module iModels
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.BriefcaseManager = void 0;
11
- // cspell:ignore cset csets ecchanges
12
- const path = require("path");
13
- const core_bentley_1 = require("@itwin/core-bentley");
14
- const core_common_1 = require("@itwin/core-common");
15
- const core_telemetry_1 = require("@itwin/core-telemetry");
16
- const BackendLoggerCategory_1 = require("./BackendLoggerCategory");
17
- const CheckpointManager_1 = require("./CheckpointManager");
18
- const IModelDb_1 = require("./IModelDb");
19
- const IModelHost_1 = require("./IModelHost");
20
- const IModelJsFs_1 = require("./IModelJsFs");
21
- const loggerCategory = BackendLoggerCategory_1.BackendLoggerCategory.IModelDb;
22
- /** Manages downloading Briefcases and downloading and uploading changesets.
23
- * @public
24
- */
25
- class BriefcaseManager {
26
- /** Get the local path of the folder storing files that are associated with an imodel */
27
- static getIModelPath(iModelId) { return path.join(this._cacheDir, iModelId); }
28
- /** @internal */
29
- static getChangeSetsPath(iModelId) { return path.join(this.getIModelPath(iModelId), "changesets"); }
30
- /** @internal */
31
- static getChangeCachePathName(iModelId) { return path.join(this.getIModelPath(iModelId), iModelId.concat(".bim.ecchanges")); }
32
- /** @internal */
33
- static getChangedElementsPathName(iModelId) { return path.join(this.getIModelPath(iModelId), iModelId.concat(".bim.elems")); }
34
- /** @internal */
35
- static getBriefcaseBasePath(iModelId) {
36
- return path.join(this.getIModelPath(iModelId), this._briefcaseSubDir);
37
- }
38
- /** Get the name of the local file that holds, or will hold, a local briefcase in the briefcase cache.
39
- * @note The briefcase cache is a local directory established in the call to [[BriefcaseManager.initialize]].
40
- * @param briefcase the iModelId and BriefcaseId for the filename
41
- * @see getIModelPath
42
- */
43
- static getFileName(briefcase) {
44
- return path.join(this.getBriefcaseBasePath(briefcase.iModelId), `${briefcase.briefcaseId}.bim`);
45
- }
46
- static setupCacheDir(cacheRootDir) {
47
- this._cacheDir = cacheRootDir;
48
- IModelJsFs_1.IModelJsFs.recursiveMkDirSync(this._cacheDir);
49
- }
50
- /** Initialize BriefcaseManager
51
- * @param cacheRootDir The root directory for storing a cache of downloaded briefcase files on the local computer.
52
- * Briefcases are stored relative to this path in sub-folders organized by IModelId.
53
- * @note It is perfectly valid for applications to store briefcases in locations they manage, outside of `cacheRootDir`.
54
- */
55
- static initialize(cacheRootDir) {
56
- if (this._initialized)
57
- return;
58
- this.setupCacheDir(cacheRootDir);
59
- IModelHost_1.IModelHost.onBeforeShutdown.addOnce(this.finalize, this);
60
- this._initialized = true;
61
- }
62
- static finalize() {
63
- this._initialized = false;
64
- }
65
- /** Get a list of the local briefcase held in the briefcase cache, optionally for a single iModelId
66
- * @param iModelId if present, only briefcases for this iModelId are returned, otherwise all briefcases for all
67
- * iModels in the briefcase cache are returned.
68
- * @note usually there should only be one briefcase per iModel.
69
- */
70
- static getCachedBriefcases(iModelId) {
71
- var _a, _b, _c;
72
- const briefcaseList = [];
73
- const iModelDirs = IModelJsFs_1.IModelJsFs.readdirSync(this._cacheDir);
74
- for (const iModelDir of iModelDirs) {
75
- if (iModelId && iModelId !== iModelDir)
76
- continue;
77
- const bcPath = path.join(this._cacheDir, iModelDir, this._briefcaseSubDir);
78
- try {
79
- if (!((_a = IModelJsFs_1.IModelJsFs.lstatSync(bcPath)) === null || _a === void 0 ? void 0 : _a.isDirectory))
80
- continue;
81
- }
82
- catch (err) {
83
- continue;
84
- }
85
- const briefcases = IModelJsFs_1.IModelJsFs.readdirSync(bcPath);
86
- for (const briefcaseName of briefcases) {
87
- if (briefcaseName.endsWith(".bim")) {
88
- try {
89
- const fileName = path.join(bcPath, briefcaseName);
90
- const fileSize = (_c = (_b = IModelJsFs_1.IModelJsFs.lstatSync(fileName)) === null || _b === void 0 ? void 0 : _b.size) !== null && _c !== void 0 ? _c : 0;
91
- const db = IModelDb_1.IModelDb.openDgnDb({ path: fileName }, core_bentley_1.OpenMode.Readonly);
92
- briefcaseList.push({ fileName, iTwinId: db.getITwinId(), iModelId: db.getIModelId(), briefcaseId: db.getBriefcaseId(), changeset: db.getCurrentChangeset(), fileSize });
93
- db.closeIModel();
94
- }
95
- catch (_err) {
96
- }
97
- }
98
- }
99
- }
100
- return briefcaseList;
101
- }
102
- /** Get the root directory for the briefcase cache */
103
- static get cacheDir() { return this._cacheDir; }
104
- /** Determine whether the supplied briefcaseId is in the range of assigned BriefcaseIds issued by iModelHub
105
- * @note this does check whether the id was actually acquired by the caller.
106
- */
107
- static isValidBriefcaseId(id) {
108
- return id >= core_common_1.BriefcaseIdValue.FirstValid && id <= core_common_1.BriefcaseIdValue.LastValid;
109
- }
110
- /** Acquire a new briefcaseId from iModelHub for the supplied iModelId
111
- * @note usually there should only be one briefcase per iModel per user. If a single user acquires more than one briefcaseId,
112
- * it's a good idea to supply different aliases for each of them.
113
- */
114
- static async acquireNewBriefcaseId(arg) {
115
- return IModelHost_1.IModelHost.hubAccess.acquireNewBriefcaseId(arg);
116
- }
117
- /**
118
- * Download a new briefcase from iModelHub for the supplied iModelId.
119
- *
120
- * Briefcases are local files holding a copy of an iModel.
121
- * Briefcases may either be specific to an individual user (so that it can be modified to create changesets), or it can be readonly so it can accept but not create changesets.
122
- * Every briefcase internally holds its [[BriefcaseId]]. Writeable briefcases have a `BriefcaseId` "assigned" to them by iModelHub. No two users will ever have the same BriefcaseId.
123
- * Readonly briefcases are "unassigned" with the special value [[BriefcaseId.Unassigned]].
124
- *
125
- * Typically a given user will have only one briefcase on their machine for a given iModelId. Rarely, it may be necessary to use more than one
126
- * briefcase to make isolated independent sets of changes, but that is exceedingly complicated and rare.
127
- *
128
- * Callers of this method may supply a BriefcaseId, or if none is supplied, a new one is acquired from iModelHub.
129
- *
130
- * @param arg The arguments that specify the briefcase file to be downloaded.
131
- * @returns The properties of the local briefcase in a Promise that is resolved after the briefcase is fully downloaded and the briefcase file is ready for use via [BriefcaseDb.open]($backend).
132
- * @note The location of the local file to hold the briefcase is arbitrary and may be any valid *local* path on your machine. If you don't supply
133
- * a filename, the local briefcase cache is used by creating a file with the briefcaseId as its name in the `briefcases` folder below the folder named
134
- * for the IModelId.
135
- * @note *It is invalid to edit briefcases on a shared network drive* and that is a sure way to corrupt your briefcase (see https://www.sqlite.org/howtocorrupt.html)
136
- */
137
- static async downloadBriefcase(arg) {
138
- var _a, _b, _c, _d, _e;
139
- const briefcaseId = (_a = arg.briefcaseId) !== null && _a !== void 0 ? _a : await this.acquireNewBriefcaseId(arg);
140
- const fileName = (_b = arg.fileName) !== null && _b !== void 0 ? _b : this.getFileName({ ...arg, briefcaseId });
141
- if (IModelJsFs_1.IModelJsFs.existsSync(fileName))
142
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.FileAlreadyExists, `Briefcase "${fileName}" already exists`);
143
- const asOf = (_c = arg.asOf) !== null && _c !== void 0 ? _c : core_common_1.IModelVersion.latest().toJSON();
144
- const changeset = await IModelHost_1.IModelHost.hubAccess.getChangesetFromVersion({ ...arg, version: core_common_1.IModelVersion.fromJSON(asOf) });
145
- const checkpoint = { ...arg, changeset };
146
- try {
147
- await CheckpointManager_1.CheckpointManager.downloadCheckpoint({ localFile: fileName, checkpoint, onProgress: arg.onProgress });
148
- }
149
- catch (error) {
150
- if (arg.accessToken && arg.briefcaseId === undefined)
151
- await this.releaseBriefcase(arg.accessToken, { briefcaseId, iModelId: arg.iModelId });
152
- throw error;
153
- }
154
- const fileSize = (_e = (_d = IModelJsFs_1.IModelJsFs.lstatSync(fileName)) === null || _d === void 0 ? void 0 : _d.size) !== null && _e !== void 0 ? _e : 0;
155
- const response = {
156
- fileName,
157
- briefcaseId,
158
- iModelId: arg.iModelId,
159
- iTwinId: arg.iTwinId,
160
- changeset: checkpoint.changeset,
161
- fileSize,
162
- };
163
- // now open the downloaded checkpoint and reset its BriefcaseId
164
- const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
165
- try {
166
- nativeDb.openIModel(fileName, core_bentley_1.OpenMode.ReadWrite);
167
- }
168
- catch (err) {
169
- throw new core_common_1.IModelError(err.errorNumber, `Could not open downloaded briefcase for write access: ${fileName}, err=${err.message}`);
170
- }
171
- try {
172
- nativeDb.enableWalMode(); // local briefcases should use WAL journal mode
173
- nativeDb.resetBriefcaseId(briefcaseId);
174
- if (nativeDb.getCurrentChangeset().id !== checkpoint.changeset.id)
175
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidId, `Downloaded briefcase has wrong changesetId: ${fileName}`);
176
- }
177
- finally {
178
- nativeDb.saveChanges();
179
- nativeDb.closeIModel();
180
- }
181
- return response;
182
- }
183
- /** Deletes change sets of an iModel from local disk
184
- * @internal
185
- */
186
- static deleteChangeSetsFromLocalDisk(iModelId) {
187
- const changesetsPath = BriefcaseManager.getChangeSetsPath(iModelId);
188
- BriefcaseManager.deleteFolderAndContents(changesetsPath);
189
- }
190
- /** Releases a briefcaseId from iModelHub. After this call it is illegal to generate changesets for the released briefcaseId.
191
- * @note generally, this method should not be called directly. Instead use [[deleteBriefcaseFiles]].
192
- * @see deleteBriefcaseFiles
193
- */
194
- static async releaseBriefcase(accessToken, briefcase) {
195
- if (this.isValidBriefcaseId(briefcase.briefcaseId))
196
- return IModelHost_1.IModelHost.hubAccess.releaseBriefcase({ accessToken, iModelId: briefcase.iModelId, briefcaseId: briefcase.briefcaseId });
197
- }
198
- /**
199
- * Delete and clean up a briefcase and all of its associated files. First, this method opens the supplied filename to determine its briefcaseId.
200
- * Then, if a requestContext is supplied, it releases a BriefcaseId from iModelHub. Finally it deletes the local briefcase file and
201
- * associated files (that is, all files in the same directory that start with the briefcase name).
202
- * @param filePath the full file name of the Briefcase to delete
203
- * @param accessToken for releasing the briefcaseId
204
- */
205
- static async deleteBriefcaseFiles(filePath, accessToken) {
206
- try {
207
- const db = IModelDb_1.IModelDb.openDgnDb({ path: filePath }, core_bentley_1.OpenMode.Readonly);
208
- const briefcase = {
209
- iModelId: db.getIModelId(),
210
- briefcaseId: db.getBriefcaseId(),
211
- };
212
- db.closeIModel();
213
- if (accessToken) {
214
- if (this.isValidBriefcaseId(briefcase.briefcaseId)) {
215
- await BriefcaseManager.releaseBriefcase(accessToken, briefcase);
216
- }
217
- }
218
- }
219
- catch (error) {
220
- }
221
- // first try to delete the briefcase file
222
- try {
223
- if (IModelJsFs_1.IModelJsFs.existsSync(filePath))
224
- IModelJsFs_1.IModelJsFs.unlinkSync(filePath);
225
- }
226
- catch (err) {
227
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadRequest, `cannot delete briefcase file ${err}`);
228
- }
229
- // next, delete all files that start with the briefcase's filePath (e.g. "a.bim-locks", "a.bim-journal", etc.)
230
- try {
231
- const dirName = path.dirname(filePath);
232
- const fileName = path.basename(filePath);
233
- const files = IModelJsFs_1.IModelJsFs.readdirSync(dirName);
234
- for (const file of files) {
235
- if (file.startsWith(fileName))
236
- this.deleteFile(path.join(dirName, file)); // don't throw on error
237
- }
238
- }
239
- catch (err) {
240
- }
241
- }
242
- /** Deletes a file
243
- * - Does not throw any error, but logs it instead
244
- * - Returns true if the delete was successful
245
- */
246
- static deleteFile(pathname) {
247
- try {
248
- IModelJsFs_1.IModelJsFs.unlinkSync(pathname);
249
- }
250
- catch (error) {
251
- core_bentley_1.Logger.logError(loggerCategory, `Cannot delete file ${pathname}, ${error}`);
252
- return false;
253
- }
254
- return true;
255
- }
256
- /** Deletes a folder, checking if it's empty
257
- * - Does not throw any error, but logs it instead
258
- * - Returns true if the delete was successful
259
- */
260
- static deleteFolderIfEmpty(folderPathname) {
261
- try {
262
- const files = IModelJsFs_1.IModelJsFs.readdirSync(folderPathname);
263
- if (files.length > 0)
264
- return false;
265
- IModelJsFs_1.IModelJsFs.rmdirSync(folderPathname);
266
- }
267
- catch (error) {
268
- core_bentley_1.Logger.logError(loggerCategory, `Cannot delete folder: ${folderPathname}`);
269
- return false;
270
- }
271
- return true;
272
- }
273
- /** Deletes the contents of a folder, but not the folder itself
274
- * - Does not throw any errors, but logs them.
275
- * - returns true if the delete was successful.
276
- */
277
- static deleteFolderContents(folderPathname) {
278
- var _a;
279
- if (!IModelJsFs_1.IModelJsFs.existsSync(folderPathname))
280
- return false;
281
- let status = true;
282
- const files = IModelJsFs_1.IModelJsFs.readdirSync(folderPathname);
283
- for (const file of files) {
284
- const curPath = path.join(folderPathname, file);
285
- const locStatus = ((_a = IModelJsFs_1.IModelJsFs.lstatSync(curPath)) === null || _a === void 0 ? void 0 : _a.isDirectory) ? BriefcaseManager.deleteFolderAndContents(curPath) : BriefcaseManager.deleteFile(curPath);
286
- if (!locStatus)
287
- status = false;
288
- }
289
- return status;
290
- }
291
- /** Deletes a folder and all it's contents.
292
- * - Does not throw any errors, but logs them.
293
- * - returns true if the delete was successful.
294
- */
295
- static deleteFolderAndContents(folderPathname) {
296
- if (!IModelJsFs_1.IModelJsFs.existsSync(folderPathname))
297
- return true;
298
- let status = false;
299
- status = BriefcaseManager.deleteFolderContents(folderPathname);
300
- if (!status)
301
- return false;
302
- status = BriefcaseManager.deleteFolderIfEmpty(folderPathname);
303
- return status;
304
- }
305
- static async applySingleChangeset(db, changesetFile) {
306
- if (changesetFile.changesType === core_common_1.ChangesetType.Schema)
307
- db.clearCaches(); // for schema changesets, statement caches may become invalid. Do this *before* applying, in case db needs to be closed (open statements hold db open.)
308
- db.nativeDb.applyChangeset(changesetFile);
309
- db.changeset = db.nativeDb.getCurrentChangeset();
310
- // we're done with this changeset, delete it
311
- IModelJsFs_1.IModelJsFs.removeSync(changesetFile.pathname);
312
- }
313
- /** @internal */
314
- static async pullAndApplyChangesets(db, arg) {
315
- if (!db.isOpen || db.nativeDb.isReadonly()) // don't use db.isReadonly - we reopen the file writable just for this operation but db.isReadonly is still true
316
- throw new core_common_1.IModelError(core_bentley_1.ChangeSetStatus.ApplyError, "Briefcase must be open ReadWrite to process change sets");
317
- let currentIndex = db.changeset.index;
318
- if (currentIndex === undefined)
319
- currentIndex = (await IModelHost_1.IModelHost.hubAccess.queryChangeset({ accessToken: arg.accessToken, iModelId: db.iModelId, changeset: { id: db.changeset.id } })).index;
320
- const reverse = (arg.toIndex && arg.toIndex < currentIndex) ? true : false;
321
- // Download change sets
322
- const changesets = await IModelHost_1.IModelHost.hubAccess.downloadChangesets({
323
- accessToken: arg.accessToken,
324
- iModelId: db.iModelId,
325
- range: { first: reverse ? arg.toIndex + 1 : currentIndex + 1, end: reverse ? currentIndex : arg.toIndex },
326
- targetDir: BriefcaseManager.getChangeSetsPath(db.iModelId),
327
- progressCallback: arg.onProgress,
328
- });
329
- if (changesets.length === 0)
330
- return; // nothing to apply
331
- if (reverse)
332
- changesets.reverse();
333
- for (const changeset of changesets)
334
- await this.applySingleChangeset(db, changeset);
335
- // notify listeners
336
- db.notifyChangesetApplied();
337
- }
338
- /** create a changeset from the current changes, and push it to iModelHub */
339
- static async pushChanges(db, arg) {
340
- var _a, _b;
341
- const changesetProps = db.nativeDb.startCreateChangeset();
342
- changesetProps.briefcaseId = db.briefcaseId;
343
- changesetProps.description = arg.description;
344
- changesetProps.size = (_a = IModelJsFs_1.IModelJsFs.lstatSync(changesetProps.pathname)) === null || _a === void 0 ? void 0 : _a.size;
345
- if (!changesetProps.size) // either undefined or 0 means error
346
- throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NoContent, "error creating changeset");
347
- let retryCount = (_b = arg.pushRetryCount) !== null && _b !== void 0 ? _b : 3;
348
- while (true) {
349
- try {
350
- const accessToken = await IModelHost_1.IModelHost.getAccessToken();
351
- const index = await IModelHost_1.IModelHost.hubAccess.pushChangeset({ accessToken, iModelId: db.iModelId, changesetProps });
352
- db.nativeDb.completeCreateChangeset({ index });
353
- db.changeset = db.nativeDb.getCurrentChangeset();
354
- if (!arg.retainLocks)
355
- await db.locks.releaseAllLocks();
356
- return;
357
- }
358
- catch (err) {
359
- const shouldRetry = () => {
360
- if (retryCount-- <= 0)
361
- return false;
362
- switch (err.errorNumber) {
363
- case core_bentley_1.IModelHubStatus.AnotherUserPushing:
364
- case core_bentley_1.IModelHubStatus.DatabaseTemporarilyLocked:
365
- case core_bentley_1.IModelHubStatus.OperationFailed:
366
- return true;
367
- }
368
- return false;
369
- };
370
- if (!shouldRetry()) {
371
- db.nativeDb.abandonCreateChangeset();
372
- throw err;
373
- }
374
- }
375
- finally {
376
- IModelJsFs_1.IModelJsFs.removeSync(changesetProps.pathname);
377
- }
378
- }
379
- }
380
- /** Pull/merge (if necessary), then push all local changes as a changeset. Called by [[BriefcaseDb.pushChanges]]
381
- * @internal
382
- */
383
- static async pullMergePush(db, arg) {
384
- var _a, _b;
385
- let retryCount = (_a = arg.mergeRetryCount) !== null && _a !== void 0 ? _a : 5;
386
- while (true) {
387
- try {
388
- await BriefcaseManager.pullAndApplyChangesets(db, arg);
389
- return await BriefcaseManager.pushChanges(db, arg);
390
- }
391
- catch (err) {
392
- if (retryCount-- <= 0 || err.errorNumber !== core_bentley_1.IModelHubStatus.PullIsRequired)
393
- throw (err);
394
- await ((_b = arg.mergeRetryDelay) !== null && _b !== void 0 ? _b : core_bentley_1.BeDuration.fromSeconds(3)).wait();
395
- }
396
- }
397
- }
398
- /** @internal */
399
- static logUsage(imodel, activity) {
400
- var _a;
401
- const telemetryEvent = new core_telemetry_1.TelemetryEvent("core-backend - Open iModel", "7a6424d1-2114-4e89-b13b-43670a38ccd4", // Feature: "iModel Use"
402
- imodel.iTwinId, imodel.iModelId, (_a = imodel.changeset) === null || _a === void 0 ? void 0 : _a.id);
403
- activity = activity !== null && activity !== void 0 ? activity : {
404
- activityId: "",
405
- applicationId: IModelHost_1.IModelHost.applicationId,
406
- applicationVersion: IModelHost_1.IModelHost.applicationVersion,
407
- sessionId: IModelHost_1.IModelHost.sessionId,
408
- accessToken: "", // IModelHost.getAccessToken(); ACCESS_TOKEN_NEEDS_WORK
409
- };
410
- IModelHost_1.IModelHost.telemetry.postTelemetry(activity, telemetryEvent); // eslint-disable-line @typescript-eslint/no-floating-promises
411
- }
412
- }
413
- exports.BriefcaseManager = BriefcaseManager;
414
- BriefcaseManager._briefcaseSubDir = "briefcases";
1
+ "use strict";
2
+ /*---------------------------------------------------------------------------------------------
3
+ * Copyright (c) Bentley Systems, Incorporated. All rights reserved.
4
+ * See LICENSE.md in the project root for license terms and full copyright notice.
5
+ *--------------------------------------------------------------------------------------------*/
6
+ /** @packageDocumentation
7
+ * @module iModels
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.BriefcaseManager = void 0;
11
+ // cspell:ignore cset csets ecchanges
12
+ const path = require("path");
13
+ const core_bentley_1 = require("@itwin/core-bentley");
14
+ const core_common_1 = require("@itwin/core-common");
15
+ const core_telemetry_1 = require("@itwin/core-telemetry");
16
+ const BackendLoggerCategory_1 = require("./BackendLoggerCategory");
17
+ const CheckpointManager_1 = require("./CheckpointManager");
18
+ const IModelDb_1 = require("./IModelDb");
19
+ const IModelHost_1 = require("./IModelHost");
20
+ const IModelJsFs_1 = require("./IModelJsFs");
21
+ const loggerCategory = BackendLoggerCategory_1.BackendLoggerCategory.IModelDb;
22
+ /** Manages downloading Briefcases and downloading and uploading changesets.
23
+ * @public
24
+ */
25
+ class BriefcaseManager {
26
+ /** Get the local path of the folder storing files that are associated with an imodel */
27
+ static getIModelPath(iModelId) { return path.join(this._cacheDir, iModelId); }
28
+ /** @internal */
29
+ static getChangeSetsPath(iModelId) { return path.join(this.getIModelPath(iModelId), "changesets"); }
30
+ /** @internal */
31
+ static getChangeCachePathName(iModelId) { return path.join(this.getIModelPath(iModelId), iModelId.concat(".bim.ecchanges")); }
32
+ /** @internal */
33
+ static getChangedElementsPathName(iModelId) { return path.join(this.getIModelPath(iModelId), iModelId.concat(".bim.elems")); }
34
+ /** @internal */
35
+ static getBriefcaseBasePath(iModelId) {
36
+ return path.join(this.getIModelPath(iModelId), this._briefcaseSubDir);
37
+ }
38
+ /** Get the name of the local file that holds, or will hold, a local briefcase in the briefcase cache.
39
+ * @note The briefcase cache is a local directory established in the call to [[BriefcaseManager.initialize]].
40
+ * @param briefcase the iModelId and BriefcaseId for the filename
41
+ * @see getIModelPath
42
+ */
43
+ static getFileName(briefcase) {
44
+ return path.join(this.getBriefcaseBasePath(briefcase.iModelId), `${briefcase.briefcaseId}.bim`);
45
+ }
46
+ static setupCacheDir(cacheRootDir) {
47
+ this._cacheDir = cacheRootDir;
48
+ IModelJsFs_1.IModelJsFs.recursiveMkDirSync(this._cacheDir);
49
+ }
50
+ /** Initialize BriefcaseManager
51
+ * @param cacheRootDir The root directory for storing a cache of downloaded briefcase files on the local computer.
52
+ * Briefcases are stored relative to this path in sub-folders organized by IModelId.
53
+ * @note It is perfectly valid for applications to store briefcases in locations they manage, outside of `cacheRootDir`.
54
+ */
55
+ static initialize(cacheRootDir) {
56
+ if (this._initialized)
57
+ return;
58
+ this.setupCacheDir(cacheRootDir);
59
+ IModelHost_1.IModelHost.onBeforeShutdown.addOnce(this.finalize, this);
60
+ this._initialized = true;
61
+ }
62
+ static finalize() {
63
+ this._initialized = false;
64
+ }
65
+ /** Get a list of the local briefcase held in the briefcase cache, optionally for a single iModelId
66
+ * @param iModelId if present, only briefcases for this iModelId are returned, otherwise all briefcases for all
67
+ * iModels in the briefcase cache are returned.
68
+ * @note usually there should only be one briefcase per iModel.
69
+ */
70
+ static getCachedBriefcases(iModelId) {
71
+ var _a, _b, _c;
72
+ const briefcaseList = [];
73
+ const iModelDirs = IModelJsFs_1.IModelJsFs.readdirSync(this._cacheDir);
74
+ for (const iModelDir of iModelDirs) {
75
+ if (iModelId && iModelId !== iModelDir)
76
+ continue;
77
+ const bcPath = path.join(this._cacheDir, iModelDir, this._briefcaseSubDir);
78
+ try {
79
+ if (!((_a = IModelJsFs_1.IModelJsFs.lstatSync(bcPath)) === null || _a === void 0 ? void 0 : _a.isDirectory))
80
+ continue;
81
+ }
82
+ catch (err) {
83
+ continue;
84
+ }
85
+ const briefcases = IModelJsFs_1.IModelJsFs.readdirSync(bcPath);
86
+ for (const briefcaseName of briefcases) {
87
+ if (briefcaseName.endsWith(".bim")) {
88
+ try {
89
+ const fileName = path.join(bcPath, briefcaseName);
90
+ const fileSize = (_c = (_b = IModelJsFs_1.IModelJsFs.lstatSync(fileName)) === null || _b === void 0 ? void 0 : _b.size) !== null && _c !== void 0 ? _c : 0;
91
+ const db = IModelDb_1.IModelDb.openDgnDb({ path: fileName }, core_bentley_1.OpenMode.Readonly);
92
+ briefcaseList.push({ fileName, iTwinId: db.getITwinId(), iModelId: db.getIModelId(), briefcaseId: db.getBriefcaseId(), changeset: db.getCurrentChangeset(), fileSize });
93
+ db.closeIModel();
94
+ }
95
+ catch (_err) {
96
+ }
97
+ }
98
+ }
99
+ }
100
+ return briefcaseList;
101
+ }
102
+ /** Get the root directory for the briefcase cache */
103
+ static get cacheDir() { return this._cacheDir; }
104
+ /** Determine whether the supplied briefcaseId is in the range of assigned BriefcaseIds issued by iModelHub
105
+ * @note this does check whether the id was actually acquired by the caller.
106
+ */
107
+ static isValidBriefcaseId(id) {
108
+ return id >= core_common_1.BriefcaseIdValue.FirstValid && id <= core_common_1.BriefcaseIdValue.LastValid;
109
+ }
110
+ /** Acquire a new briefcaseId from iModelHub for the supplied iModelId
111
+ * @note usually there should only be one briefcase per iModel per user. If a single user acquires more than one briefcaseId,
112
+ * it's a good idea to supply different aliases for each of them.
113
+ */
114
+ static async acquireNewBriefcaseId(arg) {
115
+ return IModelHost_1.IModelHost.hubAccess.acquireNewBriefcaseId(arg);
116
+ }
117
+ /**
118
+ * Download a new briefcase from iModelHub for the supplied iModelId.
119
+ *
120
+ * Briefcases are local files holding a copy of an iModel.
121
+ * Briefcases may either be specific to an individual user (so that it can be modified to create changesets), or it can be readonly so it can accept but not create changesets.
122
+ * Every briefcase internally holds its [[BriefcaseId]]. Writeable briefcases have a `BriefcaseId` "assigned" to them by iModelHub. No two users will ever have the same BriefcaseId.
123
+ * Readonly briefcases are "unassigned" with the special value [[BriefcaseId.Unassigned]].
124
+ *
125
+ * Typically a given user will have only one briefcase on their machine for a given iModelId. Rarely, it may be necessary to use more than one
126
+ * briefcase to make isolated independent sets of changes, but that is exceedingly complicated and rare.
127
+ *
128
+ * Callers of this method may supply a BriefcaseId, or if none is supplied, a new one is acquired from iModelHub.
129
+ *
130
+ * @param arg The arguments that specify the briefcase file to be downloaded.
131
+ * @returns The properties of the local briefcase in a Promise that is resolved after the briefcase is fully downloaded and the briefcase file is ready for use via [BriefcaseDb.open]($backend).
132
+ * @note The location of the local file to hold the briefcase is arbitrary and may be any valid *local* path on your machine. If you don't supply
133
+ * a filename, the local briefcase cache is used by creating a file with the briefcaseId as its name in the `briefcases` folder below the folder named
134
+ * for the IModelId.
135
+ * @note *It is invalid to edit briefcases on a shared network drive* and that is a sure way to corrupt your briefcase (see https://www.sqlite.org/howtocorrupt.html)
136
+ */
137
+ static async downloadBriefcase(arg) {
138
+ var _a, _b, _c, _d, _e;
139
+ const briefcaseId = (_a = arg.briefcaseId) !== null && _a !== void 0 ? _a : await this.acquireNewBriefcaseId(arg);
140
+ const fileName = (_b = arg.fileName) !== null && _b !== void 0 ? _b : this.getFileName({ ...arg, briefcaseId });
141
+ if (IModelJsFs_1.IModelJsFs.existsSync(fileName))
142
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.FileAlreadyExists, `Briefcase "${fileName}" already exists`);
143
+ const asOf = (_c = arg.asOf) !== null && _c !== void 0 ? _c : core_common_1.IModelVersion.latest().toJSON();
144
+ const changeset = await IModelHost_1.IModelHost.hubAccess.getChangesetFromVersion({ ...arg, version: core_common_1.IModelVersion.fromJSON(asOf) });
145
+ const checkpoint = { ...arg, changeset };
146
+ try {
147
+ await CheckpointManager_1.CheckpointManager.downloadCheckpoint({ localFile: fileName, checkpoint, onProgress: arg.onProgress });
148
+ }
149
+ catch (error) {
150
+ if (arg.accessToken && arg.briefcaseId === undefined)
151
+ await this.releaseBriefcase(arg.accessToken, { briefcaseId, iModelId: arg.iModelId });
152
+ throw error;
153
+ }
154
+ const fileSize = (_e = (_d = IModelJsFs_1.IModelJsFs.lstatSync(fileName)) === null || _d === void 0 ? void 0 : _d.size) !== null && _e !== void 0 ? _e : 0;
155
+ const response = {
156
+ fileName,
157
+ briefcaseId,
158
+ iModelId: arg.iModelId,
159
+ iTwinId: arg.iTwinId,
160
+ changeset: checkpoint.changeset,
161
+ fileSize,
162
+ };
163
+ // now open the downloaded checkpoint and reset its BriefcaseId
164
+ const nativeDb = new IModelHost_1.IModelHost.platform.DgnDb();
165
+ try {
166
+ nativeDb.openIModel(fileName, core_bentley_1.OpenMode.ReadWrite);
167
+ }
168
+ catch (err) {
169
+ throw new core_common_1.IModelError(err.errorNumber, `Could not open downloaded briefcase for write access: ${fileName}, err=${err.message}`);
170
+ }
171
+ try {
172
+ nativeDb.enableWalMode(); // local briefcases should use WAL journal mode
173
+ nativeDb.resetBriefcaseId(briefcaseId);
174
+ if (nativeDb.getCurrentChangeset().id !== checkpoint.changeset.id)
175
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.InvalidId, `Downloaded briefcase has wrong changesetId: ${fileName}`);
176
+ }
177
+ finally {
178
+ nativeDb.saveChanges();
179
+ nativeDb.closeIModel();
180
+ }
181
+ return response;
182
+ }
183
+ /** Deletes change sets of an iModel from local disk
184
+ * @internal
185
+ */
186
+ static deleteChangeSetsFromLocalDisk(iModelId) {
187
+ const changesetsPath = BriefcaseManager.getChangeSetsPath(iModelId);
188
+ BriefcaseManager.deleteFolderAndContents(changesetsPath);
189
+ }
190
+ /** Releases a briefcaseId from iModelHub. After this call it is illegal to generate changesets for the released briefcaseId.
191
+ * @note generally, this method should not be called directly. Instead use [[deleteBriefcaseFiles]].
192
+ * @see deleteBriefcaseFiles
193
+ */
194
+ static async releaseBriefcase(accessToken, briefcase) {
195
+ if (this.isValidBriefcaseId(briefcase.briefcaseId))
196
+ return IModelHost_1.IModelHost.hubAccess.releaseBriefcase({ accessToken, iModelId: briefcase.iModelId, briefcaseId: briefcase.briefcaseId });
197
+ }
198
+ /**
199
+ * Delete and clean up a briefcase and all of its associated files. First, this method opens the supplied filename to determine its briefcaseId.
200
+ * Then, if a requestContext is supplied, it releases a BriefcaseId from iModelHub. Finally it deletes the local briefcase file and
201
+ * associated files (that is, all files in the same directory that start with the briefcase name).
202
+ * @param filePath the full file name of the Briefcase to delete
203
+ * @param accessToken for releasing the briefcaseId
204
+ */
205
+ static async deleteBriefcaseFiles(filePath, accessToken) {
206
+ try {
207
+ const db = IModelDb_1.IModelDb.openDgnDb({ path: filePath }, core_bentley_1.OpenMode.Readonly);
208
+ const briefcase = {
209
+ iModelId: db.getIModelId(),
210
+ briefcaseId: db.getBriefcaseId(),
211
+ };
212
+ db.closeIModel();
213
+ if (accessToken) {
214
+ if (this.isValidBriefcaseId(briefcase.briefcaseId)) {
215
+ await BriefcaseManager.releaseBriefcase(accessToken, briefcase);
216
+ }
217
+ }
218
+ }
219
+ catch (error) {
220
+ }
221
+ // first try to delete the briefcase file
222
+ try {
223
+ if (IModelJsFs_1.IModelJsFs.existsSync(filePath))
224
+ IModelJsFs_1.IModelJsFs.unlinkSync(filePath);
225
+ }
226
+ catch (err) {
227
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.BadRequest, `cannot delete briefcase file ${err}`);
228
+ }
229
+ // next, delete all files that start with the briefcase's filePath (e.g. "a.bim-locks", "a.bim-journal", etc.)
230
+ try {
231
+ const dirName = path.dirname(filePath);
232
+ const fileName = path.basename(filePath);
233
+ const files = IModelJsFs_1.IModelJsFs.readdirSync(dirName);
234
+ for (const file of files) {
235
+ if (file.startsWith(fileName))
236
+ this.deleteFile(path.join(dirName, file)); // don't throw on error
237
+ }
238
+ }
239
+ catch (err) {
240
+ }
241
+ }
242
+ /** Deletes a file
243
+ * - Does not throw any error, but logs it instead
244
+ * - Returns true if the delete was successful
245
+ */
246
+ static deleteFile(pathname) {
247
+ try {
248
+ IModelJsFs_1.IModelJsFs.unlinkSync(pathname);
249
+ }
250
+ catch (error) {
251
+ core_bentley_1.Logger.logError(loggerCategory, `Cannot delete file ${pathname}, ${error}`);
252
+ return false;
253
+ }
254
+ return true;
255
+ }
256
+ /** Deletes a folder, checking if it's empty
257
+ * - Does not throw any error, but logs it instead
258
+ * - Returns true if the delete was successful
259
+ */
260
+ static deleteFolderIfEmpty(folderPathname) {
261
+ try {
262
+ const files = IModelJsFs_1.IModelJsFs.readdirSync(folderPathname);
263
+ if (files.length > 0)
264
+ return false;
265
+ IModelJsFs_1.IModelJsFs.rmdirSync(folderPathname);
266
+ }
267
+ catch (error) {
268
+ core_bentley_1.Logger.logError(loggerCategory, `Cannot delete folder: ${folderPathname}`);
269
+ return false;
270
+ }
271
+ return true;
272
+ }
273
+ /** Deletes the contents of a folder, but not the folder itself
274
+ * - Does not throw any errors, but logs them.
275
+ * - returns true if the delete was successful.
276
+ */
277
+ static deleteFolderContents(folderPathname) {
278
+ var _a;
279
+ if (!IModelJsFs_1.IModelJsFs.existsSync(folderPathname))
280
+ return false;
281
+ let status = true;
282
+ const files = IModelJsFs_1.IModelJsFs.readdirSync(folderPathname);
283
+ for (const file of files) {
284
+ const curPath = path.join(folderPathname, file);
285
+ const locStatus = ((_a = IModelJsFs_1.IModelJsFs.lstatSync(curPath)) === null || _a === void 0 ? void 0 : _a.isDirectory) ? BriefcaseManager.deleteFolderAndContents(curPath) : BriefcaseManager.deleteFile(curPath);
286
+ if (!locStatus)
287
+ status = false;
288
+ }
289
+ return status;
290
+ }
291
+ /** Deletes a folder and all it's contents.
292
+ * - Does not throw any errors, but logs them.
293
+ * - returns true if the delete was successful.
294
+ */
295
+ static deleteFolderAndContents(folderPathname) {
296
+ if (!IModelJsFs_1.IModelJsFs.existsSync(folderPathname))
297
+ return true;
298
+ let status = false;
299
+ status = BriefcaseManager.deleteFolderContents(folderPathname);
300
+ if (!status)
301
+ return false;
302
+ status = BriefcaseManager.deleteFolderIfEmpty(folderPathname);
303
+ return status;
304
+ }
305
+ static async applySingleChangeset(db, changesetFile) {
306
+ if (changesetFile.changesType === core_common_1.ChangesetType.Schema)
307
+ db.clearCaches(); // for schema changesets, statement caches may become invalid. Do this *before* applying, in case db needs to be closed (open statements hold db open.)
308
+ db.nativeDb.applyChangeset(changesetFile);
309
+ db.changeset = db.nativeDb.getCurrentChangeset();
310
+ // we're done with this changeset, delete it
311
+ IModelJsFs_1.IModelJsFs.removeSync(changesetFile.pathname);
312
+ }
313
+ /** @internal */
314
+ static async pullAndApplyChangesets(db, arg) {
315
+ if (!db.isOpen || db.nativeDb.isReadonly()) // don't use db.isReadonly - we reopen the file writable just for this operation but db.isReadonly is still true
316
+ throw new core_common_1.IModelError(core_bentley_1.ChangeSetStatus.ApplyError, "Briefcase must be open ReadWrite to process change sets");
317
+ let currentIndex = db.changeset.index;
318
+ if (currentIndex === undefined)
319
+ currentIndex = (await IModelHost_1.IModelHost.hubAccess.queryChangeset({ accessToken: arg.accessToken, iModelId: db.iModelId, changeset: { id: db.changeset.id } })).index;
320
+ const reverse = (arg.toIndex && arg.toIndex < currentIndex) ? true : false;
321
+ // Download change sets
322
+ const changesets = await IModelHost_1.IModelHost.hubAccess.downloadChangesets({
323
+ accessToken: arg.accessToken,
324
+ iModelId: db.iModelId,
325
+ range: { first: reverse ? arg.toIndex + 1 : currentIndex + 1, end: reverse ? currentIndex : arg.toIndex },
326
+ targetDir: BriefcaseManager.getChangeSetsPath(db.iModelId),
327
+ progressCallback: arg.onProgress,
328
+ });
329
+ if (changesets.length === 0)
330
+ return; // nothing to apply
331
+ if (reverse)
332
+ changesets.reverse();
333
+ for (const changeset of changesets)
334
+ await this.applySingleChangeset(db, changeset);
335
+ // notify listeners
336
+ db.notifyChangesetApplied();
337
+ }
338
+ /** create a changeset from the current changes, and push it to iModelHub */
339
+ static async pushChanges(db, arg) {
340
+ var _a, _b;
341
+ const changesetProps = db.nativeDb.startCreateChangeset();
342
+ changesetProps.briefcaseId = db.briefcaseId;
343
+ changesetProps.description = arg.description;
344
+ changesetProps.size = (_a = IModelJsFs_1.IModelJsFs.lstatSync(changesetProps.pathname)) === null || _a === void 0 ? void 0 : _a.size;
345
+ if (!changesetProps.size) // either undefined or 0 means error
346
+ throw new core_common_1.IModelError(core_bentley_1.IModelStatus.NoContent, "error creating changeset");
347
+ let retryCount = (_b = arg.pushRetryCount) !== null && _b !== void 0 ? _b : 3;
348
+ while (true) {
349
+ try {
350
+ const accessToken = await IModelHost_1.IModelHost.getAccessToken();
351
+ const index = await IModelHost_1.IModelHost.hubAccess.pushChangeset({ accessToken, iModelId: db.iModelId, changesetProps });
352
+ db.nativeDb.completeCreateChangeset({ index });
353
+ db.changeset = db.nativeDb.getCurrentChangeset();
354
+ if (!arg.retainLocks)
355
+ await db.locks.releaseAllLocks();
356
+ return;
357
+ }
358
+ catch (err) {
359
+ const shouldRetry = () => {
360
+ if (retryCount-- <= 0)
361
+ return false;
362
+ switch (err.errorNumber) {
363
+ case core_bentley_1.IModelHubStatus.AnotherUserPushing:
364
+ case core_bentley_1.IModelHubStatus.DatabaseTemporarilyLocked:
365
+ case core_bentley_1.IModelHubStatus.OperationFailed:
366
+ return true;
367
+ }
368
+ return false;
369
+ };
370
+ if (!shouldRetry()) {
371
+ db.nativeDb.abandonCreateChangeset();
372
+ throw err;
373
+ }
374
+ }
375
+ finally {
376
+ IModelJsFs_1.IModelJsFs.removeSync(changesetProps.pathname);
377
+ }
378
+ }
379
+ }
380
+ /** Pull/merge (if necessary), then push all local changes as a changeset. Called by [[BriefcaseDb.pushChanges]]
381
+ * @internal
382
+ */
383
+ static async pullMergePush(db, arg) {
384
+ var _a, _b;
385
+ let retryCount = (_a = arg.mergeRetryCount) !== null && _a !== void 0 ? _a : 5;
386
+ while (true) {
387
+ try {
388
+ await BriefcaseManager.pullAndApplyChangesets(db, arg);
389
+ return await BriefcaseManager.pushChanges(db, arg);
390
+ }
391
+ catch (err) {
392
+ if (retryCount-- <= 0 || err.errorNumber !== core_bentley_1.IModelHubStatus.PullIsRequired)
393
+ throw (err);
394
+ await ((_b = arg.mergeRetryDelay) !== null && _b !== void 0 ? _b : core_bentley_1.BeDuration.fromSeconds(3)).wait();
395
+ }
396
+ }
397
+ }
398
+ /** @internal */
399
+ static logUsage(imodel, activity) {
400
+ var _a;
401
+ const telemetryEvent = new core_telemetry_1.TelemetryEvent("core-backend - Open iModel", "7a6424d1-2114-4e89-b13b-43670a38ccd4", // Feature: "iModel Use"
402
+ imodel.iTwinId, imodel.iModelId, (_a = imodel.changeset) === null || _a === void 0 ? void 0 : _a.id);
403
+ activity = activity !== null && activity !== void 0 ? activity : {
404
+ activityId: "",
405
+ applicationId: IModelHost_1.IModelHost.applicationId,
406
+ applicationVersion: IModelHost_1.IModelHost.applicationVersion,
407
+ sessionId: IModelHost_1.IModelHost.sessionId,
408
+ accessToken: "", // IModelHost.getAccessToken(); ACCESS_TOKEN_NEEDS_WORK
409
+ };
410
+ IModelHost_1.IModelHost.telemetry.postTelemetry(activity, telemetryEvent); // eslint-disable-line @typescript-eslint/no-floating-promises
411
+ }
412
+ }
413
+ exports.BriefcaseManager = BriefcaseManager;
414
+ BriefcaseManager._briefcaseSubDir = "briefcases";
415
415
  //# sourceMappingURL=BriefcaseManager.js.map