@itwin/core-backend 4.1.0-dev.0 → 4.1.0-dev.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/lib/cjs/BlobContainerService.d.ts +2 -0
  3. package/lib/cjs/BlobContainerService.d.ts.map +1 -1
  4. package/lib/cjs/BlobContainerService.js.map +1 -1
  5. package/lib/cjs/ChannelControl.d.ts +13 -1
  6. package/lib/cjs/ChannelControl.d.ts.map +1 -1
  7. package/lib/cjs/ChannelControl.js +8 -5
  8. package/lib/cjs/ChannelControl.js.map +1 -1
  9. package/lib/cjs/CheckpointManager.d.ts.map +1 -1
  10. package/lib/cjs/CheckpointManager.js +2 -1
  11. package/lib/cjs/CheckpointManager.js.map +1 -1
  12. package/lib/cjs/CloudSqlite.d.ts +48 -34
  13. package/lib/cjs/CloudSqlite.d.ts.map +1 -1
  14. package/lib/cjs/CloudSqlite.js +77 -27
  15. package/lib/cjs/CloudSqlite.js.map +1 -1
  16. package/lib/cjs/CodeService.d.ts +1 -1
  17. package/lib/cjs/CodeService.d.ts.map +1 -1
  18. package/lib/cjs/CodeService.js.map +1 -1
  19. package/lib/cjs/ElementAspect.d.ts +1 -1
  20. package/lib/cjs/ElementAspect.js +1 -1
  21. package/lib/cjs/ElementAspect.js.map +1 -1
  22. package/lib/cjs/IpcHost.d.ts +8 -2
  23. package/lib/cjs/IpcHost.d.ts.map +1 -1
  24. package/lib/cjs/IpcHost.js +6 -6
  25. package/lib/cjs/IpcHost.js.map +1 -1
  26. package/lib/cjs/LocalhostIpcHost.d.ts.map +1 -1
  27. package/lib/cjs/LocalhostIpcHost.js +2 -3
  28. package/lib/cjs/LocalhostIpcHost.js.map +1 -1
  29. package/lib/cjs/NativeHost.d.ts.map +1 -1
  30. package/lib/cjs/NativeHost.js +2 -2
  31. package/lib/cjs/NativeHost.js.map +1 -1
  32. package/lib/cjs/workspace/Workspace.d.ts +2 -4
  33. package/lib/cjs/workspace/Workspace.d.ts.map +1 -1
  34. package/lib/cjs/workspace/Workspace.js +2 -3
  35. package/lib/cjs/workspace/Workspace.js.map +1 -1
  36. package/package.json +10 -10
