@equinor/fusion-framework-module-context 8.0.3 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +78 -2
  3. package/dist/esm/ContextModuleConfig.js +2 -0
  4. package/dist/esm/ContextModuleConfig.js.map +1 -0
  5. package/dist/esm/ContextModuleConfigurator.interface.js +2 -0
  6. package/dist/esm/ContextModuleConfigurator.interface.js.map +1 -0
  7. package/dist/esm/ContextModuleConfigurator.js +211 -0
  8. package/dist/esm/ContextModuleConfigurator.js.map +1 -0
  9. package/dist/esm/ContextProvider.js +1 -1
  10. package/dist/esm/ContextProvider.js.map +1 -1
  11. package/dist/esm/__tests__/ContextModuleConfigurator.test.js +282 -0
  12. package/dist/esm/__tests__/ContextModuleConfigurator.test.js.map +1 -0
  13. package/dist/esm/__tests__/mock/context-mock.test.js +101 -0
  14. package/dist/esm/__tests__/mock/context-mock.test.js.map +1 -0
  15. package/dist/esm/__tests__/mock/create-context-item-factory.test.js +45 -0
  16. package/dist/esm/__tests__/mock/create-context-item-factory.test.js.map +1 -0
  17. package/dist/esm/__tests__/mock/create-context-items.test.js +46 -0
  18. package/dist/esm/__tests__/mock/create-context-items.test.js.map +1 -0
  19. package/dist/esm/index.js +1 -1
  20. package/dist/esm/index.js.map +1 -1
  21. package/dist/esm/mock/ContextMockConfigurator.js +206 -0
  22. package/dist/esm/mock/ContextMockConfigurator.js.map +1 -0
  23. package/dist/esm/mock/fixtures/create-context-item-factory.js +50 -0
  24. package/dist/esm/mock/fixtures/create-context-item-factory.js.map +1 -0
  25. package/dist/esm/mock/fixtures/create-context-items.js +53 -0
  26. package/dist/esm/mock/fixtures/create-context-items.js.map +1 -0
  27. package/dist/esm/mock/fixtures/index.js +22 -0
  28. package/dist/esm/mock/fixtures/index.js.map +1 -0
  29. package/dist/esm/mock/fixtures/string-to-seed.js +15 -0
  30. package/dist/esm/mock/fixtures/string-to-seed.js.map +1 -0
  31. package/dist/esm/mock/index.js +31 -0
  32. package/dist/esm/mock/index.js.map +1 -0
  33. package/dist/esm/mock/module.js +41 -0
  34. package/dist/esm/mock/module.js.map +1 -0
  35. package/dist/esm/module.js +35 -6
  36. package/dist/esm/module.js.map +1 -1
  37. package/dist/esm/{get-context-selector.js → selectors/get-context-selector.js} +1 -4
  38. package/dist/esm/selectors/get-context-selector.js.map +1 -0
  39. package/dist/esm/selectors/index.js +13 -0
  40. package/dist/esm/selectors/index.js.map +1 -0
  41. package/dist/esm/{query-context-selector.js → selectors/query-context-selector.js} +1 -1
  42. package/dist/esm/selectors/query-context-selector.js.map +1 -0
  43. package/dist/esm/{related-context-selector.js → selectors/related-context-selector.js} +1 -1
  44. package/dist/esm/selectors/related-context-selector.js.map +1 -0
  45. package/dist/esm/utils/enable-context.js +1 -1
  46. package/dist/esm/utils/enable-context.js.map +1 -1
  47. package/dist/esm/utils/index.js +2 -0
  48. package/dist/esm/utils/index.js.map +1 -1
  49. package/dist/esm/utils/parse-context-item.js.map +1 -0
  50. package/dist/esm/utils/resolve-initial-context.js +3 -1
  51. package/dist/esm/utils/resolve-initial-context.js.map +1 -1
  52. package/dist/esm/version.js +1 -1
  53. package/dist/tsconfig.tsbuildinfo +1 -1
  54. package/dist/types/{configurator.d.ts → ContextModuleConfig.d.ts} +4 -64
  55. package/dist/types/ContextModuleConfigurator.d.ts +97 -0
  56. package/dist/types/{ContextConfigBuilder.d.ts → ContextModuleConfigurator.interface.d.ts} +27 -47
  57. package/dist/types/ContextProvider.d.ts +1 -1
  58. package/dist/types/__tests__/ContextModuleConfigurator.test.d.ts +1 -0
  59. package/dist/types/__tests__/mock/context-mock.test.d.ts +1 -0
  60. package/dist/types/__tests__/mock/create-context-item-factory.test.d.ts +1 -0
  61. package/dist/types/__tests__/mock/create-context-items.test.d.ts +1 -0
  62. package/dist/types/index.d.ts +3 -1
  63. package/dist/types/mock/ContextMockConfigurator.d.ts +155 -0
  64. package/dist/types/mock/fixtures/create-context-item-factory.d.ts +40 -0
  65. package/dist/types/mock/fixtures/create-context-items.d.ts +59 -0
  66. package/dist/types/mock/fixtures/index.d.ts +21 -0
  67. package/dist/types/mock/fixtures/string-to-seed.d.ts +12 -0
  68. package/dist/types/mock/index.d.ts +30 -0
  69. package/dist/types/mock/module.d.ts +38 -0
  70. package/dist/types/module.d.ts +5 -3
  71. package/dist/types/{get-context-selector.d.ts → selectors/get-context-selector.d.ts} +1 -3
  72. package/dist/types/selectors/index.d.ts +12 -0
  73. package/dist/types/{query-context-selector.d.ts → selectors/query-context-selector.d.ts} +1 -1
  74. package/dist/types/{related-context-selector.d.ts → selectors/related-context-selector.d.ts} +1 -1
  75. package/dist/types/utils/enable-context.d.ts +4 -5
  76. package/dist/types/utils/index.d.ts +2 -0
  77. package/dist/types/{parse-context-item.d.ts → utils/parse-context-item.d.ts} +1 -1
  78. package/dist/types/utils/resolve-initial-context.d.ts +1 -1
  79. package/dist/types/version.d.ts +1 -1
  80. package/docs/data-model.md +134 -0
  81. package/docs/lifecycle.md +163 -0
  82. package/docs/recipes.md +89 -0
  83. package/package.json +36 -8
  84. package/src/ContextModuleConfig.ts +147 -0
  85. package/src/ContextModuleConfigurator.interface.ts +145 -0
  86. package/src/ContextModuleConfigurator.ts +295 -0
  87. package/src/ContextProvider.ts +1 -2
  88. package/src/__tests__/ContextModuleConfigurator.test.ts +412 -0
  89. package/src/__tests__/mock/context-mock.test.ts +137 -0
  90. package/src/__tests__/mock/create-context-item-factory.test.ts +60 -0
  91. package/src/__tests__/mock/create-context-items.test.ts +58 -0
  92. package/src/index.ts +3 -5
  93. package/src/mock/ContextMockConfigurator.ts +244 -0
  94. package/src/mock/fixtures/create-context-item-factory.ts +62 -0
  95. package/src/mock/fixtures/create-context-items.ts +80 -0
  96. package/src/mock/fixtures/index.ts +28 -0
  97. package/src/mock/fixtures/string-to-seed.ts +18 -0
  98. package/src/mock/index.ts +33 -0
  99. package/src/mock/module.ts +54 -0
  100. package/src/module.ts +45 -17
  101. package/src/{get-context-selector.ts → selectors/get-context-selector.ts} +2 -6
  102. package/src/selectors/index.ts +12 -0
  103. package/src/{query-context-selector.ts → selectors/query-context-selector.ts} +2 -2
  104. package/src/{related-context-selector.ts → selectors/related-context-selector.ts} +2 -2
  105. package/src/utils/enable-context.ts +6 -10
  106. package/src/utils/index.ts +2 -0
  107. package/src/{parse-context-item.ts → utils/parse-context-item.ts} +1 -1
  108. package/src/utils/resolve-initial-context.ts +5 -2
  109. package/src/version.ts +1 -1
  110. package/tsconfig.json +6 -0
  111. package/vitest.config.ts +11 -0
  112. package/dist/esm/ContextConfigBuilder.js +0 -175
  113. package/dist/esm/ContextConfigBuilder.js.map +0 -1
  114. package/dist/esm/configurator.js +0 -104
  115. package/dist/esm/configurator.js.map +0 -1
  116. package/dist/esm/get-context-selector.js.map +0 -1
  117. package/dist/esm/parse-context-item.js.map +0 -1
  118. package/dist/esm/query-context-selector.js.map +0 -1
  119. package/dist/esm/related-context-selector.js.map +0 -1
  120. package/src/ContextConfigBuilder.ts +0 -258
  121. package/src/configurator.ts +0 -300
  122. /package/dist/esm/{parse-context-item.js → utils/parse-context-item.js} +0 -0
