@itwin/core-backend 4.0.0-dev.28 → 4.0.0-dev.32

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