@itwin/core-backend 5.7.0-dev.15 → 5.7.0-dev.17
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.
- package/CHANGELOG.md +6 -1
- package/lib/cjs/TileStorage.js +1 -1
- package/lib/cjs/TileStorage.js.map +1 -1
- package/lib/cjs/internal/IModelDbFontsImpl.js +1 -1
- package/lib/cjs/internal/IModelDbFontsImpl.js.map +1 -1
- package/lib/cjs/internal/IntegrityCheck.js +1 -1
- package/lib/cjs/internal/IntegrityCheck.js.map +1 -1
- package/lib/cjs/internal/annotations/fields.js +2 -2
- package/lib/cjs/internal/annotations/fields.js.map +1 -1
- package/lib/cjs/rpc/tracing.js +2 -2
- package/lib/cjs/rpc/tracing.js.map +1 -1
- package/lib/cjs/workspace/Workspace.js +1 -1
- package/lib/cjs/workspace/Workspace.js.map +1 -1
- package/lib/esm/TileStorage.js +1 -1
- package/lib/esm/TileStorage.js.map +1 -1
- package/lib/esm/internal/IModelDbFontsImpl.js +1 -1
- package/lib/esm/internal/IModelDbFontsImpl.js.map +1 -1
- package/lib/esm/internal/IntegrityCheck.js +1 -1
- package/lib/esm/internal/IntegrityCheck.js.map +1 -1
- package/lib/esm/internal/annotations/fields.js +2 -2
- package/lib/esm/internal/annotations/fields.js.map +1 -1
- package/lib/esm/rpc/tracing.js +2 -2
- package/lib/esm/rpc/tracing.js.map +1 -1
- package/lib/esm/test/imodel/IModel.test.js +1 -1
- package/lib/esm/test/imodel/IModel.test.js.map +1 -1
- package/lib/esm/workspace/Workspace.js +1 -1
- package/lib/esm/workspace/Workspace.js.map +1 -1
- package/package.json +12 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Workspace.js","sourceRoot":"","sources":["../../../src/workspace/Workspace.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAA2G;AAM3G,oEAAiE;AACjE,iDAAgE;AAuahE,SAAS,eAAe,CAAC,IA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D,OAAO,oBAAoB,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAuB,CAAC;IACnF,CAAC;IAFe,2BAAiB,oBAEhC,CAAA;IAED;;;;;OAKG;IACH,SAAgB,eAAe,CAAC,IAA8B;QAC5D,OAAO,oBAAoB,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,EAAE,MAAM,CAA2B,CAAC;IACrF,CAAC;IAFe,yBAAe,kBAE9B,CAAA;IAED;;;OAGG;IACH,SAAgB,cAAc,CAAC,IAAiC;QAC9D,MAAM,SAAS,GAA6C,EAAE,CAAC;QAC/D,KAAK,MAAM,EAAE,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YAC1B,EAAE,CAAC,cAAc,CAAC;gBAChB,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE;oBAClB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;wBACzB,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/B,CAAC;gBACH,CAAC;aACF,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IAC3B,CAAC;IAhBe,wBAAc,iBAgB7B,CAAA;AACH,CAAC,EAtFgB,SAAS,yBAAT,SAAS,QAsFzB","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Workspace\r\n */\r\n\r\nimport { AccessToken, BeEvent, ITwinError, Logger, Optional, UnexpectedErrors } from \"@itwin/core-bentley\";\r\nimport { LocalDirName, LocalFileName } from \"@itwin/core-common\";\r\nimport { CloudSqlite } from \"../CloudSqlite\";\r\nimport { SQLiteDb } from \"../SQLiteDb\";\r\nimport { SettingName, Settings, SettingsDictionary, SettingsPriority } from \"./Settings\";\r\nimport type { IModelJsNative } from \"@bentley/imodeljs-native\";\r\nimport { BackendLoggerCategory } from \"../BackendLoggerCategory\";\r\nimport { _implementationProhibited } from \"../internal/Symbols\";\r\n\r\n/** The unique identifier of a [[WorkspaceContainer]]. This becomes the base name for a local file directory holding the container's [[WorkspaceDb]]s.\r\n * A valid `WorkspaceContainerId` must conform to the following constraints:\r\n * - Consist solely of a combination of lower case letters, numbers, and dashes.\r\n * - May not start or end with a dash.\r\n * - Must be at least 3 characters long and no longer than 63 characters.\r\n * @beta\r\n */\r\nexport type WorkspaceContainerId = string;\r\n\r\n/** Properties describing a [[WorkspaceContainer]] for methods like [[Workspace.getContainerAsync]].\r\n * @beta\r\n */\r\nexport interface WorkspaceContainerProps extends Optional<CloudSqlite.ContainerAccessProps, \"accessToken\"> {\r\n /** Whether to synchronize the container via [[CloudSqlite.CloudContainer.checkForChanges]] whenever it is connected to a [[CloudSqlite.CloudCache]].\r\n * @note This property defaults to `true`.\r\n */\r\n readonly syncOnConnect?: boolean;\r\n /** A user-friendly description of the container's contents. */\r\n readonly description?: string;\r\n /** A message to display to the user if problems occur while loading the container. */\r\n readonly loadingHelp?: string;\r\n}\r\n\r\n/** The base name of a [[WorkspaceDb]], without any version information.\r\n * The name must conform to the following constraints:\r\n * - Case-insensitively unique among all [[WorkspaceDb]]s in the same [[WorkspaceContainer]].\r\n * - Between 1 and 255 characters in length.\r\n * - A legal filename on both [Windows](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions) and UNIX.\r\n * - Contain none of the following characters: forward or backward slash, period, single or double quote, backtick, and \"#\".\r\n * - Begin or end with a whitespace character.\r\n * @see [[WorkspaceDbFullName]] for the fully-specified name, including version information.\r\n * @beta\r\n */\r\nexport type WorkspaceDbName = string;\r\n\r\n/** The fully-specified name of a [[WorkspaceDb]], combining its [[WorkspaceDbName]] and [[WorkspaceDbVersion]] in the format \"name:version\".\r\n * @beta\r\n */\r\nexport type WorkspaceDbFullName = string;\r\n\r\n/** A [semver](https://github.com/npm/node-semver) string describing the version of a [[WorkspaceDb]], e.g., \"4.2.11\".\r\n * @beta\r\n */\r\nexport type WorkspaceDbVersion = CloudSqlite.DbVersion;\r\n\r\n/** A [semver string](https://github.com/npm/node-semver?tab=readme-ov-file#ranges) describing a range of acceptable [[WorkspaceDbVersion]]s,\r\n * e.g., \">=1.2.7 <1.3.0\".\r\n * @beta\r\n */\r\nexport type WorkspaceDbVersionRange = CloudSqlite.DbVersionRange;\r\n\r\n/** Specifies the name and version of a [[WorkspaceDb]].\r\n * @beta\r\n */\r\nexport type WorkspaceDbNameAndVersion = Optional<CloudSqlite.DbNameAndVersion, \"dbName\">;\r\n\r\n/** Properties that specify how to load a [[WorkspaceDb]] within a [[WorkspaceContainer]].\r\n * @beta\r\n */\r\nexport interface WorkspaceDbProps extends WorkspaceDbNameAndVersion {\r\n /** If true, allow semver [prerelease versions](https://github.com/npm/node-semver?tab=readme-ov-file#prerelease-tags), e.g., \"1.4.2-beta.0\".\r\n * By default, only released version are allowed.\r\n */\r\n readonly includePrerelease?: boolean;\r\n /** If true, start a prefetch operation whenever this [[WorkspaceDb]] is opened, to begin downloading pages of the database before they are needed. */\r\n readonly prefetch?: boolean;\r\n}\r\n\r\n/** Properties describing a [[WorkspaceDb]] and the [[WorkspaceContainer]] containing it.\r\n * @beta\r\n */\r\nexport type WorkspaceDbCloudProps = WorkspaceDbProps & WorkspaceContainerProps;\r\n\r\n/** A function supplied as [[WorkspaceDbQueryResourcesArgs.callback]] to be invoked to process the requested resources.\r\n * @beta\r\n */\r\nexport type WorkspaceDbQueryResourcesCallback = (resourceNames: Iterable<string>) => void;\r\n\r\n/** Arguments supplied to [[WorkspaceDb.queryResources]].\r\n * @beta\r\n */\r\nexport interface WorkspaceDbQueryResourcesArgs {\r\n /** The type of resource to query. */\r\n type?: \"string\" | \"blob\";\r\n /** A pattern against which to compare the name of each resource, using [[nameCompare]] as the comparison operator.\r\n * Only resources whose names match the pattern will be included in the query results.\r\n */\r\n namePattern?: string;\r\n /** The comparison operator by which to compare the name of each resource to [[namePattern]].\r\n * Only resources whose names match the pattern will be included in the query results.\r\n * Ignored if [[namePattern]] is undefined.\r\n */\r\n nameCompare?: \"GLOB\" | \"LIKE\" | \"NOT GLOB\" | \"NOT LIKE\" | \"=\" | \"<\" | \">\";\r\n /** A function invoked to process the resources that match the query criterion. */\r\n callback: WorkspaceDbQueryResourcesCallback;\r\n}\r\n\r\n/** Metadata stored inside a [[WorkspaceDb]] describing the database's contents, to help users understand the purpose of the [[WorkspaceDb]], who to\r\n * contact with questions about it, and so on.\r\n * @note Only the [[workspaceName]] field is required, and users may add additional fields for their own purposes.\r\n * @note Since the information is stored inside of the [[WorkspaceDb]], it is versioned along with the rest of the contents.\r\n * @beta\r\n */\r\nexport interface WorkspaceDbManifest {\r\n /** The name of the [[WorkspaceDb]] to be shown in user interfaces. Organizations should attempt to make this name informative enough\r\n * so that users may refer to this name in conversations. It should also be unique enough that there's no confusion when it appears in\r\n * lists of WorkspaceDbs.\r\n * @note it is possible and valid to change the workspaceName between new version of a WorkspaceDb (e.g. incorporating a date).\r\n */\r\n readonly workspaceName: string;\r\n /** A description of the contents of this [[WorkspaceDb]] to help users understand its purpose and appropriate usage. */\r\n readonly description?: string;\r\n /** The name of the person to contact with questions about this [[WorkspaceDb]]. */\r\n readonly contactName?: string;\r\n /** The name of the person who last modified this [[WorkspaceDb]]. */\r\n readonly lastEditedBy?: string;\r\n}\r\n\r\n/**\r\n * An exception thrown when attempting to load a [[WorkspaceDb]] or some of its data; for example, if the [[WorkspaceDb]] could not be found or the user\r\n * is not authorized to access its [[WorkspaceContainer]].\r\n * @beta\r\n */\r\nexport interface WorkspaceDbLoadError extends ITwinError {\r\n /** The properties of the [[WorkspaceDb]] that was attempted to load, including the identity of its [[WorkspaceContainer]]. */\r\n wsDbProps?: WorkspaceDbProps & Partial<WorkspaceDbCloudProps>;\r\n /** The [[WorkspaceDb]] in which the error occurred, if available. */\r\n wsDb?: WorkspaceDb;\r\n}\r\n\r\n/** An exception that may occur while opening an [[IModelDb]] if any problems are detected while loading its [[IModelDb.workspace]].\r\n * This exception is never actually thrown; instead, after the iModel is opened, the exception is forwarded to [[Workspace.exceptionDiagnosticFn]]\r\n * so that the user can be notified of the problems.\r\n * @beta\r\n */\r\nexport interface WorkspaceDbLoadErrors extends ITwinError {\r\n /** An array of problems that were encountered attempting to load [[WorkspaceDb]]s for an [[IModelDb]]. The most common problem\r\n * is that the user doesn't have read access to one or more [[WorkspaceContainer]]s used by the iModel's [[Workspace]]..\r\n */\r\n wsLoadErrors?: WorkspaceDbLoadError[];\r\n}\r\n\r\n/** Specifies a resource inside a [[WorkspaceDb]] that holds a [[SettingsDictionary]] to load into [[Workspace.settings]].\r\n * Settings of this type named [[WorkspaceSettingNames.settingsWorkspaces]] are automatically loaded by [[Workspace.loadSettingsDictionary]].\r\n * @beta\r\n */\r\nexport interface WorkspaceDbSettingsProps extends WorkspaceDbCloudProps {\r\n /** The name of the resource holding the stringified JSON of the [[SettingsDictionary]]. */\r\n resourceName: string;\r\n /** The priority to assign to the [[SettingsDictionary]]. */\r\n priority: SettingsPriority;\r\n}\r\n\r\n/** The name of a blob, string, or file resource stored in a [[WorkspaceDb]].\r\n * Resource names must conform to the following constraints:\r\n * - At least 1 character and no more than 1024 characters in length.\r\n * - No leading or trailing whitespace characters.\r\n * Each resource of a given type must has a unique name within the [[WorkspaceDb]]. It is technically possible, but discouraged, to define\r\n * resources with the same name but different types.\r\n * @beta\r\n */\r\nexport type WorkspaceResourceName = string;\r\n\r\n/** A SQLite database in a [[Workspace]] containing named resources that the application is configured to use.\r\n * Resources are referred to by their [[WorkspaceResourceName]]s and can represent any number of things, including:\r\n * - [GeographicCRS]($common)es used to define the coordinate reference system of an iTwin.\r\n * - [[SettingsDictionary]]'s that contribute to the [[Workspace.settings]].\r\n * - Files that can be extracted temporarily to the local file system to be accessed by programs directly from disk.\r\n *\r\n * Ultimately, each resource is stored in one of the following formats:\r\n * - A `string`, which is often a stringified `JSON` representation of the resource;\r\n * - A binary `blob`; or\r\n * - An embedded file.\r\n *\r\n * Strings and blobs can be accessed directly using [[getString]] and [[getBlob]]. Files must first be copied to the local file system using [[getFile]], and should be avoided unless the software\r\n * that uses them is written to access them from disk.\r\n *\r\n * A `WorkspaceDb` resides in a [[WorkspaceContainer]] that can be published to the cloud. Once published, the `WorkspaceDb` becomes immutable.\r\n * However, multiple versions of a single `WorkspaceDb` can be created, allowing the [[Workspace]] contents to evolve over time.\r\n * `WorkspaceDb`s use [semantic versioning](https://github.com/npm/node-semver).\r\n *\r\n * The set of available `WorkspaceDb`s available for use for specific purposes are defined in the [[Workspace]]'s [[Settings]]. You can obtain\r\n * a single `WorkspaceDb` using [[WorkspaceContainer.getWorkspaceDb]], but more commonly you will use [[Workspace.getWorkspaceDbs]] to obtain\r\n * a list of all of the `WorkspaceDb`s, sorted by priority, that correspond to a given [[SettingName]].\r\n *\r\n * You can create new `WorkspaceDb`s (or new versions of existing `WorkspaceDb`s) using [[WorkspaceEditor]].\r\n * @beta\r\n */\r\nexport interface WorkspaceDb {\r\n /** @internal */\r\n [_implementationProhibited]: unknown;\r\n /** The [[WorkspaceContainer]] in which this db resides. */\r\n readonly container: WorkspaceContainer;\r\n /** The base name of this WorkspaceDb, without version */\r\n readonly dbName: WorkspaceDbName;\r\n /** An event raised before this WorkspaceDb is [[close]]d. */\r\n readonly onClose: BeEvent<() => void>;\r\n /** The name by which the WorkspaceDb can be opened. This will be either a local file name or the name of a database in a [[CloudSqlite.CloudContainer]]. */\r\n readonly dbFileName: string;\r\n /** The underlying SQLite database that stores this WorkspaceDb's resources. */\r\n readonly sqliteDb: SQLiteDb;\r\n /** Whether the underlying [[sqliteDb]] is currently [[open]]ed. */\r\n readonly isOpen: boolean;\r\n /** The manifest that describes the contents and context of this WorkspaceDb. */\r\n readonly manifest: WorkspaceDbManifest;\r\n /** The version of this WorkspaceDb */\r\n readonly version: WorkspaceDbVersion;\r\n\r\n /** Open the underlying [[sqliteDb]] to perform a query. Generally WorkspaceDbs are left closed and opened/closed as they're used. However,\r\n * when there will be significant activity against a WorkspaceDb, it may be useful to open it before the operations and close it afterwards.\r\n * Methods like [[queryResources]] open the SQLite database automatically and [[close]] it before they return.\r\n */\r\n open(): void;\r\n\r\n /** Close the underlying [[sqliteDb]]. You should call this after [[open]]ing the database and completing your query. */\r\n close(): void;\r\n\r\n /** Look up a string resource by name, if one exists. */\r\n getString(rscName: WorkspaceResourceName): string | undefined;\r\n\r\n /** Look up a binary resource by name, if one exists. */\r\n getBlob(rscName: WorkspaceResourceName): Uint8Array | undefined;\r\n\r\n /** Get a BlobIO reader for a blob WorkspaceResource.\r\n * @note when finished, caller *must* call `close` on the BlobIO.\r\n * @internal\r\n */\r\n getBlobReader(rscName: WorkspaceResourceName): SQLiteDb.BlobIO;\r\n\r\n /**\r\n * Extract a local copy of a file resource from this WorkspaceDb, if present.\r\n * @param rscName The name of the file resource in the WorkspaceDb\r\n * @param targetFileName optional name for extracted file. Some applications require files in specific locations or filenames. If\r\n * you know the full path to use for the extracted file, you can supply it. Generally, it is best to *not* supply the filename and\r\n * keep the extracted files in the directory specified by [[WorkspaceContainer.filesDir]].\r\n * @returns the full path to a file on the local file system, or undefined if the no file named `rscName` exists.\r\n * @note The file is copied from the file into the local file system so it may be accessed directly. This happens only\r\n * as necessary, if the local file doesn't exist, or if it is out-of-date because it was updated in the file.\r\n * For this reason, you should not save the local file name, and instead call this method every time you access it, so its\r\n * content is always holds the correct version.\r\n * @note The filename will be a hash value, not the resource name.\r\n * @note Workspace resource files are set as read-only as they are copied from the file.\r\n * To edit them, you must first copy them to another location.\r\n */\r\n getFile(rscName: WorkspaceResourceName, targetFileName?: LocalFileName): LocalFileName | undefined;\r\n\r\n /**\r\n * Ensure that the contents of this `WorkspaceDb` are downloaded into the local cache so that it may be accessed offline.\r\n * Until the promise resolves, the `WorkspaceDb` is not fully downloaded, but it *may* be safely accessed during the download.\r\n * To determine the progress of the download, use the `localBlocks` and `totalBlocks` values returned by `CloudContainer.queryDatabase`.\r\n * @returns a [[CloudSqlite.CloudPrefetch]] object that can be used to await and/or cancel the prefetch.\r\n * @throws if this WorkspaceDb is not from a [[CloudSqlite.CloudContainer]].\r\n */\r\n prefetch(opts?: CloudSqlite.PrefetchProps): CloudSqlite.CloudPrefetch;\r\n\r\n /** Find resources of a particular type with names matching a specified pattern.\r\n * The matching resources will be supplied to [[WorkspaceDbQueryResourcesArgs.callbackk]].\r\n * @see [[Workspace.queryResources]] to query resources within multiple `WorkspaceDb`s.\r\n */\r\n queryResources(args: WorkspaceDbQueryResourcesArgs): void;\r\n\r\n /** @internal */\r\n queryFileResource(rscName: WorkspaceResourceName): { localFileName: LocalFileName, info: IModelJsNative.EmbedFileQuery } | undefined;\r\n}\r\n\r\n/** Options supplied to [[IModelHost.startup]] via [[IModelHostOptions.workspace]] to customize the initialization of [[IModelHost.appWorkspace]].\r\n * @beta\r\n */\r\nexport interface WorkspaceOpts {\r\n /** The local directory for non-cloud-based [[WorkspaceDb]] files. The [[Workspace]] API will look in this directory\r\n * for files named `${containerId}/${dbId}.itwin-workspace`.\r\n * @note if not supplied, defaults to \"iTwin/Workspace\" in the user-local folder.\r\n */\r\n containerDir?: LocalDirName;\r\n\r\n /** The name(s) of one or more local JSON files containing [[SettingsDictionary]]s to load when initializing the [[Workspace]]. */\r\n settingsFiles?: LocalFileName | LocalFileName[];\r\n}\r\n\r\n/** Arguments supplied to [[Workspace.getContainer]] and [[WorkspaceEditor.getContainer]].\r\n * @beta\r\n */\r\nexport interface GetWorkspaceContainerArgs extends WorkspaceContainerProps {\r\n /** Token required to access the container. */\r\n accessToken: AccessToken;\r\n}\r\n\r\n/**\r\n * Settings and resources that customize an application for the current session.\r\n * See the [learning article]($docs/learning/backend/Workspace) for a detailed overiew and examples.\r\n * @beta\r\n */\r\nexport interface Workspace {\r\n /** @internal */\r\n [_implementationProhibited]: unknown;\r\n\r\n /** The directory for local WorkspaceDb files with the name `${containerId}/${dbId}.itwin-workspace`.\r\n * @internal\r\n */\r\n readonly containerDir: LocalDirName;\r\n\r\n /** The current [[Settings]] for this Workspace */\r\n readonly settings: Settings;\r\n\r\n /** Get the cloud cache for cloud-based [[WorkspaceContainer]]s. */\r\n getCloudCache(): CloudSqlite.CloudCache;\r\n\r\n /** Search for a container previously opened by [[getContainer]] or [[getContainerAsync]].\r\n * @param containerId The id of the container\r\n * @returns the [[WorkspaceContainer]] for `containerId`, or `undefined` if no such container has been opened.\r\n * @internal\r\n */\r\n findContainer(containerId: WorkspaceContainerId): WorkspaceContainer | undefined;\r\n\r\n /** Obtain the [[WorkspaceContainer]] specified by `props`.\r\n * @param props The properties of the `WorkspaceContainer`, opening it if it is not already opened.\r\n * Otherwise it is created.\r\n * @note This function allows a `WorkspaceContainer.Props` without its [AccessToken]($bentley). It will attempt to obtain one from the [[BlobContainer]] service,\r\n * hence this function is async.\r\n * @see [[getContainer]] to obtain a container synchronously.\r\n */\r\n getContainerAsync(props: WorkspaceContainerProps): Promise<WorkspaceContainer>;\r\n\r\n /** Get a WorkspaceContainer with a supplied access token. This function is synchronous and may be used if:\r\n * - a valid [AccessToken]($bentley) is already available;\r\n * - the container has already been previously prefetched in another session (this is useful for offline usage); or\r\n * - the container is public and doesn't require an [AccessToken]($bentley).\r\n * @see [[getContainerAsync]] to obtain a container asynchronously if the above conditions do not apply.\r\n */\r\n getContainer(props: GetWorkspaceContainerArgs): WorkspaceContainer;\r\n\r\n /** Load a [[SettingsDictionary]] from the specified [[WorkspaceDb]] and add it to this workspace's current [[Settings]].\r\n * @note this function will load the dictionaries from the supplied list, and it will also call itself recursively for any entries in\r\n * the loaded Settings with the name [[WorkspaceSettingNames.settingsWorkspaces]]. In this manner, WorkspaceSettings may be \"chained\" together so that loading one\r\n * causes its \"dependent\" WorkspaceSettings to be loaded. Its `Promise` is resolved after all have been loaded (or failed to load).\r\n */\r\n loadSettingsDictionary(\r\n /** The properties of the [[WorkspaceDb]], plus the resourceName and [[SettingsPriority]]. May be either a single value or an array of them */\r\n props: WorkspaceDbSettingsProps | WorkspaceDbSettingsProps[],\r\n /** If present, an array that is populated with a list of problems while attempting to load the [[SettingsDictionary]](s). */\r\n problems?: WorkspaceDbLoadError[]\r\n ): Promise<void>;\r\n\r\n /** Get a single [[WorkspaceDb]]. */\r\n getWorkspaceDb(props: WorkspaceDbCloudProps): Promise<WorkspaceDb>;\r\n\r\n /**\r\n * Resolve the value of all [[Setting]]s from this workspace with the supplied `settingName` into an array of [[WorkspaceDbCloudProps]]\r\n * that can be used to query or load workspace resources. The settings must each be an array of type [[WorkspaceDbSettingsProps]].\r\n * The returned array will be sorted according to their [[SettingsPriority]], with the first entry being the highest priority [[WorkspaceDb]].\r\n * @note The list is built by combining, in order, all of the settings with the supplied [[SettingName]]. It may therefore include the\r\n * properties of same WorkspaceDb multiple times. This list is automatically de-duped by [[getWorkspaceDb]].\r\n * @note This function is rarely used directly. Usually it is called by [[getWorkspaceDbs]]. However, this function is synchronous and may sometimes\r\n * be useful for editors, tests, or diagnostics.\r\n */\r\n resolveWorkspaceDbSetting(\r\n /** the name of the setting. */\r\n settingName: SettingName,\r\n /** optional filter to choose specific WorkspaceDbs from the settings values. If present, only those WorkspaceDbs for which the filter returns `true` will be included. */\r\n filter?: Workspace.DbListFilter): WorkspaceDbCloudProps[];\r\n\r\n /**\r\n * Get a sorted array of [[WorkspaceDb]]s that can be used to query or load resources. If the arguments supply a `settingName`, this function will\r\n * use [[resolveWorkspaceDbSetting]] to get get the array of [[WorkspaceDbCloudProps]].\r\n * @returns A `Promise` resolving to an array of [[WorkspaceDb]]s sorted by [[SettingsPriority]] so that resources found in WorkspaceDbs earlier in the list take precedence\r\n * over ones with the same name in later WorkspaceDbs. No WorkspaceDb will appear more than once in the list.\r\n * @note this function may request an [AccessToken]($bentley) for each WorkspaceDb if necessary, and hence is asynchronous.\r\n */\r\n getWorkspaceDbs(\r\n args: Workspace.DbListOrSettingName & {\r\n /** if supplied, this array is populated with a list of problems (e.g. no read permission) attempting to load WorkspacesDbs. */\r\n problems?: WorkspaceDbLoadError[];\r\n /** only valid when called with a settingName, if so passed as `filter` argument to [[resolveWorkspaceDbSetting]] */\r\n filter?: Workspace.DbListFilter;\r\n }): Promise<WorkspaceDb[]>;\r\n}\r\n\r\n/**\r\n * A WorkspaceContainer is a type of [[CloudSqlite.CloudContainer]] that holds one or more [[WorkspaceDb]]s. Normally a WorkspaceContainer will hold (many versions of) a single WorkspaceDb.\r\n * Each version of a WorkspaceDb is treated as immutable after it is created and is stored in the WorkspaceContainer indefinitely. That means that\r\n * older versions of the WorkspaceDb may continue to be used, for example by archived projects. For programmers familiar with [NPM](https://www.npmjs.com/), this is conceptually\r\n * similar and versioning follows the same rules as NPM using [Semantic Versioning](https://semver.org/).\r\n * @note It is possible to store more than one WorkspaceDb in the same WorkspaceContainer, but access rights are administered per WorkspaceContainer.\r\n * That is, if a user has rights to access a WorkspaceContainer, that right applies to all WorkspaceDbs in the WorkspaceContainer.\r\n * @note Not every WorkspaceContainer is associated with a [[CloudSqlite.CloudContainer]] - WorkspaceContainers may also be loaded from the local file system.\r\n * In this case, [[cloudContainer]] will be `undefined`.\r\n * @see [[Workspace.getContainer]] and [[Workspace.getContainerAsync]] to load a container.\r\n * @beta\r\n */\r\nexport interface WorkspaceContainer {\r\n /** @internal */\r\n [_implementationProhibited]: unknown;\r\n /** the local directory where this WorkspaceContainer will store temporary files extracted for file-resources.\r\n * @internal\r\n */\r\n readonly filesDir: LocalDirName;\r\n /** The workspace into which this container was loaded. */\r\n readonly workspace: Workspace;\r\n /** Cloud container for this WorkspaceContainer, or `undefined` if this is a local WorkspaceContainer. */\r\n readonly cloudContainer?: CloudSqlite.CloudContainer;\r\n /** Properties supplied when this container was loaded */\r\n readonly fromProps: WorkspaceContainerProps;\r\n\r\n /** @internal */\r\n addWorkspaceDb(toAdd: WorkspaceDb): void;\r\n\r\n /**\r\n * Find the fully-qualified name of a [[WorkspaceDb]] satisfying the name and version criteria specified by `props`.\r\n * @throws Error if no version satisfying the criteria exists.\r\n */\r\n resolveDbFileName(props: WorkspaceDbProps): WorkspaceDbFullName;\r\n\r\n /** Obtain a [[WorkspaceDb]] satisfying the name and version criteria specified by `props`. */\r\n getWorkspaceDb(props?: WorkspaceDbProps): WorkspaceDb;\r\n\r\n /** Close and remove a currently opened [[WorkspaceDb]] from this Workspace.\r\n * @internal\r\n */\r\n closeWorkspaceDb(container: WorkspaceDb): void;\r\n}\r\n\r\nfunction makeSettingName(name: string) {\r\n return `${\"itwin/core/workspace\"}/${name}`;\r\n}\r\n\r\n/** The names of various [[Setting]]s with special meaning to the [[Workspace]] system.\r\n * @beta\r\n */\r\nexport namespace WorkspaceSettingNames {\r\n /** The name of a setting that, when present in a [[WorkspaceDb]] loaded by [[Workspace.loadSettingsDictionary]], will automatically\r\n * be used to find and load additional [[SettingsDictionary]]'s in other [[WorkspaceDb]]s. This permits you to chain the settings inside on [[WorkspaceDb]]\r\n * to others upon which they depend.\r\n * This setting's value is an array of [[WorkspaceDbSettingsProps]]s.\r\n */\r\n export const settingsWorkspaces = makeSettingName(\"settingsWorkspaces\");\r\n}\r\n\r\n/** A function supplied as part of a [[QueryWorkspaceResourcesArgs]] to iterate the resources retrieved by [[Workspace.queryResources]].\r\n * The `resources` object should only be used inside the function - it is an error to attempt to iterate it after the function returns.\r\n * @beta\r\n */\r\nexport type QueryWorkspaceResourcesCallback = (resources: Iterable<{ name: string, db: WorkspaceDb }>) => void;\r\n\r\n/** Arguments supplied to [[Workspace.queryResources]] defining the query criteria and the list of [[WorkspaceDb]]s to query.\r\n * @beta\r\n */\r\nexport interface QueryWorkspaceResourcesArgs {\r\n /** The list of `WorkspaceDb`s to query, in the order in which they are to be queried.\r\n * @see [[Workspace.resolveWorkspaceDbSetting]] or [[Workspace.getWorkspaceDbs]] to obtain an appropriate list of `WorkspaceDb`s.\r\n */\r\n dbs: WorkspaceDb[];\r\n /** The type of resource to query. */\r\n type?: \"string\" | \"blob\";\r\n /** A pattern against which to compare the name of each resource, using [[nameCompare]] as the comparison operator.\r\n * Only resources whose names match the pattern will be included in the query results.\r\n */\r\n namePattern?: string;\r\n /** The comparison operator by which to compare the name of each resource to [[namePattern]].\r\n * Only resources whose names match the pattern will be included in the query results.\r\n * Ignored i [[namePattern]] is undefined.\r\n */\r\n nameCompare?: \"GLOB\" | \"LIKE\" | \"NOT GLOB\" | \"NOT LIKE\" | \"=\" | \"<\" | \">\";\r\n /** A function invoked to process the resources that match the query criteria. */\r\n callback: QueryWorkspaceResourcesCallback;\r\n}\r\n\r\nfunction getWorkspaceResource(dbs: WorkspaceDb[], name: string, type: \"string\" | \"blob\"): string | Uint8Array | undefined {\r\n for (const db of dbs) {\r\n const val = type === \"blob\" ? db.getBlob(name) : db.getString(name);\r\n if (undefined !== val) {\r\n return val;\r\n }\r\n }\r\n\r\n return undefined;\r\n}\r\n\r\n/** Arguments supplied to [[Workspace.getStringResource]] and [[WOrkspace.getBlobResource]].\r\n * @beta\r\n */\r\nexport interface GetWorkspaceResourceArgs {\r\n /** The list of `WorkspaceDb`s to search, in the order in which they are to be searched.\r\n * @see [[Workspace.resolveWorkspaceDbSetting]] or [[Workspace.getWorkspaceDbs]] to obtain an appropriate list of `WorkspaceDb`s.\r\n */\r\n dbs: WorkspaceDb[];\r\n /** The name of the resource to find. */\r\n name: WorkspaceResourceName;\r\n}\r\n\r\n/** @beta */\r\nexport namespace Workspace {\r\n /** A function invoked to handle exceptions produced while loading workspace data.\r\n * Applications can override this function to notify the user and/or attempt to diagnose the problem.\r\n * The default implementation simply logs each exception.\r\n */\r\n export let exceptionDiagnosticFn = (e: WorkspaceDbLoadErrors) => { // eslint-disable-line prefer-const\r\n if (e instanceof Error)\r\n Logger.logException(BackendLoggerCategory.Workspace, e);\r\n else\r\n UnexpectedErrors.handle(e);\r\n };\r\n\r\n /** Arguments supplied to [[Workspace.onSettingsDictionaryLoadedFn]] for every [[SettingsDictionary]] that is loaded from a [[WorkspaceDb]]. */\r\n export interface SettingsDictionaryLoaded {\r\n /** The dictionary that was loaded */\r\n dict: SettingsDictionary;\r\n /** The WorkspaceDb from which the dictionary was loaded. */\r\n from: WorkspaceDb;\r\n }\r\n\r\n /** A function invoked each time any [[SettingsDictionary]] is loaded from a [[WorkspaceDb]].\r\n * Applications can override this function to notify the user and/or record diagnostics.\r\n * The default implementation simply records an information message in the [Logger]($bentley).\r\n */\r\n export let onSettingsDictionaryLoadedFn = (loaded: SettingsDictionaryLoaded) => { // eslint-disable-line prefer-const\r\n Logger.logInfo(BackendLoggerCategory.Workspace, `loaded setting dictionary ${loaded.dict.props.name} from ${loaded.from.dbFileName}`);\r\n };\r\n\r\n /** Either an array of [[WorkspaceDbCloudProps]] or the name of a [[Setting]] that resolves to an array of [[WorkspaceDbCloudProps]].\r\n * Used by [[Workspace.getWorkspaceDbs]].\r\n */\r\n export type DbListOrSettingName = { readonly dbs: WorkspaceDbCloudProps[], readonly settingName?: never } | { readonly settingName: SettingName, readonly dbs?: never };\r\n\r\n /** In arguments supplied to [[Workspace.getWorkspaceDbs]] and [[Workspace.resolveWorkspaceDbSetting]], an optional function used to exclude some\r\n * [[WorkspaceDb]]s. Only those [[WorkspaceDb]]s for which the function returns `true` will be included.\r\n */\r\n export type DbListFilter = (\r\n /** The properties of the WorkspaceDb to be returned */\r\n dbProp: WorkspaceDbCloudProps,\r\n /** The SettingsDictionary holding the [[WorkspaceSettingNames.settingsWorkspace]] setting. May be used, for example, to determine the\r\n * [[SettingsPriority]] of the dictionary.\r\n */\r\n dict: SettingsDictionary\r\n ) => boolean;\r\n\r\n /** Searches a list of [[WorkspaceDb]]s for a string resource of a given name.\r\n * The list is searched in order, and the first resource with the request name is returned.\r\n * If no such resource exists, the function returns `undefined`.\r\n * @see [[WorkspaceDb.getString]] if you only need to search a single `WorkspaceDb`.\r\n * @beta\r\n */\r\n export function getStringResource(args: GetWorkspaceResourceArgs): string | undefined {\r\n return getWorkspaceResource(args.dbs, args.name, \"string\") as string | undefined;\r\n }\r\n\r\n /** Searches a list of [[WorkspaceDb]]s for a blob resource of a given name.\r\n * The list is searched in order, and the first resource with the request name is returned.\r\n * If no such resource exists, the function returns `undefined`.\r\n * @see [[WorkspaceDb.getblob]] if you only need to search a single `WorkspaceDb`.\r\n * @beta\r\n */\r\n export function getBlobResource(args: GetWorkspaceResourceArgs): Uint8Array | undefined {\r\n return getWorkspaceResource(args.dbs, args.name, \"blob\") as Uint8Array | undefined;\r\n }\r\n\r\n /** Query a list of [[WorkspaceDb]]s to find resources of a particular type with names matching a specified pattern.\r\n * @see [[WorkspaceDb.queryResources]] if you only need to query a single `WorkspaceDb`.\r\n * @beta\r\n */\r\n export function queryResources(args: QueryWorkspaceResourcesArgs): void {\r\n const resources: Array<{ name: string, db: WorkspaceDb }> = [];\r\n for (const db of args.dbs) {\r\n db.queryResources({\r\n type: args.type,\r\n namePattern: args.namePattern,\r\n nameCompare: args.nameCompare,\r\n callback: (names) => {\r\n for (const name of names) {\r\n resources.push({ db, name });\r\n }\r\n },\r\n });\r\n }\r\n\r\n args.callback(resources);\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"file":"Workspace.js","sourceRoot":"","sources":["../../../src/workspace/Workspace.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,sDAA2G;AAM3G,oEAAiE;AACjE,iDAAgE;AAuahE,SAAS,eAAe,CAAC,IAAY;IACnC,OAAO,GAAG,sBAAsB,IAAI,IAAI,EAAE,CAAC;AAC7C,CAAC;AAED;;GAEG;AACH,IAAiB,qBAAqB,CAOrC;AAPD,WAAiB,qBAAqB;IACpC;;;;OAIG;IACU,wCAAkB,GAAG,eAAe,CAAC,oBAAoB,CAAC,CAAC;AAC1E,CAAC,EAPgB,qBAAqB,qCAArB,qBAAqB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CAAC,IAAI,EAAE,MAAM,CAA2B,CAAC;IACrF,CAAC;IAFe,yBAAe,kBAE9B,CAAA;IAED;;;OAGG;IACH,SAAgB,cAAc,CAAC,IAAiC;QAC9D,MAAM,SAAS,GAA6C,EAAE,CAAC;QAC/D,KAAK,MAAM,EAAE,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YAC1B,EAAE,CAAC,cAAc,CAAC;gBAChB,IAAI,EAAE,IAAI,CAAC,IAAI;gBACf,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,WAAW,EAAE,IAAI,CAAC,WAAW;gBAC7B,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE;oBAClB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;wBACzB,SAAS,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;oBAC/B,CAAC;gBACH,CAAC;aACF,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IAC3B,CAAC;IAhBe,wBAAc,iBAgB7B,CAAA;AACH,CAAC,EAtFgB,SAAS,yBAAT,SAAS,QAsFzB","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module Workspace\r\n */\r\n\r\nimport { AccessToken, BeEvent, ITwinError, Logger, Optional, UnexpectedErrors } from \"@itwin/core-bentley\";\r\nimport { LocalDirName, LocalFileName } from \"@itwin/core-common\";\r\nimport { CloudSqlite } from \"../CloudSqlite\";\r\nimport { SQLiteDb } from \"../SQLiteDb\";\r\nimport { SettingName, Settings, SettingsDictionary, SettingsPriority } from \"./Settings\";\r\nimport type { IModelJsNative } from \"@bentley/imodeljs-native\";\r\nimport { BackendLoggerCategory } from \"../BackendLoggerCategory\";\r\nimport { _implementationProhibited } from \"../internal/Symbols\";\r\n\r\n/** The unique identifier of a [[WorkspaceContainer]]. This becomes the base name for a local file directory holding the container's [[WorkspaceDb]]s.\r\n * A valid `WorkspaceContainerId` must conform to the following constraints:\r\n * - Consist solely of a combination of lower case letters, numbers, and dashes.\r\n * - May not start or end with a dash.\r\n * - Must be at least 3 characters long and no longer than 63 characters.\r\n * @beta\r\n */\r\nexport type WorkspaceContainerId = string;\r\n\r\n/** Properties describing a [[WorkspaceContainer]] for methods like [[Workspace.getContainerAsync]].\r\n * @beta\r\n */\r\nexport interface WorkspaceContainerProps extends Optional<CloudSqlite.ContainerAccessProps, \"accessToken\"> {\r\n /** Whether to synchronize the container via [[CloudSqlite.CloudContainer.checkForChanges]] whenever it is connected to a [[CloudSqlite.CloudCache]].\r\n * @note This property defaults to `true`.\r\n */\r\n readonly syncOnConnect?: boolean;\r\n /** A user-friendly description of the container's contents. */\r\n readonly description?: string;\r\n /** A message to display to the user if problems occur while loading the container. */\r\n readonly loadingHelp?: string;\r\n}\r\n\r\n/** The base name of a [[WorkspaceDb]], without any version information.\r\n * The name must conform to the following constraints:\r\n * - Case-insensitively unique among all [[WorkspaceDb]]s in the same [[WorkspaceContainer]].\r\n * - Between 1 and 255 characters in length.\r\n * - A legal filename on both [Windows](https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions) and UNIX.\r\n * - Contain none of the following characters: forward or backward slash, period, single or double quote, backtick, and \"#\".\r\n * - Begin or end with a whitespace character.\r\n * @see [[WorkspaceDbFullName]] for the fully-specified name, including version information.\r\n * @beta\r\n */\r\nexport type WorkspaceDbName = string;\r\n\r\n/** The fully-specified name of a [[WorkspaceDb]], combining its [[WorkspaceDbName]] and [[WorkspaceDbVersion]] in the format \"name:version\".\r\n * @beta\r\n */\r\nexport type WorkspaceDbFullName = string;\r\n\r\n/** A [semver](https://github.com/npm/node-semver) string describing the version of a [[WorkspaceDb]], e.g., \"4.2.11\".\r\n * @beta\r\n */\r\nexport type WorkspaceDbVersion = CloudSqlite.DbVersion;\r\n\r\n/** A [semver string](https://github.com/npm/node-semver?tab=readme-ov-file#ranges) describing a range of acceptable [[WorkspaceDbVersion]]s,\r\n * e.g., \">=1.2.7 <1.3.0\".\r\n * @beta\r\n */\r\nexport type WorkspaceDbVersionRange = CloudSqlite.DbVersionRange;\r\n\r\n/** Specifies the name and version of a [[WorkspaceDb]].\r\n * @beta\r\n */\r\nexport type WorkspaceDbNameAndVersion = Optional<CloudSqlite.DbNameAndVersion, \"dbName\">;\r\n\r\n/** Properties that specify how to load a [[WorkspaceDb]] within a [[WorkspaceContainer]].\r\n * @beta\r\n */\r\nexport interface WorkspaceDbProps extends WorkspaceDbNameAndVersion {\r\n /** If true, allow semver [prerelease versions](https://github.com/npm/node-semver?tab=readme-ov-file#prerelease-tags), e.g., \"1.4.2-beta.0\".\r\n * By default, only released version are allowed.\r\n */\r\n readonly includePrerelease?: boolean;\r\n /** If true, start a prefetch operation whenever this [[WorkspaceDb]] is opened, to begin downloading pages of the database before they are needed. */\r\n readonly prefetch?: boolean;\r\n}\r\n\r\n/** Properties describing a [[WorkspaceDb]] and the [[WorkspaceContainer]] containing it.\r\n * @beta\r\n */\r\nexport type WorkspaceDbCloudProps = WorkspaceDbProps & WorkspaceContainerProps;\r\n\r\n/** A function supplied as [[WorkspaceDbQueryResourcesArgs.callback]] to be invoked to process the requested resources.\r\n * @beta\r\n */\r\nexport type WorkspaceDbQueryResourcesCallback = (resourceNames: Iterable<string>) => void;\r\n\r\n/** Arguments supplied to [[WorkspaceDb.queryResources]].\r\n * @beta\r\n */\r\nexport interface WorkspaceDbQueryResourcesArgs {\r\n /** The type of resource to query. */\r\n type?: \"string\" | \"blob\";\r\n /** A pattern against which to compare the name of each resource, using [[nameCompare]] as the comparison operator.\r\n * Only resources whose names match the pattern will be included in the query results.\r\n */\r\n namePattern?: string;\r\n /** The comparison operator by which to compare the name of each resource to [[namePattern]].\r\n * Only resources whose names match the pattern will be included in the query results.\r\n * Ignored if [[namePattern]] is undefined.\r\n */\r\n nameCompare?: \"GLOB\" | \"LIKE\" | \"NOT GLOB\" | \"NOT LIKE\" | \"=\" | \"<\" | \">\";\r\n /** A function invoked to process the resources that match the query criterion. */\r\n callback: WorkspaceDbQueryResourcesCallback;\r\n}\r\n\r\n/** Metadata stored inside a [[WorkspaceDb]] describing the database's contents, to help users understand the purpose of the [[WorkspaceDb]], who to\r\n * contact with questions about it, and so on.\r\n * @note Only the [[workspaceName]] field is required, and users may add additional fields for their own purposes.\r\n * @note Since the information is stored inside of the [[WorkspaceDb]], it is versioned along with the rest of the contents.\r\n * @beta\r\n */\r\nexport interface WorkspaceDbManifest {\r\n /** The name of the [[WorkspaceDb]] to be shown in user interfaces. Organizations should attempt to make this name informative enough\r\n * so that users may refer to this name in conversations. It should also be unique enough that there's no confusion when it appears in\r\n * lists of WorkspaceDbs.\r\n * @note it is possible and valid to change the workspaceName between new version of a WorkspaceDb (e.g. incorporating a date).\r\n */\r\n readonly workspaceName: string;\r\n /** A description of the contents of this [[WorkspaceDb]] to help users understand its purpose and appropriate usage. */\r\n readonly description?: string;\r\n /** The name of the person to contact with questions about this [[WorkspaceDb]]. */\r\n readonly contactName?: string;\r\n /** The name of the person who last modified this [[WorkspaceDb]]. */\r\n readonly lastEditedBy?: string;\r\n}\r\n\r\n/**\r\n * An exception thrown when attempting to load a [[WorkspaceDb]] or some of its data; for example, if the [[WorkspaceDb]] could not be found or the user\r\n * is not authorized to access its [[WorkspaceContainer]].\r\n * @beta\r\n */\r\nexport interface WorkspaceDbLoadError extends ITwinError {\r\n /** The properties of the [[WorkspaceDb]] that was attempted to load, including the identity of its [[WorkspaceContainer]]. */\r\n wsDbProps?: WorkspaceDbProps & Partial<WorkspaceDbCloudProps>;\r\n /** The [[WorkspaceDb]] in which the error occurred, if available. */\r\n wsDb?: WorkspaceDb;\r\n}\r\n\r\n/** An exception that may occur while opening an [[IModelDb]] if any problems are detected while loading its [[IModelDb.workspace]].\r\n * This exception is never actually thrown; instead, after the iModel is opened, the exception is forwarded to [[Workspace.exceptionDiagnosticFn]]\r\n * so that the user can be notified of the problems.\r\n * @beta\r\n */\r\nexport interface WorkspaceDbLoadErrors extends ITwinError {\r\n /** An array of problems that were encountered attempting to load [[WorkspaceDb]]s for an [[IModelDb]]. The most common problem\r\n * is that the user doesn't have read access to one or more [[WorkspaceContainer]]s used by the iModel's [[Workspace]]..\r\n */\r\n wsLoadErrors?: WorkspaceDbLoadError[];\r\n}\r\n\r\n/** Specifies a resource inside a [[WorkspaceDb]] that holds a [[SettingsDictionary]] to load into [[Workspace.settings]].\r\n * Settings of this type named [[WorkspaceSettingNames.settingsWorkspaces]] are automatically loaded by [[Workspace.loadSettingsDictionary]].\r\n * @beta\r\n */\r\nexport interface WorkspaceDbSettingsProps extends WorkspaceDbCloudProps {\r\n /** The name of the resource holding the stringified JSON of the [[SettingsDictionary]]. */\r\n resourceName: string;\r\n /** The priority to assign to the [[SettingsDictionary]]. */\r\n priority: SettingsPriority;\r\n}\r\n\r\n/** The name of a blob, string, or file resource stored in a [[WorkspaceDb]].\r\n * Resource names must conform to the following constraints:\r\n * - At least 1 character and no more than 1024 characters in length.\r\n * - No leading or trailing whitespace characters.\r\n * Each resource of a given type must has a unique name within the [[WorkspaceDb]]. It is technically possible, but discouraged, to define\r\n * resources with the same name but different types.\r\n * @beta\r\n */\r\nexport type WorkspaceResourceName = string;\r\n\r\n/** A SQLite database in a [[Workspace]] containing named resources that the application is configured to use.\r\n * Resources are referred to by their [[WorkspaceResourceName]]s and can represent any number of things, including:\r\n * - [GeographicCRS]($common)es used to define the coordinate reference system of an iTwin.\r\n * - [[SettingsDictionary]]'s that contribute to the [[Workspace.settings]].\r\n * - Files that can be extracted temporarily to the local file system to be accessed by programs directly from disk.\r\n *\r\n * Ultimately, each resource is stored in one of the following formats:\r\n * - A `string`, which is often a stringified `JSON` representation of the resource;\r\n * - A binary `blob`; or\r\n * - An embedded file.\r\n *\r\n * Strings and blobs can be accessed directly using [[getString]] and [[getBlob]]. Files must first be copied to the local file system using [[getFile]], and should be avoided unless the software\r\n * that uses them is written to access them from disk.\r\n *\r\n * A `WorkspaceDb` resides in a [[WorkspaceContainer]] that can be published to the cloud. Once published, the `WorkspaceDb` becomes immutable.\r\n * However, multiple versions of a single `WorkspaceDb` can be created, allowing the [[Workspace]] contents to evolve over time.\r\n * `WorkspaceDb`s use [semantic versioning](https://github.com/npm/node-semver).\r\n *\r\n * The set of available `WorkspaceDb`s available for use for specific purposes are defined in the [[Workspace]]'s [[Settings]]. You can obtain\r\n * a single `WorkspaceDb` using [[WorkspaceContainer.getWorkspaceDb]], but more commonly you will use [[Workspace.getWorkspaceDbs]] to obtain\r\n * a list of all of the `WorkspaceDb`s, sorted by priority, that correspond to a given [[SettingName]].\r\n *\r\n * You can create new `WorkspaceDb`s (or new versions of existing `WorkspaceDb`s) using [[WorkspaceEditor]].\r\n * @beta\r\n */\r\nexport interface WorkspaceDb {\r\n /** @internal */\r\n [_implementationProhibited]: unknown;\r\n /** The [[WorkspaceContainer]] in which this db resides. */\r\n readonly container: WorkspaceContainer;\r\n /** The base name of this WorkspaceDb, without version */\r\n readonly dbName: WorkspaceDbName;\r\n /** An event raised before this WorkspaceDb is [[close]]d. */\r\n readonly onClose: BeEvent<() => void>;\r\n /** The name by which the WorkspaceDb can be opened. This will be either a local file name or the name of a database in a [[CloudSqlite.CloudContainer]]. */\r\n readonly dbFileName: string;\r\n /** The underlying SQLite database that stores this WorkspaceDb's resources. */\r\n readonly sqliteDb: SQLiteDb;\r\n /** Whether the underlying [[sqliteDb]] is currently [[open]]ed. */\r\n readonly isOpen: boolean;\r\n /** The manifest that describes the contents and context of this WorkspaceDb. */\r\n readonly manifest: WorkspaceDbManifest;\r\n /** The version of this WorkspaceDb */\r\n readonly version: WorkspaceDbVersion;\r\n\r\n /** Open the underlying [[sqliteDb]] to perform a query. Generally WorkspaceDbs are left closed and opened/closed as they're used. However,\r\n * when there will be significant activity against a WorkspaceDb, it may be useful to open it before the operations and close it afterwards.\r\n * Methods like [[queryResources]] open the SQLite database automatically and [[close]] it before they return.\r\n */\r\n open(): void;\r\n\r\n /** Close the underlying [[sqliteDb]]. You should call this after [[open]]ing the database and completing your query. */\r\n close(): void;\r\n\r\n /** Look up a string resource by name, if one exists. */\r\n getString(rscName: WorkspaceResourceName): string | undefined;\r\n\r\n /** Look up a binary resource by name, if one exists. */\r\n getBlob(rscName: WorkspaceResourceName): Uint8Array | undefined;\r\n\r\n /** Get a BlobIO reader for a blob WorkspaceResource.\r\n * @note when finished, caller *must* call `close` on the BlobIO.\r\n * @internal\r\n */\r\n getBlobReader(rscName: WorkspaceResourceName): SQLiteDb.BlobIO;\r\n\r\n /**\r\n * Extract a local copy of a file resource from this WorkspaceDb, if present.\r\n * @param rscName The name of the file resource in the WorkspaceDb\r\n * @param targetFileName optional name for extracted file. Some applications require files in specific locations or filenames. If\r\n * you know the full path to use for the extracted file, you can supply it. Generally, it is best to *not* supply the filename and\r\n * keep the extracted files in the directory specified by [[WorkspaceContainer.filesDir]].\r\n * @returns the full path to a file on the local file system, or undefined if the no file named `rscName` exists.\r\n * @note The file is copied from the file into the local file system so it may be accessed directly. This happens only\r\n * as necessary, if the local file doesn't exist, or if it is out-of-date because it was updated in the file.\r\n * For this reason, you should not save the local file name, and instead call this method every time you access it, so its\r\n * content is always holds the correct version.\r\n * @note The filename will be a hash value, not the resource name.\r\n * @note Workspace resource files are set as read-only as they are copied from the file.\r\n * To edit them, you must first copy them to another location.\r\n */\r\n getFile(rscName: WorkspaceResourceName, targetFileName?: LocalFileName): LocalFileName | undefined;\r\n\r\n /**\r\n * Ensure that the contents of this `WorkspaceDb` are downloaded into the local cache so that it may be accessed offline.\r\n * Until the promise resolves, the `WorkspaceDb` is not fully downloaded, but it *may* be safely accessed during the download.\r\n * To determine the progress of the download, use the `localBlocks` and `totalBlocks` values returned by `CloudContainer.queryDatabase`.\r\n * @returns a [[CloudSqlite.CloudPrefetch]] object that can be used to await and/or cancel the prefetch.\r\n * @throws if this WorkspaceDb is not from a [[CloudSqlite.CloudContainer]].\r\n */\r\n prefetch(opts?: CloudSqlite.PrefetchProps): CloudSqlite.CloudPrefetch;\r\n\r\n /** Find resources of a particular type with names matching a specified pattern.\r\n * The matching resources will be supplied to [[WorkspaceDbQueryResourcesArgs.callbackk]].\r\n * @see [[Workspace.queryResources]] to query resources within multiple `WorkspaceDb`s.\r\n */\r\n queryResources(args: WorkspaceDbQueryResourcesArgs): void;\r\n\r\n /** @internal */\r\n queryFileResource(rscName: WorkspaceResourceName): { localFileName: LocalFileName, info: IModelJsNative.EmbedFileQuery } | undefined;\r\n}\r\n\r\n/** Options supplied to [[IModelHost.startup]] via [[IModelHostOptions.workspace]] to customize the initialization of [[IModelHost.appWorkspace]].\r\n * @beta\r\n */\r\nexport interface WorkspaceOpts {\r\n /** The local directory for non-cloud-based [[WorkspaceDb]] files. The [[Workspace]] API will look in this directory\r\n * for files named `${containerId}/${dbId}.itwin-workspace`.\r\n * @note if not supplied, defaults to \"iTwin/Workspace\" in the user-local folder.\r\n */\r\n containerDir?: LocalDirName;\r\n\r\n /** The name(s) of one or more local JSON files containing [[SettingsDictionary]]s to load when initializing the [[Workspace]]. */\r\n settingsFiles?: LocalFileName | LocalFileName[];\r\n}\r\n\r\n/** Arguments supplied to [[Workspace.getContainer]] and [[WorkspaceEditor.getContainer]].\r\n * @beta\r\n */\r\nexport interface GetWorkspaceContainerArgs extends WorkspaceContainerProps {\r\n /** Token required to access the container. */\r\n accessToken: AccessToken;\r\n}\r\n\r\n/**\r\n * Settings and resources that customize an application for the current session.\r\n * See the [learning article]($docs/learning/backend/Workspace) for a detailed overiew and examples.\r\n * @beta\r\n */\r\nexport interface Workspace {\r\n /** @internal */\r\n [_implementationProhibited]: unknown;\r\n\r\n /** The directory for local WorkspaceDb files with the name `${containerId}/${dbId}.itwin-workspace`.\r\n * @internal\r\n */\r\n readonly containerDir: LocalDirName;\r\n\r\n /** The current [[Settings]] for this Workspace */\r\n readonly settings: Settings;\r\n\r\n /** Get the cloud cache for cloud-based [[WorkspaceContainer]]s. */\r\n getCloudCache(): CloudSqlite.CloudCache;\r\n\r\n /** Search for a container previously opened by [[getContainer]] or [[getContainerAsync]].\r\n * @param containerId The id of the container\r\n * @returns the [[WorkspaceContainer]] for `containerId`, or `undefined` if no such container has been opened.\r\n * @internal\r\n */\r\n findContainer(containerId: WorkspaceContainerId): WorkspaceContainer | undefined;\r\n\r\n /** Obtain the [[WorkspaceContainer]] specified by `props`.\r\n * @param props The properties of the `WorkspaceContainer`, opening it if it is not already opened.\r\n * Otherwise it is created.\r\n * @note This function allows a `WorkspaceContainer.Props` without its [AccessToken]($bentley). It will attempt to obtain one from the [[BlobContainer]] service,\r\n * hence this function is async.\r\n * @see [[getContainer]] to obtain a container synchronously.\r\n */\r\n getContainerAsync(props: WorkspaceContainerProps): Promise<WorkspaceContainer>;\r\n\r\n /** Get a WorkspaceContainer with a supplied access token. This function is synchronous and may be used if:\r\n * - a valid [AccessToken]($bentley) is already available;\r\n * - the container has already been previously prefetched in another session (this is useful for offline usage); or\r\n * - the container is public and doesn't require an [AccessToken]($bentley).\r\n * @see [[getContainerAsync]] to obtain a container asynchronously if the above conditions do not apply.\r\n */\r\n getContainer(props: GetWorkspaceContainerArgs): WorkspaceContainer;\r\n\r\n /** Load a [[SettingsDictionary]] from the specified [[WorkspaceDb]] and add it to this workspace's current [[Settings]].\r\n * @note this function will load the dictionaries from the supplied list, and it will also call itself recursively for any entries in\r\n * the loaded Settings with the name [[WorkspaceSettingNames.settingsWorkspaces]]. In this manner, WorkspaceSettings may be \"chained\" together so that loading one\r\n * causes its \"dependent\" WorkspaceSettings to be loaded. Its `Promise` is resolved after all have been loaded (or failed to load).\r\n */\r\n loadSettingsDictionary(\r\n /** The properties of the [[WorkspaceDb]], plus the resourceName and [[SettingsPriority]]. May be either a single value or an array of them */\r\n props: WorkspaceDbSettingsProps | WorkspaceDbSettingsProps[],\r\n /** If present, an array that is populated with a list of problems while attempting to load the [[SettingsDictionary]](s). */\r\n problems?: WorkspaceDbLoadError[]\r\n ): Promise<void>;\r\n\r\n /** Get a single [[WorkspaceDb]]. */\r\n getWorkspaceDb(props: WorkspaceDbCloudProps): Promise<WorkspaceDb>;\r\n\r\n /**\r\n * Resolve the value of all [[Setting]]s from this workspace with the supplied `settingName` into an array of [[WorkspaceDbCloudProps]]\r\n * that can be used to query or load workspace resources. The settings must each be an array of type [[WorkspaceDbSettingsProps]].\r\n * The returned array will be sorted according to their [[SettingsPriority]], with the first entry being the highest priority [[WorkspaceDb]].\r\n * @note The list is built by combining, in order, all of the settings with the supplied [[SettingName]]. It may therefore include the\r\n * properties of same WorkspaceDb multiple times. This list is automatically de-duped by [[getWorkspaceDb]].\r\n * @note This function is rarely used directly. Usually it is called by [[getWorkspaceDbs]]. However, this function is synchronous and may sometimes\r\n * be useful for editors, tests, or diagnostics.\r\n */\r\n resolveWorkspaceDbSetting(\r\n /** the name of the setting. */\r\n settingName: SettingName,\r\n /** optional filter to choose specific WorkspaceDbs from the settings values. If present, only those WorkspaceDbs for which the filter returns `true` will be included. */\r\n filter?: Workspace.DbListFilter): WorkspaceDbCloudProps[];\r\n\r\n /**\r\n * Get a sorted array of [[WorkspaceDb]]s that can be used to query or load resources. If the arguments supply a `settingName`, this function will\r\n * use [[resolveWorkspaceDbSetting]] to get get the array of [[WorkspaceDbCloudProps]].\r\n * @returns A `Promise` resolving to an array of [[WorkspaceDb]]s sorted by [[SettingsPriority]] so that resources found in WorkspaceDbs earlier in the list take precedence\r\n * over ones with the same name in later WorkspaceDbs. No WorkspaceDb will appear more than once in the list.\r\n * @note this function may request an [AccessToken]($bentley) for each WorkspaceDb if necessary, and hence is asynchronous.\r\n */\r\n getWorkspaceDbs(\r\n args: Workspace.DbListOrSettingName & {\r\n /** if supplied, this array is populated with a list of problems (e.g. no read permission) attempting to load WorkspacesDbs. */\r\n problems?: WorkspaceDbLoadError[];\r\n /** only valid when called with a settingName, if so passed as `filter` argument to [[resolveWorkspaceDbSetting]] */\r\n filter?: Workspace.DbListFilter;\r\n }): Promise<WorkspaceDb[]>;\r\n}\r\n\r\n/**\r\n * A WorkspaceContainer is a type of [[CloudSqlite.CloudContainer]] that holds one or more [[WorkspaceDb]]s. Normally a WorkspaceContainer will hold (many versions of) a single WorkspaceDb.\r\n * Each version of a WorkspaceDb is treated as immutable after it is created and is stored in the WorkspaceContainer indefinitely. That means that\r\n * older versions of the WorkspaceDb may continue to be used, for example by archived projects. For programmers familiar with [NPM](https://www.npmjs.com/), this is conceptually\r\n * similar and versioning follows the same rules as NPM using [Semantic Versioning](https://semver.org/).\r\n * @note It is possible to store more than one WorkspaceDb in the same WorkspaceContainer, but access rights are administered per WorkspaceContainer.\r\n * That is, if a user has rights to access a WorkspaceContainer, that right applies to all WorkspaceDbs in the WorkspaceContainer.\r\n * @note Not every WorkspaceContainer is associated with a [[CloudSqlite.CloudContainer]] - WorkspaceContainers may also be loaded from the local file system.\r\n * In this case, [[cloudContainer]] will be `undefined`.\r\n * @see [[Workspace.getContainer]] and [[Workspace.getContainerAsync]] to load a container.\r\n * @beta\r\n */\r\nexport interface WorkspaceContainer {\r\n /** @internal */\r\n [_implementationProhibited]: unknown;\r\n /** the local directory where this WorkspaceContainer will store temporary files extracted for file-resources.\r\n * @internal\r\n */\r\n readonly filesDir: LocalDirName;\r\n /** The workspace into which this container was loaded. */\r\n readonly workspace: Workspace;\r\n /** Cloud container for this WorkspaceContainer, or `undefined` if this is a local WorkspaceContainer. */\r\n readonly cloudContainer?: CloudSqlite.CloudContainer;\r\n /** Properties supplied when this container was loaded */\r\n readonly fromProps: WorkspaceContainerProps;\r\n\r\n /** @internal */\r\n addWorkspaceDb(toAdd: WorkspaceDb): void;\r\n\r\n /**\r\n * Find the fully-qualified name of a [[WorkspaceDb]] satisfying the name and version criteria specified by `props`.\r\n * @throws Error if no version satisfying the criteria exists.\r\n */\r\n resolveDbFileName(props: WorkspaceDbProps): WorkspaceDbFullName;\r\n\r\n /** Obtain a [[WorkspaceDb]] satisfying the name and version criteria specified by `props`. */\r\n getWorkspaceDb(props?: WorkspaceDbProps): WorkspaceDb;\r\n\r\n /** Close and remove a currently opened [[WorkspaceDb]] from this Workspace.\r\n * @internal\r\n */\r\n closeWorkspaceDb(container: WorkspaceDb): void;\r\n}\r\n\r\nfunction makeSettingName(name: string) {\r\n return `${\"itwin/core/workspace\"}/${name}`;\r\n}\r\n\r\n/** The names of various [[Setting]]s with special meaning to the [[Workspace]] system.\r\n * @beta\r\n */\r\nexport namespace WorkspaceSettingNames {\r\n /** The name of a setting that, when present in a [[WorkspaceDb]] loaded by [[Workspace.loadSettingsDictionary]], will automatically\r\n * be used to find and load additional [[SettingsDictionary]]'s in other [[WorkspaceDb]]s. This permits you to chain the settings inside on [[WorkspaceDb]]\r\n * to others upon which they depend.\r\n * This setting's value is an array of [[WorkspaceDbSettingsProps]]s.\r\n */\r\n export const settingsWorkspaces = makeSettingName(\"settingsWorkspaces\");\r\n}\r\n\r\n/** A function supplied as part of a [[QueryWorkspaceResourcesArgs]] to iterate the resources retrieved by [[Workspace.queryResources]].\r\n * The `resources` object should only be used inside the function - it is an error to attempt to iterate it after the function returns.\r\n * @beta\r\n */\r\nexport type QueryWorkspaceResourcesCallback = (resources: Iterable<{ name: string, db: WorkspaceDb }>) => void;\r\n\r\n/** Arguments supplied to [[Workspace.queryResources]] defining the query criteria and the list of [[WorkspaceDb]]s to query.\r\n * @beta\r\n */\r\nexport interface QueryWorkspaceResourcesArgs {\r\n /** The list of `WorkspaceDb`s to query, in the order in which they are to be queried.\r\n * @see [[Workspace.resolveWorkspaceDbSetting]] or [[Workspace.getWorkspaceDbs]] to obtain an appropriate list of `WorkspaceDb`s.\r\n */\r\n dbs: WorkspaceDb[];\r\n /** The type of resource to query. */\r\n type?: \"string\" | \"blob\";\r\n /** A pattern against which to compare the name of each resource, using [[nameCompare]] as the comparison operator.\r\n * Only resources whose names match the pattern will be included in the query results.\r\n */\r\n namePattern?: string;\r\n /** The comparison operator by which to compare the name of each resource to [[namePattern]].\r\n * Only resources whose names match the pattern will be included in the query results.\r\n * Ignored i [[namePattern]] is undefined.\r\n */\r\n nameCompare?: \"GLOB\" | \"LIKE\" | \"NOT GLOB\" | \"NOT LIKE\" | \"=\" | \"<\" | \">\";\r\n /** A function invoked to process the resources that match the query criteria. */\r\n callback: QueryWorkspaceResourcesCallback;\r\n}\r\n\r\nfunction getWorkspaceResource(dbs: WorkspaceDb[], name: string, type: \"string\" | \"blob\"): string | Uint8Array | undefined {\r\n for (const db of dbs) {\r\n const val = type === \"blob\" ? db.getBlob(name) : db.getString(name);\r\n if (undefined !== val) {\r\n return val;\r\n }\r\n }\r\n\r\n return undefined;\r\n}\r\n\r\n/** Arguments supplied to [[Workspace.getStringResource]] and [[WOrkspace.getBlobResource]].\r\n * @beta\r\n */\r\nexport interface GetWorkspaceResourceArgs {\r\n /** The list of `WorkspaceDb`s to search, in the order in which they are to be searched.\r\n * @see [[Workspace.resolveWorkspaceDbSetting]] or [[Workspace.getWorkspaceDbs]] to obtain an appropriate list of `WorkspaceDb`s.\r\n */\r\n dbs: WorkspaceDb[];\r\n /** The name of the resource to find. */\r\n name: WorkspaceResourceName;\r\n}\r\n\r\n/** @beta */\r\nexport namespace Workspace {\r\n /** A function invoked to handle exceptions produced while loading workspace data.\r\n * Applications can override this function to notify the user and/or attempt to diagnose the problem.\r\n * The default implementation simply logs each exception.\r\n */\r\n export let exceptionDiagnosticFn = (e: WorkspaceDbLoadErrors) => { // eslint-disable-line prefer-const\r\n if (e instanceof Error)\r\n Logger.logError(BackendLoggerCategory.Workspace, e);\r\n else\r\n UnexpectedErrors.handle(e);\r\n };\r\n\r\n /** Arguments supplied to [[Workspace.onSettingsDictionaryLoadedFn]] for every [[SettingsDictionary]] that is loaded from a [[WorkspaceDb]]. */\r\n export interface SettingsDictionaryLoaded {\r\n /** The dictionary that was loaded */\r\n dict: SettingsDictionary;\r\n /** The WorkspaceDb from which the dictionary was loaded. */\r\n from: WorkspaceDb;\r\n }\r\n\r\n /** A function invoked each time any [[SettingsDictionary]] is loaded from a [[WorkspaceDb]].\r\n * Applications can override this function to notify the user and/or record diagnostics.\r\n * The default implementation simply records an information message in the [Logger]($bentley).\r\n */\r\n export let onSettingsDictionaryLoadedFn = (loaded: SettingsDictionaryLoaded) => { // eslint-disable-line prefer-const\r\n Logger.logInfo(BackendLoggerCategory.Workspace, `loaded setting dictionary ${loaded.dict.props.name} from ${loaded.from.dbFileName}`);\r\n };\r\n\r\n /** Either an array of [[WorkspaceDbCloudProps]] or the name of a [[Setting]] that resolves to an array of [[WorkspaceDbCloudProps]].\r\n * Used by [[Workspace.getWorkspaceDbs]].\r\n */\r\n export type DbListOrSettingName = { readonly dbs: WorkspaceDbCloudProps[], readonly settingName?: never } | { readonly settingName: SettingName, readonly dbs?: never };\r\n\r\n /** In arguments supplied to [[Workspace.getWorkspaceDbs]] and [[Workspace.resolveWorkspaceDbSetting]], an optional function used to exclude some\r\n * [[WorkspaceDb]]s. Only those [[WorkspaceDb]]s for which the function returns `true` will be included.\r\n */\r\n export type DbListFilter = (\r\n /** The properties of the WorkspaceDb to be returned */\r\n dbProp: WorkspaceDbCloudProps,\r\n /** The SettingsDictionary holding the [[WorkspaceSettingNames.settingsWorkspace]] setting. May be used, for example, to determine the\r\n * [[SettingsPriority]] of the dictionary.\r\n */\r\n dict: SettingsDictionary\r\n ) => boolean;\r\n\r\n /** Searches a list of [[WorkspaceDb]]s for a string resource of a given name.\r\n * The list is searched in order, and the first resource with the request name is returned.\r\n * If no such resource exists, the function returns `undefined`.\r\n * @see [[WorkspaceDb.getString]] if you only need to search a single `WorkspaceDb`.\r\n * @beta\r\n */\r\n export function getStringResource(args: GetWorkspaceResourceArgs): string | undefined {\r\n return getWorkspaceResource(args.dbs, args.name, \"string\") as string | undefined;\r\n }\r\n\r\n /** Searches a list of [[WorkspaceDb]]s for a blob resource of a given name.\r\n * The list is searched in order, and the first resource with the request name is returned.\r\n * If no such resource exists, the function returns `undefined`.\r\n * @see [[WorkspaceDb.getblob]] if you only need to search a single `WorkspaceDb`.\r\n * @beta\r\n */\r\n export function getBlobResource(args: GetWorkspaceResourceArgs): Uint8Array | undefined {\r\n return getWorkspaceResource(args.dbs, args.name, \"blob\") as Uint8Array | undefined;\r\n }\r\n\r\n /** Query a list of [[WorkspaceDb]]s to find resources of a particular type with names matching a specified pattern.\r\n * @see [[WorkspaceDb.queryResources]] if you only need to query a single `WorkspaceDb`.\r\n * @beta\r\n */\r\n export function queryResources(args: QueryWorkspaceResourcesArgs): void {\r\n const resources: Array<{ name: string, db: WorkspaceDb }> = [];\r\n for (const db of args.dbs) {\r\n db.queryResources({\r\n type: args.type,\r\n namePattern: args.namePattern,\r\n nameCompare: args.nameCompare,\r\n callback: (names) => {\r\n for (const name of names) {\r\n resources.push({ db, name });\r\n }\r\n },\r\n });\r\n }\r\n\r\n args.callback(resources);\r\n }\r\n}\r\n"]}
|
package/lib/esm/TileStorage.js
CHANGED
|
@@ -152,7 +152,7 @@ export class TileStorage {
|
|
|
152
152
|
return this.storage.objectExists(getTileObjectReference(iModelId, changesetId, treeId, contentId, guid));
|
|
153
153
|
}
|
|
154
154
|
logException(message, err) {
|
|
155
|
-
Logger.
|
|
155
|
+
Logger.logError(BackendLoggerCategory.IModelTileStorage, err, { errorMessage: message });
|
|
156
156
|
}
|
|
157
157
|
}
|
|
158
158
|
//# sourceMappingURL=TileStorage.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TileStorage.js","sourceRoot":"","sources":["../../src/TileStorage.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAEjC,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,qBAAq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AC;QACxB,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,YAAY,CAAC,QAAgB,EAAE,WAAmB,EAAE,MAAc,EAAE,SAAiB,EAAE,IAAa;QAC/G,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,sBAAsB,CAAC,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;IAC3G,CAAC;IAEO,YAAY,CAAC,OAAe,EAAE,GAAY;QAChD,MAAM,CAAC,YAAY,CACjB,qBAAqB,CAAC,iBAAiB,EACvC,GAAG,EACH,CAAC,QAAQ,EAAE,GAAG,EAAE,aAAa,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,EAAE,GAAG,OAAO,kBAAkB,EAAE,EAAE,GAAG,aAAa,EAAE,YAAY,EAAE,GAAG,EAAE,CAAC,CACnI,CAAC;IACJ,CAAC;CACF","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\nimport { gunzip, gzip } from \"zlib\";\r\nimport { promisify } from \"util\";\r\nimport type { Metadata, ObjectReference, ServerStorage, TransferConfig } from \"@itwin/object-storage-core\";\r\nimport { getTileObjectReference } from \"@itwin/core-common\";\r\nimport { Logger } from \"@itwin/core-bentley\";\r\nimport { BackendLoggerCategory } from \"./BackendLoggerCategory\";\r\nimport { IModelHost } from \"./IModelHost\";\r\n\r\n/**\r\n * Identifies a tile in cloud tile cache.\r\n * @beta\r\n */\r\nexport interface TileId {\r\n treeId: string;\r\n contentId: string;\r\n guid: string;\r\n}\r\n\r\n/**\r\n * Facilitates interaction with cloud tile cache.\r\n * @beta\r\n */\r\nexport class TileStorage {\r\n /**\r\n * Allows using the underlying `ServerStorage` API directly.\r\n * @see https://github.com/iTwin/object-storage/\r\n */\r\n public readonly storage: ServerStorage;\r\n\r\n public constructor(storage: ServerStorage) {\r\n this.storage = storage;\r\n }\r\n\r\n private _initializedIModels: Set<string> = new Set();\r\n\r\n /**\r\n * Ensures any required cloud storage resources for a specific iModel are ready to use.\r\n */\r\n public async initialize(iModelId: string): Promise<void> {\r\n if (this._initializedIModels.has(iModelId))\r\n return;\r\n if (!(await this.storage.baseDirectoryExists({ baseDirectory: iModelId }))) {\r\n try {\r\n await this.storage.createBaseDirectory({ baseDirectory: iModelId });\r\n } catch (e: any) {\r\n // Ignore 409 errors. This is what Azure blob storage returns when the container already exists.\r\n // Usually this means multiple backends tried to initialize tile storage at the same time.\r\n if(e.statusCode !== 409)\r\n throw e;\r\n }\r\n }\r\n this._initializedIModels.add(iModelId);\r\n }\r\n\r\n /**\r\n * Returns config that can be used by frontends to download tiles\r\n * @param iModelId Id of the iModel\r\n * @param expiresInSeconds Optional number of seconds until the download URL expires. Defaults to expiring exactly at midnight of next Sunday to enable persistent client-side caching.\r\n * It is recommended to set this to a shorter period when using S3-compatible storage - an exact expiry date cannot be ensured due to limitations in their API.\r\n * @see [TileStorage]($frontend)\r\n */\r\n public async getDownloadConfig(iModelId: string, expiresInSeconds?: number): Promise<TransferConfig> {\r\n try {\r\n if (expiresInSeconds !== undefined)\r\n return await this.storage.getDownloadConfig({ baseDirectory: iModelId }, { expiresInSeconds });\r\n const expiresOn = new Date();\r\n expiresOn.setDate(expiresOn.getDate() + (7 - expiresOn.getDay())); // next Sunday\r\n expiresOn.setHours(0, 0, 0, 0); // exactly at midnight\r\n return await this.storage.getDownloadConfig({ baseDirectory: iModelId }, { expiresOn });\r\n } catch (err) {\r\n this.logException(\"Failed to get download config\", err);\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Uploads a tile to the cloud cache.\r\n */\r\n public async uploadTile(iModelId: string, changesetId: string, treeId: string, contentId: string, content: Uint8Array, guid?: string, metadata?: Metadata): Promise<void> {\r\n try {\r\n await this.storage.upload(\r\n getTileObjectReference(iModelId, changesetId, treeId, contentId, guid),\r\n Buffer.from(IModelHost.compressCachedTiles ? await promisify(gzip)(content.buffer) : content.buffer),\r\n metadata,\r\n IModelHost.compressCachedTiles ? { contentEncoding: \"gzip\" } : undefined,\r\n );\r\n } catch (err) {\r\n this.logException(\"Failed to upload tile\", err);\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Downloads a tile from the cloud cache.\r\n */\r\n public async downloadTile(iModelId: string, changesetId: string, treeId: string, contentId: string, guid?: string): Promise<Uint8Array> {\r\n try {\r\n const buffer = await this.storage.download(\r\n getTileObjectReference(iModelId, changesetId, treeId, contentId, guid),\r\n \"buffer\",\r\n );\r\n return IModelHost.compressCachedTiles ? await promisify(gunzip)(buffer) : buffer;\r\n } catch (err) {\r\n this.logException(\"Failed to download tile\", err);\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Returns an async iterator of all tiles that are found in the cloud cache.\r\n */\r\n public async *getCachedTilesGenerator(iModelId: string): AsyncGenerator<TileId> {\r\n const iterator = this.getCachedTilePages(iModelId);\r\n for await (const page of iterator) {\r\n for (const tile of page) {\r\n yield tile;\r\n }\r\n }\r\n }\r\n\r\n private async *getCachedTilePages(iModelId: string): AsyncGenerator<TileId[]> {\r\n const iterator = this.storage.getListObjectsPagedIterator({ baseDirectory: iModelId }, 500);\r\n let prevPage: IteratorResult<ObjectReference[], any> | undefined;\r\n do {\r\n // initiate loading the next page\r\n const page = iterator.next();\r\n // process results from the previous page\r\n if (prevPage)\r\n yield this.convertPage(prevPage.value);\r\n // finish loading the next page\r\n prevPage = await page;\r\n } while (!prevPage.done);\r\n }\r\n\r\n private convertPage(page: ObjectReference[]): TileId[] {\r\n return page\r\n .map((objectReference) => ({\r\n parts: objectReference.relativeDirectory?.split(\"/\") ?? [\"\"],\r\n objectName: objectReference.objectName,\r\n }))\r\n .filter(({ parts, objectName }) => {\r\n if (parts[0] !== \"tiles\")\r\n return false;\r\n if (parts.length !== 3) {\r\n Logger.logWarning(BackendLoggerCategory.IModelTileStorage, \"Malformed tile id found in tile cache: {tileId}\", { tileId: [...parts, objectName].join(\"/\") });\r\n return false;\r\n }\r\n return true;\r\n }).map(({ parts, objectName }) => {\r\n // relativeDirectory = tiles/<treeId>/<guid>\r\n // objectName = <contentId>\r\n return {\r\n treeId: parts[1],\r\n contentId: objectName,\r\n guid: parts[2],\r\n };\r\n });\r\n }\r\n\r\n /**\r\n * Returns a list of all tiles that are found in the cloud cache.\r\n */\r\n public async getCachedTiles(iModelId: string): Promise<TileId[]> {\r\n const results: TileId[] = [];\r\n for await (const page of this.getCachedTilePages(iModelId)) {\r\n results.push(...page);\r\n }\r\n return results;\r\n }\r\n\r\n /**\r\n * Returns a boolean indicating whether a tile exists in the cloud cache\r\n */\r\n public async isTileCached(iModelId: string, changesetId: string, treeId: string, contentId: string, guid?: string): Promise<boolean> {\r\n return this.storage.objectExists(getTileObjectReference(iModelId, changesetId, treeId, contentId, guid));\r\n }\r\n\r\n private logException(message: string, err: unknown): void {\r\n Logger.logException(\r\n BackendLoggerCategory.IModelTileStorage,\r\n err,\r\n (category, msg, errorMetadata) => Logger.logError(category, `${message}: {errorMessage}`, { ...errorMetadata, errorMessage: msg }),\r\n );\r\n }\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"file":"TileStorage.js","sourceRoot":"","sources":["../../src/TileStorage.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,MAAM,CAAC;AAEjC,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAY1C;;;GAGG;AACH,MAAM,OAAO,WAAW;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E,MAAc,EAAE,SAAiB,EAAE,IAAa;QAC/G,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,sBAAsB,CAAC,QAAQ,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;IAC3G,CAAC;IAEO,YAAY,CAAC,OAAe,EAAE,GAAY;QAChD,MAAM,CAAC,QAAQ,CACb,qBAAqB,CAAC,iBAAiB,EACvC,GAAG,EACH,EAAE,YAAY,EAAE,OAAO,EAAE,CAC1B,CAAC;IACJ,CAAC;CACF","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\nimport { gunzip, gzip } from \"zlib\";\r\nimport { promisify } from \"util\";\r\nimport type { Metadata, ObjectReference, ServerStorage, TransferConfig } from \"@itwin/object-storage-core\";\r\nimport { getTileObjectReference } from \"@itwin/core-common\";\r\nimport { Logger } from \"@itwin/core-bentley\";\r\nimport { BackendLoggerCategory } from \"./BackendLoggerCategory\";\r\nimport { IModelHost } from \"./IModelHost\";\r\n\r\n/**\r\n * Identifies a tile in cloud tile cache.\r\n * @beta\r\n */\r\nexport interface TileId {\r\n treeId: string;\r\n contentId: string;\r\n guid: string;\r\n}\r\n\r\n/**\r\n * Facilitates interaction with cloud tile cache.\r\n * @beta\r\n */\r\nexport class TileStorage {\r\n /**\r\n * Allows using the underlying `ServerStorage` API directly.\r\n * @see https://github.com/iTwin/object-storage/\r\n */\r\n public readonly storage: ServerStorage;\r\n\r\n public constructor(storage: ServerStorage) {\r\n this.storage = storage;\r\n }\r\n\r\n private _initializedIModels: Set<string> = new Set();\r\n\r\n /**\r\n * Ensures any required cloud storage resources for a specific iModel are ready to use.\r\n */\r\n public async initialize(iModelId: string): Promise<void> {\r\n if (this._initializedIModels.has(iModelId))\r\n return;\r\n if (!(await this.storage.baseDirectoryExists({ baseDirectory: iModelId }))) {\r\n try {\r\n await this.storage.createBaseDirectory({ baseDirectory: iModelId });\r\n } catch (e: any) {\r\n // Ignore 409 errors. This is what Azure blob storage returns when the container already exists.\r\n // Usually this means multiple backends tried to initialize tile storage at the same time.\r\n if(e.statusCode !== 409)\r\n throw e;\r\n }\r\n }\r\n this._initializedIModels.add(iModelId);\r\n }\r\n\r\n /**\r\n * Returns config that can be used by frontends to download tiles\r\n * @param iModelId Id of the iModel\r\n * @param expiresInSeconds Optional number of seconds until the download URL expires. Defaults to expiring exactly at midnight of next Sunday to enable persistent client-side caching.\r\n * It is recommended to set this to a shorter period when using S3-compatible storage - an exact expiry date cannot be ensured due to limitations in their API.\r\n * @see [TileStorage]($frontend)\r\n */\r\n public async getDownloadConfig(iModelId: string, expiresInSeconds?: number): Promise<TransferConfig> {\r\n try {\r\n if (expiresInSeconds !== undefined)\r\n return await this.storage.getDownloadConfig({ baseDirectory: iModelId }, { expiresInSeconds });\r\n const expiresOn = new Date();\r\n expiresOn.setDate(expiresOn.getDate() + (7 - expiresOn.getDay())); // next Sunday\r\n expiresOn.setHours(0, 0, 0, 0); // exactly at midnight\r\n return await this.storage.getDownloadConfig({ baseDirectory: iModelId }, { expiresOn });\r\n } catch (err) {\r\n this.logException(\"Failed to get download config\", err);\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Uploads a tile to the cloud cache.\r\n */\r\n public async uploadTile(iModelId: string, changesetId: string, treeId: string, contentId: string, content: Uint8Array, guid?: string, metadata?: Metadata): Promise<void> {\r\n try {\r\n await this.storage.upload(\r\n getTileObjectReference(iModelId, changesetId, treeId, contentId, guid),\r\n Buffer.from(IModelHost.compressCachedTiles ? await promisify(gzip)(content.buffer) : content.buffer),\r\n metadata,\r\n IModelHost.compressCachedTiles ? { contentEncoding: \"gzip\" } : undefined,\r\n );\r\n } catch (err) {\r\n this.logException(\"Failed to upload tile\", err);\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Downloads a tile from the cloud cache.\r\n */\r\n public async downloadTile(iModelId: string, changesetId: string, treeId: string, contentId: string, guid?: string): Promise<Uint8Array> {\r\n try {\r\n const buffer = await this.storage.download(\r\n getTileObjectReference(iModelId, changesetId, treeId, contentId, guid),\r\n \"buffer\",\r\n );\r\n return IModelHost.compressCachedTiles ? await promisify(gunzip)(buffer) : buffer;\r\n } catch (err) {\r\n this.logException(\"Failed to download tile\", err);\r\n throw err;\r\n }\r\n }\r\n\r\n /**\r\n * Returns an async iterator of all tiles that are found in the cloud cache.\r\n */\r\n public async *getCachedTilesGenerator(iModelId: string): AsyncGenerator<TileId> {\r\n const iterator = this.getCachedTilePages(iModelId);\r\n for await (const page of iterator) {\r\n for (const tile of page) {\r\n yield tile;\r\n }\r\n }\r\n }\r\n\r\n private async *getCachedTilePages(iModelId: string): AsyncGenerator<TileId[]> {\r\n const iterator = this.storage.getListObjectsPagedIterator({ baseDirectory: iModelId }, 500);\r\n let prevPage: IteratorResult<ObjectReference[], any> | undefined;\r\n do {\r\n // initiate loading the next page\r\n const page = iterator.next();\r\n // process results from the previous page\r\n if (prevPage)\r\n yield this.convertPage(prevPage.value);\r\n // finish loading the next page\r\n prevPage = await page;\r\n } while (!prevPage.done);\r\n }\r\n\r\n private convertPage(page: ObjectReference[]): TileId[] {\r\n return page\r\n .map((objectReference) => ({\r\n parts: objectReference.relativeDirectory?.split(\"/\") ?? [\"\"],\r\n objectName: objectReference.objectName,\r\n }))\r\n .filter(({ parts, objectName }) => {\r\n if (parts[0] !== \"tiles\")\r\n return false;\r\n if (parts.length !== 3) {\r\n Logger.logWarning(BackendLoggerCategory.IModelTileStorage, \"Malformed tile id found in tile cache: {tileId}\", { tileId: [...parts, objectName].join(\"/\") });\r\n return false;\r\n }\r\n return true;\r\n }).map(({ parts, objectName }) => {\r\n // relativeDirectory = tiles/<treeId>/<guid>\r\n // objectName = <contentId>\r\n return {\r\n treeId: parts[1],\r\n contentId: objectName,\r\n guid: parts[2],\r\n };\r\n });\r\n }\r\n\r\n /**\r\n * Returns a list of all tiles that are found in the cloud cache.\r\n */\r\n public async getCachedTiles(iModelId: string): Promise<TileId[]> {\r\n const results: TileId[] = [];\r\n for await (const page of this.getCachedTilePages(iModelId)) {\r\n results.push(...page);\r\n }\r\n return results;\r\n }\r\n\r\n /**\r\n * Returns a boolean indicating whether a tile exists in the cloud cache\r\n */\r\n public async isTileCached(iModelId: string, changesetId: string, treeId: string, contentId: string, guid?: string): Promise<boolean> {\r\n return this.storage.objectExists(getTileObjectReference(iModelId, changesetId, treeId, contentId, guid));\r\n }\r\n\r\n private logException(message: string, err: unknown): void {\r\n Logger.logError(\r\n BackendLoggerCategory.IModelTileStorage,\r\n err,\r\n { errorMessage: message },\r\n );\r\n }\r\n}\r\n"]}
|
|
@@ -33,7 +33,7 @@ class IModelDbFontsImpl {
|
|
|
33
33
|
faces = JSON.parse(stmt.getValueString(1));
|
|
34
34
|
}
|
|
35
35
|
catch (e) {
|
|
36
|
-
Logger.
|
|
36
|
+
Logger.logError(BackendLoggerCategory.IModelDb, e);
|
|
37
37
|
}
|
|
38
38
|
if (!Array.isArray(faces) || faces.length === 0) {
|
|
39
39
|
continue;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IModelDbFontsImpl.js","sourceRoot":"","sources":["../../../src/internal/IModelDbFontsImpl.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;GAEG;AAEH,OAAO,EAA+D,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC3G,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,yBAAyB,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAG7F,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAG/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,MAAM,iBAAiB;IACL,C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AAC,CAAC,CAAC,CAAC;gBACpC,MAAM,QAAQ,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;gBACzC,MAAM,IAAI,GAAG,CAAC,QAAQ,KAAK,QAAQ,CAAC,GAAG,IAAI,QAAQ,KAAK,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;gBACrG,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBACpB,KAAK,CAAC,IAAI,CAAC;wBACT,IAAI;wBACJ,IAAI;wBACJ,EAAE,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC;qBAC5B,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAED,MAAM,UAAU,mBAAmB,CAAC,EAAY;IAC9C,OAAO,IAAI,iBAAiB,CAAC,EAAE,CAAC,CAAC;AACnC,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module iModels\r\n */\r\n\r\nimport { FontFamilyDescriptor, FontFamilySelector, FontId, FontProps, FontType } from \"@itwin/core-common\";\r\nimport { _faceProps, _getData, _implementationProhibited, _key, _nativeDb } from \"./Symbols\";\r\nimport { IModelDb } from \"../IModelDb\";\r\nimport { EmbedFontFileArgs, IModelDbFonts, QueryMappedFamiliesArgs } from \"../IModelDbFonts\";\r\nimport { EmbeddedFontFile } from \"./FontFileImpl\";\r\nimport { assert, DbResult, Logger } from \"@itwin/core-bentley\";\r\nimport type { IModelJsNative } from \"@bentley/imodeljs-native\";\r\nimport { FontFile } from \"../FontFile\";\r\nimport { BackendLoggerCategory } from \"../BackendLoggerCategory\";\r\n\r\nclass IModelDbFontsImpl implements IModelDbFonts {\r\n public readonly [_implementationProhibited] = undefined;\r\n readonly #db: IModelDb;\r\n\r\n public constructor(iModel: IModelDb) {\r\n this.#db = iModel;\r\n }\r\n\r\n public queryMappedFamilies(args?: QueryMappedFamiliesArgs): Iterable<FontProps> {\r\n const fontProps = this.#queryFontTable();\r\n if (args?.includeNonEmbedded) {\r\n return fontProps;\r\n }\r\n\r\n const fontNames = this.#getEmbeddedFontNames();\r\n return fontProps.filter((x) => fontNames.includes(x.name));\r\n }\r\n\r\n public queryEmbeddedFontFiles(): Iterable<FontFile> {\r\n const files: FontFile[] = [];\r\n this.#db.withSqliteStatement(`SELECT Id,StrData FROM be_Prop WHERE Namespace=\"dgn_Font\" AND Name=\"EmbeddedFaceData\"`, (stmt) => {\r\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\r\n let faces;\r\n try {\r\n faces = JSON.parse(stmt.getValueString(1)) as IModelJsNative.FontFaceProps[];\r\n } catch (e) {\r\n Logger.logException(BackendLoggerCategory.IModelDb, e);\r\n }\r\n\r\n if (!Array.isArray(faces) || faces.length === 0) {\r\n continue;\r\n }\r\n\r\n let type = faces[0].type;\r\n if (type !== FontType.Rsc && type !== FontType.Shx) {\r\n type = FontType.TrueType;\r\n }\r\n\r\n files.push(new EmbeddedFontFile(this.#db, stmt.getValueInteger(0), type, faces));\r\n }\r\n });\r\n\r\n return files;\r\n }\r\n\r\n public async embedFontFile(args: EmbedFontFileArgs): Promise<void> {\r\n this.#requireWritable();\r\n\r\n if (!args.file.isEmbeddable) {\r\n throw new Error(\"Font does not permit embedding\");\r\n }\r\n\r\n const file = args.file;\r\n for (const existing of this.queryEmbeddedFontFiles()) {\r\n if (existing[_key] === file[_key]) {\r\n // Already embedded - it's a no-op.\r\n return;\r\n }\r\n }\r\n\r\n let id = 0;\r\n const codes = this.#db.codeService?.internalCodes;\r\n if (codes) {\r\n id = await codes.writeLocker.reserveEmbeddedFaceDataId(args.file[_key]);\r\n } else {\r\n // CodeService not configured - schema lock required to prevent conflicting Ids in be_Prop table.\r\n await this.#db.acquireSchemaLock();\r\n const sql = `SELECT MAX(Id) FROM be_Prop WHERE Namespace=\"dgn_Font\" AND Name=\"EmbeddedFaceData\"`;\r\n id = this.#db.withSqliteStatement(sql, (stmt) => stmt.nextRow() ? stmt.getValueInteger(0) + 1 : 1);\r\n }\r\n\r\n assert(id > 0);\r\n const data = file[_getData]();\r\n this.#db[_nativeDb].embedFontFile(id, file[_faceProps], data, true);\r\n\r\n if (!args.skipFontIdAllocation) {\r\n const familyNames = new Set<string>(args.file.faces.map((x) => x.familyName));\r\n const acquireIds = Array.from(familyNames).map(async (x) => this.#acquireId({ name: x, type: args.file.type }, true).catch());\r\n await Promise.allSettled(acquireIds);\r\n }\r\n\r\n this.#db.clearFontMap();\r\n }\r\n\r\n public findId(selector: FontFamilySelector): FontId | undefined {\r\n let id;\r\n const sqlPostlude = undefined === selector.type ? \" ORDER BY Type ASC\" : \" AND Type=?\";\r\n const sql = `SELECT Id FROM dgn_Font WHERE Name=?${sqlPostlude}`;\r\n this.#db.withPreparedSqliteStatement(sql, (stmt) => {\r\n stmt.bindString(1, selector.name);\r\n if (undefined !== selector.type) {\r\n stmt.bindInteger(2, selector.type);\r\n }\r\n\r\n if (DbResult.BE_SQLITE_ROW === stmt.step()) {\r\n id = stmt.getValueInteger(0);\r\n }\r\n });\r\n\r\n return id;\r\n }\r\n\r\n public findDescriptor(id: FontId): FontFamilyDescriptor | undefined {\r\n let name, type;\r\n this.#db.withPreparedSqliteStatement(\"SELECT Name,Type FROM dgn_Font WHERE Id=?\", (stmt) => {\r\n stmt.bindInteger(1, id);\r\n if (DbResult.BE_SQLITE_ROW === stmt.step()) {\r\n const stmtName = stmt.getValueString(0);\r\n if (stmtName.length > 0) {\r\n name = stmtName;\r\n const typeCode = stmt.getValueInteger(1);\r\n type = (typeCode === FontType.Shx || typeCode === FontType.Rsc) ? typeCode : FontType.TrueType;\r\n }\r\n }\r\n });\r\n\r\n return undefined !== name && undefined !== type ? { name, type } : undefined;\r\n }\r\n\r\n public async acquireId(descriptor: FontFamilyDescriptor): Promise<FontId> {\r\n this.#requireWritable();\r\n return this.#acquireId(descriptor, false);\r\n }\r\n\r\n async #acquireId(descriptor: FontFamilyDescriptor, embeddingFaceData: boolean): Promise<FontId> {\r\n let id = this.findId(descriptor);\r\n if (undefined !== id) {\r\n return id;\r\n }\r\n\r\n const codes = this.#db.codeService?.internalCodes;\r\n if (codes) {\r\n id = await codes.writeLocker.reserveFontId({ fontName: descriptor.name, fontType: descriptor.type });\r\n } else {\r\n // If we're being called from `embedFontFile` then the schema lock is already held, don't bother re-acquiring it.\r\n if (!embeddingFaceData) {\r\n // No CodeService configured. We must obtain the schema lock and use the next available Id.\r\n await this.#db.acquireSchemaLock();\r\n }\r\n\r\n id = this.#db.withSqliteStatement(`SELECT MAX(Id) FROM dgn_Font`, (stmt) => stmt.nextRow() ? stmt.getValueInteger(0) + 1 : 1);\r\n }\r\n\r\n this.#db.withSqliteStatement(`INSERT INTO dgn_Font (Id,Type,Name) VALUES (?,?,?)`, (stmt) => {\r\n stmt.bindInteger(1, id);\r\n stmt.bindInteger(2, descriptor.type);\r\n stmt.bindString(3, descriptor.name);\r\n\r\n if (DbResult.BE_SQLITE_DONE !== stmt.step()) {\r\n throw new Error(\"Failed to insert font Id mapping\");\r\n }\r\n });\r\n\r\n this.#db.clearFontMap();\r\n\r\n return id;\r\n }\r\n\r\n #requireWritable(): void {\r\n if (this.#db.isReadonly) {\r\n throw new Error(\"iModel is read-only\");\r\n }\r\n }\r\n\r\n #getEmbeddedFontNames(): string[] {\r\n const names: string[] = [];\r\n\r\n const sql = `select DISTINCT json_extract(face.value, '$.familyName') from be_Prop, json_each(be_Prop.StrData) as face where namespace=\"dgn_Font\" and name=\"EmbeddedFaceData\"`;\r\n this.#db.withPreparedSqliteStatement(sql, (stmt) => {\r\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\r\n names.push(stmt.getValueString(0));\r\n }\r\n });\r\n\r\n return names;\r\n }\r\n\r\n #queryFontTable(): Array<FontProps> {\r\n const fonts: FontProps[] = [];\r\n const sql = `SELECT Id,Name,Type FROM dgn_Font`;\r\n this.#db.withPreparedSqliteStatement(sql, (stmt) => {\r\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\r\n const name = stmt.getValueString(1);\r\n const typeCode = stmt.getValueInteger(2);\r\n const type = (typeCode === FontType.Shx || typeCode === FontType.Rsc) ? typeCode : FontType.TrueType;\r\n if (name.length > 0) {\r\n fonts.push({\r\n name,\r\n type,\r\n id: stmt.getValueInteger(0),\r\n });\r\n }\r\n }\r\n });\r\n\r\n return fonts;\r\n }\r\n}\r\n\r\nexport function createIModelDbFonts(db: IModelDb): IModelDbFonts {\r\n return new IModelDbFontsImpl(db);\r\n}\r\n"]}
|
|
1
|
+
{"version":3,"file":"IModelDbFontsImpl.js","sourceRoot":"","sources":["../../../src/internal/IModelDbFontsImpl.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAC/F;;GAEG;AAEH,OAAO,EAA+D,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAC3G,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,yBAAyB,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAG7F,OAAO,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAG/D,OAAO,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,MAAM,iBAAiB;IACL,CAAC,yBAAyB,CAAC,GAAG,SAAS,CAAC;IAC/C,GAAG,CAAW;IAEvB,YAAmB,MAAgB;QACjC,IAAI,CAAC,GAAG,GAAG,MAAM,CAAC;IACpB,CAAC;IAEM,mBAAmB,CAAC,IAA8B;QACvD,MAAM,SAAS,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;QACzC,IAAI,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CAAC,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC;gBACrG,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBACpB,KAAK,CAAC,IAAI,CAAC;wBACT,IAAI;wBACJ,IAAI;wBACJ,EAAE,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC,CAAC;qBAC5B,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAED,MAAM,UAAU,mBAAmB,CAAC,EAAY;IAC9C,OAAO,IAAI,iBAAiB,CAAC,EAAE,CAAC,CAAC;AACnC,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n/** @packageDocumentation\r\n * @module iModels\r\n */\r\n\r\nimport { FontFamilyDescriptor, FontFamilySelector, FontId, FontProps, FontType } from \"@itwin/core-common\";\r\nimport { _faceProps, _getData, _implementationProhibited, _key, _nativeDb } from \"./Symbols\";\r\nimport { IModelDb } from \"../IModelDb\";\r\nimport { EmbedFontFileArgs, IModelDbFonts, QueryMappedFamiliesArgs } from \"../IModelDbFonts\";\r\nimport { EmbeddedFontFile } from \"./FontFileImpl\";\r\nimport { assert, DbResult, Logger } from \"@itwin/core-bentley\";\r\nimport type { IModelJsNative } from \"@bentley/imodeljs-native\";\r\nimport { FontFile } from \"../FontFile\";\r\nimport { BackendLoggerCategory } from \"../BackendLoggerCategory\";\r\n\r\nclass IModelDbFontsImpl implements IModelDbFonts {\r\n public readonly [_implementationProhibited] = undefined;\r\n readonly #db: IModelDb;\r\n\r\n public constructor(iModel: IModelDb) {\r\n this.#db = iModel;\r\n }\r\n\r\n public queryMappedFamilies(args?: QueryMappedFamiliesArgs): Iterable<FontProps> {\r\n const fontProps = this.#queryFontTable();\r\n if (args?.includeNonEmbedded) {\r\n return fontProps;\r\n }\r\n\r\n const fontNames = this.#getEmbeddedFontNames();\r\n return fontProps.filter((x) => fontNames.includes(x.name));\r\n }\r\n\r\n public queryEmbeddedFontFiles(): Iterable<FontFile> {\r\n const files: FontFile[] = [];\r\n this.#db.withSqliteStatement(`SELECT Id,StrData FROM be_Prop WHERE Namespace=\"dgn_Font\" AND Name=\"EmbeddedFaceData\"`, (stmt) => {\r\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\r\n let faces;\r\n try {\r\n faces = JSON.parse(stmt.getValueString(1)) as IModelJsNative.FontFaceProps[];\r\n } catch (e) {\r\n Logger.logError(BackendLoggerCategory.IModelDb, e);\r\n }\r\n\r\n if (!Array.isArray(faces) || faces.length === 0) {\r\n continue;\r\n }\r\n\r\n let type = faces[0].type;\r\n if (type !== FontType.Rsc && type !== FontType.Shx) {\r\n type = FontType.TrueType;\r\n }\r\n\r\n files.push(new EmbeddedFontFile(this.#db, stmt.getValueInteger(0), type, faces));\r\n }\r\n });\r\n\r\n return files;\r\n }\r\n\r\n public async embedFontFile(args: EmbedFontFileArgs): Promise<void> {\r\n this.#requireWritable();\r\n\r\n if (!args.file.isEmbeddable) {\r\n throw new Error(\"Font does not permit embedding\");\r\n }\r\n\r\n const file = args.file;\r\n for (const existing of this.queryEmbeddedFontFiles()) {\r\n if (existing[_key] === file[_key]) {\r\n // Already embedded - it's a no-op.\r\n return;\r\n }\r\n }\r\n\r\n let id = 0;\r\n const codes = this.#db.codeService?.internalCodes;\r\n if (codes) {\r\n id = await codes.writeLocker.reserveEmbeddedFaceDataId(args.file[_key]);\r\n } else {\r\n // CodeService not configured - schema lock required to prevent conflicting Ids in be_Prop table.\r\n await this.#db.acquireSchemaLock();\r\n const sql = `SELECT MAX(Id) FROM be_Prop WHERE Namespace=\"dgn_Font\" AND Name=\"EmbeddedFaceData\"`;\r\n id = this.#db.withSqliteStatement(sql, (stmt) => stmt.nextRow() ? stmt.getValueInteger(0) + 1 : 1);\r\n }\r\n\r\n assert(id > 0);\r\n const data = file[_getData]();\r\n this.#db[_nativeDb].embedFontFile(id, file[_faceProps], data, true);\r\n\r\n if (!args.skipFontIdAllocation) {\r\n const familyNames = new Set<string>(args.file.faces.map((x) => x.familyName));\r\n const acquireIds = Array.from(familyNames).map(async (x) => this.#acquireId({ name: x, type: args.file.type }, true).catch());\r\n await Promise.allSettled(acquireIds);\r\n }\r\n\r\n this.#db.clearFontMap();\r\n }\r\n\r\n public findId(selector: FontFamilySelector): FontId | undefined {\r\n let id;\r\n const sqlPostlude = undefined === selector.type ? \" ORDER BY Type ASC\" : \" AND Type=?\";\r\n const sql = `SELECT Id FROM dgn_Font WHERE Name=?${sqlPostlude}`;\r\n this.#db.withPreparedSqliteStatement(sql, (stmt) => {\r\n stmt.bindString(1, selector.name);\r\n if (undefined !== selector.type) {\r\n stmt.bindInteger(2, selector.type);\r\n }\r\n\r\n if (DbResult.BE_SQLITE_ROW === stmt.step()) {\r\n id = stmt.getValueInteger(0);\r\n }\r\n });\r\n\r\n return id;\r\n }\r\n\r\n public findDescriptor(id: FontId): FontFamilyDescriptor | undefined {\r\n let name, type;\r\n this.#db.withPreparedSqliteStatement(\"SELECT Name,Type FROM dgn_Font WHERE Id=?\", (stmt) => {\r\n stmt.bindInteger(1, id);\r\n if (DbResult.BE_SQLITE_ROW === stmt.step()) {\r\n const stmtName = stmt.getValueString(0);\r\n if (stmtName.length > 0) {\r\n name = stmtName;\r\n const typeCode = stmt.getValueInteger(1);\r\n type = (typeCode === FontType.Shx || typeCode === FontType.Rsc) ? typeCode : FontType.TrueType;\r\n }\r\n }\r\n });\r\n\r\n return undefined !== name && undefined !== type ? { name, type } : undefined;\r\n }\r\n\r\n public async acquireId(descriptor: FontFamilyDescriptor): Promise<FontId> {\r\n this.#requireWritable();\r\n return this.#acquireId(descriptor, false);\r\n }\r\n\r\n async #acquireId(descriptor: FontFamilyDescriptor, embeddingFaceData: boolean): Promise<FontId> {\r\n let id = this.findId(descriptor);\r\n if (undefined !== id) {\r\n return id;\r\n }\r\n\r\n const codes = this.#db.codeService?.internalCodes;\r\n if (codes) {\r\n id = await codes.writeLocker.reserveFontId({ fontName: descriptor.name, fontType: descriptor.type });\r\n } else {\r\n // If we're being called from `embedFontFile` then the schema lock is already held, don't bother re-acquiring it.\r\n if (!embeddingFaceData) {\r\n // No CodeService configured. We must obtain the schema lock and use the next available Id.\r\n await this.#db.acquireSchemaLock();\r\n }\r\n\r\n id = this.#db.withSqliteStatement(`SELECT MAX(Id) FROM dgn_Font`, (stmt) => stmt.nextRow() ? stmt.getValueInteger(0) + 1 : 1);\r\n }\r\n\r\n this.#db.withSqliteStatement(`INSERT INTO dgn_Font (Id,Type,Name) VALUES (?,?,?)`, (stmt) => {\r\n stmt.bindInteger(1, id);\r\n stmt.bindInteger(2, descriptor.type);\r\n stmt.bindString(3, descriptor.name);\r\n\r\n if (DbResult.BE_SQLITE_DONE !== stmt.step()) {\r\n throw new Error(\"Failed to insert font Id mapping\");\r\n }\r\n });\r\n\r\n this.#db.clearFontMap();\r\n\r\n return id;\r\n }\r\n\r\n #requireWritable(): void {\r\n if (this.#db.isReadonly) {\r\n throw new Error(\"iModel is read-only\");\r\n }\r\n }\r\n\r\n #getEmbeddedFontNames(): string[] {\r\n const names: string[] = [];\r\n\r\n const sql = `select DISTINCT json_extract(face.value, '$.familyName') from be_Prop, json_each(be_Prop.StrData) as face where namespace=\"dgn_Font\" and name=\"EmbeddedFaceData\"`;\r\n this.#db.withPreparedSqliteStatement(sql, (stmt) => {\r\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\r\n names.push(stmt.getValueString(0));\r\n }\r\n });\r\n\r\n return names;\r\n }\r\n\r\n #queryFontTable(): Array<FontProps> {\r\n const fonts: FontProps[] = [];\r\n const sql = `SELECT Id,Name,Type FROM dgn_Font`;\r\n this.#db.withPreparedSqliteStatement(sql, (stmt) => {\r\n while (DbResult.BE_SQLITE_ROW === stmt.step()) {\r\n const name = stmt.getValueString(1);\r\n const typeCode = stmt.getValueInteger(2);\r\n const type = (typeCode === FontType.Shx || typeCode === FontType.Rsc) ? typeCode : FontType.TrueType;\r\n if (name.length > 0) {\r\n fonts.push({\r\n name,\r\n type,\r\n id: stmt.getValueInteger(0),\r\n });\r\n }\r\n }\r\n });\r\n\r\n return fonts;\r\n }\r\n}\r\n\r\nexport function createIModelDbFonts(db: IModelDb): IModelDbFonts {\r\n return new IModelDbFontsImpl(db);\r\n}\r\n"]}
|
|
@@ -181,7 +181,7 @@ export async function performSpecificIntegrityCheck(iModel, check) {
|
|
|
181
181
|
return results;
|
|
182
182
|
}
|
|
183
183
|
default:
|
|
184
|
-
throw new IModelError(IModelStatus.BadRequest, `Unknown integrity check type
|
|
184
|
+
throw new IModelError(IModelStatus.BadRequest, `Unknown integrity check type`);
|
|
185
185
|
}
|
|
186
186
|
}
|
|
187
187
|
//# sourceMappingURL=IntegrityCheck.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IntegrityCheck.js","sourceRoot":"","sources":["../../../src/internal/IntegrityCheck.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAE/F,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAGjD;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,gBAAgB,EAAE;QAChB,IAAI,EAAE,oBAAoB;QAC1B,UAAU,EAAE,2BAA2B;QACvC,UAAU,EAAE,oBAAoB;QAChC,QAAQ,EAAE,iFAAiF;KAC5F;IACD,cAAc,EAAE;QACd,IAAI,EAAE,kBAAkB;QACxB,UAAU,EAAE,yBAAyB;QACrC,UAAU,EAAE,kBAAkB;QAC9B,QAAQ,EAAE,+EAA+E;KAC1F;IACD,uBAAuB,EAAE;QACvB,IAAI,EAAE,4BAA4B;QAClC,UAAU,EAAE,2BAA2B;QACvC,UAAU,EAAE,qBAAqB;QACjC,QAAQ,EAAE,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;QACD,KAAK,uBAAuB,CAAC,CAAC,CAAC;YAC7B,MAAM,OAAO,GAAqC,EAAE,CAAC;YACrD,IAAI,KAAK,EAAE,MAAM,GAAG,IAAI,MAAM,CAAC,iBAAiB,CAAC,qBAAqB,CAAC,qBAAqB,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACvG,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,OAAO,EAAE,GAAG,CAAC,QAAQ,EAAE,kBAAkB,EAAE,GAAG,CAAC,kBAAkB,EAAE,CAAC,CAAC;YAClI,CAAC;YACD,OAAO,OAAO,CAAC;QACjB,CAAC;QACD;YACE,MAAM,IAAI,WAAW,CAAC,YAAY,CAAC,UAAU,EAAE,iCAAiC,KAAK,EAAE,CAAC,CAAC;IAC7F,CAAC;AACH,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\nimport { IModelStatus } from \"@itwin/core-bentley\";\r\nimport { IModelError } from \"@itwin/core-common\";\r\nimport { IModelDb } from \"../IModelDb\";\r\n\r\n/**\r\n * Information about each integrity check type, including the name, expected result type, and SQL query to execute\r\n * @internal\r\n */\r\nexport const integrityCheckTypeMap = {\r\n checkDataColumns: {\r\n name: \"Check Data Columns\",\r\n resultType: \"CheckDataColumnsResultRow\",\r\n sqlCommand: \"check_data_columns\",\r\n sqlQuery: `PRAGMA integrity_check(check_data_columns) options enable_experimental_features`,\r\n },\r\n checkECProfile: {\r\n name: \"Check EC Profile\",\r\n resultType: \"CheckECProfileResultRow\",\r\n sqlCommand: \"check_ec_profile\",\r\n sqlQuery: `PRAGMA integrity_check(check_ec_profile) options enable_experimental_features`,\r\n },\r\n checkNavigationClassIds: {\r\n name: \"Check Navigation Class Ids\",\r\n resultType: \"CheckNavClassIdsResultRow\",\r\n sqlCommand: \"check_nav_class_ids\",\r\n sqlQuery: `PRAGMA integrity_check(check_nav_class_ids) options enable_experimental_features`,\r\n },\r\n checkNavigationIds: {\r\n name: \"Check Navigation Ids\",\r\n resultType: \"CheckNavIdsResultRow\",\r\n sqlCommand: \"check_nav_ids\",\r\n sqlQuery: `PRAGMA integrity_check(check_nav_ids) options enable_experimental_features`,\r\n },\r\n checkLinktableForeignKeyClassIds: {\r\n name: \"Check Link Table Foreign Key Class Ids\",\r\n resultType: \"CheckLinkTableFkClassIdsResultRow\",\r\n sqlCommand: \"check_linktable_fk_class_ids\",\r\n sqlQuery: `PRAGMA integrity_check(check_linktable_fk_class_ids) options enable_experimental_features`,\r\n },\r\n checkLinktableForeignKeyIds: {\r\n name: \"Check Link Table Foreign Key Ids\",\r\n resultType: \"CheckLinkTableFkIdsResultRow\",\r\n sqlCommand: \"check_linktable_fk_ids\",\r\n sqlQuery: `PRAGMA integrity_check(check_linktable_fk_ids) options enable_experimental_features`,\r\n },\r\n checkClassIds: {\r\n name: \"Check Class Ids\",\r\n resultType: \"CheckClassIdsResultRow\",\r\n sqlCommand: \"check_class_ids\",\r\n sqlQuery: `PRAGMA integrity_check(check_class_ids) options enable_experimental_features`,\r\n },\r\n checkDataSchema: {\r\n name: \"Check Data Schema\",\r\n resultType: \"CheckDataSchemaResultRow\",\r\n sqlCommand: \"check_data_schema\",\r\n sqlQuery: `PRAGMA integrity_check(check_data_schema) options enable_experimental_features`,\r\n },\r\n checkSchemaLoad: {\r\n name: \"Check Schema Load\",\r\n resultType: \"CheckSchemaLoadResultRow\",\r\n sqlCommand: \"check_schema_load\",\r\n sqlQuery: `PRAGMA integrity_check(check_schema_load) options enable_experimental_features`,\r\n },\r\n checkMissingChildRows: {\r\n name: \"Check Missing Child Rows\",\r\n resultType: \"CheckMissingChildRowsResultRow\",\r\n sqlCommand: \"check_missing_child_rows\",\r\n sqlQuery: `PRAGMA integrity_check(check_missing_child_rows) options enable_experimental_features`,\r\n },\r\n} as const;\r\n\r\n/**\r\n * Type representing the keys of the integrityCheckType map, which correspond to the different types of integrity checks that can be performed.\r\n */\r\nexport type IntegrityCheckKey = keyof typeof integrityCheckTypeMap;\r\n\r\n/** Map of integrity check keys to their result row types */\r\ninterface IntegrityCheckResultTypeMap {\r\n checkDataColumns: CheckDataColumnsResultRow;\r\n checkECProfile: CheckECProfileResultRow;\r\n checkNavigationClassIds: CheckNavClassIdsResultRow;\r\n checkNavigationIds: CheckNavIdsResultRow;\r\n checkLinktableForeignKeyClassIds: CheckLinkTableFkClassIdsResultRow;\r\n checkLinktableForeignKeyIds: CheckLinkTableFkIdsResultRow;\r\n checkClassIds: CheckClassIdsResultRow;\r\n checkDataSchema: CheckDataSchemaResultRow;\r\n checkSchemaLoad: CheckSchemaLoadResultRow;\r\n checkMissingChildRows: CheckMissingChildRowsResultRow;\r\n}\r\n\r\n/** Checks the Map to give the return type of a specific integrity check */\r\ntype IntegrityCheckResultRow<K extends IntegrityCheckKey> = IntegrityCheckResultTypeMap[K];\r\n\r\n/**\r\n * Return type for quick integrity check\r\n */\r\nexport interface QuickIntegrityCheckResultRow {\r\n check: string;\r\n passed: boolean;\r\n elapsedSeconds: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Data Columns integrity check\r\n */\r\nexport interface CheckDataColumnsResultRow {\r\n sno: number;\r\n table: string;\r\n column: string;\r\n}\r\n\r\n/**\r\n * Return type for Check EC Profile integrity check\r\n */\r\nexport interface CheckECProfileResultRow {\r\n sno: number;\r\n type: string;\r\n name: string;\r\n issue: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Navigation Class Ids integrity check\r\n */\r\nexport interface CheckNavClassIdsResultRow {\r\n sno: number;\r\n id: string;\r\n class: string;\r\n property: string;\r\n navId: string;\r\n navClassId: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Navigation Ids integrity check\r\n */\r\nexport interface CheckNavIdsResultRow {\r\n sno: number;\r\n id: string;\r\n class: string;\r\n property: string;\r\n navId: string;\r\n primaryClass: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Link Table Foreign Key Class Ids integrity check\r\n */\r\nexport interface CheckLinkTableFkClassIdsResultRow {\r\n sno: number;\r\n id: string;\r\n relationship: string;\r\n property: string;\r\n keyId: string;\r\n keyClassId: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Link Table Foreign Key Ids integrity check\r\n */\r\nexport interface CheckLinkTableFkIdsResultRow {\r\n sno: number;\r\n id: string;\r\n relationship: string;\r\n property: string;\r\n keyId: string;\r\n primaryClass: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Class Ids integrity check\r\n */\r\nexport interface CheckClassIdsResultRow {\r\n sno: number;\r\n class: string;\r\n id: string;\r\n classId: string;\r\n type: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Data Schema integrity check\r\n */\r\nexport interface CheckDataSchemaResultRow {\r\n sno: number;\r\n type: string;\r\n name: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Schema Load integrity check\r\n */\r\nexport interface CheckSchemaLoadResultRow {\r\n sno: number;\r\n schema: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Missing Child Rows integrity check\r\n */\r\nexport interface CheckMissingChildRowsResultRow {\r\n sno: number;\r\n class: string;\r\n id: string;\r\n classId: string;\r\n missingRowInTables: string;\r\n}\r\n\r\n/**\r\n * Return type for integrity check results, including the check name, whether it passed, and the specific results (if any)\r\n */\r\nexport interface IntegrityCheckResult {\r\n /** The name of the integrity check that was performed */\r\n check: string;\r\n /** Whether the integrity check passed (i.e. no issues were found = true) */\r\n passed: boolean;\r\n /** The specific results returned by the integrity check, which may include details about any issues that were found.\r\n * In the case where issues are found, this will be an array of result rows specific to the type of check that was performed,\r\n * or an array of quick integrity check results if it was a quick check. */\r\n results: IntegrityCheckResultRow<IntegrityCheckKey>[] | QuickIntegrityCheckResultRow[];\r\n}\r\n\r\n/**\r\n * Gets the user-friendly name of an integrity check based on its key or SQL command.\r\n * It first attempts to find a direct match for the key in the integrityCheckTypeMap. If not found, it searches for a match based on the SQL command.\r\n * If still not found, it returns the original check string.\r\n * @param check - The integrity check key or SQL command to get the name of\r\n * @returns The user-friendly name of the integrity check, or the original check string if no match is found\r\n * @internal\r\n */\r\nexport function getIntegrityCheckName(check: string): string {\r\n // First try direct lookup by key\r\n const directLookup = integrityCheckTypeMap[check as IntegrityCheckKey];\r\n if (directLookup) {\r\n return directLookup.name;\r\n }\r\n // If not found, search by sqlCommand\r\n for (const [, value] of Object.entries(integrityCheckTypeMap)) {\r\n if (value.sqlCommand === check) {\r\n return value.name;\r\n }\r\n }\r\n // Fallback to the original check string\r\n return check;\r\n}\r\n\r\n/**\r\n * Performs a quick integrity check on the given iModel.\r\n * @param iModel The IModelDb instance to perform the integrity check on\r\n * @returns An array of results for each check performed, including the check name, whether it passed, and the elapsed time in seconds\r\n * @internal\r\n */\r\nexport async function performQuickIntegrityCheck(iModel: IModelDb): Promise<QuickIntegrityCheckResultRow[]> {\r\n const integrityCheckQuery = \"PRAGMA integrity_check options enable_experimental_features\";\r\n const integrityCheckResults: QuickIntegrityCheckResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckQuery)) {\r\n integrityCheckResults.push({ check: getIntegrityCheckName(row.check), passed: row.result, elapsedSeconds: row.elapsed_sec});\r\n };\r\n return integrityCheckResults;\r\n}\r\n\r\n/**\r\n * Performs a specific integrity check on the given iModel based on the provided check key, and returns the results specific to that check type.\r\n * @param iModel The IModelDb instance to perform the integrity check on\r\n * @param check The key of the specific integrity check to perform\r\n * @return An array of results specific to the integrity check that was performed. The type of the result rows will depend on the check that was executed.\r\n * @throws IModelError with status BadRequest if an unknown integrity check key is provided\r\n * @internal\r\n */\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkDataColumns\"): Promise<IntegrityCheckResultRow<\"checkDataColumns\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkECProfile\"): Promise<IntegrityCheckResultRow<\"checkECProfile\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkNavigationClassIds\"): Promise<IntegrityCheckResultRow<\"checkNavigationClassIds\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkNavigationIds\"): Promise<IntegrityCheckResultRow<\"checkNavigationIds\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkLinktableForeignKeyClassIds\"): Promise<IntegrityCheckResultRow<\"checkLinktableForeignKeyClassIds\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkLinktableForeignKeyIds\"): Promise<IntegrityCheckResultRow<\"checkLinktableForeignKeyIds\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkClassIds\"): Promise<IntegrityCheckResultRow<\"checkClassIds\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkDataSchema\"): Promise<IntegrityCheckResultRow<\"checkDataSchema\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkSchemaLoad\"): Promise<IntegrityCheckResultRow<\"checkSchemaLoad\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkMissingChildRows\"): Promise<IntegrityCheckResultRow<\"checkMissingChildRows\">[]>;\r\nexport async function performSpecificIntegrityCheck<K extends IntegrityCheckKey>(iModel: IModelDb, check: K): Promise<IntegrityCheckResultRow<K>[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: IntegrityCheckKey): Promise<IntegrityCheckResultRow<IntegrityCheckKey>[]> {\r\n switch (check) {\r\n case \"checkDataColumns\": {\r\n const results: CheckDataColumnsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkDataColumns.sqlQuery)) {\r\n results.push({ sno: row.sno, table: row.table, column: row.column });\r\n }\r\n return results;\r\n }\r\n case \"checkECProfile\": {\r\n const results: CheckECProfileResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkECProfile.sqlQuery)) {\r\n results.push({ sno: row.sno, type: row.type, name: row.name, issue: row.issue });\r\n }\r\n return results;\r\n }\r\n case \"checkNavigationClassIds\": {\r\n const results: CheckNavClassIdsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkNavigationClassIds.sqlQuery)) {\r\n results.push({ sno: row.sno, id: row.id, class: row.class, property: row.property, navId: row.nav_id, navClassId: row.nav_classId });\r\n }\r\n return results;\r\n }\r\n case \"checkNavigationIds\": {\r\n const results: CheckNavIdsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkNavigationIds.sqlQuery)) {\r\n results.push({ sno: row.sno, id: row.id, class: row.class, property: row.property, navId: row.nav_id, primaryClass: row.primary_class });\r\n }\r\n return results;\r\n }\r\n case \"checkLinktableForeignKeyClassIds\": {\r\n const results: CheckLinkTableFkClassIdsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkLinktableForeignKeyClassIds.sqlQuery)) {\r\n results.push({ sno: row.sno, id: row.id, relationship: row.relationship, property: row.property, keyId: row.key_id, keyClassId: row.key_classId });\r\n }\r\n return results;\r\n }\r\n case \"checkLinktableForeignKeyIds\": {\r\n const results: CheckLinkTableFkIdsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkLinktableForeignKeyIds.sqlQuery)) {\r\n results.push({ sno: row.sno, id: row.id, relationship: row.relationship, property: row.property, keyId: row.key_id, primaryClass: row.primary_class });\r\n }\r\n return results;\r\n }\r\n case \"checkClassIds\": {\r\n const results: CheckClassIdsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkClassIds.sqlQuery)) {\r\n results.push({ sno: row.sno, class: row.class, id: row.id, classId: row.class_id, type: row.type });\r\n }\r\n return results;\r\n }\r\n case \"checkDataSchema\": {\r\n const results: CheckDataSchemaResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkDataSchema.sqlQuery)) {\r\n results.push({ sno: row.sno, type: row.type, name: row.name });\r\n }\r\n return results;\r\n }\r\n case \"checkSchemaLoad\": {\r\n const results: CheckSchemaLoadResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkSchemaLoad.sqlQuery)) {\r\n results.push({ sno: row.sno, schema: row.schema });\r\n }\r\n return results;\r\n }\r\n case \"checkMissingChildRows\": {\r\n const results: CheckMissingChildRowsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkMissingChildRows.sqlQuery)) {\r\n results.push({ sno: row.sno, class: row.class, id: row.id, classId: row.class_id, missingRowInTables: row.MissingRowInTables });\r\n }\r\n return results;\r\n }\r\n default:\r\n throw new IModelError(IModelStatus.BadRequest, `Unknown integrity check type: ${check}`);\r\n }\r\n}"]}
|
|
1
|
+
{"version":3,"file":"IntegrityCheck.js","sourceRoot":"","sources":["../../../src/internal/IntegrityCheck.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAE/F,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAGjD;;;GAGG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,gBAAgB,EAAE;QAChB,IAAI,EAAE,oBAAoB;QAC1B,UAAU,EAAE,2BAA2B;QACvC,UAAU,EAAE,oBAAoB;QAChC,QAAQ,EAAE,iFAAiF;KAC5F;IACD,cAAc,EAAE;QACd,IAAI,EAAE,kBAAkB;QACxB,UAAU,EAAE,yBAAyB;QACrC,UAAU,EAAE,kBAAkB;QAC9B,QAAQ,EAAE,+EAA+E;KAC1F;IACD,uBAAuB,EAAE;QACvB,IAAI,EAAE,4BAA4B;QAClC,UAAU,EAAE,2BAA2B;QACvC,UAAU,EAAE,qBAAqB;QACjC,QAAQ,EAA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AC;QACD,KAAK,uBAAuB,CAAC,CAAC,CAAC;YAC7B,MAAM,OAAO,GAAqC,EAAE,CAAC;YACrD,IAAI,KAAK,EAAE,MAAM,GAAG,IAAI,MAAM,CAAC,iBAAiB,CAAC,qBAAqB,CAAC,qBAAqB,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACvG,OAAO,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,CAAC,KAAK,EAAE,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,OAAO,EAAE,GAAG,CAAC,QAAQ,EAAE,kBAAkB,EAAE,GAAG,CAAC,kBAAkB,EAAE,CAAC,CAAC;YAClI,CAAC;YACD,OAAO,OAAO,CAAC;QACjB,CAAC;QACD;YACE,MAAM,IAAI,WAAW,CAAC,YAAY,CAAC,UAAU,EAAE,8BAA8B,CAAC,CAAC;IACnF,CAAC;AACH,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\nimport { IModelStatus } from \"@itwin/core-bentley\";\r\nimport { IModelError } from \"@itwin/core-common\";\r\nimport { IModelDb } from \"../IModelDb\";\r\n\r\n/**\r\n * Information about each integrity check type, including the name, expected result type, and SQL query to execute\r\n * @internal\r\n */\r\nexport const integrityCheckTypeMap = {\r\n checkDataColumns: {\r\n name: \"Check Data Columns\",\r\n resultType: \"CheckDataColumnsResultRow\",\r\n sqlCommand: \"check_data_columns\",\r\n sqlQuery: `PRAGMA integrity_check(check_data_columns) options enable_experimental_features`,\r\n },\r\n checkECProfile: {\r\n name: \"Check EC Profile\",\r\n resultType: \"CheckECProfileResultRow\",\r\n sqlCommand: \"check_ec_profile\",\r\n sqlQuery: `PRAGMA integrity_check(check_ec_profile) options enable_experimental_features`,\r\n },\r\n checkNavigationClassIds: {\r\n name: \"Check Navigation Class Ids\",\r\n resultType: \"CheckNavClassIdsResultRow\",\r\n sqlCommand: \"check_nav_class_ids\",\r\n sqlQuery: `PRAGMA integrity_check(check_nav_class_ids) options enable_experimental_features`,\r\n },\r\n checkNavigationIds: {\r\n name: \"Check Navigation Ids\",\r\n resultType: \"CheckNavIdsResultRow\",\r\n sqlCommand: \"check_nav_ids\",\r\n sqlQuery: `PRAGMA integrity_check(check_nav_ids) options enable_experimental_features`,\r\n },\r\n checkLinktableForeignKeyClassIds: {\r\n name: \"Check Link Table Foreign Key Class Ids\",\r\n resultType: \"CheckLinkTableFkClassIdsResultRow\",\r\n sqlCommand: \"check_linktable_fk_class_ids\",\r\n sqlQuery: `PRAGMA integrity_check(check_linktable_fk_class_ids) options enable_experimental_features`,\r\n },\r\n checkLinktableForeignKeyIds: {\r\n name: \"Check Link Table Foreign Key Ids\",\r\n resultType: \"CheckLinkTableFkIdsResultRow\",\r\n sqlCommand: \"check_linktable_fk_ids\",\r\n sqlQuery: `PRAGMA integrity_check(check_linktable_fk_ids) options enable_experimental_features`,\r\n },\r\n checkClassIds: {\r\n name: \"Check Class Ids\",\r\n resultType: \"CheckClassIdsResultRow\",\r\n sqlCommand: \"check_class_ids\",\r\n sqlQuery: `PRAGMA integrity_check(check_class_ids) options enable_experimental_features`,\r\n },\r\n checkDataSchema: {\r\n name: \"Check Data Schema\",\r\n resultType: \"CheckDataSchemaResultRow\",\r\n sqlCommand: \"check_data_schema\",\r\n sqlQuery: `PRAGMA integrity_check(check_data_schema) options enable_experimental_features`,\r\n },\r\n checkSchemaLoad: {\r\n name: \"Check Schema Load\",\r\n resultType: \"CheckSchemaLoadResultRow\",\r\n sqlCommand: \"check_schema_load\",\r\n sqlQuery: `PRAGMA integrity_check(check_schema_load) options enable_experimental_features`,\r\n },\r\n checkMissingChildRows: {\r\n name: \"Check Missing Child Rows\",\r\n resultType: \"CheckMissingChildRowsResultRow\",\r\n sqlCommand: \"check_missing_child_rows\",\r\n sqlQuery: `PRAGMA integrity_check(check_missing_child_rows) options enable_experimental_features`,\r\n },\r\n} as const;\r\n\r\n/**\r\n * Type representing the keys of the integrityCheckType map, which correspond to the different types of integrity checks that can be performed.\r\n */\r\nexport type IntegrityCheckKey = keyof typeof integrityCheckTypeMap;\r\n\r\n/** Map of integrity check keys to their result row types */\r\ninterface IntegrityCheckResultTypeMap {\r\n checkDataColumns: CheckDataColumnsResultRow;\r\n checkECProfile: CheckECProfileResultRow;\r\n checkNavigationClassIds: CheckNavClassIdsResultRow;\r\n checkNavigationIds: CheckNavIdsResultRow;\r\n checkLinktableForeignKeyClassIds: CheckLinkTableFkClassIdsResultRow;\r\n checkLinktableForeignKeyIds: CheckLinkTableFkIdsResultRow;\r\n checkClassIds: CheckClassIdsResultRow;\r\n checkDataSchema: CheckDataSchemaResultRow;\r\n checkSchemaLoad: CheckSchemaLoadResultRow;\r\n checkMissingChildRows: CheckMissingChildRowsResultRow;\r\n}\r\n\r\n/** Checks the Map to give the return type of a specific integrity check */\r\ntype IntegrityCheckResultRow<K extends IntegrityCheckKey> = IntegrityCheckResultTypeMap[K];\r\n\r\n/**\r\n * Return type for quick integrity check\r\n */\r\nexport interface QuickIntegrityCheckResultRow {\r\n check: string;\r\n passed: boolean;\r\n elapsedSeconds: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Data Columns integrity check\r\n */\r\nexport interface CheckDataColumnsResultRow {\r\n sno: number;\r\n table: string;\r\n column: string;\r\n}\r\n\r\n/**\r\n * Return type for Check EC Profile integrity check\r\n */\r\nexport interface CheckECProfileResultRow {\r\n sno: number;\r\n type: string;\r\n name: string;\r\n issue: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Navigation Class Ids integrity check\r\n */\r\nexport interface CheckNavClassIdsResultRow {\r\n sno: number;\r\n id: string;\r\n class: string;\r\n property: string;\r\n navId: string;\r\n navClassId: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Navigation Ids integrity check\r\n */\r\nexport interface CheckNavIdsResultRow {\r\n sno: number;\r\n id: string;\r\n class: string;\r\n property: string;\r\n navId: string;\r\n primaryClass: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Link Table Foreign Key Class Ids integrity check\r\n */\r\nexport interface CheckLinkTableFkClassIdsResultRow {\r\n sno: number;\r\n id: string;\r\n relationship: string;\r\n property: string;\r\n keyId: string;\r\n keyClassId: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Link Table Foreign Key Ids integrity check\r\n */\r\nexport interface CheckLinkTableFkIdsResultRow {\r\n sno: number;\r\n id: string;\r\n relationship: string;\r\n property: string;\r\n keyId: string;\r\n primaryClass: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Class Ids integrity check\r\n */\r\nexport interface CheckClassIdsResultRow {\r\n sno: number;\r\n class: string;\r\n id: string;\r\n classId: string;\r\n type: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Data Schema integrity check\r\n */\r\nexport interface CheckDataSchemaResultRow {\r\n sno: number;\r\n type: string;\r\n name: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Schema Load integrity check\r\n */\r\nexport interface CheckSchemaLoadResultRow {\r\n sno: number;\r\n schema: string;\r\n}\r\n\r\n/**\r\n * Return type for Check Missing Child Rows integrity check\r\n */\r\nexport interface CheckMissingChildRowsResultRow {\r\n sno: number;\r\n class: string;\r\n id: string;\r\n classId: string;\r\n missingRowInTables: string;\r\n}\r\n\r\n/**\r\n * Return type for integrity check results, including the check name, whether it passed, and the specific results (if any)\r\n */\r\nexport interface IntegrityCheckResult {\r\n /** The name of the integrity check that was performed */\r\n check: string;\r\n /** Whether the integrity check passed (i.e. no issues were found = true) */\r\n passed: boolean;\r\n /** The specific results returned by the integrity check, which may include details about any issues that were found.\r\n * In the case where issues are found, this will be an array of result rows specific to the type of check that was performed,\r\n * or an array of quick integrity check results if it was a quick check. */\r\n results: IntegrityCheckResultRow<IntegrityCheckKey>[] | QuickIntegrityCheckResultRow[];\r\n}\r\n\r\n/**\r\n * Gets the user-friendly name of an integrity check based on its key or SQL command.\r\n * It first attempts to find a direct match for the key in the integrityCheckTypeMap. If not found, it searches for a match based on the SQL command.\r\n * If still not found, it returns the original check string.\r\n * @param check - The integrity check key or SQL command to get the name of\r\n * @returns The user-friendly name of the integrity check, or the original check string if no match is found\r\n * @internal\r\n */\r\nexport function getIntegrityCheckName(check: string): string {\r\n // First try direct lookup by key\r\n const directLookup = integrityCheckTypeMap[check as IntegrityCheckKey];\r\n if (directLookup) {\r\n return directLookup.name;\r\n }\r\n // If not found, search by sqlCommand\r\n for (const [, value] of Object.entries(integrityCheckTypeMap)) {\r\n if (value.sqlCommand === check) {\r\n return value.name;\r\n }\r\n }\r\n // Fallback to the original check string\r\n return check;\r\n}\r\n\r\n/**\r\n * Performs a quick integrity check on the given iModel.\r\n * @param iModel The IModelDb instance to perform the integrity check on\r\n * @returns An array of results for each check performed, including the check name, whether it passed, and the elapsed time in seconds\r\n * @internal\r\n */\r\nexport async function performQuickIntegrityCheck(iModel: IModelDb): Promise<QuickIntegrityCheckResultRow[]> {\r\n const integrityCheckQuery = \"PRAGMA integrity_check options enable_experimental_features\";\r\n const integrityCheckResults: QuickIntegrityCheckResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckQuery)) {\r\n integrityCheckResults.push({ check: getIntegrityCheckName(row.check), passed: row.result, elapsedSeconds: row.elapsed_sec});\r\n };\r\n return integrityCheckResults;\r\n}\r\n\r\n/**\r\n * Performs a specific integrity check on the given iModel based on the provided check key, and returns the results specific to that check type.\r\n * @param iModel The IModelDb instance to perform the integrity check on\r\n * @param check The key of the specific integrity check to perform\r\n * @return An array of results specific to the integrity check that was performed. The type of the result rows will depend on the check that was executed.\r\n * @throws IModelError with status BadRequest if an unknown integrity check key is provided\r\n * @internal\r\n */\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkDataColumns\"): Promise<IntegrityCheckResultRow<\"checkDataColumns\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkECProfile\"): Promise<IntegrityCheckResultRow<\"checkECProfile\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkNavigationClassIds\"): Promise<IntegrityCheckResultRow<\"checkNavigationClassIds\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkNavigationIds\"): Promise<IntegrityCheckResultRow<\"checkNavigationIds\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkLinktableForeignKeyClassIds\"): Promise<IntegrityCheckResultRow<\"checkLinktableForeignKeyClassIds\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkLinktableForeignKeyIds\"): Promise<IntegrityCheckResultRow<\"checkLinktableForeignKeyIds\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkClassIds\"): Promise<IntegrityCheckResultRow<\"checkClassIds\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkDataSchema\"): Promise<IntegrityCheckResultRow<\"checkDataSchema\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkSchemaLoad\"): Promise<IntegrityCheckResultRow<\"checkSchemaLoad\">[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: \"checkMissingChildRows\"): Promise<IntegrityCheckResultRow<\"checkMissingChildRows\">[]>;\r\nexport async function performSpecificIntegrityCheck<K extends IntegrityCheckKey>(iModel: IModelDb, check: K): Promise<IntegrityCheckResultRow<K>[]>;\r\nexport async function performSpecificIntegrityCheck(iModel: IModelDb, check: IntegrityCheckKey): Promise<IntegrityCheckResultRow<IntegrityCheckKey>[]> {\r\n switch (check) {\r\n case \"checkDataColumns\": {\r\n const results: CheckDataColumnsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkDataColumns.sqlQuery)) {\r\n results.push({ sno: row.sno, table: row.table, column: row.column });\r\n }\r\n return results;\r\n }\r\n case \"checkECProfile\": {\r\n const results: CheckECProfileResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkECProfile.sqlQuery)) {\r\n results.push({ sno: row.sno, type: row.type, name: row.name, issue: row.issue });\r\n }\r\n return results;\r\n }\r\n case \"checkNavigationClassIds\": {\r\n const results: CheckNavClassIdsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkNavigationClassIds.sqlQuery)) {\r\n results.push({ sno: row.sno, id: row.id, class: row.class, property: row.property, navId: row.nav_id, navClassId: row.nav_classId });\r\n }\r\n return results;\r\n }\r\n case \"checkNavigationIds\": {\r\n const results: CheckNavIdsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkNavigationIds.sqlQuery)) {\r\n results.push({ sno: row.sno, id: row.id, class: row.class, property: row.property, navId: row.nav_id, primaryClass: row.primary_class });\r\n }\r\n return results;\r\n }\r\n case \"checkLinktableForeignKeyClassIds\": {\r\n const results: CheckLinkTableFkClassIdsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkLinktableForeignKeyClassIds.sqlQuery)) {\r\n results.push({ sno: row.sno, id: row.id, relationship: row.relationship, property: row.property, keyId: row.key_id, keyClassId: row.key_classId });\r\n }\r\n return results;\r\n }\r\n case \"checkLinktableForeignKeyIds\": {\r\n const results: CheckLinkTableFkIdsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkLinktableForeignKeyIds.sqlQuery)) {\r\n results.push({ sno: row.sno, id: row.id, relationship: row.relationship, property: row.property, keyId: row.key_id, primaryClass: row.primary_class });\r\n }\r\n return results;\r\n }\r\n case \"checkClassIds\": {\r\n const results: CheckClassIdsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkClassIds.sqlQuery)) {\r\n results.push({ sno: row.sno, class: row.class, id: row.id, classId: row.class_id, type: row.type });\r\n }\r\n return results;\r\n }\r\n case \"checkDataSchema\": {\r\n const results: CheckDataSchemaResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkDataSchema.sqlQuery)) {\r\n results.push({ sno: row.sno, type: row.type, name: row.name });\r\n }\r\n return results;\r\n }\r\n case \"checkSchemaLoad\": {\r\n const results: CheckSchemaLoadResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkSchemaLoad.sqlQuery)) {\r\n results.push({ sno: row.sno, schema: row.schema });\r\n }\r\n return results;\r\n }\r\n case \"checkMissingChildRows\": {\r\n const results: CheckMissingChildRowsResultRow[] = [];\r\n for await (const row of iModel.createQueryReader(integrityCheckTypeMap.checkMissingChildRows.sqlQuery)) {\r\n results.push({ sno: row.sno, class: row.class, id: row.id, classId: row.class_id, missingRowInTables: row.MissingRowInTables });\r\n }\r\n return results;\r\n }\r\n default:\r\n throw new IModelError(IModelStatus.BadRequest, `Unknown integrity check type`);\r\n }\r\n}"]}
|
|
@@ -192,7 +192,7 @@ export function updateField(field, context) {
|
|
|
192
192
|
}
|
|
193
193
|
}
|
|
194
194
|
catch (err) {
|
|
195
|
-
Logger.
|
|
195
|
+
Logger.logError(BackendLoggerCategory.IModelDb, err);
|
|
196
196
|
}
|
|
197
197
|
newContent = newContent ?? FieldRun.invalidContentIndicator;
|
|
198
198
|
if (newContent === field.cachedContent) {
|
|
@@ -230,7 +230,7 @@ function doUpdateFields(annotationId, sourceId, iModel, deleted) {
|
|
|
230
230
|
}
|
|
231
231
|
}
|
|
232
232
|
catch (err) {
|
|
233
|
-
Logger.
|
|
233
|
+
Logger.logError(BackendLoggerCategory.IModelDb, err);
|
|
234
234
|
}
|
|
235
235
|
}
|
|
236
236
|
// Invoked by ElementDrivesTextAnnotation to update fields in target element when source element changes or is deleted.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fields.js","sourceRoot":"","sources":["../../../../src/internal/annotations/fields.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAE/F,OAAO,EAAE,cAAc,EAA0C,QAAQ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AC;YACzB,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,aAAa,EAAE,EAAE,CAAC;gBAC3C,IAAI,YAAY,CAAC,KAAK,CAAC,SAAS,EAAE,OAAO,CAAC,EAAE,CAAC;oBAC3C,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;gBAC5B,CAAC;YACH,CAAC;YAED,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC7B,MAAM,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;gBACvC,MAAM,CAAC,MAAM,EAAE,CAAC;YAClB,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,CAAC,YAAY,CAAC,qBAAqB,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IAC3D,CAAC;AACH,CAAC;AAED,uHAAuH;AACvH,MAAM,UAAU,mBAAmB,CAAC,KAAwB,EAAE,MAAgB,EAAE,OAAgB;IAC9F,cAAc,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAClE,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,mBAA+B,EAAE,MAAgB;IAC/E,cAAc,CAAC,mBAAmB,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\nimport { ECSqlValueType, FieldPrimitiveValue, FieldPropertyType, FieldRun, FieldValue, formatFieldValue, RelationshipProps, TextBlock, traverseTextBlockComponent } from \"@itwin/core-common\";\r\nimport { IModelDb } from \"../../IModelDb\";\r\nimport { assert, DbResult, expectDefined, Id64String, Logger } from \"@itwin/core-bentley\";\r\nimport { BackendLoggerCategory } from \"../../BackendLoggerCategory\";\r\nimport { isITextAnnotation } from \"../../annotations/ElementDrivesTextAnnotation\";\r\nimport { AnyClass, EntityClass, PrimitiveType, Property, PropertyType, StructArrayProperty } from \"@itwin/ecschema-metadata\";\r\n\r\ninterface FieldStructValue { [key: string]: any }\r\n\r\n// An intermediate value obtained while evaluating a FieldPropertyPath.\r\ntype FieldValueType = {\r\n primitive: FieldPrimitiveValue;\r\n struct?: never;\r\n primitiveArray?: never;\r\n structArray?: never;\r\n} | {\r\n primitive?: never;\r\n struct: FieldStructValue;\r\n primitiveArray?: never;\r\n structArray?: never;\r\n} | {\r\n primitive?: never;\r\n struct?: never;\r\n primitiveArray: FieldPrimitiveValue[];\r\n structArray?: never;\r\n} | {\r\n primitive?: never;\r\n struct?: never;\r\n primitiveArray?: never;\r\n structArray: FieldStructValue[];\r\n}\r\n\r\nexport interface UpdateFieldsContext {\r\n readonly hostElementId: Id64String | undefined;\r\n\r\n getProperty(field: FieldRun): FieldValue | undefined\r\n}\r\n\r\n// Resolve the raw primitive value of the property that a field points to.\r\nfunction getFieldPropertyValue(field: FieldRun, iModel: IModelDb): FieldValue | undefined {\r\n const host = field.propertyHost;\r\n const schemaItem = iModel.schemaContext.getSchemaItemSync(host.schemaName, host.className);\r\n if (!EntityClass.isEntityClass(schemaItem)) {\r\n return undefined;\r\n }\r\n\r\n let ecClass: AnyClass = schemaItem;\r\n const { propertyName, accessors } = field.propertyPath;\r\n let ecProp = ecClass.getPropertySync(propertyName);\r\n if (!ecProp) {\r\n return undefined;\r\n }\r\n\r\n const isAspect = ecClass.isSync(\"ElementAspect\", \"BisCore\");\r\n const where = ` WHERE ${isAspect ? \"Element.Id\" : \"ECInstanceId\"}=${host.elementId}`;\r\n // eslint-disable-next-line @typescript-eslint/no-deprecated\r\n let curValue: FieldValueType | undefined = iModel.withPreparedStatement(`SELECT ${propertyName} FROM ${host.schemaName}.${host.className} ${where}`, (stmt) => {\r\n if (stmt.step() !== DbResult.BE_SQLITE_ROW) {\r\n return undefined;\r\n }\r\n\r\n const rootValue = stmt.getValue(0);\r\n if (undefined === rootValue || rootValue.isNull) {\r\n return undefined;\r\n }\r\n\r\n switch (rootValue.columnInfo.getType()) {\r\n case ECSqlValueType.Blob:\r\n return { primitive: rootValue.getBlob() };\r\n case ECSqlValueType.Boolean:\r\n return { primitive: rootValue.getBoolean() };\r\n case ECSqlValueType.DateTime:\r\n return { primitive: new Date(rootValue.getDateTime()) };\r\n case ECSqlValueType.Double:\r\n return { primitive: rootValue.getDouble() };\r\n case ECSqlValueType.Guid:\r\n return { primitive: rootValue.getGuid() };\r\n case ECSqlValueType.Int:\r\n case ECSqlValueType.Int64:\r\n return { primitive: rootValue.getInteger() };\r\n case ECSqlValueType.Point2d:\r\n return { primitive: rootValue.getXAndY() };\r\n case ECSqlValueType.Point3d:\r\n return { primitive: rootValue.getXYAndZ() };\r\n case ECSqlValueType.String:\r\n return { primitive: rootValue.getString() };\r\n case ECSqlValueType.Struct: {\r\n ecProp = expectDefined(ecProp);\r\n assert(ecProp.isStruct());\r\n ecClass = ecProp.structClass;\r\n return { struct: rootValue.getStruct() };\r\n }\r\n case ECSqlValueType.PrimitiveArray: {\r\n return { primitiveArray: rootValue.getArray() };\r\n }\r\n case ECSqlValueType.StructArray: {\r\n return { structArray: rootValue.getArray() };\r\n }\r\n // Unsupported:\r\n // case ECSqlValueType.Geometry:\r\n // case ECSqlValueType.Navigation:\r\n // case ECSqlValueType.Id:\r\n }\r\n\r\n return undefined;\r\n });\r\n\r\n if (undefined === curValue) {\r\n return undefined;\r\n }\r\n\r\n if (accessors) {\r\n for (const accessor of accessors) {\r\n if (undefined !== curValue.primitive) {\r\n // Can't index into a primitive.\r\n return undefined;\r\n }\r\n\r\n if (typeof accessor === \"number\") {\r\n const array: FieldPrimitiveValue[] | FieldStructValue[] | undefined = curValue.primitiveArray ?? curValue.structArray;\r\n if (!array) {\r\n return undefined;\r\n }\r\n\r\n const index: number = accessor < 0 ? (array.length + accessor) : accessor;\r\n const item: FieldPrimitiveValue | FieldStructValue = array[index];\r\n if (undefined === item) {\r\n return undefined;\r\n } else if (curValue.primitiveArray) {\r\n curValue = { primitive: curValue.primitiveArray[index] };\r\n } else {\r\n assert(undefined !== curValue.structArray);\r\n assert(ecProp instanceof StructArrayProperty);\r\n\r\n ecClass = ecProp.structClass;\r\n curValue = { struct: curValue.structArray[index] };\r\n }\r\n } else {\r\n if (undefined === curValue.struct) {\r\n return undefined;\r\n }\r\n\r\n const item: any = curValue.struct[accessor];\r\n if (undefined === item) {\r\n return undefined;\r\n }\r\n\r\n ecProp = ecClass.getPropertySync(accessor);\r\n if (!ecProp) {\r\n return undefined;\r\n }\r\n\r\n if (ecProp.isArray()) {\r\n curValue = ecProp.isStruct() ? { structArray: item } : { primitiveArray: item };\r\n } else if (ecProp.isStruct()) {\r\n ecClass = ecProp.structClass;\r\n curValue = { struct: item };\r\n } else if (ecProp.isPrimitive()) {\r\n curValue = { primitive: item };\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n }\r\n }\r\n\r\n const propertyType = determineFieldPropertyType(ecProp);\r\n if(!propertyType) {\r\n return undefined;\r\n }\r\n\r\n // The ultimate result must be a primitive value.\r\n if (undefined === curValue.primitive) {\r\n return undefined;\r\n }\r\n\r\n return { value: curValue.primitive, type: propertyType };\r\n}\r\n\r\nfunction determineFieldPropertyType(prop: Property): FieldPropertyType | undefined {\r\n if (prop.isEnumeration()) {\r\n switch (prop.propertyType) {\r\n case PropertyType.Integer_Enumeration:\r\n return \"int-enum\";\r\n case PropertyType.String_Enumeration:\r\n return \"string-enum\";\r\n default:\r\n return undefined;\r\n }\r\n }\r\n\r\n if (prop.isPrimitive()) {\r\n switch (prop.primitiveType) {\r\n case PrimitiveType.Boolean:\r\n return \"boolean\";\r\n case PrimitiveType.String:\r\n return prop.extendedTypeName === \"DateTime\" ? \"datetime\" : \"string\";\r\n case PrimitiveType.DateTime:\r\n return \"datetime\";\r\n case PrimitiveType.Double:\r\n case PrimitiveType.Long:\r\n return \"quantity\";\r\n case PrimitiveType.Point2d:\r\n case PrimitiveType.Point3d:\r\n return \"coordinate\";\r\n case PrimitiveType.Binary:\r\n return prop.extendedTypeName === \"BeGuid\" ? \"string\" : undefined;\r\n case PrimitiveType.Integer:\r\n case PrimitiveType.Long:\r\n return \"string\";\r\n default:\r\n return undefined;\r\n }\r\n }\r\n\r\n return undefined;\r\n}\r\n\r\nexport function createUpdateContext(hostElementId: string | undefined, iModel: IModelDb, deleted: boolean): UpdateFieldsContext {\r\n return {\r\n hostElementId,\r\n getProperty: deleted ? () => undefined : (field) => getFieldPropertyValue(field, iModel),\r\n };\r\n}\r\n\r\n// Recompute the display value of a single field, return false if it couldn't be evaluated.\r\nexport function updateField(field: FieldRun, context: UpdateFieldsContext): boolean {\r\n if (context.hostElementId && context.hostElementId !== field.propertyHost.elementId) {\r\n return false;\r\n }\r\n\r\n let newContent: string | undefined;\r\n try {\r\n const propValue = context.getProperty(field);\r\n if (undefined !== propValue) {\r\n newContent = formatFieldValue(propValue, field.formatOptions);\r\n }\r\n } catch (err) {\r\n Logger.logException(BackendLoggerCategory.IModelDb, err);\r\n }\r\n\r\n newContent = newContent ?? FieldRun.invalidContentIndicator;\r\n if (newContent === field.cachedContent) {\r\n return false;\r\n }\r\n\r\n field.setCachedContent(newContent);\r\n return true;\r\n}\r\n\r\n// Re-evaluates the display strings for all fields that target the element specified by `context` and returns the number\r\n// of fields whose display strings changed as a result.\r\nexport function updateFields(textBlock: TextBlock, context: UpdateFieldsContext): number {\r\n let numUpdated = 0;\r\n for (const { child } of traverseTextBlockComponent(textBlock)) {\r\n if (child.type === \"field\" && updateField(child, context)) {\r\n ++numUpdated;\r\n }\r\n }\r\n\r\n return numUpdated;\r\n}\r\n\r\nfunction doUpdateFields(annotationId: Id64String, sourceId: Id64String | undefined, iModel: IModelDb, deleted: boolean): void {\r\n try {\r\n const target = iModel.elements.getElement(annotationId);\r\n if (isITextAnnotation(target)) {\r\n const context = createUpdateContext(sourceId, iModel, deleted);\r\n const updatedBlocks = [];\r\n for (const block of target.getTextBlocks()) {\r\n if (updateFields(block.textBlock, context)) {\r\n updatedBlocks.push(block);\r\n }\r\n }\r\n\r\n if (updatedBlocks.length > 0) {\r\n target.updateTextBlocks(updatedBlocks);\r\n target.update();\r\n }\r\n }\r\n } catch (err) {\r\n Logger.logException(BackendLoggerCategory.IModelDb, err);\r\n }\r\n}\r\n\r\n// Invoked by ElementDrivesTextAnnotation to update fields in target element when source element changes or is deleted.\r\nexport function updateElementFields(props: RelationshipProps, iModel: IModelDb, deleted: boolean): void {\r\n doUpdateFields(props.targetId, props.sourceId, iModel, deleted);\r\n}\r\n\r\nexport function updateAllFields(annotationElementId: Id64String, iModel: IModelDb): void {\r\n doUpdateFields(annotationElementId, undefined, iModel, false);\r\n}\r\n\r\n"]}
|
|
1
|
+
{"version":3,"file":"fields.js","sourceRoot":"","sources":["../../../../src/internal/annotations/fields.ts"],"names":[],"mappings":"AAAA;;;+FAG+F;AAE/F,OAAO,EAAE,cAAc,EAA0C,QAAQ,EAAc,gBAAgB,EAAgC,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAE9L,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,aAAa,EAAc,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAC1F,OAAO,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACpE,OAAO,EAAE,iBAAiB,EAAE,MAAM,+CAA+C,CAAC;AAClF,OAAO,EAAY,WAAW,EAAE,aAAa,EAAY,YAAY,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAiC7H,0EAA0E;AAC1E,SAAS,qBAAqB,CAAC,KAAe,EAAE,MAAgB;IAC9D,MAAM,IAAI,GAAG,KAAK,CAAC,YAAY,CAAC;IAChC,MAAM,UAAU,GAAG,MAAM,CAAC,aAAa,CAAC,iBAAiB,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IAC3F,IAAI,CAAC,WAAW,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AAgB;IAC9F,cAAc,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;AAClE,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,mBAA+B,EAAE,MAAgB;IAC/E,cAAc,CAAC,mBAAmB,EAAE,SAAS,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/*---------------------------------------------------------------------------------------------\r\n* Copyright (c) Bentley Systems, Incorporated. All rights reserved.\r\n* See LICENSE.md in the project root for license terms and full copyright notice.\r\n*--------------------------------------------------------------------------------------------*/\r\n\r\nimport { ECSqlValueType, FieldPrimitiveValue, FieldPropertyType, FieldRun, FieldValue, formatFieldValue, RelationshipProps, TextBlock, traverseTextBlockComponent } from \"@itwin/core-common\";\r\nimport { IModelDb } from \"../../IModelDb\";\r\nimport { assert, DbResult, expectDefined, Id64String, Logger } from \"@itwin/core-bentley\";\r\nimport { BackendLoggerCategory } from \"../../BackendLoggerCategory\";\r\nimport { isITextAnnotation } from \"../../annotations/ElementDrivesTextAnnotation\";\r\nimport { AnyClass, EntityClass, PrimitiveType, Property, PropertyType, StructArrayProperty } from \"@itwin/ecschema-metadata\";\r\n\r\ninterface FieldStructValue { [key: string]: any }\r\n\r\n// An intermediate value obtained while evaluating a FieldPropertyPath.\r\ntype FieldValueType = {\r\n primitive: FieldPrimitiveValue;\r\n struct?: never;\r\n primitiveArray?: never;\r\n structArray?: never;\r\n} | {\r\n primitive?: never;\r\n struct: FieldStructValue;\r\n primitiveArray?: never;\r\n structArray?: never;\r\n} | {\r\n primitive?: never;\r\n struct?: never;\r\n primitiveArray: FieldPrimitiveValue[];\r\n structArray?: never;\r\n} | {\r\n primitive?: never;\r\n struct?: never;\r\n primitiveArray?: never;\r\n structArray: FieldStructValue[];\r\n}\r\n\r\nexport interface UpdateFieldsContext {\r\n readonly hostElementId: Id64String | undefined;\r\n\r\n getProperty(field: FieldRun): FieldValue | undefined\r\n}\r\n\r\n// Resolve the raw primitive value of the property that a field points to.\r\nfunction getFieldPropertyValue(field: FieldRun, iModel: IModelDb): FieldValue | undefined {\r\n const host = field.propertyHost;\r\n const schemaItem = iModel.schemaContext.getSchemaItemSync(host.schemaName, host.className);\r\n if (!EntityClass.isEntityClass(schemaItem)) {\r\n return undefined;\r\n }\r\n\r\n let ecClass: AnyClass = schemaItem;\r\n const { propertyName, accessors } = field.propertyPath;\r\n let ecProp = ecClass.getPropertySync(propertyName);\r\n if (!ecProp) {\r\n return undefined;\r\n }\r\n\r\n const isAspect = ecClass.isSync(\"ElementAspect\", \"BisCore\");\r\n const where = ` WHERE ${isAspect ? \"Element.Id\" : \"ECInstanceId\"}=${host.elementId}`;\r\n // eslint-disable-next-line @typescript-eslint/no-deprecated\r\n let curValue: FieldValueType | undefined = iModel.withPreparedStatement(`SELECT ${propertyName} FROM ${host.schemaName}.${host.className} ${where}`, (stmt) => {\r\n if (stmt.step() !== DbResult.BE_SQLITE_ROW) {\r\n return undefined;\r\n }\r\n\r\n const rootValue = stmt.getValue(0);\r\n if (undefined === rootValue || rootValue.isNull) {\r\n return undefined;\r\n }\r\n\r\n switch (rootValue.columnInfo.getType()) {\r\n case ECSqlValueType.Blob:\r\n return { primitive: rootValue.getBlob() };\r\n case ECSqlValueType.Boolean:\r\n return { primitive: rootValue.getBoolean() };\r\n case ECSqlValueType.DateTime:\r\n return { primitive: new Date(rootValue.getDateTime()) };\r\n case ECSqlValueType.Double:\r\n return { primitive: rootValue.getDouble() };\r\n case ECSqlValueType.Guid:\r\n return { primitive: rootValue.getGuid() };\r\n case ECSqlValueType.Int:\r\n case ECSqlValueType.Int64:\r\n return { primitive: rootValue.getInteger() };\r\n case ECSqlValueType.Point2d:\r\n return { primitive: rootValue.getXAndY() };\r\n case ECSqlValueType.Point3d:\r\n return { primitive: rootValue.getXYAndZ() };\r\n case ECSqlValueType.String:\r\n return { primitive: rootValue.getString() };\r\n case ECSqlValueType.Struct: {\r\n ecProp = expectDefined(ecProp);\r\n assert(ecProp.isStruct());\r\n ecClass = ecProp.structClass;\r\n return { struct: rootValue.getStruct() };\r\n }\r\n case ECSqlValueType.PrimitiveArray: {\r\n return { primitiveArray: rootValue.getArray() };\r\n }\r\n case ECSqlValueType.StructArray: {\r\n return { structArray: rootValue.getArray() };\r\n }\r\n // Unsupported:\r\n // case ECSqlValueType.Geometry:\r\n // case ECSqlValueType.Navigation:\r\n // case ECSqlValueType.Id:\r\n }\r\n\r\n return undefined;\r\n });\r\n\r\n if (undefined === curValue) {\r\n return undefined;\r\n }\r\n\r\n if (accessors) {\r\n for (const accessor of accessors) {\r\n if (undefined !== curValue.primitive) {\r\n // Can't index into a primitive.\r\n return undefined;\r\n }\r\n\r\n if (typeof accessor === \"number\") {\r\n const array: FieldPrimitiveValue[] | FieldStructValue[] | undefined = curValue.primitiveArray ?? curValue.structArray;\r\n if (!array) {\r\n return undefined;\r\n }\r\n\r\n const index: number = accessor < 0 ? (array.length + accessor) : accessor;\r\n const item: FieldPrimitiveValue | FieldStructValue = array[index];\r\n if (undefined === item) {\r\n return undefined;\r\n } else if (curValue.primitiveArray) {\r\n curValue = { primitive: curValue.primitiveArray[index] };\r\n } else {\r\n assert(undefined !== curValue.structArray);\r\n assert(ecProp instanceof StructArrayProperty);\r\n\r\n ecClass = ecProp.structClass;\r\n curValue = { struct: curValue.structArray[index] };\r\n }\r\n } else {\r\n if (undefined === curValue.struct) {\r\n return undefined;\r\n }\r\n\r\n const item: any = curValue.struct[accessor];\r\n if (undefined === item) {\r\n return undefined;\r\n }\r\n\r\n ecProp = ecClass.getPropertySync(accessor);\r\n if (!ecProp) {\r\n return undefined;\r\n }\r\n\r\n if (ecProp.isArray()) {\r\n curValue = ecProp.isStruct() ? { structArray: item } : { primitiveArray: item };\r\n } else if (ecProp.isStruct()) {\r\n ecClass = ecProp.structClass;\r\n curValue = { struct: item };\r\n } else if (ecProp.isPrimitive()) {\r\n curValue = { primitive: item };\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n }\r\n }\r\n\r\n const propertyType = determineFieldPropertyType(ecProp);\r\n if(!propertyType) {\r\n return undefined;\r\n }\r\n\r\n // The ultimate result must be a primitive value.\r\n if (undefined === curValue.primitive) {\r\n return undefined;\r\n }\r\n\r\n return { value: curValue.primitive, type: propertyType };\r\n}\r\n\r\nfunction determineFieldPropertyType(prop: Property): FieldPropertyType | undefined {\r\n if (prop.isEnumeration()) {\r\n switch (prop.propertyType) {\r\n case PropertyType.Integer_Enumeration:\r\n return \"int-enum\";\r\n case PropertyType.String_Enumeration:\r\n return \"string-enum\";\r\n default:\r\n return undefined;\r\n }\r\n }\r\n\r\n if (prop.isPrimitive()) {\r\n switch (prop.primitiveType) {\r\n case PrimitiveType.Boolean:\r\n return \"boolean\";\r\n case PrimitiveType.String:\r\n return prop.extendedTypeName === \"DateTime\" ? \"datetime\" : \"string\";\r\n case PrimitiveType.DateTime:\r\n return \"datetime\";\r\n case PrimitiveType.Double:\r\n case PrimitiveType.Long:\r\n return \"quantity\";\r\n case PrimitiveType.Point2d:\r\n case PrimitiveType.Point3d:\r\n return \"coordinate\";\r\n case PrimitiveType.Binary:\r\n return prop.extendedTypeName === \"BeGuid\" ? \"string\" : undefined;\r\n case PrimitiveType.Integer:\r\n case PrimitiveType.Long:\r\n return \"string\";\r\n default:\r\n return undefined;\r\n }\r\n }\r\n\r\n return undefined;\r\n}\r\n\r\nexport function createUpdateContext(hostElementId: string | undefined, iModel: IModelDb, deleted: boolean): UpdateFieldsContext {\r\n return {\r\n hostElementId,\r\n getProperty: deleted ? () => undefined : (field) => getFieldPropertyValue(field, iModel),\r\n };\r\n}\r\n\r\n// Recompute the display value of a single field, return false if it couldn't be evaluated.\r\nexport function updateField(field: FieldRun, context: UpdateFieldsContext): boolean {\r\n if (context.hostElementId && context.hostElementId !== field.propertyHost.elementId) {\r\n return false;\r\n }\r\n\r\n let newContent: string | undefined;\r\n try {\r\n const propValue = context.getProperty(field);\r\n if (undefined !== propValue) {\r\n newContent = formatFieldValue(propValue, field.formatOptions);\r\n }\r\n } catch (err) {\r\n Logger.logError(BackendLoggerCategory.IModelDb, err);\r\n }\r\n\r\n newContent = newContent ?? FieldRun.invalidContentIndicator;\r\n if (newContent === field.cachedContent) {\r\n return false;\r\n }\r\n\r\n field.setCachedContent(newContent);\r\n return true;\r\n}\r\n\r\n// Re-evaluates the display strings for all fields that target the element specified by `context` and returns the number\r\n// of fields whose display strings changed as a result.\r\nexport function updateFields(textBlock: TextBlock, context: UpdateFieldsContext): number {\r\n let numUpdated = 0;\r\n for (const { child } of traverseTextBlockComponent(textBlock)) {\r\n if (child.type === \"field\" && updateField(child, context)) {\r\n ++numUpdated;\r\n }\r\n }\r\n\r\n return numUpdated;\r\n}\r\n\r\nfunction doUpdateFields(annotationId: Id64String, sourceId: Id64String | undefined, iModel: IModelDb, deleted: boolean): void {\r\n try {\r\n const target = iModel.elements.getElement(annotationId);\r\n if (isITextAnnotation(target)) {\r\n const context = createUpdateContext(sourceId, iModel, deleted);\r\n const updatedBlocks = [];\r\n for (const block of target.getTextBlocks()) {\r\n if (updateFields(block.textBlock, context)) {\r\n updatedBlocks.push(block);\r\n }\r\n }\r\n\r\n if (updatedBlocks.length > 0) {\r\n target.updateTextBlocks(updatedBlocks);\r\n target.update();\r\n }\r\n }\r\n } catch (err) {\r\n Logger.logError(BackendLoggerCategory.IModelDb, err);\r\n }\r\n}\r\n\r\n// Invoked by ElementDrivesTextAnnotation to update fields in target element when source element changes or is deleted.\r\nexport function updateElementFields(props: RelationshipProps, iModel: IModelDb, deleted: boolean): void {\r\n doUpdateFields(props.targetId, props.sourceId, iModel, deleted);\r\n}\r\n\r\nexport function updateAllFields(annotationElementId: Id64String, iModel: IModelDb): void {\r\n doUpdateFields(annotationElementId, undefined, iModel, false);\r\n}\r\n\r\n"]}
|
package/lib/esm/rpc/tracing.js
CHANGED
|
@@ -61,8 +61,8 @@ export function initializeTracing(enableOpenTelemetry = false) {
|
|
|
61
61
|
RpcInvocation.runActivity = async (activity, fn) => RpcTrace.runWithSpan(activity, fn); // wrap invocation in an OpenTelemetry span in addition to RpcTrace
|
|
62
62
|
}
|
|
63
63
|
catch (e) {
|
|
64
|
-
Logger.
|
|
65
|
-
Logger.
|
|
64
|
+
Logger.logWarning(BackendLoggerCategory.IModelHost, "Failed to initialize OpenTelemetry");
|
|
65
|
+
Logger.logError(BackendLoggerCategory.IModelHost, e);
|
|
66
66
|
}
|
|
67
67
|
}
|
|
68
68
|
// set up static logger metadata to include current RpcActivity information for logs during rpc processing
|