@@ -0,0 +1,244 @@
1
+ import { EMPTY, from, lastValueFrom, of, throwError } from 'rxjs';
2
+
3
+ import type { ModuleInitializerArgs } from '@equinor/fusion-framework-module';
4
+ import type { NavigationModule } from '@equinor/fusion-framework-module-navigation';
5
+ import type { ServicesModule } from '@equinor/fusion-framework-module-services';
6
+
7
+ import { ContextModuleConfigurator } from '../ContextModuleConfigurator';
8
+ import type { ContextModuleConfig } from '../ContextModuleConfig';
9
+ import type { IContextModuleConfigurator } from '../ContextModuleConfigurator.interface';
10
+ import type { ContextItem } from '../types';
11
+
12
+ /**
13
+ * Resolves a context item by id, or `undefined` if none matches.
14
+ *
15
+ * @remarks
16
+ * The escape hatch for {@link ContextMockConfigurator.setResolver} — anything
17
+ * the friendly seeding methods did not anticipate can be expressed here instead.
18
+ */
19
+ export type ContextResolverFn = (id: string) => ContextItem | undefined;
20
+
21
+ /**
22
+ * A {@link ContextModuleConfigurator} backed by in-memory context items instead
23
+ * of a real context API, for seeding context in tests.
24
+ *
25
+ * @remarks
26
+ * Two layers cover different needs, both running through the real
27
+ * `ContextProvider` logic underneath — only the data source is substituted,
28
+ * never `validateContext`, `resolveContext`, or parent-context propagation:
29
+ *
30
+ * - **Friendly layer** — {@link setCurrentContext}, {@link setContexts},
31
+ * {@link addContext}, {@link setRelatedContexts} — a small, context-domain
32
+ * vocabulary for the common case: seed a known item, get it back.
33
+ * - **Escape hatch** — {@link setResolver} — a raw id-lookup function for a
34
+ * custom id-based resolution strategy or a shape the friendly layer did not
35
+ * cover. Only replaces id-based lookup (used by `setCurrentContextById` and
36
+ * the initial context); it does not affect related-context resolution by
37
+ * item, which always goes through {@link setRelatedContexts} instead.
38
+ *
39
+ * Seeding the initial context (via {@link setCurrentContext}) overrides
40
+ * `resolveInitialContext` directly with the seeded item, so a test never needs
41
+ * to construct a fake navigation module or parent framework instance to make an
42
+ * app start up with a known context selected. Resolving a context id from a URL
43
+ * path on startup is not covered — that needs a fake router, which is separate,
44
+ * not-yet-built work.
45
+ *
46
+ * Seeded ids are never generated for you — every item is looked up and
47
+ * returned exactly by the id it was seeded with, so a test never sees a
48
+ * different id than the one it wrote. Use `createContextItemFactory` or
49
+ * `createContextItems` for fixtures needing ids of their own, rather than a
50
+ * random generator that would change on every run.
51
+ *
52
+ * Related-context resolution defaults to the same seeded pool, filtered to
53
+ * whichever type(s) the query asked for — related context is the same
54
+ * context, just a different type, exactly as `ContextProvider.resolveContext`
55
+ * uses it to resolve an item of an unexpected type into one of the configured
56
+ * type. Seed items of both types and resolution works with no extra wiring;
57
+ * {@link setRelatedContexts} overrides that default for one specific item.
58
+ *
59
+ * @example Seed and select a known context item
60
+ * ```ts
61
+ * enableContextMock(configurator, (mock) => {
62
+ * mock.setCurrentContext({ id: 'my-ctx', type: { id: 'ProjectMaster' }, value: {} });
63
+ * });
64
+ * ```
65
+ *
66
+ * @example Resolve a child-typed item into its parent type
67
+ * ```ts
68
+ * enableContextMock(configurator, (mock) => {
69
+ * // no explicit wiring needed — relatedContexts filters this same pool by type
70
+ * mock.setContexts([project, facility]);
71
+ * });
72
+ * ```
73
+ *
74
+ * @example Override related contexts for one specific item
75
+ * ```ts
76
+ * enableContextMock(configurator, (mock) => {
77
+ * mock.addContext(project);
78
+ * mock.setRelatedContexts(project.id, [facilityA, facilityB]);
79
+ * });
80
+ * ```
81
+ *
82
+ * @example Escape hatch for a custom resolution need
83
+ * ```ts
84
+ * enableContextMock(configurator, (mock) => {
85
+ * mock.setResolver((id) => (id === 'special' ? specialContextItem : undefined));
86
+ * });
87
+ * ```
88
+ */
89
+ export class ContextMockConfigurator extends ContextModuleConfigurator {
90
+ #contexts = new Map<string, ContextItem>();
91
+ #related = new Map<string, ContextItem[]>();
92
+ #resolver?: ContextResolverFn;
93
+ #pendingCurrentId?: string;
94
+
95
+ /**
96
+ * Registers the in-memory client up front, so `createConfig` never falls
97
+ * back to building one from a real `ServicesModule` — a mock needs neither
98
+ * an API provider nor a network to answer `get`/`query`/`related`.
99
+ */
100
+ constructor() {
101
+ super();
102
+ this.addConfigBuilder((builder) => {
103
+ builder.setContextClient({
104
+ get: (args) => {
105
+ const item = this.#resolve(args.id);
106
+ // a caller asking for an unseeded id gets a clear error, not a silent miss
107
+ return item
108
+ ? of(item)
109
+ : throwError(
110
+ () =>
111
+ new Error(
112
+ `ContextMockConfigurator: no context item resolves for id "${args.id}" — seed it with setCurrentContext/setContexts/addContext, or provide setResolver.`,
113
+ ),
114
+ );
115
+ },
116
+ query: () => of([...this.#contexts.values()]),
117
+ related: (args) => {
118
+ const override = this.#related.get(args.item.id);
119
+ // an explicit override for this exact item always wins
120
+ if (override) return of(override);
121
+ const types = args.filter?.type;
122
+ // otherwise: related context is the same seeded pool, filtered to the requested type(s)
123
+ return of(
124
+ [...this.#contexts.values()].filter(
125
+ (item) => item.id !== args.item.id && (!types || types.includes(item.type.id)),
126
+ ),
127
+ );
128
+ },
129
+ });
130
+ });
131
+ }
132
+
133
+ /**
134
+ * Seeds a context item and selects it as the context the app resolves on startup.
135
+ *
136
+ * @param item - The context item to seed and select.
137
+ * @returns This configurator, for chaining.
138
+ */
139
+ public setCurrentContext(item: ContextItem): this {
140
+ this.#contexts.set(item.id, item);
141
+ this.#pendingCurrentId = item.id;
142
+ return this;
143
+ }
144
+
145
+ /**
146
+ * Seeds multiple context items, making each resolvable by id.
147
+ *
148
+ * @remarks
149
+ * Does not select any of them as current — pair with {@link setCurrentContext}
150
+ * for that.
151
+ *
152
+ * @param items - The context items to seed.
153
+ * @returns This configurator, for chaining.
154
+ */
155
+ public setContexts(items: ContextItem[]): this {
156
+ // seed every item so each is individually resolvable by id
157
+ for (const item of items) this.#contexts.set(item.id, item);
158
+ return this;
159
+ }
160
+
161
+ /**
162
+ * Seeds a single context item, making it resolvable by id.
163
+ *
164
+ * @param item - The context item to seed.
165
+ * @returns This configurator, for chaining.
166
+ */
167
+ public addContext(item: ContextItem): this {
168
+ this.#contexts.set(item.id, item);
169
+ return this;
170
+ }
171
+
172
+ /**
173
+ * Overrides related-context resolution for one specific source item.
174
+ *
175
+ * @remarks
176
+ * Without this, `relatedContexts` filters the seeded pool by the requested
177
+ * type(s) — this is only needed when a test wants a specific item to resolve
178
+ * something other than that default (e.g. no related items at all).
179
+ *
180
+ * @param itemId - The id of the item relations are being overridden for.
181
+ * @param items - The context items to return from `relatedContexts` for that item.
182
+ * @returns This configurator, for chaining.
183
+ */
184
+ public setRelatedContexts(itemId: string, items: ContextItem[]): this {
185
+ this.#related.set(itemId, items);
186
+ return this;
187
+ }
188
+
189
+ /**
190
+ * Escape hatch: overrides id-based context resolution directly.
191
+ *
192
+ * @remarks
193
+ * For a custom id-lookup strategy or a shape the friendly seeding methods
194
+ * above did not cover — reaching for this means they were already tried
195
+ * and did not fit. Only replaces lookup by id (used by
196
+ * `setCurrentContextById` and the seeded initial context) — related-context
197
+ * resolution by item always goes through {@link setRelatedContexts} instead,
198
+ * regardless of this setting.
199
+ *
200
+ * @param fn - Resolves a context item by id, or returns `undefined` if none matches.
201
+ * @returns This configurator, for chaining.
202
+ */
203
+ public setResolver(fn: ContextResolverFn): this {
204
+ this.#resolver = fn;
205
+ return this;
206
+ }
207
+
208
+ /**
209
+ * Resolves an id through the escape hatch if one is set, otherwise the seeded map.
210
+ *
211
+ * @param id - The context id to resolve.
212
+ * @returns The matching context item, or `undefined`.
213
+ */
214
+ #resolve(id: string): ContextItem | undefined {
215
+ // the escape hatch, when set, replaces the seeded map entirely
216
+ return this.#resolver ? this.#resolver(id) : this.#contexts.get(id);
217
+ }
218
+
219
+ /**
220
+ * Defaults `resolveInitialContext` from the seeded/resolved state, once the
221
+ * real config has been assembled.
222
+ *
223
+ * @param config - The context module config assembled by the base configurator.
224
+ * @param init - Module initializer arguments.
225
+ * @returns The context module configuration, backed by seeded/resolved data.
226
+ */
227
+ protected override async _processConfig(
228
+ config: Partial<ContextModuleConfig>,
229
+ init: ModuleInitializerArgs<IContextModuleConfigurator, [ServicesModule, NavigationModule]>,
230
+ ): Promise<ContextModuleConfig> {
231
+ // the base default is a plain Observable (`of(...)`), not a thenable — unwrap it explicitly
232
+ const resolved = await lastValueFrom(from(super._processConfig(config, init)));
233
+ const id = this.#pendingCurrentId;
234
+
235
+ // The base default resolves from the URL path or a parent framework, and
236
+ // throws when neither is present — the common case for an isolated mock.
237
+ // Resolve the seeded item when one was selected, otherwise resolve none.
238
+ resolved.resolveInitialContext = id ? () => of(this.#resolve(id)) : () => EMPTY;
239
+
240
+ return resolved;
241
+ }
242
+ }
243
+
244
+ export default ContextMockConfigurator;
@@ -0,0 +1,62 @@
1
+ import { Faker, en } from '@faker-js/faker';
2
+
3
+ import type { ContextItem } from '../../types';
4
+ import { stringToSeed } from './string-to-seed';
5
+
6
+ /**
7
+ * Creates one {@link ContextItem} fixture per call, for a single factory instance.
8
+ *
9
+ * @param overrides - Fields to override on the generated item. Supplying `id`
10
+ * skips the sequential generator for that one item.
11
+ * @returns A fully-formed {@link ContextItem}.
12
+ */
13
+ export type MockContextItemFactory = (overrides?: Partial<ContextItem>) => ContextItem;
14
+
15
+ /**
16
+ * Builds a {@link MockContextItemFactory} producing deterministic, sequential
17
+ * ids of the form `<prefix>-<n>`, with a realistic `title` filled in by
18
+ * {@link https://fakerjs.dev/ | faker} (`@faker-js/faker`, a peer dependency —
19
+ * only required if this factory is imported).
20
+ *
21
+ * @remarks
22
+ * Ids are scoped to the returned factory, not shared globally, so two tests
23
+ * creating their own factory each start counting from `1` — a random id (e.g.
24
+ * `crypto.randomUUID()`) would change on every run and break any assertion
25
+ * that seeds one item and expects to see that same id again. The faker seed
26
+ * is derived from that same id, so the generated `title` is just as
27
+ * deterministic. For fixtures spanning several context types (e.g. a
28
+ * parent/child type hierarchy), use `createContextItems` instead — it
29
+ * assigns ids per type and wires the type hierarchy for you.
30
+ *
31
+ * @param prefix - The id prefix. Defaults to `'ctx'`.
32
+ * @returns A function creating one {@link ContextItem} fixture per call.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const createContextItem = createContextItemFactory();
37
+ *
38
+ * const project = createContextItem(); // id: 'ctx-1', title: a deterministic faker company name
39
+ * const facility = createContextItem({ title: 'Facility A' }); // id: 'ctx-2', title overridden
40
+ *
41
+ * mock.setContexts([project, facility]);
42
+ * ```
43
+ */
44
+ export const createContextItemFactory = (prefix = 'ctx'): MockContextItemFactory => {
45
+ const created: ContextItem[] = [];
46
+ return (overrides: Partial<ContextItem> = {}): ContextItem => {
47
+ // overrides.id, when supplied, always wins over the sequential generator
48
+ const id = overrides.id ?? `${prefix}-${created.length + 1}`;
49
+ const faker = new Faker({ seed: stringToSeed(id), locale: en });
50
+ const item: ContextItem = {
51
+ type: { id: 'Mock' },
52
+ value: {},
53
+ title: faker.company.name(),
54
+ ...overrides,
55
+ id,
56
+ };
57
+ created.push(item);
58
+ return item;
59
+ };
60
+ };
61
+
62
+ export default createContextItemFactory;
@@ -0,0 +1,80 @@
1
+ import { Faker, en } from '@faker-js/faker';
2
+
3
+ import type { ContextItem } from '../../types';
4
+ import { stringToSeed } from './string-to-seed';
5
+
6
+ /** Overridable {@link ContextItem} fields. `id` and `type` are always assigned by the type seed itself. */
7
+ export type ContextItemOverrides = Partial<Omit<ContextItem, 'id' | 'type'>>;
8
+
9
+ /**
10
+ * Describes one context type to generate fixtures for.
11
+ *
12
+ * @param type - The context type id (e.g. `'ProjectMaster'`, `'Contract'`).
13
+ * @param count - Number of items to generate for this type. Defaults to `1`.
14
+ * @param parentTypeIds - Parent type ids, when this type is a child in the
15
+ * type hierarchy — sets `type.isChildType`/`type.parentTypeIds` on every
16
+ * generated item of this type.
17
+ * @param item - Per-item overrides, called with the item's 1-based index
18
+ * within this type.
19
+ */
20
+ export interface ContextTypeSeed {
21
+ type: string;
22
+ count?: number;
23
+ parentTypeIds?: string[];
24
+ item?: (index: number) => ContextItemOverrides;
25
+ }
26
+
27
+ /**
28
+ * Generates a batch of {@link ContextItem} fixtures across one or more
29
+ * context types, with deterministic ids, a realistic `title` from
30
+ * {@link https://fakerjs.dev/ | faker} (`@faker-js/faker`, a peer dependency —
31
+ * only required if this factory is imported), and a consistent type hierarchy.
32
+ *
33
+ * @remarks
34
+ * Ids are `<type>-<n>` (lowercased type, 1-based per type), so results are
35
+ * stable across runs and readable in test failures. `title` is filled in from
36
+ * a faker instance seeded by that same id, so it's just as deterministic.
37
+ * Feeding the result to `ContextMockConfigurator.setContexts` is enough to
38
+ * make related-context resolution work across types — the mock's
39
+ * `relatedContexts` filters this same seeded pool by type, so a child-typed
40
+ * item resolves into a parent of its `parentTypeIds` without any per-item
41
+ * wiring. That default is a simplification: the real context API resolves
42
+ * relations per specific instance (a `Contract` belongs to one particular
43
+ * `ProjectMaster`, not every `ProjectMaster` in the system) — seed only one
44
+ * instance per type when that distinction doesn't matter to the test, or use
45
+ * `ContextMockConfigurator.setRelatedContexts` to pin a specific item's
46
+ * relations when it does.
47
+ *
48
+ * @param types - The context types, and how many items to generate for each.
49
+ * @returns The generated context items, in the order the type seeds were given.
50
+ *
51
+ * @example Seed a project type and a child contract type
52
+ * ```ts
53
+ * const [project] = createContextItems([{ type: 'ProjectMaster' }]);
54
+ * const [contract] = createContextItems([
55
+ * { type: 'Contract', parentTypeIds: ['ProjectMaster'] },
56
+ * ]);
57
+ *
58
+ * enableContextMock(configurator, (mock) => {
59
+ * mock.setContexts([project, contract]);
60
+ * // relatedContexts({ item: contract, filter: { type: ['ProjectMaster'] } }) now resolves `project`
61
+ * });
62
+ * ```
63
+ */
64
+ export const createContextItems = (types: ContextTypeSeed[]): ContextItem[] =>
65
+ types.flatMap(({ type, count = 1, parentTypeIds, item }) =>
66
+ Array.from({ length: count }, (_, i): ContextItem => {
67
+ const index = i + 1;
68
+ const id = `${type.toLowerCase()}-${index}`;
69
+ const faker = new Faker({ seed: stringToSeed(id), locale: en });
70
+ return {
71
+ value: {},
72
+ title: faker.company.name(),
73
+ ...item?.(index),
74
+ id,
75
+ type: parentTypeIds ? { id: type, isChildType: true, parentTypeIds } : { id: type },
76
+ };
77
+ }),
78
+ );
79
+
80
+ export default createContextItems;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Fixture generators for {@link ContextMockConfigurator} test data.
3
+ *
4
+ * @remarks
5
+ * A separate entry point from `@equinor/fusion-framework-module-context/mock`
6
+ * because these factories use {@link https://fakerjs.dev/ | faker}
7
+ * (`@faker-js/faker`) for realistic values — an optional peer dependency, only
8
+ * required if this entry point is imported. `enableContextMock` and
9
+ * `ContextMockConfigurator` on the main `/mock` entry point never require it.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * import { createContextItems } from '@equinor/fusion-framework-module-context/mock/fixtures';
14
+ *
15
+ * const [project] = createContextItems([{ type: 'ProjectMaster' }]);
16
+ * ```
17
+ *
18
+ * @packageDocumentation
19
+ */
20
+ export {
21
+ createContextItemFactory,
22
+ type MockContextItemFactory,
23
+ } from './create-context-item-factory';
24
+ export {
25
+ createContextItems,
26
+ type ContextTypeSeed,
27
+ type ContextItemOverrides,
28
+ } from './create-context-items';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Derives a numeric seed from a string, for a deterministic {@link https://fakerjs.dev/ | faker} instance.
3
+ *
4
+ * @remarks
5
+ * A pure-JS hash (no `node:crypto`) so fixtures stay usable in browser-like test
6
+ * environments, not just Node. Same id in, same seed out, every run.
7
+ *
8
+ * @param value - The string to derive a seed from (typically a generated item id).
9
+ * @returns A 32-bit unsigned integer seed.
10
+ */
11
+ export const stringToSeed = (value: string): number =>
12
+ // FNV-1a-style hash: fold each char in, keep the running hash unsigned 32-bit
13
+ [...value].reduce(
14
+ (hash, char) => Math.imul(hash ^ char.charCodeAt(0), 16777619) >>> 0,
15
+ 2166136261,
16
+ );
17
+
18
+ export default stringToSeed;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Mock context module for tests: real provider, real configurator, in-memory data.
3
+ *
4
+ * @remarks
5
+ * Substituting the data source is the smallest change that removes the context
6
+ * API, HTTP mocking, and service-discovery mocking from a test. Everything
7
+ * above it — validation, resolution, parent-context propagation, initial-context
8
+ * selection — is the production code path.
9
+ *
10
+ * This is one of two ways to mock context data in tests: a small, static,
11
+ * in-memory pool (this module — no HTTP layer involved at all). The other is
12
+ * mocking the context API's HTTP responses directly (e.g. with MSW), which
13
+ * exercises the real `ContextModuleConfigurator`/services/HTTP pipeline —
14
+ * reach for that instead when the test needs to cover that pipeline itself.
15
+ * For fixture generators with realistic fake data, see
16
+ * `@equinor/fusion-framework-module-context/mock/fixtures`.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * import { enableContextMock } from '@equinor/fusion-framework-module-context/mock';
21
+ *
22
+ * enableContextMock(configurator, (mock) => {
23
+ * mock.setCurrentContext({ id: 'my-ctx', type: { id: 'ProjectMaster' }, value: {} });
24
+ * });
25
+ * ```
26
+ *
27
+ * @packageDocumentation
28
+ */
29
+ export {
30
+ ContextMockConfigurator,
31
+ type ContextResolverFn,
32
+ } from './ContextMockConfigurator';
33
+ export { enableContextMock, contextMockModule, type ContextMockConfigFn } from './module';
@@ -0,0 +1,54 @@
1
+ import type { IModulesConfigurator } from '@equinor/fusion-framework-module';
2
+
3
+ import { module, type ContextModule } from '../module';
4
+
5
+ import { ContextMockConfigurator } from './ContextMockConfigurator';
6
+
7
+ /**
8
+ * The context module with an in-memory mock configurator instead of a real
9
+ * context API.
10
+ *
11
+ * @remarks
12
+ * Only `configure` differs from the real module. `initialize` is the production
13
+ * one, untouched, so a test exercises the real `ContextProvider` startup path,
14
+ * `validateContext`/`resolveContext`, and parent-context propagation — a
15
+ * rehearsal of the module, not a stand-in for it.
16
+ */
17
+ export const contextMockModule: ContextModule = {
18
+ ...module,
19
+ configure: () => new ContextMockConfigurator(),
20
+ };
21
+
22
+ /**
23
+ * Configuration callback for {@link enableContextMock}.
24
+ */
25
+ export type ContextMockConfigFn = (mock: ContextMockConfigurator) => void | Promise<void>;
26
+
27
+ /**
28
+ * Enables the context module against in-memory seeded data, so a test needs no
29
+ * context API, no HTTP mock, and no service-discovery mock.
30
+ *
31
+ * @remarks
32
+ * Registered last, this replaces whichever context module the configurator
33
+ * already carries, so it works on a `FrameworkConfigurator` that pre-registers
34
+ * the real one.
35
+ *
36
+ * @param configurator - The modules configurator to register on.
37
+ * @param configure - Optional callback to seed context items or override resolution.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * enableContextMock(configurator, (mock) => {
42
+ * mock.setCurrentContext({ id: 'my-ctx', type: { id: 'ProjectMaster' }, value: {} });
43
+ * });
44
+ * ```
45
+ */
46
+ export const enableContextMock = (
47
+ // biome-ignore lint/suspicious/noExplicitAny: must be any to support all module types
48
+ configurator: IModulesConfigurator<any, any>,
49
+ configure?: ContextMockConfigFn,
50
+ ): void => {
51
+ configurator.addConfig({ module: contextMockModule, configure } as {
52
+ module: ContextModule;
53
+ });
54
+ };
package/src/module.ts CHANGED
@@ -5,8 +5,16 @@ import type { Module, ModulesInstance } from '@equinor/fusion-framework-module';
5
5
  import type { EventModule } from '@equinor/fusion-framework-module-event';
6
6
  import type { ServicesModule } from '@equinor/fusion-framework-module-services';
7
7
  import type { NavigationModule } from '@equinor/fusion-framework-module-navigation';
8
-
9
- import { type IContextModuleConfigurator, ContextModuleConfigurator } from './configurator';
8
+ import {
9
+ TelemetryLevel,
10
+ TelemetryScope,
11
+ type TelemetryModule,
12
+ } from '@equinor/fusion-framework-module-telemetry';
13
+
14
+ import {
15
+ type IContextModuleConfigurator,
16
+ ContextModuleConfigurator,
17
+ } from './ContextModuleConfigurator';
10
18
  import { type IContextProvider, ContextProvider } from './ContextProvider';
11
19
  import type { ContextItem } from './types';
12
20
 
@@ -31,7 +39,7 @@ export const moduleKey: ContextModuleKey = 'context';
31
39
  * @typeParam ContextModuleKey - The unique key identifying the context module.
32
40
  * @typeParam IContextProvider - The provider interface for context-related services.
33
41
  * @typeParam IContextModuleConfigurator - The configurator interface for customizing the context module.
34
- * @typeParam [ServicesModule, EventModule, NavigationModule] - The tuple of dependent modules required by the context module.
42
+ * @typeParam [ServicesModule, EventModule, NavigationModule, TelemetryModule] - The tuple of dependent modules required by the context module.
35
43
  *
36
44
  * @see Module
37
45
  */
@@ -39,7 +47,7 @@ export type ContextModule = Module<
39
47
  ContextModuleKey,
40
48
  IContextProvider,
41
49
  IContextModuleConfigurator,
42
- [ServicesModule, EventModule, NavigationModule]
50
+ [ServicesModule, EventModule, NavigationModule, TelemetryModule]
43
51
  >;
44
52
 
45
53
  /**
@@ -68,16 +76,21 @@ export const module: ContextModule = {
68
76
  configure: () => new ContextModuleConfigurator(),
69
77
  initialize: async function (args) {
70
78
  // create config from configurator
71
- const config = await (args.config as ContextModuleConfigurator).createConfig(args);
79
+ const config = await (args.config as ContextModuleConfigurator).createConfigAsync(args);
72
80
 
73
81
  // get event module if available
74
82
  const event = args.hasModule('event') ? await args.requireInstance('event') : undefined;
75
83
 
84
+ // get telemetry module if available, for tracking context resolution outcomes
85
+ const telemetry = args.hasModule('telemetry')
86
+ ? await args.requireInstance('telemetry')
87
+ : undefined;
88
+
76
89
  // get parent context provider if available
77
90
  const parentProvider = (args.ref as ModulesInstance<[ContextModule]>)?.context;
78
91
 
79
- // create context provider
80
- const provider = new ContextProvider({ config, event, parentContext: parentProvider });
92
+ // create context provider; parent context is wired up later via connectParentContext, not the deprecated ctor arg
93
+ const provider = new ContextProvider({ config, event });
81
94
 
82
95
  // create subscription for disposing the provider
83
96
  const subscription = new Subscription(() => provider.dispose());
@@ -106,27 +119,42 @@ export const module: ContextModule = {
106
119
  resolveInitialContext$
107
120
  .pipe(
108
121
  catchError((err) => {
109
- console.warn(
110
- 'ContextModule.postInitialize',
111
- 'failed to resolve initial context',
112
- err,
113
- );
122
+ const exception = err instanceof Error ? err : new Error(String(err));
123
+ // report through telemetry when available, otherwise fall back to console.warn below
124
+ if (telemetry) {
125
+ telemetry.trackException({
126
+ name: 'Context::postInitialize.resolveInitialContext',
127
+ exception,
128
+ level: TelemetryLevel.Warning,
129
+ scope: ['context', TelemetryScope.Framework],
130
+ });
131
+ } else {
132
+ // no telemetry module registered - fall back to a visible warning so a
133
+ // genuine resolution failure isn't silently swallowed
134
+ console.warn('Context::postInitialize.resolveInitialContext', exception);
135
+ }
114
136
  // failed to resolve initial context, complete immediately
115
137
  return EMPTY;
116
138
  }),
117
139
  )
118
140
  .subscribe({
119
141
  next: (item) => {
120
- console.debug(
121
- 'ContextModule.postInitialize',
122
- `initial context was resolved to [${item ? item.id : 'none'}]`,
123
- item,
124
- );
142
+ telemetry?.trackEvent({
143
+ name: 'Context::postInitialize.initialContextResolved',
144
+ level: TelemetryLevel.Debug,
145
+ scope: ['context', TelemetryScope.Framework],
146
+ properties: { contextId: item ? item.id : 'none' },
147
+ });
125
148
  },
126
149
  complete: () => {
127
150
  // connect parent context if available when stream completes
128
151
  if (config.connectParentContext !== false && parentProvider) {
129
152
  provider.connectParentContext(parentProvider);
153
+ telemetry?.trackEvent({
154
+ name: 'Context::postInitialize.parentContextConnected',
155
+ level: TelemetryLevel.Debug,
156
+ scope: ['context', TelemetryScope.Framework],
157
+ });
130
158
  }
131
159
  subscriber.complete();
132
160
  },
@@ -1,7 +1,7 @@
1
1
  import type { GetContextResponse } from '@equinor/fusion-framework-module-services/context/get';
2
2
 
3
- import { parseContextItem } from './parse-context-item';
4
- import type { ContextItem } from './types';
3
+ import { parseContextItem } from '../utils/parse-context-item';
4
+ import type { ContextItem } from '../types';
5
5
 
6
6
  /**
7
7
  * Parse the response from the GetContext API into a context item.
@@ -12,7 +12,3 @@ export const getContextSelector = async (response: Response): Promise<ContextIte
12
12
  const result = (await response.json()) as GetContextResponse<'v1'>;
13
13
  return parseContextItem(result);
14
14
  };
15
-
16
- // Deliberately re-exported from here to preserve the package's existing selectors entry point
17
- export { queryContextSelector } from './query-context-selector';
18
- export { relatedContextSelector } from './related-context-selector';
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Response selectors that parse raw context API responses into {@link ContextItem}s.
3
+ *
4
+ * - {@link getContextSelector} — parses a single-item GetContext response.
5
+ * - {@link queryContextSelector} — parses a multi-item QueryContext response.
6
+ * - {@link relatedContextSelector} — parses a multi-item RelatedContext response.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ export { getContextSelector } from './get-context-selector';
11
+ export { queryContextSelector } from './query-context-selector';
12
+ export { relatedContextSelector } from './related-context-selector';