@@ -1 +1 @@
1
- {"version":3,"file":"CodeService.js","sourceRoot":"","sources":["../../src/CodeService.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;;;AAE/F,sDAAoG;AAyCpG,aAAa;AACb,IAAiB,WAAW,CA2d3B;AA3dD,WAAiB,WAAW;IA+H1B,gBAAgB;IAChB,MAAM,aAAa,GAAG,IAAI,GAAG,EAAwB,CAAC;IAKtD,8EAA8E;IAC9E,SAAgB,gBAAgB,CAAC,GAAiB;QAChD,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;IAC3C,CAAC;IAFe,4BAAgB,mBAE/B,CAAA;IAED;;OAEG;IACH,SAAgB,WAAW,CAAC,IAAY;QACtC,MAAM,GAAG,GAAG,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,CAAC,GAAG;YACN,MAAM,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC,CAAC,EAAE,iBAAiB,IAAI,YAAY,CAAC,CAAC;QAC7E,OAAO,GAAG,CAAC;IACb,CAAC;IALe,uBAAW,cAK1B,CAAA;IAED;;;;;OAKG;IACH,SAAgB,gBAAgB,CAAC,MAAgB,EAAE,IAAe;QAChE,MAAM,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,KAAK,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC,cAAc,CAAC;QAC/G,IAAI,SAAS,KAAK,SAAS;YACzB,MAAM,IAAI,WAAW,CAAC,KAAK,CAAC,aAAa,EAAE,2BAAY,CAAC,WAAW,EAAE,0CAA0C,CAAC,CAAC;QAEnH,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3E,CAAC;IANe,4BAAgB,mBAM/B,CAAA;IAED;;OAEG;IACH,SAAgB,gBAAgB,CAAC,GAAqC;QACpE,OAAO;YACL,GAAG,GAAG,CAAC,KAAK;YACZ,KAAK,EAAE,GAAG,CAAC,IAAI,CAAC,KAAK;YACrB,GAAG,gBAAgB,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC;SAC1C,CAAC;IACJ,CAAC;IANe,4BAAgB,mBAM/B,CAAA;IAoQD,uDAAuD;IACvD,MAAa,KAAM,SAAQ,2BAAY;QAMrC,gBAAgB;QAChB,YAAY,OAAgB,EAAE,MAAc,EAAE,OAAe,EAAE,QAA6C;YAC1G,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YACvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;YACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC3B,CAAC;KACF;IAZY,iBAAK,QAYjB,CAAA;AA+BH,CAAC,EA3dgB,WAAW,GAAX,mBAAW,KAAX,mBAAW,QA2d3B","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 { BentleyError, GuidString, IModelStatus, MarkRequired, Mutable } from \"@itwin/core-bentley\";\r\nimport { CodeProps, FontId, FontType } from \"@itwin/core-common\";\r\nimport { CloudSqlite } from \"./CloudSqlite\";\r\nimport { IModelDb } from \"./IModelDb\";\r\nimport { SettingObject } from \"./workspace/Settings\";\r\nimport { VersionedSqliteDb } from \"./SQLiteDb\";\r\n\r\n/**\r\n * The services for querying, reserving, updating, and deleting codes for a BriefcaseDb (available via `BriefcaseDb.codeService`) whenever it is opened for write access.\r\n * See [CodeService]($docs/learning/backend/CodeService).\r\n * @alpha\r\n */\r\nexport interface CodeService {\r\n /** @internal */\r\n close: () => void;\r\n\r\n initialize(iModel: IModelDb): Promise<void>;\r\n\r\n /** the index for external Codes for this CodeService */\r\n readonly externalCodes?: CloudSqlite.DbAccess<CodeService.CodesDb, CodeService.ReadMethods, CodeService.WriteMethods>;\r\n\r\n /** the index for internal Codes for this CodeService */\r\n readonly internalCodes?: CloudSqlite.DbAccess<CodeService.InternalCodes, CodeService.InternalReadMethods, CodeService.InternalWriteMethods>;\r\n\r\n /**\r\n * Application-supplied parameters for reserving new codes.\r\n */\r\n readonly appParams: CodeService.AuthorAndOrigin;\r\n\r\n /**\r\n * Verify that the Code of a to-be-inserted or to-be-updated Element:\r\n * 1. has already been reserved,\r\n * 2. if the element has a `federationGuid`, it must match the reserved value. If the federationGuid is undefined,\r\n * the value from the code index is returned.\r\n *\r\n * If not, throw an exception. Elements with no CodeValue are ignored.\r\n * @note this method is automatically called whenever elements are added or updated by a BriefcaseDb with a CodeService.\r\n */\r\n verifyCode(props: CodeService.ElementCodeProps): void;\r\n}\r\n\r\n/** @alpha */\r\nexport namespace CodeService {\r\n\r\n export interface WriteMethods {\r\n /** Add a new code spec to this code service.\r\n */\r\n addCodeSpec(val: CodeService.NameAndJson): Promise<void>;\r\n\r\n /**\r\n * Add all of the codes and code specs from this CodeService's BriefcaseDb into the code index.\r\n * @returns the number of codes actually added.\r\n * @note It is not necessary to call this method unless the BriefcaseDb somehow becomes out of sync with its CodeService,\r\n * for example when migrating iModels to a new code service. It is safe (but relatively expensive) to call this method multiple times, since\r\n * any codes or code specs that are already in the index are ignored.\r\n */\r\n addAllCodes(iModel: IModelDb): Promise<number>;\r\n\r\n /**\r\n * Attempt to reserve a single proposed code.\r\n * @throws `CodeService.Error` if the proposed code cannot be reserved.\r\n */\r\n reserveCode(code: CodeService.ProposedCode): Promise<void>;\r\n\r\n /**\r\n * Attempt to reserve an array of proposed codes.\r\n * @returns number of codes actually reserved.\r\n * @see the `problems` member of the `CodeService.Error` exception\r\n * @note If you have a set of codes to reserve, it is considerably more efficient to do them as an array rather than one at a time.\r\n * @throws `CodeService.Error` if any of the proposed code cannot be reserved. The details for each failed code are in the `problems` member.\r\n */\r\n reserveCodes(arg: CodeService.ReserveCodesArgs): Promise<number>;\r\n\r\n /**\r\n * Attempt to reserve the next available code for a code sequence and scope.\r\n */\r\n reserveNextAvailableCode(arg: CodeService.ReserveNextArgs): Promise<void>;\r\n\r\n /**\r\n * Attempt to reserve an array of the next available codes for a code sequence and scope.\r\n * The length of the array determines the number of codes requested. The values for the new codes are returned\r\n * in the array, so they can be associated with the supplied GUIDs.\r\n * @returns number of codes actually reserved.\r\n */\r\n reserveNextAvailableCodes(arg: CodeService.ReserveNextArrayArgs): Promise<number>;\r\n\r\n /**\r\n * Update the properties of a single code.\r\n */\r\n updateCode(props: CodeService.UpdatedCode): Promise<void>;\r\n\r\n /**\r\n * Update the properties of an array codes.\r\n * @note If you have a set of codes to update, it is considerably more efficient to do them as an array rather than one at a time.\r\n * @returns number of codes actually updated.\r\n */\r\n updateCodes(arg: CodeService.UpdateCodesArgs): Promise<number>;\r\n\r\n /** Delete an array of codes by their guids. */\r\n deleteCodes(guid: CodeService.CodeGuid[]): Promise<void>;\r\n }\r\n\r\n export interface ReadMethods {\r\n /**\r\n * Find the next available value for the supplied `SequenceScope`.\r\n * If the sequence is full (there are no available values), this will throw an exception with `errorId=\"SequenceFull\"`\r\n * @param from the sequence and scope to search\r\n * @returns the next available CodeValue in the sequence.\r\n */\r\n findNextAvailable(from: CodeService.SequenceScope): CodeService.CodeValue;\r\n\r\n /**\r\n * Find the highest currently used value for the supplied `SequenceScope`\r\n * @param from the sequence and scope to search\r\n * @returns the highest used value, or undefined if no values have been used.\r\n */\r\n findHighestUsed(from: CodeService.SequenceScope): CodeService.CodeValue | undefined;\r\n\r\n /** Determine whether a code is present in this CodeIndex by its Guid. */\r\n isCodePresent(guid: CodeService.CodeGuid): boolean;\r\n\r\n /** Get the data for a code in this CodeIndex by its Guid.\r\n * @returns the data for the code or undefined if no code is present for the supplied Guid.\r\n */\r\n getCode(guid: CodeService.CodeGuid): CodeService.CodeEntry | undefined;\r\n\r\n /** Look up a code by its Scope, Spec, and Value.\r\n * @returns the Guid of the code, or undefined if not present.\r\n */\r\n findCode(code: CodeService.ScopeSpecAndValue): CodeService.CodeGuid | undefined;\r\n\r\n /** Look up a code spec by its name\r\n * @throws if the spec is not present.\r\n */\r\n getCodeSpec(props: CodeService.CodeSpecName): CodeService.NameAndJson;\r\n\r\n /** Call a `CodeIteration` function for all codes in this index, optionally filtered by a `CodeFilter ` */\r\n forAllCodes(iter: CodeService.CodeIteration, filter?: CodeService.CodeFilter): void;\r\n\r\n /** Call an iteration function for all code specs in this index, optionally filtered by a `ValueFilter ` */\r\n forAllCodeSpecs(iter: CodeService.NameAndJsonIteration, filter?: CodeService.ValueFilter): void;\r\n\r\n /**\r\n * Verify that the Code of a to-be-inserted or to-be-updated Element:\r\n * 1. has already been reserved,\r\n * 2. if the element has a `federationGuid`, it must match the reserved value. If the federationGuid is undefined,\r\n * the value from the code index is returned.\r\n *\r\n * If not, throw an exception. Elements with no CodeValue are ignored.\r\n * @note this method is automatically called whenever elements are added or updated by a BriefcaseDb with a CodeService.\r\n */\r\n verifyCode(specName: string, arg: CodeService.ElementCodeProps): void;\r\n }\r\n\r\n export type CodesDb = VersionedSqliteDb & WriteMethods & ReadMethods;\r\n\r\n export interface InternalWriteMethods extends WriteMethods {\r\n /** @internal */\r\n reserveFontId(props: CodeService.FontIndexProps): Promise<FontId>;\r\n /** @internal */\r\n reserveBisCodeSpecs(specs: CodeService.BisCodeSpecIndexProps[]): Promise<void>;\r\n }\r\n export interface InternalReadMethods extends ReadMethods {\r\n /** @internal */\r\n verifyBisCodeSpec(spec: CodeService.BisCodeSpecIndexProps): void;\r\n }\r\n\r\n export type InternalCodes = CodesDb & InternalWriteMethods & InternalReadMethods;\r\n\r\n /** @internal */\r\n const codeSequences = new Map<string, CodeSequence>();\r\n\r\n /** @internal */\r\n export let createForIModel: ((db: IModelDb) => Promise<CodeService>) | undefined;\r\n\r\n /** Register an instance of a`CodeSequence` so it can be looked up by name. */\r\n export function registerSequence(seq: CodeSequence) {\r\n codeSequences.set(seq.sequenceName, seq);\r\n }\r\n\r\n /** Get a previously registered `CodeSequence` by its name.\r\n * @throws if no sequence by that name was registered.\r\n */\r\n export function getSequence(name: string): CodeSequence {\r\n const seq = codeSequences.get(name);\r\n if (!seq)\r\n throw new Error(\"SequenceNotFound\", -1, `code sequence ${name} not found`);\r\n return seq;\r\n }\r\n\r\n /**\r\n * Turn a `CodePops` for the briefcase of this CodeService into a `ScopeAndSpec` object for use with a CodeService.\r\n * This is necessary because the `spec` member of `CodeProps` refers to the id of a code spec in the iModel, and\r\n * the `scope` member refers to the element Id of the scope element in the iModel. This helper function\r\n * converts the spec Id to the spec name and looks up the `FederationGuid` of the scope element.\r\n */\r\n export function makeScopeAndSpec(iModel: IModelDb, code: CodeProps): CodeService.ScopeAndSpec {\r\n const scopeGuid = iModel.elements.getElementProps({ id: code.scope, onlyBaseProperties: true }).federationGuid;\r\n if (undefined === scopeGuid)\r\n throw new CodeService.Error(\"MissingGuid\", IModelStatus.InvalidCode, \"code scope element has no federationGuid\");\r\n\r\n return { scopeGuid, specName: iModel.codeSpecs.getById(code.spec).name };\r\n }\r\n\r\n /** Turn a `CodeProps` and `ProposedCodeProps` into a `ProposedCode` for use with a CodeService.\r\n * @see [[makeScopeAndSpec]] for explanation of why this is necessary.\r\n */\r\n export function makeProposedCode(arg: CodeService.MakeProposedCodeArgs): CodeService.ProposedCode {\r\n return {\r\n ...arg.props,\r\n value: arg.code.value,\r\n ...makeScopeAndSpec(arg.iModel, arg.code),\r\n };\r\n }\r\n\r\n /** The name of a code spec */\r\n export type CodeSpecName = string;\r\n\r\n /**\r\n * The name that identifies the \"originator\" of a code. Usually this is the Guid of the iModel from which a code was added,\r\n * but can also be used to identify a system or type from an external code service.\r\n */\r\n export type CodeOriginName = string;\r\n\r\n /** The name that identifies the \"author\" of a code. Generally, this is intended to be the name of a person or group that helps identify the purpose of the code. */\r\n export type AuthorName = string;\r\n\r\n /** The value for a code. */\r\n export type CodeValue = string;\r\n\r\n /** The guid for a code. This identifies the real-world entity associated with the code. */\r\n export type CodeGuid = GuidString;\r\n\r\n /** The guid of the scope for a code. This identifies the real-world entity that provides the uniqueness scope for code values. */\r\n export type ScopeGuid = GuidString;\r\n\r\n /** An optional number associated with a code that may be used for \"status\" information. Values must be defined by applications. */\r\n export type CodeState = number;\r\n\r\n /** The return status of an iteration function. The value \"stop\" causes the iteration to terminate. */\r\n export type IterationReturn = void | \"stop\";\r\n\r\n /** An iteration function over codes in a code index. It is called with the Guid of a each code. */\r\n export type CodeIteration = (guid: GuidString) => IterationReturn;\r\n\r\n /** An iteration function over code specs in a code index. It is called with the name and json of a each code spec. */\r\n export type NameAndJsonIteration = (nameAndJson: NameAndJson) => IterationReturn;\r\n\r\n /** Argument for reserving an array of new codes. */\r\n export interface ReserveCodesArgs {\r\n /** an array of proposed codes to reserve.\r\n * @note the guid of each proposed code must be supplied by the caller.\r\n */\r\n readonly codes: CodeService.ProposedCode[];\r\n /** If true, unless all codes are available, don't reserve any codes. Otherwise reserve all available codes. */\r\n readonly allOrNothing?: true;\r\n }\r\n\r\n /** Argument for reserving a code from a code sequence. */\r\n export interface ReserveNextArgs {\r\n /** the properties of the new code */\r\n readonly code: CodeService.ProposedCodeProps;\r\n /** The code sequence and scope for the new code. */\r\n readonly from: SequenceScope;\r\n }\r\n\r\n /** Argument for reserving an array of codes from a code sequence. */\r\n export interface ReserveNextArrayArgs {\r\n /** an array of proposed codes to reserve. */\r\n readonly codes: CodeService.ProposedCodeProps[];\r\n /** The code sequence and scope for the new codes. */\r\n readonly from: CodeService.SequenceScope;\r\n /** If true, and in the event that the code sequence does not have enough available codes to fulfill all the entries in `codes`,\r\n * return as many as possible. Otherwise no codes are reserved. The `problems` member of the exception can be used to determine how many codes were available.\r\n * @note if `asManyAsPossible` is true, no error is thrown if the sequence becomes full. You must check the return value to see how many\r\n * were actually available. The `value` member will be undefined for any proposed codes that were not reserved.\r\n */\r\n readonly asManyAsPossible?: true;\r\n }\r\n\r\n /** Argument for updating an array of codes. */\r\n export interface UpdateCodesArgs {\r\n /** Properties of the codes to update */\r\n readonly props: CodeService.UpdatedCode[];\r\n /** If true, unless all codes are updated, don't update any codes. Otherwise update all possible codes. */\r\n readonly allOrNothing?: true;\r\n }\r\n\r\n /** Arguments for CodeService.makeProposedCode */\r\n export interface MakeProposedCodeArgs {\r\n readonly iModel: IModelDb;\r\n readonly code: Required<CodeProps>;\r\n readonly props: CodeService.CodeGuidStateJson;\r\n }\r\n\r\n /** The properties of an Element to be checked against the code index.\r\n * @see CodeService.verifyCode\r\n */\r\n export interface ElementCodeProps {\r\n /** iModel from which the code is being inserted/updated. */\r\n readonly iModel: IModelDb;\r\n /** Properties of the code */\r\n readonly props: {\r\n /** The imodel-specific code properties. */\r\n readonly code: CodeProps;\r\n /**\r\n * The federationGuid of the element being inserted or updated.\r\n * If federationGuid is defined, it is must match the value in the code index or an error is thrown.\r\n * If it is undefined, the value from the code index is returned here.\r\n */\r\n federationGuid?: GuidString;\r\n };\r\n }\r\n\r\n /** a name and a json object. Used for code specs, authors and origins. */\r\n export interface NameAndJson {\r\n readonly name: string;\r\n readonly json?: SettingObject;\r\n }\r\n\r\n /** A code Scope guid, and code spec name. */\r\n export interface ScopeAndSpec {\r\n readonly specName: CodeSpecName;\r\n readonly scopeGuid: ScopeGuid;\r\n }\r\n\r\n /** A code Scope guid, code spec, and code value. */\r\n export interface ScopeSpecAndValue extends ScopeAndSpec {\r\n readonly value: CodeValue;\r\n }\r\n\r\n /** The data held in a code index for a single code. */\r\n export interface CodeEntry {\r\n /** The name of the code spec for this code. */\r\n readonly specName: CodeSpecName;\r\n /** The guid of the entity that provides the scope for this code. */\r\n readonly scopeGuid: ScopeGuid;\r\n /** The value of this code. */\r\n readonly value: CodeValue;\r\n /** The guid of the entity this code identifies. */\r\n readonly guid: CodeGuid;\r\n /** the state of the code. May be undefined. */\r\n readonly state?: CodeState;\r\n /** The name of the originating source of this code (usually an iModel Guid). May be undefined. */\r\n readonly origin: CodeOriginName;\r\n /** The name of the author of this code. May be undefined. */\r\n readonly author?: AuthorName;\r\n /** Option json properties associated with this code. May be undefined. */\r\n readonly json?: SettingObject;\r\n }\r\n\r\n /** A filter used to limit and/or sort the values returned by an iteration. */\r\n export interface ValueFilter {\r\n /** A value filter. May include wild cards when used with `GLOB` or `LIKE` */\r\n readonly value?: string;\r\n /** The comparison operator for `value`. Default is `=` */\r\n readonly valueCompare?: \"GLOB\" | \"LIKE\" | \"NOT GLOB\" | \"NOT LIKE\" | \"=\" | \"<\" | \">\";\r\n /** Order results ascending or descending. If not supplied, the results are unordered (random). */\r\n readonly orderBy?: \"ASC\" | \"DESC\";\r\n /** An SQL expression to further filter results. This string is appended to the `WHERE` clause with an `AND` (that should not be part of the sqlExpression) */\r\n readonly sqlExpression?: string;\r\n }\r\n\r\n /** A filter to limit and/or sort the values for the [[CodeIndex.forAllCodes]] iteration. */\r\n export interface CodeFilter extends ValueFilter {\r\n /** If supplied, limit results to only those with this spec */\r\n readonly specName?: CodeSpecName;\r\n /** If supplied, limit results to only those with this scope Guid */\r\n readonly scopeGuid?: ScopeGuid;\r\n /** If supplied, limit results to only those with this origin */\r\n readonly origin?: CodeOriginName;\r\n }\r\n\r\n /** Author and origin information supplied when codes are reserved. */\r\n export interface AuthorAndOrigin {\r\n /** The name of the individual or group for whom the code was reserved. */\r\n readonly author: Mutable<NameAndJson>;\r\n /** The identity of the \"originator\" of the code. This is usually a guid of an iModel, but can be any unique string. */\r\n readonly origin: Mutable<NameAndJson>;\r\n }\r\n\r\n /** The Guid, state, and json properties of a code. */\r\n export interface CodeGuidStateJson {\r\n /** The Guid of the new code. This must be always be supplied by the application. */\r\n readonly guid: CodeGuid;\r\n /** An optional value for the state of the code. */\r\n readonly state?: CodeState;\r\n /** An optional json object to be stored with the code. */\r\n readonly json?: SettingObject;\r\n }\r\n\r\n /** Properties of a \"proposed\" new code to be reserved.\r\n * @note the Guid of the entity identified by this code *must* be supplied, but `value` is optional, since\r\n * this may be used to reserve codes from a sequence where the value is generated.\r\n */\r\n export interface ProposedCodeProps extends CodeGuidStateJson {\r\n /** The value for the proposed code.\r\n * @note For code sequence operations, this value is ignored on input and is set with a new value from the sequence on successful return.\r\n */\r\n value?: CodeValue;\r\n }\r\n\r\n /** Properties of a proposed new code that is not from a code sequence (its `value` is required). */\r\n export type ProposedCode = ProposedCodeProps & ScopeSpecAndValue;\r\n\r\n /** Properties that describe a code sequence and a scope and spec for a proposed code or array of codes from a sequence. */\r\n export interface SequenceScope extends ScopeAndSpec {\r\n /** The code sequence. */\r\n readonly seq: CodeSequence;\r\n /** A valid current value. If supplied, the returned value will always be later in the sequence than this. */\r\n readonly start?: CodeValue;\r\n }\r\n\r\n /** Properties of a code to be updated.\r\n * @note The `guid` member identifies the code to be updated and is required.\r\n * All other properties are optional - if `undefined`, its value is not changed.\r\n */\r\n export type UpdatedCode = MarkRequired<Partial<ProposedCode>, \"guid\">;\r\n\r\n /** A proposed code that could not be reserved due to some error. */\r\n export interface ReserveProblem {\r\n /** the proposed code that failed. */\r\n readonly code: ProposedCode;\r\n /** the reason for the failure */\r\n readonly errorId: ErrorId;\r\n /** the error message from the exception for this proposed code. */\r\n readonly message: string;\r\n }\r\n\r\n /** A update to a code that failed for some error. */\r\n export interface UpdateProblem {\r\n /** The properties of the code that was to be updated */\r\n readonly prop: UpdatedCode;\r\n /** the reason for the failure */\r\n readonly errorId: ErrorId;\r\n /** the error message from the exception for the update request. */\r\n readonly message: string;\r\n }\r\n\r\n /**\r\n * A sequence of code values following a increasing pattern. Valid code sequences must have a first value, a last value, and\r\n * a way to get the next valid value from an existing valid value.\r\n * Code sequences have a `sequenceName` so they can be registered using `CodeService.registerSequence`.\r\n */\r\n export interface CodeSequence {\r\n /** the name of this CodeSequence. */\r\n get sequenceName(): string;\r\n /** Get the first valid value for this CodeSequence */\r\n getFirstValue(): CodeValue;\r\n /** Get the last valid value for this CodeSequence */\r\n getLastValue(): CodeValue;\r\n /** Get the next valid value for this CodeSequence from the supplied value.\r\n * If the sequence is full (that is, the next value is greater than the last value, this method should throw with errorId=\"SequenceFull\".\r\n * @return the next valid value according to the rules of this CodeSequence.\r\n */\r\n getNextValue(code: CodeValue): CodeValue;\r\n /** Determine whether this supplied value is valid for this sequence. */\r\n isValidCode(code: CodeValue): boolean;\r\n }\r\n\r\n /** @internal */\r\n export interface FontIndexProps {\r\n id?: number;\r\n fontType: FontType;\r\n fontName: string;\r\n }\r\n /** @internal */\r\n export interface BisCodeSpecIndexProps {\r\n id?: number;\r\n name: string;\r\n props: string;\r\n }\r\n\r\n /** Exception class thrown by `CodeService` methods. */\r\n export class Error extends BentleyError {\r\n /** A string that indicates the type of problem that caused the exception. */\r\n public readonly errorId: ErrorId;\r\n /** For [[CodeService.reserveCodes]] and [[CodeService.updateCodes]], a list of the problem details. */\r\n public readonly problems?: ReserveProblem[] | UpdateProblem[];\r\n\r\n /** @internal */\r\n constructor(errorId: ErrorId, errNum: number, message: string, problems?: ReserveProblem[] | UpdateProblem[]) {\r\n super(errNum, message);\r\n this.errorId = errorId;\r\n this.problems = problems;\r\n }\r\n }\r\n\r\n /** Identifiers for exceptions thrown by `CodeService` methods.\r\n * @see [[CodeService.Error.errorId]]\r\n */\r\n export type ErrorId =\r\n \"BadIndexProps\" |\r\n \"CorruptIModel\" |\r\n \"CorruptIndex\" |\r\n \"DuplicateValue\" |\r\n \"GuidIsInUse\" |\r\n \"GuidMismatch\" |\r\n \"IllegalValue\" |\r\n \"InconsistentIModels\" |\r\n \"IndexReadonly\" |\r\n \"InvalidCodeScope\" |\r\n \"InvalidGuid\" |\r\n \"InvalidSequence\" |\r\n \"MissingCode\" |\r\n \"MissingGuid\" |\r\n \"MissingInput\" |\r\n \"MissingSpec\" |\r\n \"NoCodeIndex\" |\r\n \"SequenceFull\" |\r\n \"ReserveErrors\" |\r\n \"SequenceNotFound\" |\r\n \"SqlLogicError\" |\r\n \"UpdateErrors\" |\r\n \"ValueIsInUse\" |\r\n \"WrongVersion\";\r\n\r\n}\r\n"]}
1
+ {"version":3,"file":"CodeService.js","sourceRoot":"","sources":["../../src/CodeService.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;;;AAE/F,sDAAoG;AAyCpG,aAAa;AACb,IAAiB,WAAW,CA4d3B;AA5dD,WAAiB,WAAW;IA+H1B,gBAAgB;IAChB,MAAM,aAAa,GAAG,IAAI,GAAG,EAAwB,CAAC;IAKtD,8EAA8E;IAC9E,SAAgB,gBAAgB,CAAC,GAAiB;QAChD,aAAa,CAAC,GAAG,CAAC,GAAG,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;IAC3C,CAAC;IAFe,4BAAgB,mBAE/B,CAAA;IAED;;OAEG;IACH,SAAgB,WAAW,CAAC,IAAY;QACtC,MAAM,GAAG,GAAG,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACpC,IAAI,CAAC,GAAG;YACN,MAAM,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC,CAAC,EAAE,iBAAiB,IAAI,YAAY,CAAC,CAAC;QAC7E,OAAO,GAAG,CAAC;IACb,CAAC;IALe,uBAAW,cAK1B,CAAA;IAED;;;;;OAKG;IACH,SAAgB,gBAAgB,CAAC,MAAgB,EAAE,IAAe;QAChE,MAAM,SAAS,GAAG,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,KAAK,EAAE,kBAAkB,EAAE,IAAI,EAAE,CAAC,CAAC,cAAc,CAAC;QAC/G,IAAI,SAAS,KAAK,SAAS;YACzB,MAAM,IAAI,WAAW,CAAC,KAAK,CAAC,aAAa,EAAE,2BAAY,CAAC,WAAW,EAAE,0CAA0C,CAAC,CAAC;QAEnH,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;IAC3E,CAAC;IANe,4BAAgB,mBAM/B,CAAA;IAED;;OAEG;IACH,SAAgB,gBAAgB,CAAC,GAAqC;QACpE,OAAO;YACL,GAAG,GAAG,CAAC,KAAK;YACZ,KAAK,EAAE,GAAG,CAAC,IAAI,CAAC,KAAK;YACrB,GAAG,gBAAgB,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC;SAC1C,CAAC;IACJ,CAAC;IANe,4BAAgB,mBAM/B,CAAA;IAoQD,uDAAuD;IACvD,MAAa,KAAM,SAAQ,2BAAY;QAMrC,gBAAgB;QAChB,YAAY,OAAgB,EAAE,MAAc,EAAE,OAAe,EAAE,QAA6C;YAC1G,KAAK,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YACvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;YACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC3B,CAAC;KACF;IAZY,iBAAK,QAYjB,CAAA;AAgCH,CAAC,EA5dgB,WAAW,GAAX,mBAAW,KAAX,mBAAW,QA4d3B","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 { BentleyError, GuidString, IModelStatus, MarkRequired, Mutable } from \"@itwin/core-bentley\";\r\nimport { CodeProps, FontId, FontType } from \"@itwin/core-common\";\r\nimport { CloudSqlite } from \"./CloudSqlite\";\r\nimport { IModelDb } from \"./IModelDb\";\r\nimport { SettingObject } from \"./workspace/Settings\";\r\nimport { VersionedSqliteDb } from \"./SQLiteDb\";\r\n\r\n/**\r\n * The services for querying, reserving, updating, and deleting codes for a BriefcaseDb (available via `BriefcaseDb.codeService`) whenever it is opened for write access.\r\n * See [CodeService]($docs/learning/backend/CodeService).\r\n * @alpha\r\n */\r\nexport interface CodeService {\r\n /** @internal */\r\n close: () => void;\r\n\r\n initialize(iModel: IModelDb): Promise<void>;\r\n\r\n /** the index for external Codes for this CodeService */\r\n readonly externalCodes?: CloudSqlite.DbAccess<CodeService.CodesDb, CodeService.ReadMethods, CodeService.WriteMethods>;\r\n\r\n /** the index for internal Codes for this CodeService */\r\n readonly internalCodes?: CloudSqlite.DbAccess<CodeService.InternalCodes, CodeService.InternalReadMethods, CodeService.InternalWriteMethods>;\r\n\r\n /**\r\n * Application-supplied parameters for reserving new codes.\r\n */\r\n readonly appParams: CodeService.AuthorAndOrigin;\r\n\r\n /**\r\n * Verify that the Code of a to-be-inserted or to-be-updated Element:\r\n * 1. has already been reserved,\r\n * 2. if the element has a `federationGuid`, it must match the reserved value. If the federationGuid is undefined,\r\n * the value from the code index is returned.\r\n *\r\n * If not, throw an exception. Elements with no CodeValue are ignored.\r\n * @note this method is automatically called whenever elements are added or updated by a BriefcaseDb with a CodeService.\r\n */\r\n verifyCode(props: CodeService.ElementCodeProps): void;\r\n}\r\n\r\n/** @alpha */\r\nexport namespace CodeService {\r\n\r\n export interface WriteMethods {\r\n /** Add a new code spec to this code service.\r\n */\r\n addCodeSpec(val: CodeService.NameAndJson): Promise<void>;\r\n\r\n /**\r\n * Add all of the codes and code specs from this CodeService's BriefcaseDb into the code index.\r\n * @returns the number of codes actually added.\r\n * @note It is not necessary to call this method unless the BriefcaseDb somehow becomes out of sync with its CodeService,\r\n * for example when migrating iModels to a new code service. It is safe (but relatively expensive) to call this method multiple times, since\r\n * any codes or code specs that are already in the index are ignored.\r\n */\r\n addAllCodes(iModel: IModelDb): Promise<number>;\r\n\r\n /**\r\n * Attempt to reserve a single proposed code.\r\n * @throws `CodeService.Error` if the proposed code cannot be reserved.\r\n */\r\n reserveCode(code: CodeService.ProposedCode): Promise<void>;\r\n\r\n /**\r\n * Attempt to reserve an array of proposed codes.\r\n * @returns number of codes actually reserved.\r\n * @see the `problems` member of the `CodeService.Error` exception\r\n * @note If you have a set of codes to reserve, it is considerably more efficient to do them as an array rather than one at a time.\r\n * @throws `CodeService.Error` if any of the proposed code cannot be reserved. The details for each failed code are in the `problems` member.\r\n */\r\n reserveCodes(arg: CodeService.ReserveCodesArgs): Promise<number>;\r\n\r\n /**\r\n * Attempt to reserve the next available code for a code sequence and scope.\r\n */\r\n reserveNextAvailableCode(arg: CodeService.ReserveNextArgs): Promise<void>;\r\n\r\n /**\r\n * Attempt to reserve an array of the next available codes for a code sequence and scope.\r\n * The length of the array determines the number of codes requested. The values for the new codes are returned\r\n * in the array, so they can be associated with the supplied GUIDs.\r\n * @returns number of codes actually reserved.\r\n */\r\n reserveNextAvailableCodes(arg: CodeService.ReserveNextArrayArgs): Promise<number>;\r\n\r\n /**\r\n * Update the properties of a single code.\r\n */\r\n updateCode(props: CodeService.UpdatedCode): Promise<void>;\r\n\r\n /**\r\n * Update the properties of an array codes.\r\n * @note If you have a set of codes to update, it is considerably more efficient to do them as an array rather than one at a time.\r\n * @returns number of codes actually updated.\r\n */\r\n updateCodes(arg: CodeService.UpdateCodesArgs): Promise<number>;\r\n\r\n /** Delete an array of codes by their guids. */\r\n deleteCodes(guid: CodeService.CodeGuid[]): Promise<void>;\r\n }\r\n\r\n export interface ReadMethods {\r\n /**\r\n * Find the next available value for the supplied `SequenceScope`.\r\n * If the sequence is full (there are no available values), this will throw an exception with `errorId=\"SequenceFull\"`\r\n * @param from the sequence and scope to search\r\n * @returns the next available CodeValue in the sequence.\r\n */\r\n findNextAvailable(from: CodeService.SequenceScope): CodeService.CodeValue;\r\n\r\n /**\r\n * Find the highest currently used value for the supplied `SequenceScope`\r\n * @param from the sequence and scope to search\r\n * @returns the highest used value, or undefined if no values have been used.\r\n */\r\n findHighestUsed(from: CodeService.SequenceScope): CodeService.CodeValue | undefined;\r\n\r\n /** Determine whether a code is present in this CodeIndex by its Guid. */\r\n isCodePresent(guid: CodeService.CodeGuid): boolean;\r\n\r\n /** Get the data for a code in this CodeIndex by its Guid.\r\n * @returns the data for the code or undefined if no code is present for the supplied Guid.\r\n */\r\n getCode(guid: CodeService.CodeGuid): CodeService.CodeEntry | undefined;\r\n\r\n /** Look up a code by its Scope, Spec, and Value.\r\n * @returns the Guid of the code, or undefined if not present.\r\n */\r\n findCode(code: CodeService.ScopeSpecAndValue): CodeService.CodeGuid | undefined;\r\n\r\n /** Look up a code spec by its name\r\n * @throws if the spec is not present.\r\n */\r\n getCodeSpec(props: CodeService.CodeSpecName): CodeService.NameAndJson;\r\n\r\n /** Call a `CodeIteration` function for all codes in this index, optionally filtered by a `CodeFilter ` */\r\n forAllCodes(iter: CodeService.CodeIteration, filter?: CodeService.CodeFilter): void;\r\n\r\n /** Call an iteration function for all code specs in this index, optionally filtered by a `ValueFilter ` */\r\n forAllCodeSpecs(iter: CodeService.NameAndJsonIteration, filter?: CodeService.ValueFilter): void;\r\n\r\n /**\r\n * Verify that the Code of a to-be-inserted or to-be-updated Element:\r\n * 1. has already been reserved,\r\n * 2. if the element has a `federationGuid`, it must match the reserved value. If the federationGuid is undefined,\r\n * the value from the code index is returned.\r\n *\r\n * If not, throw an exception. Elements with no CodeValue are ignored.\r\n * @note this method is automatically called whenever elements are added or updated by a BriefcaseDb with a CodeService.\r\n */\r\n verifyCode(specName: string, arg: CodeService.ElementCodeProps): void;\r\n }\r\n\r\n export type CodesDb = VersionedSqliteDb & WriteMethods & ReadMethods;\r\n\r\n export interface InternalWriteMethods extends WriteMethods {\r\n /** @internal */\r\n reserveFontId(props: CodeService.FontIndexProps): Promise<FontId>;\r\n /** @internal */\r\n reserveBisCodeSpecs(specs: CodeService.BisCodeSpecIndexProps[]): Promise<void>;\r\n }\r\n export interface InternalReadMethods extends ReadMethods {\r\n /** @internal */\r\n verifyBisCodeSpec(spec: CodeService.BisCodeSpecIndexProps): void;\r\n }\r\n\r\n export type InternalCodes = CodesDb & InternalWriteMethods & InternalReadMethods;\r\n\r\n /** @internal */\r\n const codeSequences = new Map<string, CodeSequence>();\r\n\r\n /** @internal */\r\n export let createForIModel: ((db: IModelDb) => Promise<CodeService>) | undefined;\r\n\r\n /** Register an instance of a`CodeSequence` so it can be looked up by name. */\r\n export function registerSequence(seq: CodeSequence) {\r\n codeSequences.set(seq.sequenceName, seq);\r\n }\r\n\r\n /** Get a previously registered `CodeSequence` by its name.\r\n * @throws if no sequence by that name was registered.\r\n */\r\n export function getSequence(name: string): CodeSequence {\r\n const seq = codeSequences.get(name);\r\n if (!seq)\r\n throw new Error(\"SequenceNotFound\", -1, `code sequence ${name} not found`);\r\n return seq;\r\n }\r\n\r\n /**\r\n * Turn a `CodePops` for the briefcase of this CodeService into a `ScopeAndSpec` object for use with a CodeService.\r\n * This is necessary because the `spec` member of `CodeProps` refers to the id of a code spec in the iModel, and\r\n * the `scope` member refers to the element Id of the scope element in the iModel. This helper function\r\n * converts the spec Id to the spec name and looks up the `FederationGuid` of the scope element.\r\n */\r\n export function makeScopeAndSpec(iModel: IModelDb, code: CodeProps): CodeService.ScopeAndSpec {\r\n const scopeGuid = iModel.elements.getElementProps({ id: code.scope, onlyBaseProperties: true }).federationGuid;\r\n if (undefined === scopeGuid)\r\n throw new CodeService.Error(\"MissingGuid\", IModelStatus.InvalidCode, \"code scope element has no federationGuid\");\r\n\r\n return { scopeGuid, specName: iModel.codeSpecs.getById(code.spec).name };\r\n }\r\n\r\n /** Turn a `CodeProps` and `ProposedCodeProps` into a `ProposedCode` for use with a CodeService.\r\n * @see [[makeScopeAndSpec]] for explanation of why this is necessary.\r\n */\r\n export function makeProposedCode(arg: CodeService.MakeProposedCodeArgs): CodeService.ProposedCode {\r\n return {\r\n ...arg.props,\r\n value: arg.code.value,\r\n ...makeScopeAndSpec(arg.iModel, arg.code),\r\n };\r\n }\r\n\r\n /** The name of a code spec */\r\n export type CodeSpecName = string;\r\n\r\n /**\r\n * The name that identifies the \"originator\" of a code. Usually this is the Guid of the iModel from which a code was added,\r\n * but can also be used to identify a system or type from an external code service.\r\n */\r\n export type CodeOriginName = string;\r\n\r\n /** The name that identifies the \"author\" of a code. Generally, this is intended to be the name of a person or group that helps identify the purpose of the code. */\r\n export type AuthorName = string;\r\n\r\n /** The value for a code. */\r\n export type CodeValue = string;\r\n\r\n /** The guid for a code. This identifies the real-world entity associated with the code. */\r\n export type CodeGuid = GuidString;\r\n\r\n /** The guid of the scope for a code. This identifies the real-world entity that provides the uniqueness scope for code values. */\r\n export type ScopeGuid = GuidString;\r\n\r\n /** An optional number associated with a code that may be used for \"status\" information. Values must be defined by applications. */\r\n export type CodeState = number;\r\n\r\n /** The return status of an iteration function. The value \"stop\" causes the iteration to terminate. */\r\n export type IterationReturn = void | \"stop\";\r\n\r\n /** An iteration function over codes in a code index. It is called with the Guid of a each code. */\r\n export type CodeIteration = (guid: GuidString) => IterationReturn;\r\n\r\n /** An iteration function over code specs in a code index. It is called with the name and json of a each code spec. */\r\n export type NameAndJsonIteration = (nameAndJson: NameAndJson) => IterationReturn;\r\n\r\n /** Argument for reserving an array of new codes. */\r\n export interface ReserveCodesArgs {\r\n /** an array of proposed codes to reserve.\r\n * @note the guid of each proposed code must be supplied by the caller.\r\n */\r\n readonly codes: CodeService.ProposedCode[];\r\n /** If true, unless all codes are available, don't reserve any codes. Otherwise reserve all available codes. */\r\n readonly allOrNothing?: true;\r\n }\r\n\r\n /** Argument for reserving a code from a code sequence. */\r\n export interface ReserveNextArgs {\r\n /** the properties of the new code */\r\n readonly code: CodeService.ProposedCodeProps;\r\n /** The code sequence and scope for the new code. */\r\n readonly from: SequenceScope;\r\n }\r\n\r\n /** Argument for reserving an array of codes from a code sequence. */\r\n export interface ReserveNextArrayArgs {\r\n /** an array of proposed codes to reserve. */\r\n readonly codes: CodeService.ProposedCodeProps[];\r\n /** The code sequence and scope for the new codes. */\r\n readonly from: CodeService.SequenceScope;\r\n /** If true, and in the event that the code sequence does not have enough available codes to fulfill all the entries in `codes`,\r\n * return as many as possible. Otherwise no codes are reserved. The `problems` member of the exception can be used to determine how many codes were available.\r\n * @note if `asManyAsPossible` is true, no error is thrown if the sequence becomes full. You must check the return value to see how many\r\n * were actually available. The `value` member will be undefined for any proposed codes that were not reserved.\r\n */\r\n readonly asManyAsPossible?: true;\r\n }\r\n\r\n /** Argument for updating an array of codes. */\r\n export interface UpdateCodesArgs {\r\n /** Properties of the codes to update */\r\n readonly props: CodeService.UpdatedCode[];\r\n /** If true, unless all codes are updated, don't update any codes. Otherwise update all possible codes. */\r\n readonly allOrNothing?: true;\r\n }\r\n\r\n /** Arguments for CodeService.makeProposedCode */\r\n export interface MakeProposedCodeArgs {\r\n readonly iModel: IModelDb;\r\n readonly code: Required<CodeProps>;\r\n readonly props: CodeService.CodeGuidStateJson;\r\n }\r\n\r\n /** The properties of an Element to be checked against the code index.\r\n * @see CodeService.verifyCode\r\n */\r\n export interface ElementCodeProps {\r\n /** iModel from which the code is being inserted/updated. */\r\n readonly iModel: IModelDb;\r\n /** Properties of the code */\r\n readonly props: {\r\n /** The imodel-specific code properties. */\r\n readonly code: CodeProps;\r\n /**\r\n * The federationGuid of the element being inserted or updated.\r\n * If federationGuid is defined, it is must match the value in the code index or an error is thrown.\r\n * If it is undefined, the value from the code index is returned here.\r\n */\r\n federationGuid?: GuidString;\r\n };\r\n }\r\n\r\n /** a name and a json object. Used for code specs, authors and origins. */\r\n export interface NameAndJson {\r\n readonly name: string;\r\n readonly json?: SettingObject;\r\n }\r\n\r\n /** A code Scope guid, and code spec name. */\r\n export interface ScopeAndSpec {\r\n readonly specName: CodeSpecName;\r\n readonly scopeGuid: ScopeGuid;\r\n }\r\n\r\n /** A code Scope guid, code spec, and code value. */\r\n export interface ScopeSpecAndValue extends ScopeAndSpec {\r\n readonly value: CodeValue;\r\n }\r\n\r\n /** The data held in a code index for a single code. */\r\n export interface CodeEntry {\r\n /** The name of the code spec for this code. */\r\n readonly specName: CodeSpecName;\r\n /** The guid of the entity that provides the scope for this code. */\r\n readonly scopeGuid: ScopeGuid;\r\n /** The value of this code. */\r\n readonly value: CodeValue;\r\n /** The guid of the entity this code identifies. */\r\n readonly guid: CodeGuid;\r\n /** the state of the code. May be undefined. */\r\n readonly state?: CodeState;\r\n /** The name of the originating source of this code (usually an iModel Guid). May be undefined. */\r\n readonly origin: CodeOriginName;\r\n /** The name of the author of this code. May be undefined. */\r\n readonly author?: AuthorName;\r\n /** Option json properties associated with this code. May be undefined. */\r\n readonly json?: SettingObject;\r\n }\r\n\r\n /** A filter used to limit and/or sort the values returned by an iteration. */\r\n export interface ValueFilter {\r\n /** A value filter. May include wild cards when used with `GLOB` or `LIKE` */\r\n readonly value?: string;\r\n /** The comparison operator for `value`. Default is `=` */\r\n readonly valueCompare?: \"GLOB\" | \"LIKE\" | \"NOT GLOB\" | \"NOT LIKE\" | \"=\" | \"<\" | \">\";\r\n /** Order results ascending or descending. If not supplied, the results are unordered (random). */\r\n readonly orderBy?: \"ASC\" | \"DESC\";\r\n /** An SQL expression to further filter results. This string is appended to the `WHERE` clause with an `AND` (that should not be part of the sqlExpression) */\r\n readonly sqlExpression?: string;\r\n }\r\n\r\n /** A filter to limit and/or sort the values for the [[CodeIndex.forAllCodes]] iteration. */\r\n export interface CodeFilter extends ValueFilter {\r\n /** If supplied, limit results to only those with this spec */\r\n readonly specName?: CodeSpecName;\r\n /** If supplied, limit results to only those with this scope Guid */\r\n readonly scopeGuid?: ScopeGuid;\r\n /** If supplied, limit results to only those with this origin */\r\n readonly origin?: CodeOriginName;\r\n }\r\n\r\n /** Author and origin information supplied when codes are reserved. */\r\n export interface AuthorAndOrigin {\r\n /** The name of the individual or group for whom the code was reserved. */\r\n readonly author: Mutable<NameAndJson>;\r\n /** The identity of the \"originator\" of the code. This is usually a guid of an iModel, but can be any unique string. */\r\n readonly origin: Mutable<NameAndJson>;\r\n }\r\n\r\n /** The Guid, state, and json properties of a code. */\r\n export interface CodeGuidStateJson {\r\n /** The Guid of the new code. This must be always be supplied by the application. */\r\n readonly guid: CodeGuid;\r\n /** An optional value for the state of the code. */\r\n readonly state?: CodeState;\r\n /** An optional json object to be stored with the code. */\r\n readonly json?: SettingObject;\r\n }\r\n\r\n /** Properties of a \"proposed\" new code to be reserved.\r\n * @note the Guid of the entity identified by this code *must* be supplied, but `value` is optional, since\r\n * this may be used to reserve codes from a sequence where the value is generated.\r\n */\r\n export interface ProposedCodeProps extends CodeGuidStateJson {\r\n /** The value for the proposed code.\r\n * @note For code sequence operations, this value is ignored on input and is set with a new value from the sequence on successful return.\r\n */\r\n value?: CodeValue;\r\n }\r\n\r\n /** Properties of a proposed new code that is not from a code sequence (its `value` is required). */\r\n export type ProposedCode = ProposedCodeProps & ScopeSpecAndValue;\r\n\r\n /** Properties that describe a code sequence and a scope and spec for a proposed code or array of codes from a sequence. */\r\n export interface SequenceScope extends ScopeAndSpec {\r\n /** The code sequence. */\r\n readonly seq: CodeSequence;\r\n /** A valid current value. If supplied, the returned value will always be later in the sequence than this. */\r\n readonly start?: CodeValue;\r\n }\r\n\r\n /** Properties of a code to be updated.\r\n * @note The `guid` member identifies the code to be updated and is required.\r\n * All other properties are optional - if `undefined`, its value is not changed.\r\n */\r\n export type UpdatedCode = MarkRequired<Partial<ProposedCode>, \"guid\">;\r\n\r\n /** A proposed code that could not be reserved due to some error. */\r\n export interface ReserveProblem {\r\n /** the proposed code that failed. */\r\n readonly code: ProposedCode;\r\n /** the reason for the failure */\r\n readonly errorId: ErrorId;\r\n /** the error message from the exception for this proposed code. */\r\n readonly message: string;\r\n }\r\n\r\n /** A update to a code that failed for some error. */\r\n export interface UpdateProblem {\r\n /** The properties of the code that was to be updated */\r\n readonly prop: UpdatedCode;\r\n /** the reason for the failure */\r\n readonly errorId: ErrorId;\r\n /** the error message from the exception for the update request. */\r\n readonly message: string;\r\n }\r\n\r\n /**\r\n * A sequence of code values following a increasing pattern. Valid code sequences must have a first value, a last value, and\r\n * a way to get the next valid value from an existing valid value.\r\n * Code sequences have a `sequenceName` so they can be registered using `CodeService.registerSequence`.\r\n */\r\n export interface CodeSequence {\r\n /** the name of this CodeSequence. */\r\n get sequenceName(): string;\r\n /** Get the first valid value for this CodeSequence */\r\n getFirstValue(): CodeValue;\r\n /** Get the last valid value for this CodeSequence */\r\n getLastValue(): CodeValue;\r\n /** Get the next valid value for this CodeSequence from the supplied value.\r\n * If the sequence is full (that is, the next value is greater than the last value, this method should throw with errorId=\"SequenceFull\".\r\n * @return the next valid value according to the rules of this CodeSequence.\r\n */\r\n getNextValue(code: CodeValue): CodeValue;\r\n /** Determine whether this supplied value is valid for this sequence. */\r\n isValidCode(code: CodeValue): boolean;\r\n }\r\n\r\n /** @internal */\r\n export interface FontIndexProps {\r\n id?: number;\r\n fontType: FontType;\r\n fontName: string;\r\n }\r\n /** @internal */\r\n export interface BisCodeSpecIndexProps {\r\n id?: number;\r\n name: string;\r\n props: string;\r\n }\r\n\r\n /** Exception class thrown by `CodeService` methods. */\r\n export class Error extends BentleyError {\r\n /** A string that indicates the type of problem that caused the exception. */\r\n public readonly errorId: ErrorId;\r\n /** For [[CodeService.reserveCodes]] and [[CodeService.updateCodes]], a list of the problem details. */\r\n public readonly problems?: ReserveProblem[] | UpdateProblem[];\r\n\r\n /** @internal */\r\n constructor(errorId: ErrorId, errNum: number, message: string, problems?: ReserveProblem[] | UpdateProblem[]) {\r\n super(errNum, message);\r\n this.errorId = errorId;\r\n this.problems = problems;\r\n }\r\n }\r\n\r\n /** Identifiers for exceptions thrown by `CodeService` methods.\r\n * @see [[CodeService.Error.errorId]]\r\n */\r\n export type ErrorId =\r\n \"BadIndexProps\" |\r\n \"CorruptIModel\" |\r\n \"CorruptIndex\" |\r\n \"DuplicateValue\" |\r\n \"GuidIsInUse\" |\r\n \"GuidMismatch\" |\r\n \"IllegalValue\" |\r\n \"InconsistentIModels\" |\r\n \"IndexReadonly\" |\r\n \"InvalidCodeScope\" |\r\n \"InvalidGuid\" |\r\n \"InvalidSequence\" |\r\n \"MissingCode\" |\r\n \"MissingGuid\" |\r\n \"MissingInput\" |\r\n \"MissingSpec\" |\r\n \"NoCodeIndex\" |\r\n \"NotAuthorized\" |\r\n \"SequenceFull\" |\r\n \"ReserveErrors\" |\r\n \"SequenceNotFound\" |\r\n \"SqlLogicError\" |\r\n \"UpdateErrors\" |\r\n \"ValueIsInUse\" |\r\n \"WrongVersion\";\r\n\r\n}\r\n"]}
@@ -96,7 +96,7 @@ export declare class ChannelRootAspect extends ElementUniqueAspect {
96
96
  /** @internal */
97
97
  static get className(): string;
98
98
  /** Insert a ChannelRootAspect on the specified element.
99
- * @deprecated in 4.0 use [[ChannelControl.insertChannelSubject]]
99
+ * @deprecated in 4.0 use [[ChannelControl.makeChannelRoot]]. This method does not enforce the rule that channels may not nest and is therefore dangerous.
100
100
  */
101
101
  static insert(iModel: IModelDb, ownerId: Id64String, channelName: string): void;
102
102
  }
@@ -94,7 +94,7 @@ class ChannelRootAspect extends ElementUniqueAspect {
94
94
  /** @internal */
95
95
  static get className() { return "ChannelRootAspect"; }
96
96
  /** Insert a ChannelRootAspect on the specified element.
97
- * @deprecated in 4.0 use [[ChannelControl.insertChannelSubject]]
97
+ * @deprecated in 4.0 use [[ChannelControl.makeChannelRoot]]. This method does not enforce the rule that channels may not nest and is therefore dangerous.
98
98
  */
99
99
  static insert(iModel, ownerId, channelName) {
100
100
  const props = { classFullName: this.classFullName, element: { id: ownerId }, owner: channelName };
@@ -1 +1 @@
1
- {"version":3,"file":"ElementAspect.js","sourceRoot":"","sources":["../../src/ElementAspect.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,oDAA+I;AAC/I,qCAAkC;AAGlC,sDAA2D;AA0B3D;;;;GAIG;AACH,MAAa,aAAc,SAAQ,eAAM;IACvC,gBAAgB;IACT,MAAM,KAAc,SAAS,KAAa,OAAO,eAAe,CAAC,CAAC,CAAC;IAG1E,gBAAgB;IAChB,YAAY,KAAyB,EAAE,MAAgB;QACrD,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,4BAAc,CAAC,QAAQ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;WAEG;QACH,uBAAe,CAAA;IACjB,CAAC,EATW,IAAI,GAAJ,yBAAI,KAAJ,yBAAI,QASf;AACH,CAAC,EAdgB,oBAAoB,GAApB,4BAAoB,KAApB,4BAAoB,QAcpC","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 ElementAspects\r\n */\r\n\r\nimport { ChannelRootAspectProps, ElementAspectProps, EntityReferenceSet, ExternalSourceAspectProps, RelatedElement } from \"@itwin/core-common\";\r\nimport { Entity } from \"./Entity\";\r\nimport { IModelDb } from \"./IModelDb\";\r\nimport { ECSqlStatement } from \"./ECSqlStatement\";\r\nimport { DbResult, Id64String } from \"@itwin/core-bentley\";\r\n\r\n/** Argument for the `ElementAspect.onXxx` static methods\r\n * @beta\r\n */\r\nexport interface OnAspectArg {\r\n /** The iModel for the aspect affected by this event. */\r\n iModel: IModelDb;\r\n /** The model for the aspect affected by this event */\r\n model: Id64String;\r\n}\r\n/** Argument for the `ElementAspect.onXxx` static methods that supply the properties of an aspect to be inserted or updated.\r\n * @beta\r\n */\r\nexport interface OnAspectPropsArg extends OnAspectArg {\r\n /** The new properties of the aspect affected by this event. */\r\n props: Readonly<ElementAspectProps>;\r\n}\r\n/** Argument for the `ElementAspect.onXxx` static methods that only supply the Id of the affected aspect.\r\n * @beta\r\n */\r\nexport interface OnAspectIdArg extends OnAspectArg {\r\n /** The Id of the aspect affected by this event */\r\n aspectId: Id64String;\r\n}\r\n\r\n/** An Element Aspect is a class that defines a set of properties that are related to (and owned by) a single element.\r\n * Semantically, an ElementAspect can be considered part of the Element. Thus, an ElementAspect is deleted if its owning Element is deleted.\r\n * BIS Guideline: Subclass ElementUniqueAspect or ElementMultiAspect rather than subclassing ElementAspect directly.\r\n * @public\r\n */\r\nexport class ElementAspect extends Entity {\r\n /** @internal */\r\n public static override get className(): string { return \"ElementAspect\"; }\r\n public element: RelatedElement;\r\n\r\n /** @internal */\r\n constructor(props: ElementAspectProps, iModel: IModelDb) {\r\n super(props, iModel);\r\n this.element = RelatedElement.fromJSON(props.element)!; // eslint-disable-line @typescript-eslint/no-non-null-assertion\r\n }\r\n\r\n /** @internal */\r\n public override toJSON(): ElementAspectProps {\r\n const val = super.toJSON() as ElementAspectProps;\r\n val.element = this.element;\r\n return val;\r\n }\r\n\r\n /** Called before a new ElementAspect is inserted.\r\n * @note throw an exception to disallow the insert\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onInsert(arg: OnAspectPropsArg): void {\r\n arg.iModel.channels.verifyChannel(arg.model);\r\n }\r\n\r\n /** Called after a new ElementAspect was inserted.\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onInserted(_arg: OnAspectPropsArg): void { }\r\n\r\n /** Called before an ElementAspect is updated.\r\n * @note throw an exception to disallow the update\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onUpdate(arg: OnAspectPropsArg): void {\r\n arg.iModel.channels.verifyChannel(arg.model);\r\n }\r\n\r\n /** Called after an ElementAspect was updated.\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onUpdated(_arg: OnAspectPropsArg): void { }\r\n\r\n /** Called before an ElementAspect is deleted.\r\n * @note throw an exception to disallow the delete\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onDelete(arg: OnAspectIdArg): void {\r\n arg.iModel.channels.verifyChannel(arg.model);\r\n }\r\n\r\n /** Called after an ElementAspect was deleted.\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onDeleted(_arg: OnAspectIdArg): void { }\r\n}\r\n\r\n/** An Element Unique Aspect is an ElementAspect where there can be only zero or one instance of the Element Aspect class per Element.\r\n * @public\r\n */\r\nexport class ElementUniqueAspect extends ElementAspect {\r\n /** @internal */\r\n public static override get className(): string { return \"ElementUniqueAspect\"; }\r\n}\r\n\r\n/** An Element Multi-Aspect is an ElementAspect where there can be **n** instances of the Element Aspect class per Element.\r\n * @public\r\n */\r\nexport class ElementMultiAspect extends ElementAspect {\r\n /** @internal */\r\n public static override get className(): string { return \"ElementMultiAspect\"; }\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport class ChannelRootAspect extends ElementUniqueAspect {\r\n /** @internal */\r\n public static override get className(): string { return \"ChannelRootAspect\"; }\r\n /** Insert a ChannelRootAspect on the specified element.\r\n * @deprecated in 4.0 use [[ChannelControl.insertChannelSubject]]\r\n */\r\n public static insert(iModel: IModelDb, ownerId: Id64String, channelName: string) {\r\n const props: ChannelRootAspectProps = { classFullName: this.classFullName, element: { id: ownerId }, owner: channelName };\r\n iModel.elements.insertAspect(props);\r\n }\r\n}\r\n\r\n/** An ElementMultiAspect that stores synchronization information for an Element originating from an external source.\r\n * @note The associated ECClass was added to the BisCore schema in version 1.0.2\r\n * @public\r\n */\r\nexport class ExternalSourceAspect extends ElementMultiAspect {\r\n /** @internal */\r\n public static override get className(): string { return \"ExternalSourceAspect\"; }\r\n\r\n /** An element that scopes the combination of `kind` and `identifier` to uniquely identify the object from the external source.\r\n * @note Warning: in a future major release the `scope` property will be optional, since the scope is intended to be potentially invalid.\r\n * all references should treat it as potentially undefined, but we cannot change the type yet since that is a breaking change.\r\n */\r\n public scope: RelatedElement;\r\n /** The identifier of the object in the source repository. */\r\n public identifier: string;\r\n /** The kind of object within the source repository. */\r\n public kind: string;\r\n /** The cryptographic hash (any algorithm) of the source object's content. If defined, it must be guaranteed to change when the source object's content changes. */\r\n public checksum?: string;\r\n /** An optional value that is typically a version number or a pseudo version number like last modified time.\r\n * It will be used by the synchronization process to detect that a source object is unchanged so that computing a cryptographic hash can be avoided.\r\n * If present, this value must be guaranteed to change when any of the source object's content changes.\r\n */\r\n public version?: string;\r\n /** A place where additional JSON properties can be stored. For example, provenance information or properties relating to the synchronization process.\r\n * @note Warning: in a future major release, the type of `jsonProperties` will be changed to object, and itwin.js will automatically stringify it when writing to the iModel.\r\n * This will be a breaking change, since application code will have to change from supplying a string to supplying an object.\r\n */\r\n public jsonProperties?: string;\r\n /** The source of the imported/synchronized object. Should point to an instance of [ExternalSource]($backend). */\r\n public source?: RelatedElement;\r\n\r\n /** @internal */\r\n constructor(props: ExternalSourceAspectProps, iModel: IModelDb) {\r\n super(props, iModel);\r\n this.scope = RelatedElement.fromJSON(props.scope)!; // eslint-disable-line @typescript-eslint/no-non-null-assertion\r\n this.source = RelatedElement.fromJSON(props.source);\r\n this.identifier = props.identifier;\r\n this.kind = props.kind;\r\n this.checksum = props.checksum;\r\n this.version = props.version;\r\n this.jsonProperties = props.jsonProperties;\r\n }\r\n\r\n /** @deprecated in 3.x. findAllBySource */\r\n public static findBySource(iModelDb: IModelDb, scope: Id64String, kind: string, identifier: string): { elementId?: Id64String, aspectId?: Id64String } {\r\n const sql = `SELECT Element.Id, ECInstanceId FROM ${ExternalSourceAspect.classFullName} WHERE (Scope.Id=:scope AND Kind=:kind AND Identifier=:identifier)`;\r\n let elementId: Id64String | undefined;\r\n let aspectId: Id64String | undefined;\r\n iModelDb.withPreparedStatement(sql, (statement: ECSqlStatement) => {\r\n statement.bindId(\"scope\", scope);\r\n statement.bindString(\"kind\", kind);\r\n statement.bindString(\"identifier\", identifier);\r\n if (DbResult.BE_SQLITE_ROW === statement.step()) {\r\n elementId = statement.getValue(0).getId();\r\n aspectId = statement.getValue(1).getId();\r\n }\r\n });\r\n return { elementId, aspectId };\r\n }\r\n\r\n /** Look up the elements that contain one or more ExternalSourceAspect with the specified Scope, Kind, and Identifier.\r\n * The result of this function is an array of all of the ExternalSourceAspects that were found, each associated with the owning element.\r\n * A given element could have more than one ExternalSourceAspect with the given scope, kind, and identifier.\r\n * Also, many elements could have ExternalSourceAspect with the same scope, kind, and identifier.\r\n * Therefore, the result array could have more than one entry with the same elementId.\r\n * Aspects are never shared. Each aspect has its own unique ECInstanceId.\r\n * @param iModelDb The iModel to query\r\n * @param scope The scope of the ExternalSourceAspects to find\r\n * @param kind The kind of the ExternalSourceAspects to find\r\n * @param identifier The identifier of the ExternalSourceAspects to find\r\n * @returns the query results\r\n */\r\n public static findAllBySource(iModelDb: IModelDb, scope: Id64String, kind: string, identifier: string): Array<{ elementId: Id64String, aspectId: Id64String }> {\r\n const sql = `SELECT Element.Id, ECInstanceId FROM ${ExternalSourceAspect.classFullName} WHERE (Scope.Id=:scope AND Kind=:kind AND Identifier=:identifier)`;\r\n const found: Array<{ elementId: Id64String, aspectId: Id64String }> = [];\r\n iModelDb.withPreparedStatement(sql, (statement: ECSqlStatement) => {\r\n statement.bindId(\"scope\", scope);\r\n statement.bindString(\"kind\", kind);\r\n statement.bindString(\"identifier\", identifier);\r\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\r\n found.push({ elementId: statement.getValue(0).getId(), aspectId: statement.getValue(1).getId() });\r\n }\r\n });\r\n return found;\r\n }\r\n\r\n /** @internal */\r\n public override toJSON(): ExternalSourceAspectProps {\r\n const val = super.toJSON() as ExternalSourceAspectProps;\r\n val.scope = this.scope;\r\n val.source = this.source;\r\n val.identifier = this.identifier;\r\n val.kind = this.kind;\r\n val.checksum = this.checksum;\r\n val.version = this.version;\r\n val.jsonProperties = this.jsonProperties;\r\n return val;\r\n }\r\n\r\n protected override collectReferenceIds(referenceIds: EntityReferenceSet): void {\r\n super.collectReferenceIds(referenceIds);\r\n if (this.scope)\r\n referenceIds.addElement(this.scope.id);\r\n referenceIds.addElement(this.element.id);\r\n if (this.source)\r\n referenceIds.addElement(this.source.id);\r\n }\r\n}\r\n\r\n/** @public */\r\nexport namespace ExternalSourceAspect { // eslint-disable-line no-redeclare\r\n /** Standard values for the `Kind` property of `ExternalSourceAspect`.\r\n * @public\r\n */\r\n export enum Kind {\r\n /** Indicates that the [[ExternalSourceAspect]] is storing [[Element]] provenance */\r\n Element = \"Element\",\r\n /** Indicates that the [[ExternalSourceAspect]] is storing [[Relationship]] provenance */\r\n Relationship = \"Relationship\",\r\n /** Indicates that the [[ExternalSourceAspect]] is storing *scope* provenance\r\n * @see [[ExternalSourceAspect.scope]]\r\n */\r\n Scope = \"Scope\",\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"ElementAspect.js","sourceRoot":"","sources":["../../src/ElementAspect.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,oDAA+I;AAC/I,qCAAkC;AAGlC,sDAA2D;AA0B3D;;;;GAIG;AACH,MAAa,aAAc,SAAQ,eAAM;IACvC,gBAAgB;IACT,MAAM,KAAc,SAAS,KAAa,OAAO,eAAe,CAAC,CAAC,CAAC;IAG1E,gBAAgB;IAChB,YAAY,KAAyB,EAAE,MAAgB;QACrD,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,4BAAc,CAAC,QAAQ,CAAC,KAAK,CAAC,OAAO,CAAE,CAAC,CAAC,+DAA+D;IACzH,CAAC;IAED,gBAAgB;IACA,MAAM;QACpB,MAAM,GAAG,GAAG,KAAK,CAAC,MAAM,EAAwB,CAAC;QACjD,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAC3B,OAAO,GAAG,CAAC;IACb,CAAC;IAED;;;;OAIG;IACO,MAAM,CAAC,QAAQ,CAAC,GAAqB;QAC7C,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC;IAED;;;OAGG;IACO,MAAM,CAAC,UAAU,CAAC,IAAsB,IAAU,CAAC;IAE7D;;;;OAIG;IACO,MAAM,CAAC,QAAQ,CAAC,GAAqB;QAC7C,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC/C,CAAC;IAED;;;OAGG;IACO,MAAM,CAAC,SAAS,CAAC,IAAsB,IAAU,CAAC;IAE5D;;;;OAIG;IACO,MA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AC;IAEkB,mBAAmB,CAAC,YAAgC;QACrE,KAAK,CAAC,mBAAmB,CAAC,YAAY,CAAC,CAAC;QACxC,IAAI,IAAI,CAAC,KAAK;YACZ,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACzC,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;QACzC,IAAI,IAAI,CAAC,MAAM;YACb,YAAY,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAC5C,CAAC;CACF;AAxGD,oDAwGC;AAED,cAAc;AACd,WAAiB,oBAAoB;IACnC;;OAEG;IACH,IAAY,IASX;IATD,WAAY,IAAI;QACd,oFAAoF;QACpF,2BAAmB,CAAA;QACnB,yFAAyF;QACzF,qCAA6B,CAAA;QAC7B;;WAEG;QACH,uBAAe,CAAA;IACjB,CAAC,EATW,IAAI,GAAJ,yBAAI,KAAJ,yBAAI,QASf;AACH,CAAC,EAdgB,oBAAoB,GAApB,4BAAoB,KAApB,4BAAoB,QAcpC","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 ElementAspects\r\n */\r\n\r\nimport { ChannelRootAspectProps, ElementAspectProps, EntityReferenceSet, ExternalSourceAspectProps, RelatedElement } from \"@itwin/core-common\";\r\nimport { Entity } from \"./Entity\";\r\nimport { IModelDb } from \"./IModelDb\";\r\nimport { ECSqlStatement } from \"./ECSqlStatement\";\r\nimport { DbResult, Id64String } from \"@itwin/core-bentley\";\r\n\r\n/** Argument for the `ElementAspect.onXxx` static methods\r\n * @beta\r\n */\r\nexport interface OnAspectArg {\r\n /** The iModel for the aspect affected by this event. */\r\n iModel: IModelDb;\r\n /** The model for the aspect affected by this event */\r\n model: Id64String;\r\n}\r\n/** Argument for the `ElementAspect.onXxx` static methods that supply the properties of an aspect to be inserted or updated.\r\n * @beta\r\n */\r\nexport interface OnAspectPropsArg extends OnAspectArg {\r\n /** The new properties of the aspect affected by this event. */\r\n props: Readonly<ElementAspectProps>;\r\n}\r\n/** Argument for the `ElementAspect.onXxx` static methods that only supply the Id of the affected aspect.\r\n * @beta\r\n */\r\nexport interface OnAspectIdArg extends OnAspectArg {\r\n /** The Id of the aspect affected by this event */\r\n aspectId: Id64String;\r\n}\r\n\r\n/** An Element Aspect is a class that defines a set of properties that are related to (and owned by) a single element.\r\n * Semantically, an ElementAspect can be considered part of the Element. Thus, an ElementAspect is deleted if its owning Element is deleted.\r\n * BIS Guideline: Subclass ElementUniqueAspect or ElementMultiAspect rather than subclassing ElementAspect directly.\r\n * @public\r\n */\r\nexport class ElementAspect extends Entity {\r\n /** @internal */\r\n public static override get className(): string { return \"ElementAspect\"; }\r\n public element: RelatedElement;\r\n\r\n /** @internal */\r\n constructor(props: ElementAspectProps, iModel: IModelDb) {\r\n super(props, iModel);\r\n this.element = RelatedElement.fromJSON(props.element)!; // eslint-disable-line @typescript-eslint/no-non-null-assertion\r\n }\r\n\r\n /** @internal */\r\n public override toJSON(): ElementAspectProps {\r\n const val = super.toJSON() as ElementAspectProps;\r\n val.element = this.element;\r\n return val;\r\n }\r\n\r\n /** Called before a new ElementAspect is inserted.\r\n * @note throw an exception to disallow the insert\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onInsert(arg: OnAspectPropsArg): void {\r\n arg.iModel.channels.verifyChannel(arg.model);\r\n }\r\n\r\n /** Called after a new ElementAspect was inserted.\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onInserted(_arg: OnAspectPropsArg): void { }\r\n\r\n /** Called before an ElementAspect is updated.\r\n * @note throw an exception to disallow the update\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onUpdate(arg: OnAspectPropsArg): void {\r\n arg.iModel.channels.verifyChannel(arg.model);\r\n }\r\n\r\n /** Called after an ElementAspect was updated.\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onUpdated(_arg: OnAspectPropsArg): void { }\r\n\r\n /** Called before an ElementAspect is deleted.\r\n * @note throw an exception to disallow the delete\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onDelete(arg: OnAspectIdArg): void {\r\n arg.iModel.channels.verifyChannel(arg.model);\r\n }\r\n\r\n /** Called after an ElementAspect was deleted.\r\n * @note If you override this method, you must call super.\r\n * @beta\r\n */\r\n protected static onDeleted(_arg: OnAspectIdArg): void { }\r\n}\r\n\r\n/** An Element Unique Aspect is an ElementAspect where there can be only zero or one instance of the Element Aspect class per Element.\r\n * @public\r\n */\r\nexport class ElementUniqueAspect extends ElementAspect {\r\n /** @internal */\r\n public static override get className(): string { return \"ElementUniqueAspect\"; }\r\n}\r\n\r\n/** An Element Multi-Aspect is an ElementAspect where there can be **n** instances of the Element Aspect class per Element.\r\n * @public\r\n */\r\nexport class ElementMultiAspect extends ElementAspect {\r\n /** @internal */\r\n public static override get className(): string { return \"ElementMultiAspect\"; }\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport class ChannelRootAspect extends ElementUniqueAspect {\r\n /** @internal */\r\n public static override get className(): string { return \"ChannelRootAspect\"; }\r\n /** Insert a ChannelRootAspect on the specified element.\r\n * @deprecated in 4.0 use [[ChannelControl.makeChannelRoot]]. This method does not enforce the rule that channels may not nest and is therefore dangerous.\r\n */\r\n public static insert(iModel: IModelDb, ownerId: Id64String, channelName: string) {\r\n const props: ChannelRootAspectProps = { classFullName: this.classFullName, element: { id: ownerId }, owner: channelName };\r\n iModel.elements.insertAspect(props);\r\n }\r\n}\r\n\r\n/** An ElementMultiAspect that stores synchronization information for an Element originating from an external source.\r\n * @note The associated ECClass was added to the BisCore schema in version 1.0.2\r\n * @public\r\n */\r\nexport class ExternalSourceAspect extends ElementMultiAspect {\r\n /** @internal */\r\n public static override get className(): string { return \"ExternalSourceAspect\"; }\r\n\r\n /** An element that scopes the combination of `kind` and `identifier` to uniquely identify the object from the external source.\r\n * @note Warning: in a future major release the `scope` property will be optional, since the scope is intended to be potentially invalid.\r\n * all references should treat it as potentially undefined, but we cannot change the type yet since that is a breaking change.\r\n */\r\n public scope: RelatedElement;\r\n /** The identifier of the object in the source repository. */\r\n public identifier: string;\r\n /** The kind of object within the source repository. */\r\n public kind: string;\r\n /** The cryptographic hash (any algorithm) of the source object's content. If defined, it must be guaranteed to change when the source object's content changes. */\r\n public checksum?: string;\r\n /** An optional value that is typically a version number or a pseudo version number like last modified time.\r\n * It will be used by the synchronization process to detect that a source object is unchanged so that computing a cryptographic hash can be avoided.\r\n * If present, this value must be guaranteed to change when any of the source object's content changes.\r\n */\r\n public version?: string;\r\n /** A place where additional JSON properties can be stored. For example, provenance information or properties relating to the synchronization process.\r\n * @note Warning: in a future major release, the type of `jsonProperties` will be changed to object, and itwin.js will automatically stringify it when writing to the iModel.\r\n * This will be a breaking change, since application code will have to change from supplying a string to supplying an object.\r\n */\r\n public jsonProperties?: string;\r\n /** The source of the imported/synchronized object. Should point to an instance of [ExternalSource]($backend). */\r\n public source?: RelatedElement;\r\n\r\n /** @internal */\r\n constructor(props: ExternalSourceAspectProps, iModel: IModelDb) {\r\n super(props, iModel);\r\n this.scope = RelatedElement.fromJSON(props.scope)!; // eslint-disable-line @typescript-eslint/no-non-null-assertion\r\n this.source = RelatedElement.fromJSON(props.source);\r\n this.identifier = props.identifier;\r\n this.kind = props.kind;\r\n this.checksum = props.checksum;\r\n this.version = props.version;\r\n this.jsonProperties = props.jsonProperties;\r\n }\r\n\r\n /** @deprecated in 3.x. findAllBySource */\r\n public static findBySource(iModelDb: IModelDb, scope: Id64String, kind: string, identifier: string): { elementId?: Id64String, aspectId?: Id64String } {\r\n const sql = `SELECT Element.Id, ECInstanceId FROM ${ExternalSourceAspect.classFullName} WHERE (Scope.Id=:scope AND Kind=:kind AND Identifier=:identifier)`;\r\n let elementId: Id64String | undefined;\r\n let aspectId: Id64String | undefined;\r\n iModelDb.withPreparedStatement(sql, (statement: ECSqlStatement) => {\r\n statement.bindId(\"scope\", scope);\r\n statement.bindString(\"kind\", kind);\r\n statement.bindString(\"identifier\", identifier);\r\n if (DbResult.BE_SQLITE_ROW === statement.step()) {\r\n elementId = statement.getValue(0).getId();\r\n aspectId = statement.getValue(1).getId();\r\n }\r\n });\r\n return { elementId, aspectId };\r\n }\r\n\r\n /** Look up the elements that contain one or more ExternalSourceAspect with the specified Scope, Kind, and Identifier.\r\n * The result of this function is an array of all of the ExternalSourceAspects that were found, each associated with the owning element.\r\n * A given element could have more than one ExternalSourceAspect with the given scope, kind, and identifier.\r\n * Also, many elements could have ExternalSourceAspect with the same scope, kind, and identifier.\r\n * Therefore, the result array could have more than one entry with the same elementId.\r\n * Aspects are never shared. Each aspect has its own unique ECInstanceId.\r\n * @param iModelDb The iModel to query\r\n * @param scope The scope of the ExternalSourceAspects to find\r\n * @param kind The kind of the ExternalSourceAspects to find\r\n * @param identifier The identifier of the ExternalSourceAspects to find\r\n * @returns the query results\r\n */\r\n public static findAllBySource(iModelDb: IModelDb, scope: Id64String, kind: string, identifier: string): Array<{ elementId: Id64String, aspectId: Id64String }> {\r\n const sql = `SELECT Element.Id, ECInstanceId FROM ${ExternalSourceAspect.classFullName} WHERE (Scope.Id=:scope AND Kind=:kind AND Identifier=:identifier)`;\r\n const found: Array<{ elementId: Id64String, aspectId: Id64String }> = [];\r\n iModelDb.withPreparedStatement(sql, (statement: ECSqlStatement) => {\r\n statement.bindId(\"scope\", scope);\r\n statement.bindString(\"kind\", kind);\r\n statement.bindString(\"identifier\", identifier);\r\n while (DbResult.BE_SQLITE_ROW === statement.step()) {\r\n found.push({ elementId: statement.getValue(0).getId(), aspectId: statement.getValue(1).getId() });\r\n }\r\n });\r\n return found;\r\n }\r\n\r\n /** @internal */\r\n public override toJSON(): ExternalSourceAspectProps {\r\n const val = super.toJSON() as ExternalSourceAspectProps;\r\n val.scope = this.scope;\r\n val.source = this.source;\r\n val.identifier = this.identifier;\r\n val.kind = this.kind;\r\n val.checksum = this.checksum;\r\n val.version = this.version;\r\n val.jsonProperties = this.jsonProperties;\r\n return val;\r\n }\r\n\r\n protected override collectReferenceIds(referenceIds: EntityReferenceSet): void {\r\n super.collectReferenceIds(referenceIds);\r\n if (this.scope)\r\n referenceIds.addElement(this.scope.id);\r\n referenceIds.addElement(this.element.id);\r\n if (this.source)\r\n referenceIds.addElement(this.source.id);\r\n }\r\n}\r\n\r\n/** @public */\r\nexport namespace ExternalSourceAspect { // eslint-disable-line no-redeclare\r\n /** Standard values for the `Kind` property of `ExternalSourceAspect`.\r\n * @public\r\n */\r\n export enum Kind {\r\n /** Indicates that the [[ExternalSourceAspect]] is storing [[Element]] provenance */\r\n Element = \"Element\",\r\n /** Indicates that the [[ExternalSourceAspect]] is storing [[Relationship]] provenance */\r\n Relationship = \"Relationship\",\r\n /** Indicates that the [[ExternalSourceAspect]] is storing *scope* provenance\r\n * @see [[ExternalSourceAspect.scope]]\r\n */\r\n Scope = \"Scope\",\r\n }\r\n}\r\n"]}
@@ -2,9 +2,9 @@
2
2
  * @module NativeApp
3
3
  */
4
4
  import { EditingScopeNotifications, IpcAppNotifications, IpcListener, IpcSocketBackend, RemoveFunction, TxnNotifications } from "@itwin/core-common";
5
+ import { ProgressFunction, ProgressStatus } from "./CheckpointManager";
5
6
  import { BriefcaseDb, StandaloneDb } from "./IModelDb";
6
7
  import { IModelHostOptions } from "./IModelHost";
7
- import { ProgressFunction, ProgressStatus } from "./CheckpointManager";
8
8
  /**
9
9
  * Options for [[IpcHost.startup]]
10
10
  * @public
@@ -87,7 +87,13 @@ export declare class IpcHost {
87
87
  * @public
88
88
  */
89
89
  export declare abstract class IpcHandler {
90
- /** All subclasses must implement this method to specify their channel name. */
90
+ /**
91
+ * All subclasses *must* implement this method to specify their channel name.
92
+ *
93
+ * Channel names are the key that connects Handlers and senders. The channel name of IpcHandlers must exactly match the name used by senders.
94
+ * By convention, channel names should be prefixed by a *namespace* (e.g. `${appName}/`)
95
+ * unique enough to disambiguate them from channels for other apps that may be running in the same processes.
96
+ */
91
97
  abstract get channelName(): string;
92
98
  /**
93
99
  * Register this class as the handler for methods on its channel. This static method creates a new instance
@@ -1 +1 @@
1
- {"version":3,"file":"IpcHost.d.ts","sourceRoot":"","sources":["../../src/IpcHost.ts"],"names":[],"mappings":"AAIA;;GAEG;AAGH,OAAO,EACgC,yBAAyB,EAC9B,mBAAmB,EAAmB,WAAW,EAAE,gBAAgB,EAC/E,cAAc,EAA6C,gBAAgB,EAChG,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,WAAW,EAAY,YAAY,EAAE,MAAM,YAAY,CAAC;AACjE,OAAO,EAAc,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAE7D,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAEvE;;;IAGI;AACJ,MAAM,WAAW,WAAW;IAC1B,UAAU,CAAC,EAAE,iBAAiB,CAAC;IAC/B,OAAO,CAAC,EAAE;QACR,wGAAwG;QACxG,MAAM,CAAC,EAAE,gBAAgB,CAAC;QAE1B,iDAAiD;QACjD,UAAU,CAAC,EAAE;YACX,OAAO,CAAC,EAAE,OAAO,CAAC;SACnB,CAAC;KACH,CAAC;CACH;AAED;;;;GAIG;AACH,qBAAa,OAAO;IAClB,OAAc,OAAO,UAAS;IAC9B,OAAO,CAAC,MAAM,CAAC,IAAI,CAA+B;IAClD,2EAA2E;IAC3E,OAAO,CAAC,MAAM,KAAK,GAAG,GAA2C;IACjE,gIAAgI;IAChI,WAAkB,OAAO,IAAI,OAAO,CAAoC;IAExE;;;;OAIG;WACW,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,IAAI,EAAE,GAAG,EAAE,GAAG,IAAI;IAIzD;;;;;OAKG;WACW,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,GA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G,cAAc;IAGjF;;;;OAIG;WACW,cAAc,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,WAAW,GAAG,IAAI;IAI1E,OAAO,CAAC,MAAM,CAAC,MAAM;IAKrB,gBAAgB;WACF,iBAAiB,CAAC,CAAC,SAAS,MAAM,mBAAmB,EAAE,UAAU,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC;IAI/H,gBAAgB;WACF,UAAU,CAAC,CAAC,SAAS,MAAM,gBAAgB,EAAE,SAAS,EAAE,WAAW,GAAG,YAAY,EAAE,UAAU,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAIzJ,gBAAgB;WACF,kBAAkB,CAAC,CAAC,SAAS,MAAM,yBAAyB,EAAE,SAAS,EAAE,WAAW,GAAG,YAAY,EAAE,UAAU,EAAE,CAAC,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC;IAInL;;;;OAIG;WACiB,OAAO,CAAC,GAAG,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAY7D,mEAAmE;WAC/C,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAI9C;AAED;;;;;;;;;;;GAWG;AACH,8BAAsB,UAAU;IAC9B;;;;;;OAMG;IACH,aAAoB,WAAW,IAAI,MAAM,CAAC;IAE1C;;;;;OAKG;WACW,QAAQ,IAAI,cAAc;CAuBzC;AA+HD;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,cAAc,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,gBAAgB,CAa9I"}
@@ -10,10 +10,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
10
10
  exports.throttleProgressCallback = exports.IpcHandler = exports.IpcHost = void 0;
11
11
  const core_bentley_1 = require("@itwin/core-bentley");
12
12
  const core_common_1 = require("@itwin/core-common");
13
+ const CheckpointManager_1 = require("./CheckpointManager");
13
14
  const IModelDb_1 = require("./IModelDb");
14
15
  const IModelHost_1 = require("./IModelHost");
15
16
  const IModelTileRpcImpl_1 = require("./rpc-impl/IModelTileRpcImpl");
16
- const CheckpointManager_1 = require("./CheckpointManager");
17
17
  /**
18
18
  * Used by applications that have a dedicated backend. IpcHosts may send messages to their corresponding IpcApp.
19
19
  * @note if either end terminates, the other must too.
@@ -60,19 +60,19 @@ class IpcHost {
60
60
  }
61
61
  static notify(channel, briefcase, methodName, ...args) {
62
62
  if (this.isValid)
63
- return this.send(`${channel}:${briefcase.key}`, methodName, ...args);
63
+ return this.send(`${channel}/${briefcase.key}`, methodName, ...args);
64
64
  }
65
65
  /** @internal */
66
66
  static notifyIpcFrontend(methodName, ...args) {
67
- return IpcHost.send(core_common_1.IpcAppChannel.AppNotify, methodName, ...args);
67
+ return IpcHost.send(core_common_1.ipcAppChannels.appNotify, methodName, ...args);
68
68
  }
69
69
  /** @internal */
70
70
  static notifyTxns(briefcase, methodName, ...args) {
71
- this.notify(core_common_1.IpcAppChannel.Txns, briefcase, methodName, ...args);
71
+ this.notify(core_common_1.ipcAppChannels.txns, briefcase, methodName, ...args);
72
72
  }
73
73
  /** @internal */
74
74
  static notifyEditingScope(briefcase, methodName, ...args) {
75
- this.notify(core_common_1.IpcAppChannel.EditingScope, briefcase, methodName, ...args);
75
+ this.notify(core_common_1.ipcAppChannels.editingScope, briefcase, methodName, ...args);
76
76
  }
77
77
  /**
78
78
  * Start the backend of an Ipc app.
@@ -148,7 +148,7 @@ class IpcAppHandler extends IpcHandler {
148
148
  super(...arguments);
149
149
  this._iModelKeyToPullStatus = new Map();
150
150
  }
151
- get channelName() { return core_common_1.IpcAppChannel.Functions; }
151
+ get channelName() { return core_common_1.ipcAppChannels.functions; }
152
152
  async log(_timestamp, level, category, message, metaData) {
153
153
  switch (level) {
154
154
  case core_bent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AiB,CAAC,GAAW;QACxC,OAAO,mBAAQ,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,iBAAiB,EAAE,CAAC;IAC9D,CAAC;IAEM,KAAK,CAAC,gBAAgB,CAAC,IAAkB;QAC9C,OAAO,uBAAU,CAAC,QAAQ,CAAC,gBAAgB,CAAC,IAAI,CAAC,CAAC;IACpD,CAAC;CACF;AAED;;;GAGG;AACH,SAAgB,wBAAwB,CAAC,IAAsB,EAAE,UAAgC,EAAE,gBAAyB;IAC1H,MAAM,QAAQ,GAAG,gBAAgB,IAAI,GAAG,CAAC,CAAC,+DAA+D;IACzG,IAAI,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,QAAQ,CAAC;IACrC,MAAM,gBAAgB,GAAqB,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE;QAC3D,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,MAAM,IAAI,KAAK,IAAI,GAAG,IAAI,QAAQ,EAAE;YACtC,QAAQ,GAAG,GAAG,GAAG,QAAQ,CAAC;YAC1B,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;SAC5B;QACD,OAAO,UAAU,EAAE,CAAC;IACtB,CAAC,CAAC;IAEF,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAbD,4DAaC","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 NativeApp\r\n */\r\n\r\nimport { assert, BentleyError, IModelStatus, Logger, LogLevel, OpenMode } from \"@itwin/core-bentley\";\r\nimport {\r\n ChangesetIndex, ChangesetIndexAndId, EditingScopeNotifications, getPullChangesIpcChannel, IModelConnectionProps, IModelError, IModelRpcProps,\r\n IpcAppChannel, IpcAppFunctions, IpcAppNotifications, IpcInvokeReturn, IpcListener, IpcSocketBackend, iTwinChannel, OpenBriefcaseProps,\r\n PullChangesOptions, RemoveFunction, StandaloneOpenOptions, TileTreeContentIds, TxnNotifications,\r\n} from \"@itwin/core-common\";\r\nimport { IModelJsNative } from \"@bentley/imodeljs-native\";\r\nimport { BriefcaseDb, IModelDb, StandaloneDb } from \"./IModelDb\";\r\nimport { IModelHost, IModelHostOptions } from \"./IModelHost\";\r\nimport { cancelTileContentRequests } from \"./rpc-impl/IModelTileRpcImpl\";\r\nimport { ProgressFunction, ProgressStatus } from \"./CheckpointManager\";\r\n\r\n/**\r\n * Options for [[IpcHost.startup]]\r\n * @public\r\n */\r\nexport interface IpcHostOpts {\r\n iModelHost?: IModelHostOptions;\r\n ipcHost?: {\r\n /** The Ipc socket to use for communications with frontend. Allows undefined only for headless tests. */\r\n socket?: IpcSocketBackend;\r\n\r\n /** don't send stack information on exceptions */\r\n exceptions?: {\r\n noStack?: boolean;\r\n };\r\n };\r\n}\r\n\r\n/**\r\n * Used by applications that have a dedicated backend. IpcHosts may send messages to their corresponding IpcApp.\r\n * @note if either end terminates, the other must too.\r\n * @public\r\n */\r\nexport class IpcHost {\r\n public static noStack = false;\r\n private static _ipc: IpcSocketBackend | undefined;\r\n /** Get the implementation of the [IpcSocketBackend]($common) interface. */\r\n private static get ipc(): IpcSocketBackend { return this._ipc!; } // eslint-disable-line @typescript-eslint/no-non-null-assertion\r\n /** Determine whether Ipc is available for this backend. This will only be true if [[startup]] has been called on this class. */\r\n public static get isValid(): boolean { return undefined !== this._ipc; }\r\n\r\n /**\r\n * Send a message to the frontend over an Ipc channel.\r\n * @param channel the name of the channel matching the name registered with [[IpcApp.addListener]].\r\n * @param data The content of the message.\r\n */\r\n public static send(channel: string, ...data: any[]): void {\r\n this.ipc.send(iTwinChannel(channel), ...data);\r\n }\r\n\r\n /**\r\n * Establish a handler for an Ipc channel to receive [[Frontend.invoke]] calls\r\n * @param channel The name of the channel for this handler.\r\n * @param handler A function that supplies the implementation for `channel`\r\n * @note returns A function to call to remove the handler.\r\n */\r\n public static handle(channel: string, handler: (...args: any[]) => Promise<any>): RemoveFunction {\r\n return this.ipc.handle(iTwinChannel(channel), handler);\r\n }\r\n /**\r\n * Establish a handler to receive messages sent via [[IpcApp.send]].\r\n * @param channel The name of the channel for the messages.\r\n * @param listener A function called when messages are sent over `channel`\r\n * @note returns A function to call to remove the listener.\r\n */\r\n public static addListener(channel: string, listener: IpcListener): RemoveFunction {\r\n return this.ipc.addListener(iTwinChannel(channel), listener);\r\n }\r\n /**\r\n * Remove a previously registered listener\r\n * @param channel The name of the channel for the listener previously registered with [[addListener]]\r\n * @param listener The function passed to [[addListener]]\r\n */\r\n public static removeListener(channel: string, listener: IpcListener): void {\r\n this.ipc.removeListener(iTwinChannel(channel), listener);\r\n }\r\n\r\n private static notify(channel: string, briefcase: BriefcaseDb | StandaloneDb, methodName: string, ...args: any[]) {\r\n if (this.isValid)\r\n return this.send(`${channel}:${briefcase.key}`, methodName, ...args);\r\n }\r\n\r\n /** @internal */\r\n public static notifyIpcFrontend<T extends keyof IpcAppNotifications>(methodName: T, ...args: Parameters<IpcAppNotifications[T]>) {\r\n return IpcHost.send(IpcAppChannel.AppNotify, methodName, ...args);\r\n }\r\n\r\n /** @internal */\r\n public static notifyTxns<T extends keyof TxnNotifications>(briefcase: BriefcaseDb | StandaloneDb, methodName: T, ...args: Parameters<TxnNotifications[T]>) {\r\n this.notify(IpcAppChannel.Txns, briefcase, methodName, ...args);\r\n }\r\n\r\n /** @internal */\r\n public static notifyEditingScope<T extends keyof EditingScopeNotifications>(briefcase: BriefcaseDb | StandaloneDb, methodName: T, ...args: Parameters<EditingScopeNotifications[T]>) {\r\n this.notify(IpcAppChannel.EditingScope, briefcase, methodName, ...args);\r\n }\r\n\r\n /**\r\n * Start the backend of an Ipc app.\r\n * @param opt\r\n * @note this method calls [[IModelHost.startup]] internally.\r\n */\r\n public static async startup(opt?: IpcHostOpts): Promise<void> {\r\n this._ipc = opt?.ipcHost?.socket;\r\n if (opt?.ipcHost?.exceptions?.noStack)\r\n this.noStack = true;\r\n\r\n if (this.isValid) { // for tests, we use IpcHost but don't have a frontend\r\n IpcAppHandler.register();\r\n }\r\n\r\n await IModelHost.startup(opt?.iModelHost);\r\n }\r\n\r\n /** Shutdown IpcHost backend. Also calls [[IModelHost.shutdown]] */\r\n public static async shutdown(): Promise<void> {\r\n this._ipc = undefined;\r\n await IModelHost.shutdown();\r\n }\r\n}\r\n\r\n/**\r\n * Base class for all implementations of an Ipc interface.\r\n *\r\n * Create a subclass to implement your Ipc interface. Your class should be declared like this:\r\n * ```ts\r\n * class MyHandler extends IpcHandler implements MyInterface\r\n * ```\r\n * to ensure all methods and signatures are correct.\r\n *\r\n * Then, call `MyClass.register` at startup to connect your class to your channel.\r\n * @public\r\n */\r\nexport abstract class IpcHandler {\r\n /** All subclasses must implement this method to specify their channel name. */\r\n public abstract get channelName(): string;\r\n\r\n /**\r\n * Register this class as the handler for methods on its channel. This static method creates a new instance\r\n * that becomes the handler and is `this` when its methods are called.\r\n * @returns A function that can be called to remove the handler.\r\n * @note this method should only be called once per channel. If it is called multiple times, subsequent calls replace the previous ones.\r\n */\r\n public static register(): RemoveFunction {\r\n const impl = new (this as any)() as IpcHandler; // create an instance of subclass. \"as any\" is necessary because base class is abstract\r\n return IpcHost.handle(impl.channelName, async (_evt: Event, funcName: string, ...args: any[]): Promise<IpcInvokeReturn> => {\r\n try {\r\n const func = (impl as any)[funcName];\r\n if (typeof func !== \"function\")\r\n throw new IModelError(IModelStatus.FunctionNotFound, `Method \"${impl.constructor.name}.${funcName}\" not found on IpcHandler registered for channel: ${impl.channelName}`);\r\n\r\n return { result: await func.call(impl, ...args) };\r\n } catch (err: any) {\r\n const ret: IpcInvokeReturn = {\r\n error: {\r\n name: err.hasOwnProperty(\"name\") ? err.name : err.constructor?.name ?? \"Unknown Error\",\r\n message: err.message ?? BentleyError.getErrorMessage(err),\r\n errorNumber: err.errorNumber ?? 0,\r\n },\r\n };\r\n if (!IpcHost.noStack)\r\n ret.error.stack = BentleyError.getErrorStack(err);\r\n return ret;\r\n }\r\n });\r\n }\r\n}\r\n\r\n/**\r\n * Implementation of IpcAppFunctions\r\n */\r\nclass IpcAppHandler extends IpcHandler implements IpcAppFunctions {\r\n public get channelName() { return IpcAppChannel.Functions; }\r\n\r\n private _iModelKeyToPullStatus = new Map<string, ProgressStatus>();\r\n\r\n public async log(_timestamp: number, level: LogLevel, category: string, message: string, metaData?: any): Promise<void> {\r\n switch (level) {\r\n case LogLevel.Error:\r\n Logger.logError(category, message, metaData);\r\n break;\r\n case LogLevel.Info:\r\n Logger.logInfo(category, message, metaData);\r\n break;\r\n case LogLevel.Trace:\r\n Logger.logTrace(category, message, metaData);\r\n break;\r\n case LogLevel.Warning:\r\n Logger.logWarning(category, message, metaData);\r\n break;\r\n }\r\n }\r\n\r\n public async cancelTileContentRequests(tokenProps: IModelRpcProps, contentIds: TileTreeContentIds[]): Promise<void> {\r\n return cancelTileContentRequests(tokenProps, contentIds);\r\n }\r\n public async cancelElementGraphicsRequests(key: string, requestIds: string[]): Promise<void> {\r\n return IModelDb.findByKey(key).nativeDb.cancelElementGraphicsRequests(requestIds);\r\n }\r\n public async openBriefcase(args: OpenBriefcaseProps): Promise<IModelConnectionProps> {\r\n const db = await BriefcaseDb.open(args);\r\n return db.toJSON();\r\n }\r\n public async openStandalone(filePath: string, openMode: OpenMode, opts?: StandaloneOpenOptions): Promise<IModelConnectionProps> {\r\n return StandaloneDb.openFile(filePath, openMode, opts).getConnectionProps();\r\n }\r\n public async closeIModel(key: string): Promise<void> {\r\n IModelDb.findByKey(key).close();\r\n }\r\n public async saveChanges(key: string, description?: string): Promise<void> {\r\n IModelDb.findByKey(key).saveChanges(description);\r\n }\r\n public async hasPendingTxns(key: string): Promise<boolean> {\r\n return IModelDb.findByKey(key).nativeDb.hasPendingTxns();\r\n }\r\n\r\n public async isUndoPossible(key: string): Promise<boolean> {\r\n return IModelDb.findByKey(key).nativeDb.isUndoPossible();\r\n }\r\n public async isRedoPossible(key: string): Promise<boolean> {\r\n return IModelDb.findByKey(key).nativeDb.isRedoPossible();\r\n }\r\n public async getUndoString(key: string): Promise<string> {\r\n return IModelDb.findByKey(key).nativeDb.getUndoString();\r\n }\r\n public async getRedoString(key: string): Promise<string> {\r\n return IModelDb.findByKey(key).nativeDb.getUndoString();\r\n }\r\n\r\n public async pullChanges(key: string, toIndex?: ChangesetIndex, options?: PullChangesOptions): Promise<ChangesetIndexAndId> {\r\n const iModelDb = BriefcaseDb.findByKey(key);\r\n\r\n this._iModelKeyToPullStatus.set(key, ProgressStatus.Continue);\r\n const checkAbort = () => this._iModelKeyToPullStatus.get(key) ?? ProgressStatus.Continue;\r\n\r\n let onProgress: ProgressFunction | undefined;\r\n if (options?.reportProgress) {\r\n const progressCallback: ProgressFunction = (loaded, total) => {\r\n IpcHost.send(getPullChangesIpcChannel(iModelDb.iModelId), { loaded, total });\r\n return checkAbort();\r\n };\r\n onProgress = throttleProgressCallback(progressCallback, checkAbort, options?.progressInterval);\r\n } else if (options?.enableCancellation) {\r\n onProgress = checkAbort;\r\n }\r\n\r\n try {\r\n await iModelDb.pullChanges({ toIndex, onProgress });\r\n } finally {\r\n this._iModelKeyToPullStatus.delete(key);\r\n }\r\n\r\n return iModelDb.changeset as ChangesetIndexAndId;\r\n }\r\n public async cancelPullChangesRequest(key: string): Promise<void> {\r\n this._iModelKeyToPullStatus.set(key, ProgressStatus.Abort);\r\n }\r\n\r\n public async pushChanges(key: string, description: string): Promise<ChangesetIndexAndId> {\r\n const iModelDb = BriefcaseDb.findByKey(key);\r\n await iModelDb.pushChanges({ description });\r\n return iModelDb.changeset as ChangesetIndexAndId;\r\n }\r\n\r\n public async toggleGraphicalEditingScope(key: string, startSession: boolean): Promise<boolean> {\r\n const val: IModelJsNative.ErrorStatusOrResult<any, boolean> = IModelDb.findByKey(key).nativeDb.setGeometricModelTrackingEnabled(startSession);\r\n if (val.error)\r\n throw new IModelError(val.error.status, \"Failed to toggle graphical editing scope\");\r\n assert(undefined !== val.result);\r\n return val.result;\r\n }\r\n public async isGraphicalEditingSupported(key: string): Promise<boolean> {\r\n return IModelDb.findByKey(key).nativeDb.isGeometricModelTrackingSupported();\r\n }\r\n\r\n public async reverseTxns(key: string, numOperations: number): Promise<IModelStatus> {\r\n return IModelDb.findByKey(key).nativeDb.reverseTxns(numOperations);\r\n }\r\n public async reverseAllTxn(key: string): Promise<IModelStatus> {\r\n return IModelDb.findByKey(key).nativeDb.reverseAll();\r\n }\r\n public async reinstateTxn(key: string): Promise<IModelStatus> {\r\n return IModelDb.findByKey(key).nativeDb.reinstateTxn();\r\n }\r\n public async restartTxnSession(key: string): Promise<void> {\r\n return IModelDb.findByKey(key).nativeDb.restartTxnSession();\r\n }\r\n\r\n public async queryConcurrency(pool: \"io\" | \"cpu\"): Promise<number> {\r\n return IModelHost.platform.queryConcurrency(pool);\r\n }\r\n}\r\n\r\n/**\r\n * Prevents progress callback being called more frequently when provided interval.\r\n * @internal\r\n */\r\nexport function throttleProgressCallback(func: ProgressFunction, checkAbort: () => ProgressStatus, progressInterval?: number): ProgressFunction {\r\n const interval = progressInterval ?? 250; // by default, only send progress events every 250 milliseconds\r\n let nextTime = Date.now() + interval;\r\n const progressCallback: ProgressFunction = (loaded, total) => {\r\n const now = Date.now();\r\n if (loaded >= total || now >= nextTime) {\r\n nextTime = now + interval;\r\n return func(loaded, total);\r\n }\r\n return checkAbort();\r\n };\r\n\r\n return progressCallback;\r\n}\r\n"]}
1
+ {"version":3,"file":"IpcHost.js","sourceRoot":"","sources":["../../src/IpcHost.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAGH,sDAAqG;AACrG,oDAI4B;AAC5B,2DAAuE;AACvE,yCAAiE;AACjE,6CAA6D;AAC7D,oEAAyE;AAmBzE;;;;GAIG;AACH,MAAa,OAAO;IAGlB,2EAA2E;IACnE,MAAM,KAAK,GAAG,KAAuB,OAAO,IAAI,CAAC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AC1H,MAAM,QAAQ,GAAG,gBAAgB,IAAI,GAAG,CAAC,CAAC,+DAA+D;IACzG,IAAI,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,QAAQ,CAAC;IACrC,MAAM,gBAAgB,GAAqB,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE;QAC3D,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,MAAM,IAAI,KAAK,IAAI,GAAG,IAAI,QAAQ,EAAE;YACtC,QAAQ,GAAG,GAAG,GAAG,QAAQ,CAAC;YAC1B,OAAO,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;SAC5B;QACD,OAAO,UAAU,EAAE,CAAC;IACtB,CAAC,CAAC;IAEF,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAbD,4DAaC","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 NativeApp\r\n */\r\n\r\nimport { IModelJsNative } from \"@bentley/imodeljs-native\";\r\nimport { assert, BentleyError, IModelStatus, Logger, LogLevel, OpenMode } from \"@itwin/core-bentley\";\r\nimport {\r\n ChangesetIndex, ChangesetIndexAndId, EditingScopeNotifications, getPullChangesIpcChannel, IModelConnectionProps, IModelError, IModelRpcProps,\r\n ipcAppChannels, IpcAppFunctions, IpcAppNotifications, IpcInvokeReturn, IpcListener, IpcSocketBackend, iTwinChannel,\r\n OpenBriefcaseProps, PullChangesOptions, RemoveFunction, StandaloneOpenOptions, TileTreeContentIds, TxnNotifications,\r\n} from \"@itwin/core-common\";\r\nimport { ProgressFunction, ProgressStatus } from \"./CheckpointManager\";\r\nimport { BriefcaseDb, IModelDb, StandaloneDb } from \"./IModelDb\";\r\nimport { IModelHost, IModelHostOptions } from \"./IModelHost\";\r\nimport { cancelTileContentRequests } from \"./rpc-impl/IModelTileRpcImpl\";\r\n\r\n/**\r\n * Options for [[IpcHost.startup]]\r\n * @public\r\n */\r\nexport interface IpcHostOpts {\r\n iModelHost?: IModelHostOptions;\r\n ipcHost?: {\r\n /** The Ipc socket to use for communications with frontend. Allows undefined only for headless tests. */\r\n socket?: IpcSocketBackend;\r\n\r\n /** don't send stack information on exceptions */\r\n exceptions?: {\r\n noStack?: boolean;\r\n };\r\n };\r\n}\r\n\r\n/**\r\n * Used by applications that have a dedicated backend. IpcHosts may send messages to their corresponding IpcApp.\r\n * @note if either end terminates, the other must too.\r\n * @public\r\n */\r\nexport class IpcHost {\r\n public static noStack = false;\r\n private static _ipc: IpcSocketBackend | undefined;\r\n /** Get the implementation of the [IpcSocketBackend]($common) interface. */\r\n private static get ipc(): IpcSocketBackend { return this._ipc!; } // eslint-disable-line @typescript-eslint/no-non-null-assertion\r\n /** Determine whether Ipc is available for this backend. This will only be true if [[startup]] has been called on this class. */\r\n public static get isValid(): boolean { return undefined !== this._ipc; }\r\n\r\n /**\r\n * Send a message to the frontend over an Ipc channel.\r\n * @param channel the name of the channel matching the name registered with [[IpcApp.addListener]].\r\n * @param data The content of the message.\r\n */\r\n public static send(channel: string, ...data: any[]): void {\r\n this.ipc.send(iTwinChannel(channel), ...data);\r\n }\r\n\r\n /**\r\n * Establish a handler for an Ipc channel to receive [[Frontend.invoke]] calls\r\n * @param channel The name of the channel for this handler.\r\n * @param handler A function that supplies the implementation for `channel`\r\n * @note returns A function to call to remove the handler.\r\n */\r\n public static handle(channel: string, handler: (...args: any[]) => Promise<any>): RemoveFunction {\r\n return this.ipc.handle(iTwinChannel(channel), handler);\r\n }\r\n /**\r\n * Establish a handler to receive messages sent via [[IpcApp.send]].\r\n * @param channel The name of the channel for the messages.\r\n * @param listener A function called when messages are sent over `channel`\r\n * @note returns A function to call to remove the listener.\r\n */\r\n public static addListener(channel: string, listener: IpcListener): RemoveFunction {\r\n return this.ipc.addListener(iTwinChannel(channel), listener);\r\n }\r\n /**\r\n * Remove a previously registered listener\r\n * @param channel The name of the channel for the listener previously registered with [[addListener]]\r\n * @param listener The function passed to [[addListener]]\r\n */\r\n public static removeListener(channel: string, listener: IpcListener): void {\r\n this.ipc.removeListener(iTwinChannel(channel), listener);\r\n }\r\n\r\n private static notify(channel: string, briefcase: BriefcaseDb | StandaloneDb, methodName: string, ...args: any[]) {\r\n if (this.isValid)\r\n return this.send(`${channel}/${briefcase.key}`, methodName, ...args);\r\n }\r\n\r\n /** @internal */\r\n public static notifyIpcFrontend<T extends keyof IpcAppNotifications>(methodName: T, ...args: Parameters<IpcAppNotifications[T]>) {\r\n return IpcHost.send(ipcAppChannels.appNotify, methodName, ...args);\r\n }\r\n\r\n /** @internal */\r\n public static notifyTxns<T extends keyof TxnNotifications>(briefcase: BriefcaseDb | StandaloneDb, methodName: T, ...args: Parameters<TxnNotifications[T]>) {\r\n this.notify(ipcAppChannels.txns, briefcase, methodName, ...args);\r\n }\r\n\r\n /** @internal */\r\n public static notifyEditingScope<T extends keyof EditingScopeNotifications>(briefcase: BriefcaseDb | StandaloneDb, methodName: T, ...args: Parameters<EditingScopeNotifications[T]>) {\r\n this.notify(ipcAppChannels.editingScope, briefcase, methodName, ...args);\r\n }\r\n\r\n /**\r\n * Start the backend of an Ipc app.\r\n * @param opt\r\n * @note this method calls [[IModelHost.startup]] internally.\r\n */\r\n public static async startup(opt?: IpcHostOpts): Promise<void> {\r\n this._ipc = opt?.ipcHost?.socket;\r\n if (opt?.ipcHost?.exceptions?.noStack)\r\n this.noStack = true;\r\n\r\n if (this.isValid) { // for tests, we use IpcHost but don't have a frontend\r\n IpcAppHandler.register();\r\n }\r\n\r\n await IModelHost.startup(opt?.iModelHost);\r\n }\r\n\r\n /** Shutdown IpcHost backend. Also calls [[IModelHost.shutdown]] */\r\n public static async shutdown(): Promise<void> {\r\n this._ipc = undefined;\r\n await IModelHost.shutdown();\r\n }\r\n}\r\n\r\n/**\r\n * Base class for all implementations of an Ipc interface.\r\n *\r\n * Create a subclass to implement your Ipc interface. Your class should be declared like this:\r\n * ```ts\r\n * class MyHandler extends IpcHandler implements MyInterface\r\n * ```\r\n * to ensure all methods and signatures are correct.\r\n *\r\n * Then, call `MyClass.register` at startup to connect your class to your channel.\r\n * @public\r\n */\r\nexport abstract class IpcHandler {\r\n /**\r\n * All subclasses *must* implement this method to specify their channel name.\r\n *\r\n * Channel names are the key that connects Handlers and senders. The channel name of IpcHandlers must exactly match the name used by senders.\r\n * By convention, channel names should be prefixed by a *namespace* (e.g. `${appName}/`)\r\n * unique enough to disambiguate them from channels for other apps that may be running in the same processes.\r\n */\r\n public abstract get channelName(): string;\r\n\r\n /**\r\n * Register this class as the handler for methods on its channel. This static method creates a new instance\r\n * that becomes the handler and is `this` when its methods are called.\r\n * @returns A function that can be called to remove the handler.\r\n * @note this method should only be called once per channel. If it is called multiple times, subsequent calls replace the previous ones.\r\n */\r\n public static register(): RemoveFunction {\r\n const impl = new (this as any)() as IpcHandler; // create an instance of subclass. \"as any\" is necessary because base class is abstract\r\n return IpcHost.handle(impl.channelName, async (_evt: Event, funcName: string, ...args: any[]): Promise<IpcInvokeReturn> => {\r\n try {\r\n const func = (impl as any)[funcName];\r\n if (typeof func !== \"function\")\r\n throw new IModelError(IModelStatus.FunctionNotFound, `Method \"${impl.constructor.name}.${funcName}\" not found on IpcHandler registered for channel: ${impl.channelName}`);\r\n\r\n return { result: await func.call(impl, ...args) };\r\n } catch (err: any) {\r\n const ret: IpcInvokeReturn = {\r\n error: {\r\n name: err.hasOwnProperty(\"name\") ? err.name : err.constructor?.name ?? \"Unknown Error\",\r\n message: err.message ?? BentleyError.getErrorMessage(err),\r\n errorNumber: err.errorNumber ?? 0,\r\n },\r\n };\r\n if (!IpcHost.noStack)\r\n ret.error.stack = BentleyError.getErrorStack(err);\r\n return ret;\r\n }\r\n });\r\n }\r\n}\r\n\r\n/**\r\n * Implementation of IpcAppFunctions\r\n */\r\nclass IpcAppHandler extends IpcHandler implements IpcAppFunctions {\r\n public get channelName() { return ipcAppChannels.functions; }\r\n\r\n private _iModelKeyToPullStatus = new Map<string, ProgressStatus>();\r\n\r\n public async log(_timestamp: number, level: LogLevel, category: string, message: string, metaData?: any): Promise<void> {\r\n switch (level) {\r\n case LogLevel.Error:\r\n Logger.logError(category, message, metaData);\r\n break;\r\n case LogLevel.Info:\r\n Logger.logInfo(category, message, metaData);\r\n break;\r\n case LogLevel.Trace:\r\n Logger.logTrace(category, message, metaData);\r\n break;\r\n case LogLevel.Warning:\r\n Logger.logWarning(category, message, metaData);\r\n break;\r\n }\r\n }\r\n\r\n public async cancelTileContentRequests(tokenProps: IModelRpcProps, contentIds: TileTreeContentIds[]): Promise<void> {\r\n return cancelTileContentRequests(tokenProps, contentIds);\r\n }\r\n public async cancelElementGraphicsRequests(key: string, requestIds: string[]): Promise<void> {\r\n return IModelDb.findByKey(key).nativeDb.cancelElementGraphicsRequests(requestIds);\r\n }\r\n public async openBriefcase(args: OpenBriefcaseProps): Promise<IModelConnectionProps> {\r\n const db = await BriefcaseDb.open(args);\r\n return db.toJSON();\r\n }\r\n public async openStandalone(filePath: string, openMode: OpenMode, opts?: StandaloneOpenOptions): Promise<IModelConnectionProps> {\r\n return StandaloneDb.openFile(filePath, openMode, opts).getConnectionProps();\r\n }\r\n public async closeIModel(key: string): Promise<void> {\r\n IModelDb.findByKey(key).close();\r\n }\r\n public async saveChanges(key: string, description?: string): Promise<void> {\r\n IModelDb.findByKey(key).saveChanges(description);\r\n }\r\n public async hasPendingTxns(key: string): Promise<boolean> {\r\n return IModelDb.findByKey(key).nativeDb.hasPendingTxns();\r\n }\r\n\r\n public async isUndoPossible(key: string): Promise<boolean> {\r\n return IModelDb.findByKey(key).nativeDb.isUndoPossible();\r\n }\r\n public async isRedoPossible(key: string): Promise<boolean> {\r\n return IModelDb.findByKey(key).nativeDb.isRedoPossible();\r\n }\r\n public async getUndoString(key: string): Promise<string> {\r\n return IModelDb.findByKey(key).nativeDb.getUndoString();\r\n }\r\n public async getRedoString(key: string): Promise<string> {\r\n return IModelDb.findByKey(key).nativeDb.getUndoString();\r\n }\r\n\r\n public async pullChanges(key: string, toIndex?: ChangesetIndex, options?: PullChangesOptions): Promise<ChangesetIndexAndId> {\r\n const iModelDb = BriefcaseDb.findByKey(key);\r\n\r\n this._iModelKeyToPullStatus.set(key, ProgressStatus.Continue);\r\n const checkAbort = () => this._iModelKeyToPullStatus.get(key) ?? ProgressStatus.Continue;\r\n\r\n let onProgress: ProgressFunction | undefined;\r\n if (options?.reportProgress) {\r\n const progressCallback: ProgressFunction = (loaded, total) => {\r\n IpcHost.send(getPullChangesIpcChannel(iModelDb.iModelId), { loaded, total });\r\n return checkAbort();\r\n };\r\n onProgress = throttleProgressCallback(progressCallback, checkAbort, options?.progressInterval);\r\n } else if (options?.enableCancellation) {\r\n onProgress = checkAbort;\r\n }\r\n\r\n try {\r\n await iModelDb.pullChanges({ toIndex, onProgress });\r\n } finally {\r\n this._iModelKeyToPullStatus.delete(key);\r\n }\r\n\r\n return iModelDb.changeset as ChangesetIndexAndId;\r\n }\r\n public async cancelPullChangesRequest(key: string): Promise<void> {\r\n this._iModelKeyToPullStatus.set(key, ProgressStatus.Abort);\r\n }\r\n\r\n public async pushChanges(key: string, description: string): Promise<ChangesetIndexAndId> {\r\n const iModelDb = BriefcaseDb.findByKey(key);\r\n await iModelDb.pushChanges({ description });\r\n return iModelDb.changeset as ChangesetIndexAndId;\r\n }\r\n\r\n public async toggleGraphicalEditingScope(key: string, startSession: boolean): Promise<boolean> {\r\n const val: IModelJsNative.ErrorStatusOrResult<any, boolean> = IModelDb.findByKey(key).nativeDb.setGeometricModelTrackingEnabled(startSession);\r\n if (val.error)\r\n throw new IModelError(val.error.status, \"Failed to toggle graphical editing scope\");\r\n assert(undefined !== val.result);\r\n return val.result;\r\n }\r\n public async isGraphicalEditingSupported(key: string): Promise<boolean> {\r\n return IModelDb.findByKey(key).nativeDb.isGeometricModelTrackingSupported();\r\n }\r\n\r\n public async reverseTxns(key: string, numOperations: number): Promise<IModelStatus> {\r\n return IModelDb.findByKey(key).nativeDb.reverseTxns(numOperations);\r\n }\r\n public async reverseAllTxn(key: string): Promise<IModelStatus> {\r\n return IModelDb.findByKey(key).nativeDb.reverseAll();\r\n }\r\n public async reinstateTxn(key: string): Promise<IModelStatus> {\r\n return IModelDb.findByKey(key).nativeDb.reinstateTxn();\r\n }\r\n public async restartTxnSession(key: string): Promise<void> {\r\n return IModelDb.findByKey(key).nativeDb.restartTxnSession();\r\n }\r\n\r\n public async queryConcurrency(pool: \"io\" | \"cpu\"): Promise<number> {\r\n return IModelHost.platform.queryConcurrency(pool);\r\n }\r\n}\r\n\r\n/**\r\n * Prevents progress callback being called more frequently when provided interval.\r\n * @internal\r\n */\r\nexport function throttleProgressCallback(func: ProgressFunction, checkAbort: () => ProgressStatus, progressInterval?: number): ProgressFunction {\r\n const interval = progressInterval ?? 250; // by default, only send progress events every 250 milliseconds\r\n let nextTime = Date.now() + interval;\r\n const progressCallback: ProgressFunction = (loaded, total) => {\r\n const now = Date.now();\r\n if (loaded >= total || now >= nextTime) {\r\n nextTime = now + interval;\r\n return func(loaded, total);\r\n }\r\n return checkAbort();\r\n };\r\n\r\n return progressCallback;\r\n}\r\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"LocalhostIpcHost.d.ts","sourceRoot":"","sources":["../../src/LocalhostIpcHost.ts"],"names":[],"mappings":"AAIA;;GAEG;AAEH,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAuC,mBAAmB,EAAoE,MAAM,oBAAoB,CAAC;AAEhK,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAEjD,gBAAgB;AAChB,MAAM,WAAW,oBAAoB;IACnC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAuDD,gBAAgB;AAChB,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,MAAM,CAAC,YAAY,CAAS;IACpC,OAAc,MAAM,EAAE,mBAAmB,CAAC;WAE5B,OAAO,CAAC,UAAU,EAAE,EAAE;WAIhB,OAAO,CAAC,IAAI,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,oBAAoB,CAAC;QAAC,UAAU,CAAC,EAAE,iBAAiB,CAAA;KAAE;CAgB/G"}
1
+ {"version":3,"file":"LocalhostIpcHost.d.ts","sourceRoot":"","sources":["../../src/LocalhostIpcHost.ts"],"names":[],"mappings":"AAIA;;GAEG;AAEH,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EACgC,mBAAmB,EACzD,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAGjD,gBAAgB;AAChB,MAAM,WAAW,oBAAoB;IACnC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAuDD,gBAAgB;AAChB,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,MAAM,CAAC,YAAY,CAAS;IACpC,OAAc,MAAM,EAAE,mBAAmB,CAAC;WAE5B,OAAO,CAAC,UAAU,EAAE,EAAE;WAIhB,OAAO,CAAC,IAAI,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,oBAAoB,CAAC;QAAC,UAAU,CAAC,EAAE,iBAAiB,CAAA;KAAE;CAe/G"}
@@ -48,7 +48,7 @@ class LocalTransport extends core_common_1.IpcWebSocketTransport {
48
48
  class RpcHandler extends IpcHost_1.IpcHandler {
49
49
  constructor() {
50
50
  super(...arguments);
51
- this.channelName = "RPC";
51
+ this.channelName = core_common_1.rpcOverIpcStrings.channelName;
52
52
  }
53
53
  async request(info) {
54
54
  const invocation = core_common_1.RpcSessionInvocation.create(info);
@@ -70,9 +70,8 @@ class LocalhostIpcHost {
70
70
  this._initialized = true;
71
71
  }
72
72
  await IpcHost_1.IpcHost.startup({ ipcHost: { socket: this.socket }, iModelHost: opts?.iModelHost });
73
- if (registerHandler) {
73
+ if (registerHandler)
74
74
  RpcHandler.register();
75
- }
76
75
  }
77
76
  }
78
77
  LocalhostIpcHost._initialized = false;
@@ -1 +1 @@
1
- {"version":3,"file":"LocalhostIpcHost.js","sourceRoot":"","sources":["../../src/LocalhostIpcHost.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,yBAAyB;AACzB,oDAAgK;AAChK,uCAAgD;AAShD,MAAM,cAAe,SAAQ,mCAAqB;IAIhD,YAAmB,IAA0B;QAC3C,KAAK,EAAE,CAAC;QAHF,iBAAY,GAAoB,IAAI,GAAG,EAAE,CAAC;QAKhD,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE;YAClB,IAAI,CAAC,OAAO,GAAG,IAAI,EAAE,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,UAAU,IAAI,IAAI,EAAE,CAAC,CAAC;YAChE,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,YAAY,EAAE,CAAC,UAAU,EAAE,EAAE,CAAC,gBAAgB,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC;SACrF;IACH,CAAC;IAEM,IAAI,CAAC,OAA4B;QACtC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,UAAU,EAAE,EAAE;YAC7C,OAAO,CAAC,QAAQ,GAAG,IAAI,GAAG,CAAC,CAAC;YAC5B,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,UAAU,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;YACpD,MAAM,KAAK,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;YACtC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACjD,CAAC,CAAC,CAAC;IACL,CAAC;IAEM,OAAO,CAAC,UAAc;QAC3B,IAAI,CAAC,YAAY,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IAAI,eAAe,GAAG,KAAK,CAAC;QAE5B,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE;YACtB,eAAe,GAAG,IAAI,CAAC;YACvB,0BAAY,CAAC,SAAS,GAAG,IAAI,cAAc,CAAC,IAAI,EAAE,gBAAgB,IAAI,EAAE,CAAC,CAAC;YAC1E,IAAI,CAAC,MAAM,GAAG,IAAI,iCAAmB,EAAE,CAAC;YACxC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;SAC1B;QAED,MAAM,iBAAO,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;QAE1F,IAAI,eAAe,EAAE;YACnB,UAAU,CAAC,QAAQ,EAAE,CAAC;SACvB;IACH,CAAC;;AAtBc,6BAAY,GAAG,KAAK,CAAC;AADzB,4CAAgB","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 IModelHost\r\n */\r\n\r\nimport * as ws from \"ws\";\r\nimport { InterceptedRpcRequest, IpcWebSocket, IpcWebSocketBackend, IpcWebSocketMessage, IpcWebSocketTransport, RpcSessionInvocation } from \"@itwin/core-common\";\r\nimport { IpcHandler, IpcHost } from \"./IpcHost\";\r\nimport { IModelHostOptions } from \"./IModelHost\";\r\n\r\n/** @internal */\r\nexport interface LocalhostIpcHostOpts {\r\n socketPort?: number;\r\n noServer?: boolean;\r\n}\r\n\r\nclass LocalTransport extends IpcWebSocketTransport {\r\n private _server: ws.Server | undefined;\r\n private _connections: Map<ws, number> = new Map();\r\n\r\n public constructor(opts: LocalhostIpcHostOpts) {\r\n super();\r\n\r\n if (!opts.noServer) {\r\n this._server = new ws.Server({ port: opts.socketPort ?? 3002 });\r\n this._server.on(\"connection\", (connection) => LocalhostIpcHost.connect(connection));\r\n }\r\n }\r\n\r\n public send(message: IpcWebSocketMessage): void {\r\n this._connections.forEach((last, connection) => {\r\n message.sequence = last + 1;\r\n this._connections.set(connection, message.sequence);\r\n const parts = this.serialize(message);\r\n parts.forEach((part) => connection.send(part));\r\n });\r\n }\r\n\r\n public connect(connection: ws) {\r\n this._connections.set(connection, -1);\r\n\r\n connection.on(\"message\", async (data) => {\r\n const message = await this.notifyIncoming(data, connection);\r\n if (IpcWebSocketMessage.skip(message)) {\r\n return;\r\n }\r\n\r\n for (const listener of IpcWebSocket.receivers) {\r\n listener({} as Event, message);\r\n }\r\n });\r\n\r\n connection.on(\"close\", () => {\r\n this._connections.delete(connection);\r\n this.notifyClose(connection);\r\n });\r\n }\r\n}\r\n\r\nclass RpcHandler extends IpcHandler {\r\n public channelName = \"RPC\";\r\n\r\n public async request(info: InterceptedRpcRequest) {\r\n const invocation = RpcSessionInvocation.create(info);\r\n const fulfillment = await invocation.fulfillment;\r\n return invocation.rejected ? Promise.reject(fulfillment.rawResult) : fulfillment.rawResult;\r\n }\r\n}\r\n\r\n/** @internal */\r\nexport class LocalhostIpcHost {\r\n private static _initialized = false;\r\n public static socket: IpcWebSocketBackend;\r\n\r\n public static connect(connection: ws) {\r\n (IpcWebSocket.transport as LocalTransport).connect(connection);\r\n }\r\n\r\n public static async startup(opts?: { localhostIpcHost?: LocalhostIpcHostOpts, iModelHost?: IModelHostOptions }) {\r\n let registerHandler = false;\r\n\r\n if (!this._initialized) {\r\n registerHandler = true;\r\n IpcWebSocket.transport = new LocalTransport(opts?.localhostIpcHost ?? {});\r\n this.socket = new IpcWebSocketBackend();\r\n this._initialized = true;\r\n }\r\n\r\n await IpcHost.startup({ ipcHost: { socket: this.socket }, iModelHost: opts?.iModelHost });\r\n\r\n if (registerHandler) {\r\n RpcHandler.register();\r\n }\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"LocalhostIpcHost.js","sourceRoot":"","sources":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AAC,IAAI,EAAE,gBAAgB,IAAI,EAAE,CAAC,CAAC;YAC1E,IAAI,CAAC,MAAM,GAAG,IAAI,iCAAmB,EAAE,CAAC;YACxC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;SAC1B;QAED,MAAM,iBAAO,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC;QAE1F,IAAI,eAAe;YACjB,UAAU,CAAC,QAAQ,EAAE,CAAC;IAC1B,CAAC;;AArBc,6BAAY,GAAG,KAAK,CAAC;AADzB,4CAAgB","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 IModelHost\r\n */\r\n\r\nimport * as ws from \"ws\";\r\nimport {\r\n InterceptedRpcRequest, IpcWebSocket, IpcWebSocketBackend, IpcWebSocketMessage, IpcWebSocketTransport, rpcOverIpcStrings, RpcSessionInvocation,\r\n} from \"@itwin/core-common\";\r\nimport { IModelHostOptions } from \"./IModelHost\";\r\nimport { IpcHandler, IpcHost } from \"./IpcHost\";\r\n\r\n/** @internal */\r\nexport interface LocalhostIpcHostOpts {\r\n socketPort?: number;\r\n noServer?: boolean;\r\n}\r\n\r\nclass LocalTransport extends IpcWebSocketTransport {\r\n private _server: ws.Server | undefined;\r\n private _connections: Map<ws, number> = new Map();\r\n\r\n public constructor(opts: LocalhostIpcHostOpts) {\r\n super();\r\n\r\n if (!opts.noServer) {\r\n this._server = new ws.Server({ port: opts.socketPort ?? 3002 });\r\n this._server.on(\"connection\", (connection) => LocalhostIpcHost.connect(connection));\r\n }\r\n }\r\n\r\n public send(message: IpcWebSocketMessage): void {\r\n this._connections.forEach((last, connection) => {\r\n message.sequence = last + 1;\r\n this._connections.set(connection, message.sequence);\r\n const parts = this.serialize(message);\r\n parts.forEach((part) => connection.send(part));\r\n });\r\n }\r\n\r\n public connect(connection: ws) {\r\n this._connections.set(connection, -1);\r\n\r\n connection.on(\"message\", async (data) => {\r\n const message = await this.notifyIncoming(data, connection);\r\n if (IpcWebSocketMessage.skip(message)) {\r\n return;\r\n }\r\n\r\n for (const listener of IpcWebSocket.receivers) {\r\n listener({} as Event, message);\r\n }\r\n });\r\n\r\n connection.on(\"close\", () => {\r\n this._connections.delete(connection);\r\n this.notifyClose(connection);\r\n });\r\n }\r\n}\r\n\r\nclass RpcHandler extends IpcHandler {\r\n public channelName = rpcOverIpcStrings.channelName;\r\n\r\n public async request(info: InterceptedRpcRequest) {\r\n const invocation = RpcSessionInvocation.create(info);\r\n const fulfillment = await invocation.fulfillment;\r\n return invocation.rejected ? Promise.reject(fulfillment.rawResult) : fulfillment.rawResult;\r\n }\r\n}\r\n\r\n/** @internal */\r\nexport class LocalhostIpcHost {\r\n private static _initialized = false;\r\n public static socket: IpcWebSocketBackend;\r\n\r\n public static connect(connection: ws) {\r\n (IpcWebSocket.transport as LocalTransport).connect(connection);\r\n }\r\n\r\n public static async startup(opts?: { localhostIpcHost?: LocalhostIpcHostOpts, iModelHost?: IModelHostOptions }) {\r\n let registerHandler = false;\r\n\r\n if (!this._initialized) {\r\n registerHandler = true;\r\n IpcWebSocket.transport = new LocalTransport(opts?.localhostIpcHost ?? {});\r\n this.socket = new IpcWebSocketBackend();\r\n this._initialized = true;\r\n }\r\n\r\n await IpcHost.startup({ ipcHost: { socket: this.socket }, iModelHost: opts?.iModelHost });\r\n\r\n if (registerHandler)\r\n RpcHandler.register();\r\n }\r\n}\r\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"NativeHost.d.ts","sourceRoot":"","sources":["../../src/NativeHost.ts"],"names":[],"mappings":"AAIA;;GAEG;AAGH,OAAO,EAAuB,OAAO,EAAc,MAAM,qBAAqB,CAAC;AAC/E,OAAO,EACW,0BAA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;IAM7C,iDAAiD;WACnC,yBAAyB,IAAI,0BAA0B;IAIrE;;;;OAIG;WACW,4BAA4B,CAAC,YAAY,EAAE,YAAY,EAAE,MAAM,EAAE,0BAA0B,GAAG,IAAI;CAMjH"}
@@ -20,7 +20,7 @@ const NativeAppStorage_1 = require("./NativeAppStorage");
20
20
  * Implementation of NativeAppFunctions
21
21
  */
22
22
  class NativeAppHandler extends IpcHost_1.IpcHandler {
23
- get channelName() { return core_common_1.nativeAppChannel; }
23
+ get channelName() { return core_common_1.nativeAppIpcStrings.channelName; }
24
24
  async getAccessToken() {
25
25
  return IModelHost_1.IModelHost.authorizationClient?.getAccessToken();
26
26
  }
@@ -108,7 +108,7 @@ class NativeHost {
108
108
  }
109
109
  /** Send a notification to the NativeApp connected to this NativeHost. */
110
110
  static notifyNativeFrontend(methodName, ...args) {
111
- return IpcHost_1.IpcHost.send(core_common_1.nativeAppNotify, methodName, ...args);
111
+ return IpcHost_1.IpcHost.send(core_common_1.nativeAppIpcStrings.notifyChannel, methodName, ...args);
112
112
  }
113
113
  static get isValid() { return this._isValid; }
114
114
  static get applicationName() { return this._applicationName; }
@@ -1 +1 @@
1
- {"version":3,"file":"NativeHost.js","sourceRoot":"","sources":["../../src/NativeHost.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,+BAA4B;AAC5B,sDAA+E;AAC/E,oDAG4B;AAC5B,yDAA8E;AAC9E,2DAAkF;AAClF,6CAA0C;AAC1C,uCAAuF;AACvF,yDAAsD;AAEtD;;GAEG;AACH,MAAM,gBAAiB,SAAQ,oBAAU;IACvC,IAAW,WAAW,KAAK,OAAO,8BAAgB,CAAC,CAAC,CAAC;IAE9C,KAAK,CAAC,cAAc;QACzB,OAAO,uBAAU,CAAC,mBAAmB,EAAE,cAAc,EAAE,CAAC;IAC1D,CAAC;IAEM,KAAK,CAAC,yBAAyB;QACpC,OAAO,UAAU,CAAC,yBAAyB,EAAE,CAAC;IAChD,CAAC;IACM,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,KAAK,CAAC;AApBrB,gCAAU","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 NativeApp\r\n */\r\n\r\nimport { join } from \"path\";\r\nimport { AccessToken, assert, BeEvent, GuidString } from \"@itwin/core-bentley\";\r\nimport {\r\n BriefcaseProps, InternetConnectivityStatus, LocalBriefcaseProps, nativeAppChannel, NativeAppFunctions, NativeAppNotifications, nativeAppNotify,\r\n OverriddenBy, RequestNewBriefcaseProps, StorageValue,\r\n} from \"@itwin/core-common\";\r\nimport { BriefcaseManager, RequestNewBriefcaseArg } from \"./BriefcaseManager\";\r\nimport { Downloads, ProgressFunction, ProgressStatus } from \"./CheckpointManager\";\r\nimport { IModelHost } from \"./IModelHost\";\r\nimport { IpcHandler, IpcHost, IpcHostOpts, throttleProgressCallback } from \"./IpcHost\";\r\nimport { NativeAppStorage } from \"./NativeAppStorage\";\r\n\r\n/**\r\n * Implementation of NativeAppFunctions\r\n */\r\nclass NativeAppHandler extends IpcHandler implements NativeAppFunctions {\r\n public get channelName() { return nativeAppChannel; }\r\n\r\n public async getAccessToken(): Promise<AccessToken | undefined> {\r\n return IModelHost.authorizationClient?.getAccessToken();\r\n }\r\n\r\n public async checkInternetConnectivity(): Promise<InternetConnectivityStatus> {\r\n return NativeHost.checkInternetConnectivity();\r\n }\r\n public async overrideInternetConnectivity(by: OverriddenBy, status: InternetConnectivityStatus): Promise<void> {\r\n NativeHost.overrideInternetConnectivity(by, status);\r\n }\r\n public async acquireNewBriefcaseId(iModelId: GuidString): Promise<number> {\r\n return BriefcaseManager.acquireNewBriefcaseId({ iModelId });\r\n }\r\n public async getBriefcaseFileName(props: BriefcaseProps): Promise<string> {\r\n return BriefcaseManager.getFileName(props);\r\n }\r\n public async downloadBriefcase(request: RequestNewBriefcaseProps, reportProgress: boolean, progressInterval?: number): Promise<LocalBriefcaseProps> {\r\n const args: RequestNewBriefcaseArg = {\r\n ...request,\r\n accessToken: await this.getAccessToken(),\r\n onProgress: (_a: number, _b: number) => checkAbort(),\r\n };\r\n\r\n const checkAbort = () => {\r\n assert(undefined !== args.fileName);\r\n const job = Downloads.isInProgress(args.fileName);\r\n return (job && (job.request as any).abort === 1) ? ProgressStatus.Abort : ProgressStatus.Continue;\r\n };\r\n\r\n if (reportProgress) {\r\n const progressCallback: ProgressFunction = (loaded, total) => {\r\n IpcHost.send(`nativeApp.progress-${request.iModelId}`, { loaded, total });\r\n return checkAbort();\r\n };\r\n args.onProgress = throttleProgressCallback(progressCallback, checkAbort, progressInterval);\r\n }\r\n\r\n return BriefcaseManager.downloadBriefcase(args);\r\n }\r\n\r\n public async requestCancelDownloadBriefcase(fileName: string): Promise<boolean> {\r\n const job = Downloads.isInProgress(fileName);\r\n if (job)\r\n (job.request as any).abort = 1;\r\n return job !== undefined;\r\n }\r\n\r\n public async deleteBriefcaseFiles(fileName: string): Promise<void> {\r\n await BriefcaseManager.deleteBriefcaseFiles(fileName, await IModelHost.getAccessToken());\r\n }\r\n\r\n public async getCachedBriefcases(iModelId?: GuidString): Promise<LocalBriefcaseProps[]> {\r\n return BriefcaseManager.getCachedBriefcases(iModelId);\r\n }\r\n\r\n public async storageMgrOpen(storageId: string): Promise<string> {\r\n return NativeAppStorage.open(storageId).id;\r\n }\r\n\r\n public async storageMgrClose(storageId: string, deleteIt: boolean): Promise<void> {\r\n NativeAppStorage.find(storageId).close(deleteIt);\r\n }\r\n\r\n public async storageMgrNames(): Promise<string[]> {\r\n return NativeAppStorage.getStorageNames();\r\n }\r\n\r\n public async storageGetValueType(storageId: string, key: string): Promise<\"number\" | \"string\" | \"boolean\" | \"Uint8Array\" | \"null\" | undefined> {\r\n return NativeAppStorage.find(storageId).getValueType(key);\r\n }\r\n\r\n public async storageGet(storageId: string, key: string): Promise<StorageValue | undefined> {\r\n return NativeAppStorage.find(storageId).getData(key);\r\n }\r\n\r\n public async storageSet(storageId: string, key: string, value: StorageValue): Promise<void> {\r\n NativeAppStorage.find(storageId).setData(key, value);\r\n }\r\n\r\n public async storageRemove(storageId: string, key: string): Promise<void> {\r\n NativeAppStorage.find(storageId).removeData(key);\r\n }\r\n\r\n public async storageKeys(storageId: string): Promise<string[]> {\r\n return NativeAppStorage.find(storageId).getKeys();\r\n }\r\n\r\n public async storageRemoveAll(storageId: string): Promise<void> {\r\n NativeAppStorage.find(storageId).removeAll();\r\n }\r\n}\r\n\r\n/** Options for [[NativeHost.startup]]\r\n * @public\r\n */\r\nexport interface NativeHostOpts extends IpcHostOpts {\r\n nativeHost?: {\r\n /** Application name. Used, for example, to name the settings file. If not supplied, defaults to \"iTwinApp\". */\r\n applicationName?: string;\r\n };\r\n}\r\n\r\n/**\r\n * Backend for desktop/mobile native applications\r\n * @public\r\n */\r\nexport class NativeHost {\r\n private static _reachability?: InternetConnectivityStatus;\r\n private static _applicationName: string;\r\n private constructor() { } // no instances - static methods only\r\n\r\n /** Event called when the internet connectivity changes, if known. */\r\n public static readonly onInternetConnectivityChanged = new BeEvent<(status: InternetConnectivityStatus) => void>();\r\n\r\n private static _appSettingsCacheDir?: string;\r\n\r\n /** Get the local cache folder for application settings */\r\n public static get appSettingsCacheDir(): string {\r\n return this._appSettingsCacheDir ??= join(IModelHost.cacheDir, \"appSettings\");\r\n }\r\n\r\n /** Send a notification to the NativeApp connected to this NativeHost. */\r\n public static notifyNativeFrontend<T extends keyof NativeAppNotifications>(methodName: T, ...args: Parameters<NativeAppNotifications[T]>) {\r\n return IpcHost.send(nativeAppNotify, methodName, ...args);\r\n }\r\n\r\n private static _isValid = false;\r\n public static get isValid(): boolean { return this._isValid; }\r\n public static get applicationName() { return this._applicationName; }\r\n /** Get the settings store for this NativeHost. */\r\n public static get settingsStore() {\r\n return NativeAppStorage.open(this.applicationName);\r\n }\r\n\r\n /**\r\n * Start the backend of a native app.\r\n * @note this method calls [[IpcHost.startup]] internally.\r\n */\r\n public static async startup(opt?: NativeHostOpts): Promise<void> {\r\n if (!this.isValid) {\r\n this._isValid = true;\r\n this.onInternetConnectivityChanged.addListener((status: InternetConnectivityStatus) =>\r\n NativeHost.notifyNativeFrontend(\"notifyInternetConnectivityChanged\", status));\r\n this._applicationName = opt?.nativeHost?.applicationName ?? \"iTwinApp\";\r\n }\r\n\r\n await IpcHost.startup(opt);\r\n if (IpcHost.isValid) // for tests, we use NativeHost but don't have a frontend\r\n NativeAppHandler.register();\r\n }\r\n\r\n /** Shutdown native app backend. Also calls [[IpcHost.shutdown]] */\r\n public static async shutdown(): Promise<void> {\r\n this._isValid = false;\r\n this.onInternetConnectivityChanged.clear();\r\n await IpcHost.shutdown();\r\n }\r\n\r\n /** get current value of internet connectivity */\r\n public static checkInternetConnectivity(): InternetConnectivityStatus {\r\n return this._reachability ?? InternetConnectivityStatus.Online;\r\n }\r\n\r\n /**\r\n * Override internet connectivity state\r\n * @param _overridenBy who overrode the value.\r\n * @internal\r\n */\r\n public static overrideInternetConnectivity(_overridenBy: OverriddenBy, status: InternetConnectivityStatus): void {\r\n if (this._reachability !== status) {\r\n this._reachability = status;\r\n this.onInternetConnectivityChanged.raiseEvent(status);\r\n }\r\n }\r\n}\r\n"]}
1
+ {"version":3,"file":"NativeHost.js","sourceRoot":"","sources":["../../src/NativeHost.ts"],"names":[],"mappings":";AAAA;;;+FAG+F;AAC/F;;GAEG;;;AAEH,+BAA4B;AAC5B,sDAA+E;AAC/E,oDAG4B;AAC5B,yDAA8E;AAC9E,2DAAkF;AAClF,6CAA0C;AAC1C,uCAAuF;AACvF,yDAAsD;AAEtD;;GAEG;AACH,MAAM,gBAAiB,SAAQ,oBAAU;IACvC,IAAW,WAAW,KAAK,OAAO,iCAAmB,CAAC,WAAW,CAAC,CAAC,CAAC;IAE7D,KAAK,CAAC,cAAc;QACzB,OAAO,uBAAU,CAAC,mBAAmB,EAAE,cAAc,EAAE,CAAC;IAC1D,CAAC;IAEM,KAAK,C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C;;AA9DD,qEAAqE;AAC9C,wCAA6B,GAAG,IAAI,sBAAO,EAAgD,CAAC;AAcpG,mBAAQ,GAAG,KAAK,CAAC;AApBrB,gCAAU","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 NativeApp\r\n */\r\n\r\nimport { join } from \"path\";\r\nimport { AccessToken, assert, BeEvent, GuidString } from \"@itwin/core-bentley\";\r\nimport {\r\n BriefcaseProps, InternetConnectivityStatus, LocalBriefcaseProps, NativeAppFunctions, nativeAppIpcStrings, NativeAppNotifications,\r\n OverriddenBy, RequestNewBriefcaseProps, StorageValue,\r\n} from \"@itwin/core-common\";\r\nimport { BriefcaseManager, RequestNewBriefcaseArg } from \"./BriefcaseManager\";\r\nimport { Downloads, ProgressFunction, ProgressStatus } from \"./CheckpointManager\";\r\nimport { IModelHost } from \"./IModelHost\";\r\nimport { IpcHandler, IpcHost, IpcHostOpts, throttleProgressCallback } from \"./IpcHost\";\r\nimport { NativeAppStorage } from \"./NativeAppStorage\";\r\n\r\n/**\r\n * Implementation of NativeAppFunctions\r\n */\r\nclass NativeAppHandler extends IpcHandler implements NativeAppFunctions {\r\n public get channelName() { return nativeAppIpcStrings.channelName; }\r\n\r\n public async getAccessToken(): Promise<AccessToken | undefined> {\r\n return IModelHost.authorizationClient?.getAccessToken();\r\n }\r\n\r\n public async checkInternetConnectivity(): Promise<InternetConnectivityStatus> {\r\n return NativeHost.checkInternetConnectivity();\r\n }\r\n public async overrideInternetConnectivity(by: OverriddenBy, status: InternetConnectivityStatus): Promise<void> {\r\n NativeHost.overrideInternetConnectivity(by, status);\r\n }\r\n public async acquireNewBriefcaseId(iModelId: GuidString): Promise<number> {\r\n return BriefcaseManager.acquireNewBriefcaseId({ iModelId });\r\n }\r\n public async getBriefcaseFileName(props: BriefcaseProps): Promise<string> {\r\n return BriefcaseManager.getFileName(props);\r\n }\r\n public async downloadBriefcase(request: RequestNewBriefcaseProps, reportProgress: boolean, progressInterval?: number): Promise<LocalBriefcaseProps> {\r\n const args: RequestNewBriefcaseArg = {\r\n ...request,\r\n accessToken: await this.getAccessToken(),\r\n onProgress: (_a: number, _b: number) => checkAbort(),\r\n };\r\n\r\n const checkAbort = () => {\r\n assert(undefined !== args.fileName);\r\n const job = Downloads.isInProgress(args.fileName);\r\n return (job && (job.request as any).abort === 1) ? ProgressStatus.Abort : ProgressStatus.Continue;\r\n };\r\n\r\n if (reportProgress) {\r\n const progressCallback: ProgressFunction = (loaded, total) => {\r\n IpcHost.send(`nativeApp.progress-${request.iModelId}`, { loaded, total });\r\n return checkAbort();\r\n };\r\n args.onProgress = throttleProgressCallback(progressCallback, checkAbort, progressInterval);\r\n }\r\n\r\n return BriefcaseManager.downloadBriefcase(args);\r\n }\r\n\r\n public async requestCancelDownloadBriefcase(fileName: string): Promise<boolean> {\r\n const job = Downloads.isInProgress(fileName);\r\n if (job)\r\n (job.request as any).abort = 1;\r\n return job !== undefined;\r\n }\r\n\r\n public async deleteBriefcaseFiles(fileName: string): Promise<void> {\r\n await BriefcaseManager.deleteBriefcaseFiles(fileName, await IModelHost.getAccessToken());\r\n }\r\n\r\n public async getCachedBriefcases(iModelId?: GuidString): Promise<LocalBriefcaseProps[]> {\r\n return BriefcaseManager.getCachedBriefcases(iModelId);\r\n }\r\n\r\n public async storageMgrOpen(storageId: string): Promise<string> {\r\n return NativeAppStorage.open(storageId).id;\r\n }\r\n\r\n public async storageMgrClose(storageId: string, deleteIt: boolean): Promise<void> {\r\n NativeAppStorage.find(storageId).close(deleteIt);\r\n }\r\n\r\n public async storageMgrNames(): Promise<string[]> {\r\n return NativeAppStorage.getStorageNames();\r\n }\r\n\r\n public async storageGetValueType(storageId: string, key: string): Promise<\"number\" | \"string\" | \"boolean\" | \"Uint8Array\" | \"null\" | undefined> {\r\n return NativeAppStorage.find(storageId).getValueType(key);\r\n }\r\n\r\n public async storageGet(storageId: string, key: string): Promise<StorageValue | undefined> {\r\n return NativeAppStorage.find(storageId).getData(key);\r\n }\r\n\r\n public async storageSet(storageId: string, key: string, value: StorageValue): Promise<void> {\r\n NativeAppStorage.find(storageId).setData(key, value);\r\n }\r\n\r\n public async storageRemove(storageId: string, key: string): Promise<void> {\r\n NativeAppStorage.find(storageId).removeData(key);\r\n }\r\n\r\n public async storageKeys(storageId: string): Promise<string[]> {\r\n return NativeAppStorage.find(storageId).getKeys();\r\n }\r\n\r\n public async storageRemoveAll(storageId: string): Promise<void> {\r\n NativeAppStorage.find(storageId).removeAll();\r\n }\r\n}\r\n\r\n/** Options for [[NativeHost.startup]]\r\n * @public\r\n */\r\nexport interface NativeHostOpts extends IpcHostOpts {\r\n nativeHost?: {\r\n /** Application name. Used, for example, to name the settings file. If not supplied, defaults to \"iTwinApp\". */\r\n applicationName?: string;\r\n };\r\n}\r\n\r\n/**\r\n * Backend for desktop/mobile native applications\r\n * @public\r\n */\r\nexport class NativeHost {\r\n private static _reachability?: InternetConnectivityStatus;\r\n private static _applicationName: string;\r\n private constructor() { } // no instances - static methods only\r\n\r\n /** Event called when the internet connectivity changes, if known. */\r\n public static readonly onInternetConnectivityChanged = new BeEvent<(status: InternetConnectivityStatus) => void>();\r\n\r\n private static _appSettingsCacheDir?: string;\r\n\r\n /** Get the local cache folder for application settings */\r\n public static get appSettingsCacheDir(): string {\r\n return this._appSettingsCacheDir ??= join(IModelHost.cacheDir, \"appSettings\");\r\n }\r\n\r\n /** Send a notification to the NativeApp connected to this NativeHost. */\r\n public static notifyNativeFrontend<T extends keyof NativeAppNotifications>(methodName: T, ...args: Parameters<NativeAppNotifications[T]>) {\r\n return IpcHost.send(nativeAppIpcStrings.notifyChannel, methodName, ...args);\r\n }\r\n\r\n private static _isValid = false;\r\n public static get isValid(): boolean { return this._isValid; }\r\n public static get applicationName() { return this._applicationName; }\r\n /** Get the settings store for this NativeHost. */\r\n public static get settingsStore() {\r\n return NativeAppStorage.open(this.applicationName);\r\n }\r\n\r\n /**\r\n * Start the backend of a native app.\r\n * @note this method calls [[IpcHost.startup]] internally.\r\n */\r\n public static async startup(opt?: NativeHostOpts): Promise<void> {\r\n if (!this.isValid) {\r\n this._isValid = true;\r\n this.onInternetConnectivityChanged.addListener((status: InternetConnectivityStatus) =>\r\n NativeHost.notifyNativeFrontend(\"notifyInternetConnectivityChanged\", status));\r\n this._applicationName = opt?.nativeHost?.applicationName ?? \"iTwinApp\";\r\n }\r\n\r\n await IpcHost.startup(opt);\r\n if (IpcHost.isValid) // for tests, we use NativeHost but don't have a frontend\r\n NativeAppHandler.register();\r\n }\r\n\r\n /** Shutdown native app backend. Also calls [[IpcHost.shutdown]] */\r\n public static async shutdown(): Promise<void> {\r\n this._isValid = false;\r\n this.onInternetConnectivityChanged.clear();\r\n await IpcHost.shutdown();\r\n }\r\n\r\n /** get current value of internet connectivity */\r\n public static checkInternetConnectivity(): InternetConnectivityStatus {\r\n return this._reachability ?? InternetConnectivityStatus.Online;\r\n }\r\n\r\n /**\r\n * Override internet connectivity state\r\n * @param _overridenBy who overrode the value.\r\n * @internal\r\n */\r\n public static overrideInternetConnectivity(_overridenBy: OverriddenBy, status: InternetConnectivityStatus): void {\r\n if (this._reachability !== status) {\r\n this._reachability = status;\r\n this.onInternetConnectivityChanged.raiseEvent(status);\r\n }\r\n }\r\n}\r\n"]}