@xrmforge/helpers 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 XrmForge Contributors
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 XrmForge Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,164 @@
1
+ # @xrmforge/helpers
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@xrmforge/helpers.svg)](https://www.npmjs.com/package/@xrmforge/helpers)
4
+ [![license](https://img.shields.io/npm/l/@xrmforge/helpers.svg)](https://github.com/juergenbeck/XrmForge/blob/main/LICENSE)
5
+
6
+ **Browser-safe runtime helpers for Dynamics 365 form scripts.** Zero Node.js dependencies, safe to bundle into esbuild IIFE Web Resources. Pairs with the types generated by [`@xrmforge/typegen`](https://www.npmjs.com/package/@xrmforge/typegen) to eliminate raw strings and magic values from your form code.
7
+
8
+ > Part of [XrmForge](https://github.com/juergenbeck/XrmForge#readme). This is the package you import in actual D365 form scripts.
9
+
10
+ ---
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ npm install @xrmforge/helpers
16
+ ```
17
+
18
+ Install as a regular **dependency** (not `devDependency`): generated Custom API action files import the action factories from this package at runtime.
19
+
20
+ **Requirements:** `@types/xrm` (>= 9.0.0) as a peer dependency.
21
+
22
+ ---
23
+
24
+ ## What you get
25
+
26
+ | Area | Exports |
27
+ |------|---------|
28
+ | Web API query strings | `select`, `selectExpand`, `parseLookup`, `parseLookups`, `parseFormattedValue`, `parseMultiSelect`, `formLookup`, `formLookupId` |
29
+ | Typed form proxy | `typedForm`, `normalizeGuid`, types `TypedForm`, `FormTypeInfoProtocol` |
30
+ | Xrm constants (`const enum`) | `DisplayState`, `FormType`, `isFormType`, `FormNotificationLevel`, `AppNotificationLevel`, `RequiredLevel`, `SubmitMode`, `SaveMode`, `ClientType`, `ClientState`, `OperationType`, `StructuralProperty`, `BindingType` |
31
+ | Custom API runtime | `createBoundAction`, `createUnboundAction`, `createBoundFunction`, `createUnboundFunction`, `executeRequest`, `executeMultiple` |
32
+ | Convenience | `withProgress`, `callCloudFlow`, `clearAndSubmit`, `setUnsafeAndSubmit`, `addAppNotification` |
33
+
34
+ ---
35
+
36
+ ## TypedForm: direct, typed field access
37
+
38
+ `typedForm()` wraps a `FormContext` so you can read and write fields as properties instead of `getAttribute("...")` chains. Pass the generated `<Form>TypeInfo` type (typegen >= 0.10.0) -- it bundles the field/attribute/control maps so type extraction works reliably across package boundaries.
39
+
40
+ ```typescript
41
+ import { typedForm } from '@xrmforge/helpers';
42
+ import type { AccountMainFormTypeInfo } from '../../generated/forms/account.js';
43
+
44
+ export function onLoad(ctx: Xrm.Events.EventContext): void {
45
+ const form = typedForm<AccountMainFormTypeInfo>(ctx.getFormContext());
46
+
47
+ form.name.getValue(); // string | null (typed StringAttribute)
48
+ form.revenue.setValue(150000); // typed NumberAttribute
49
+
50
+ form.controls.name.setDisabled(true); // typed control access
51
+ form.$context.ui.tabs.get('SUMMARY_TAB'); // full FormContext escape hatch
52
+ form.$unsafe('off_form_field')?.setValue('x'); // off-form field (nullable)
53
+ }
54
+ ```
55
+
56
+ `setValue()` on the proxy automatically calls `setSubmitMode('always')`, so programmatically set values are not silently dropped by D365 AutoSave. Assigning to a field directly (`form.name = ...`) throws a `TypeError` telling you to use `.setValue()`.
57
+
58
+ ---
59
+
60
+ ## Web API helpers
61
+
62
+ Build OData query strings from generated `Fields` enums and parse responses without hand-written annotation keys.
63
+
64
+ ```typescript
65
+ import { select, parseLookup, parseFormattedValue, parseMultiSelect } from '@xrmforge/helpers';
66
+ import { AccountFields } from '../../generated/fields/account.js';
67
+ import { AccountNavigationProperties as Nav } from '../../generated/entities/account.js';
68
+
69
+ const result = await Xrm.WebApi.retrieveRecord('account', id,
70
+ select(AccountFields.Name, AccountFields.WebsiteUrl, AccountFields.PrimaryContact));
71
+
72
+ const contact = parseLookup(result, Nav.PrimaryContact); // { id, name, entityType } | null
73
+ const status = parseFormattedValue(result, 'statecode'); // "Active" instead of 0
74
+ const types = parseMultiSelect(result.markant_typesmulticode); // normalize to number[]
75
+ ```
76
+
77
+ `formLookup()` / `formLookupId()` extract a lookup (with a brace-normalized GUID) straight from a form attribute:
78
+
79
+ ```typescript
80
+ import { formLookupId } from '@xrmforge/helpers';
81
+ const accountId = formLookupId(form.getAttribute(Fields.AccountId)); // string | null
82
+ ```
83
+
84
+ ---
85
+
86
+ ## Xrm constants instead of raw strings
87
+
88
+ `@types/xrm` types these values as string literals but provides **no runtime constants** (`XrmEnum` does not exist at runtime under esbuild). These `const enum`s are inlined at compile time -- zero runtime cost, no `XrmEnum is not defined` surprises.
89
+
90
+ ```typescript
91
+ import { DisplayState, FormNotificationLevel, RequiredLevel, SubmitMode, SaveMode } from '@xrmforge/helpers';
92
+
93
+ tab.setDisplayState(DisplayState.Expanded);
94
+ form.$context.ui.setFormNotification('Saved.', FormNotificationLevel.Info, 'saved');
95
+ form.email.setRequiredLevel(RequiredLevel.Required);
96
+ ```
97
+
98
+ Comparing form types needs care: `getFormType()` is typed as the distinct `XrmEnum.FormType`, so a direct `===` fails to compile under `strict`. Use `isFormType()`:
99
+
100
+ ```typescript
101
+ import { isFormType, FormType } from '@xrmforge/helpers';
102
+ if (isFormType(form.$context, FormType.Create)) { /* only on create */ }
103
+ ```
104
+
105
+ ---
106
+
107
+ ## Custom API executors
108
+
109
+ Generated action files (in `generated/actions/`) use the runtime factories from this package. Each executor exposes `.execute()` (calls `Xrm.WebApi`) and `.request()` (for batching).
110
+
111
+ ```typescript
112
+ import { WinQuote } from '../generated/actions/quote';
113
+ import { ValidateMandatoryFields } from '../generated/actions/global';
114
+
115
+ // Bound action: void result throws on failure, so just await
116
+ await WinQuote.execute(quoteId);
117
+
118
+ // Unbound action with typed params and response
119
+ const result = await ValidateMandatoryFields.execute({ TargetId: id, RuleSet: 'Full', Language: 'de' });
120
+ if (!result.IsValid) alert(result.MessageDe);
121
+ ```
122
+
123
+ Batch multiple calls in one round-trip with `executeMultiple` and `.request()`:
124
+
125
+ ```typescript
126
+ import { executeMultiple } from '@xrmforge/helpers';
127
+ await executeMultiple([
128
+ ApproveRecord.request({ RecordId: id }),
129
+ NotifyOwner.request({ RecordId: id, Message: 'Approved' }),
130
+ ]);
131
+ ```
132
+
133
+ You can also build executors by hand with `createBoundAction` / `createUnboundAction` / `createBoundFunction` / `createUnboundFunction`.
134
+
135
+ ---
136
+
137
+ ## Convenience helpers
138
+
139
+ ```typescript
140
+ import { withProgress, callCloudFlow, clearAndSubmit, setUnsafeAndSubmit, addAppNotification, AppNotificationLevel } from '@xrmforge/helpers';
141
+
142
+ // Progress spinner around an async operation (errors propagate to your handler wrapper)
143
+ await withProgress('Processing...', () => WinQuote.execute(quoteId));
144
+
145
+ // Typed Power Automate cloud-flow call (HTTP-trigger URL from configuration, never hard-coded)
146
+ const price = await callCloudFlow<{ quoteId: string }, { total: number }>(FLOW_URL, { quoteId });
147
+
148
+ // Clear / set an attribute and force it to submit (avoids silent AutoSave drops)
149
+ clearAndSubmit(form.revenue);
150
+ setUnsafeAndSubmit(form, OpportunityFields.VslBeauftragung, closeDate);
151
+
152
+ // Global banner notification
153
+ await addAppNotification('Saved.', AppNotificationLevel.Success, { showCloseButton: true });
154
+ ```
155
+
156
+ ---
157
+
158
+ ## Documentation
159
+
160
+ Full guide and patterns: [XrmForge on GitHub](https://github.com/juergenbeck/XrmForge#readme).
161
+
162
+ ## License
163
+
164
+ [MIT](https://github.com/juergenbeck/XrmForge/blob/main/LICENSE) (c) XrmForge Contributors.
package/dist/index.d.ts CHANGED
@@ -93,6 +93,30 @@ declare function parseLookups(response: Record<string, unknown>, navigationPrope
93
93
  * ```
94
94
  */
95
95
  declare function parseFormattedValue(response: Record<string, unknown>, fieldName: string): string | null;
96
+ /**
97
+ * Parse a MultiSelect OptionSet value into a number array.
98
+ *
99
+ * MultiSelect OptionSets come back in different shapes: the Web API returns a
100
+ * comma-separated string (`"595300000,595300001"`), a form attribute returns a
101
+ * `number[]`. This normalizes all shapes (comma string, number[], single number,
102
+ * null/undefined) to a clean `number[]` (empty/whitespace parts dropped).
103
+ *
104
+ * @param value - The raw value (comma string, number[], number, or null)
105
+ * @param emptyAsNull - When `true`, an empty result yields `null` instead of `[]`
106
+ * (handy for `setValue`, which treats `null` as "clear")
107
+ * @returns The parsed option values
108
+ *
109
+ * @example
110
+ * // Web API response -> number[] for comparison:
111
+ * const types = parseMultiSelect(account.markant_customertypemulticode);
112
+ * if (types.includes(CustomerType.Industry)) { ... }
113
+ *
114
+ * // Writing back to a form field (empty -> null clears it):
115
+ * form.markant_customertypemulticode.setValue(parseMultiSelect(raw, true));
116
+ */
117
+ declare function parseMultiSelect(value: unknown): number[];
118
+ declare function parseMultiSelect(value: unknown, emptyAsNull: false): number[];
119
+ declare function parseMultiSelect(value: unknown, emptyAsNull: true): number[] | null;
96
120
  /**
97
121
  * Build an OData $select and $expand query string.
98
122
  *
@@ -223,6 +247,19 @@ declare const enum FormNotificationLevel {
223
247
  Warning = "WARNING",
224
248
  Info = "INFO"
225
249
  }
250
+ /**
251
+ * App-level (global) notification level for Xrm.App.addGlobalNotification.
252
+ *
253
+ * Mirrors XrmEnum.AppNotificationLevel, which (like all XrmEnum const enums) does
254
+ * NOT exist at runtime. Use this enum; {@link addAppNotification} applies the cast
255
+ * to the @types/xrm typings at a single boundary.
256
+ */
257
+ declare const enum AppNotificationLevel {
258
+ Success = 1,
259
+ Error = 2,
260
+ Warning = 3,
261
+ Information = 4
262
+ }
226
263
  /** Attribute required level (attribute.setRequiredLevel) */
227
264
  declare const enum RequiredLevel {
228
265
  None = "none",
@@ -306,9 +343,9 @@ declare const enum BindingType {
306
343
  * import { createBoundAction } from '@xrmforge/helpers';
307
344
  * export const WinQuote = createBoundAction('markant_winquote', 'quote');
308
345
  *
309
- * // Developer code (in quote-form.ts):
346
+ * // Developer code (in quote-form.ts): void action throws on failure, so just await it
310
347
  * import { WinQuote } from '../generated/actions/quote';
311
- * const response = await WinQuote.execute(recordId);
348
+ * await WinQuote.execute(recordId);
312
349
  * ```
313
350
  */
314
351
  /** Parameter metadata for getMetadata().parameterTypes */
@@ -320,22 +357,22 @@ interface ParameterMeta {
320
357
  type ParameterMetaMap = Record<string, ParameterMeta>;
321
358
  /** Executor for a bound action without additional parameters */
322
359
  interface BoundActionExecutor<TResult = void> {
323
- execute(recordId: string): Promise<TResult extends void ? Response : TResult>;
360
+ execute(recordId: string): Promise<TResult extends void ? void : TResult>;
324
361
  request(recordId: string): Record<string, unknown>;
325
362
  }
326
363
  /** Executor for a bound action with typed parameters */
327
364
  interface BoundActionWithParamsExecutor<TParams, TResult = void> {
328
- execute(recordId: string, params: TParams): Promise<TResult extends void ? Response : TResult>;
365
+ execute(recordId: string, params: TParams): Promise<TResult extends void ? void : TResult>;
329
366
  request(recordId: string, params: TParams): Record<string, unknown>;
330
367
  }
331
368
  /** Executor for an unbound action without parameters */
332
369
  interface UnboundActionExecutor<TResult = void> {
333
- execute(): Promise<TResult extends void ? Response : TResult>;
370
+ execute(): Promise<TResult extends void ? void : TResult>;
334
371
  request(): Record<string, unknown>;
335
372
  }
336
373
  /** Executor for an unbound action with typed parameters and optional typed response */
337
374
  interface UnboundActionWithParamsExecutor<TParams, TResult = void> {
338
- execute(params: TParams): Promise<TResult extends void ? Response : TResult>;
375
+ execute(params: TParams): Promise<TResult extends void ? void : TResult>;
339
376
  request(params: TParams): Record<string, unknown>;
340
377
  }
341
378
  /** Executor for an unbound function with typed response */
@@ -668,4 +705,74 @@ interface CloudFlowOptions {
668
705
  */
669
706
  declare function callCloudFlow<TReq = unknown, TRes = unknown>(triggerUrl: string, body?: TReq, options?: CloudFlowOptions): Promise<TRes>;
670
707
 
671
- export { BindingType, type BoundActionExecutor, type BoundActionWithParamsExecutor, type BoundFunctionExecutor, ClientState, ClientType, type CloudFlowOptions, DisplayState, type FormFields, FormNotificationLevel, FormType, type FormTypeInfoProtocol, OperationType, type ParameterMeta, type ParameterMetaMap, RequiredLevel, SaveMode, StructuralProperty, SubmitMode, type TypedForm, type UnboundActionExecutor, type UnboundActionWithParamsExecutor, type UnboundFunctionExecutor, callCloudFlow, createBoundAction, createBoundFunction, createUnboundAction, createUnboundFunction, executeMultiple, executeRequest, formLookup, formLookupId, isFormType, normalizeGuid, parseFormattedValue, parseLookup, parseLookups, select, selectExpand, typedForm, withProgress };
708
+ /**
709
+ * @xrmforge/helpers - Attribute submit helpers
710
+ *
711
+ * Set or clear an attribute and force it to be submitted (SubmitMode.Always).
712
+ * D365 AutoSave only submits dirty attributes; programmatically set values on
713
+ * locked/calculated or off-form fields can otherwise be silently dropped.
714
+ */
715
+ /**
716
+ * Clear an attribute (`setValue(null)`) and force it to be submitted.
717
+ *
718
+ * Prefer this over a generic `setAndSubmit(attr, null)`: passing a literal `null`
719
+ * as the value makes TypeScript infer the value type as `null` and fights the
720
+ * attribute's real value type (F-LMA7-09). A dedicated clear helper has no value
721
+ * parameter, so there is nothing to mis-infer.
722
+ *
723
+ * @param attr - A settable attribute (e.g. `form.revenue` from the typedForm proxy)
724
+ */
725
+ declare function clearAndSubmit(attr: {
726
+ setValue(value: null): void;
727
+ setSubmitMode(mode: Xrm.SubmitMode): void;
728
+ }): void;
729
+ /**
730
+ * Set an off-form attribute (loaded by D365 but not on the current form layout,
731
+ * reached via the typedForm `$unsafe` proxy) and force submit.
732
+ *
733
+ * The typedForm proxy only exposes on-form fields; off-form fields go through
734
+ * `$unsafe()`, which returns `Attribute | null`. This helper bundles the null
735
+ * check, `setValue` and `setSubmitMode(Always)` (F-LMA7-07). For on-form fields
736
+ * use the typed proxy directly (`form.field.setValue(v)` + `setSubmitMode`).
737
+ *
738
+ * @param form - The typedForm proxy (anything exposing `$unsafe`)
739
+ * @param field - The off-form attribute logical name (use an entity Fields enum, never a raw string)
740
+ * @param value - The value to set (off-form fields are untyped)
741
+ * @returns `true` if the field existed and was set, `false` if it was absent
742
+ */
743
+ declare function setUnsafeAndSubmit(form: {
744
+ $unsafe(name: string): Xrm.Attributes.Attribute | null;
745
+ }, field: string, value: unknown): boolean;
746
+
747
+ /**
748
+ * @xrmforge/helpers - App-level (global) notification helper
749
+ *
750
+ * Wraps Xrm.App.addGlobalNotification and hides the XrmEnum.AppNotificationLevel
751
+ * runtime gap (XrmEnum const enums do not exist at runtime; see AGENT.md pitfall).
752
+ */
753
+
754
+ /** Options for {@link addAppNotification}. */
755
+ interface AppNotificationOptions {
756
+ /** Show a close (X) button on the banner (default: false). */
757
+ showCloseButton?: boolean;
758
+ /** Optional action button. */
759
+ action?: Xrm.App.Action;
760
+ }
761
+ /**
762
+ * Show a global app-level notification banner and return its id.
763
+ *
764
+ * Pass an {@link AppNotificationLevel} (Success/Error/Warning/Information). The
765
+ * cast to the @types/xrm `XrmEnum.AppNotificationLevel` (which has no runtime
766
+ * representation) happens here, once, instead of at every call site.
767
+ *
768
+ * @param message - The banner message
769
+ * @param level - The notification level
770
+ * @param options - Optional banner settings
771
+ * @returns The created notification id (pass to `Xrm.App.clearGlobalNotification`)
772
+ *
773
+ * @example
774
+ * const id = await addAppNotification(lang.saved, AppNotificationLevel.Success, { showCloseButton: true });
775
+ */
776
+ declare function addAppNotification(message: string, level: AppNotificationLevel, options?: AppNotificationOptions): Promise<string>;
777
+
778
+ export { AppNotificationLevel, type AppNotificationOptions, BindingType, type BoundActionExecutor, type BoundActionWithParamsExecutor, type BoundFunctionExecutor, ClientState, ClientType, type CloudFlowOptions, DisplayState, type FormFields, FormNotificationLevel, FormType, type FormTypeInfoProtocol, OperationType, type ParameterMeta, type ParameterMetaMap, RequiredLevel, SaveMode, StructuralProperty, SubmitMode, type TypedForm, type UnboundActionExecutor, type UnboundActionWithParamsExecutor, type UnboundFunctionExecutor, addAppNotification, callCloudFlow, clearAndSubmit, createBoundAction, createBoundFunction, createUnboundAction, createUnboundFunction, executeMultiple, executeRequest, formLookup, formLookupId, isFormType, normalizeGuid, parseFormattedValue, parseLookup, parseLookups, parseMultiSelect, select, selectExpand, setUnsafeAndSubmit, typedForm, withProgress };
package/dist/index.js CHANGED
@@ -24,6 +24,21 @@ function parseLookups(response, navigationProperties) {
24
24
  function parseFormattedValue(response, fieldName) {
25
25
  return response[`${fieldName}@OData.Community.Display.V1.FormattedValue`] ?? null;
26
26
  }
27
+ function parseMultiSelect(value, emptyAsNull = false) {
28
+ let nums;
29
+ if (value == null) {
30
+ nums = [];
31
+ } else if (Array.isArray(value)) {
32
+ nums = value.map((v) => Number(v)).filter(Number.isFinite);
33
+ } else if (typeof value === "number") {
34
+ nums = [value];
35
+ } else if (typeof value === "string") {
36
+ nums = value.split(",").map((s) => s.trim()).filter((s) => s !== "").map(Number).filter(Number.isFinite);
37
+ } else {
38
+ nums = [];
39
+ }
40
+ return nums.length === 0 && emptyAsNull ? null : nums;
41
+ }
27
42
  function selectExpand(fields, expand) {
28
43
  const parts = [];
29
44
  if (fields.length > 0) parts.push(`$select=${fields.join(",")}`);
@@ -70,6 +85,13 @@ var FormNotificationLevel = /* @__PURE__ */ ((FormNotificationLevel2) => {
70
85
  FormNotificationLevel2["Info"] = "INFO";
71
86
  return FormNotificationLevel2;
72
87
  })(FormNotificationLevel || {});
88
+ var AppNotificationLevel = /* @__PURE__ */ ((AppNotificationLevel2) => {
89
+ AppNotificationLevel2[AppNotificationLevel2["Success"] = 1] = "Success";
90
+ AppNotificationLevel2[AppNotificationLevel2["Error"] = 2] = "Error";
91
+ AppNotificationLevel2[AppNotificationLevel2["Warning"] = 3] = "Warning";
92
+ AppNotificationLevel2[AppNotificationLevel2["Information"] = 4] = "Information";
93
+ return AppNotificationLevel2;
94
+ })(AppNotificationLevel || {});
73
95
  var RequiredLevel = /* @__PURE__ */ ((RequiredLevel2) => {
74
96
  RequiredLevel2["None"] = "none";
75
97
  RequiredLevel2["Required"] = "required";
@@ -211,7 +233,7 @@ function createBoundAction(operationName, entityLogicalName, paramMeta) {
211
233
  if (response.status !== 204) {
212
234
  return response.json();
213
235
  }
214
- return response;
236
+ return void 0;
215
237
  },
216
238
  request(recordId, params) {
217
239
  return buildBoundRequest(
@@ -242,7 +264,7 @@ function createUnboundAction(operationName, paramMeta) {
242
264
  if (response.status !== 204) {
243
265
  return response.json();
244
266
  }
245
- return response;
267
+ return void 0;
246
268
  },
247
269
  request(params) {
248
270
  return buildUnboundRequest(
@@ -389,7 +411,36 @@ async function callCloudFlow(triggerUrl, body, options = {}) {
389
411
  const text = await response.text();
390
412
  return text === "" ? void 0 : text;
391
413
  }
414
+
415
+ // src/form-submit.ts
416
+ function clearAndSubmit(attr) {
417
+ attr.setValue(null);
418
+ attr.setSubmitMode("always" /* Always */);
419
+ }
420
+ function setUnsafeAndSubmit(form, field, value) {
421
+ const attr = form.$unsafe(field);
422
+ if (attr == null) return false;
423
+ attr.setValue(value);
424
+ attr.setSubmitMode("always" /* Always */);
425
+ return true;
426
+ }
427
+
428
+ // src/app-notification.ts
429
+ var NOTIFICATION_TYPE_BANNER = 2;
430
+ async function addAppNotification(message, level, options = {}) {
431
+ const notification = {
432
+ type: NOTIFICATION_TYPE_BANNER,
433
+ // XrmEnum.AppNotificationLevel has no runtime value; AppNotificationLevel carries
434
+ // the same numbers. Cast at this single boundary to satisfy the typings.
435
+ level,
436
+ message,
437
+ showCloseButton: options.showCloseButton ?? false,
438
+ ...options.action ? { action: options.action } : {}
439
+ };
440
+ return Xrm.App.addGlobalNotification(notification);
441
+ }
392
442
  export {
443
+ AppNotificationLevel,
393
444
  BindingType,
394
445
  ClientState,
395
446
  ClientType,
@@ -401,7 +452,9 @@ export {
401
452
  SaveMode,
402
453
  StructuralProperty,
403
454
  SubmitMode,
455
+ addAppNotification,
404
456
  callCloudFlow,
457
+ clearAndSubmit,
405
458
  createBoundAction,
406
459
  createBoundFunction,
407
460
  createUnboundAction,
@@ -415,8 +468,10 @@ export {
415
468
  parseFormattedValue,
416
469
  parseLookup,
417
470
  parseLookups,
471
+ parseMultiSelect,
418
472
  select,
419
473
  selectExpand,
474
+ setUnsafeAndSubmit,
420
475
  typedForm,
421
476
  withProgress
422
477
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/webapi-helpers.ts","../src/xrm-constants.ts","../src/action-runtime.ts","../src/typed-form.ts","../src/cloud-flow.ts"],"sourcesContent":["/**\r\n * @xrmforge/helpers - Web API Helper Functions\r\n *\r\n * Lightweight utility functions for building OData query strings\r\n * with type-safe field names from generated Fields enums.\r\n *\r\n * Zero runtime overhead when used with const enums (values are inlined).\r\n *\r\n * @example\r\n * ```typescript\r\n * import { select } from '@xrmforge/helpers';\r\n *\r\n * Xrm.WebApi.retrieveRecord(ref.entityType, ref.id, select(\r\n * AccountFields.Name,\r\n * AccountFields.WebsiteUrl,\r\n * AccountFields.Address1Line1,\r\n * ));\r\n * ```\r\n */\r\n\r\n/**\r\n * Build an OData $select query string from field names.\r\n *\r\n * Accepts either variadic arguments or a single array:\r\n * - `select(Fields.Name, Fields.Email)` (variadic)\r\n * - `select([Fields.Name, Fields.Email])` (array)\r\n *\r\n * @param fields - Field names (use generated Fields enum for type safety)\r\n * @returns OData query string (e.g. \"?$select=name,websiteurl,address1_line1\")\r\n */\r\nexport function select(fields: string[]): string;\r\nexport function select(...fields: string[]): string;\r\nexport function select(...args: string[] | [string[]]): string {\r\n const fields = args.length === 1 && Array.isArray(args[0]) ? args[0] : args as string[];\r\n if (fields.length === 0) return '';\r\n return `?$select=${fields.join(',')}`;\r\n}\r\n\r\n/**\r\n * Parse a lookup field from a Dataverse Web API response into a LookupValue.\r\n *\r\n * Dataverse returns lookups as `_fieldname_value` with OData annotations:\r\n * - `_fieldname_value` (GUID)\r\n * - `_fieldname_value@OData.Community.Display.V1.FormattedValue` (display name)\r\n * - `_fieldname_value@Microsoft.Dynamics.CRM.lookuplogicalname` (entity type)\r\n *\r\n * This function extracts all three into an `Xrm.LookupValue` object.\r\n *\r\n * @param response - The raw Web API response object\r\n * @param navigationProperty - Navigation property name (use NavigationProperties enum for type safety)\r\n * @returns Xrm.LookupValue or null if the lookup is empty\r\n *\r\n * @example\r\n * ```typescript\r\n * // With NavigationProperties enum (recommended):\r\n * parseLookup(result, AccountNav.Country);\r\n *\r\n * // Or with navigation property name directly:\r\n * parseLookup(result, 'markant_address1_countryid');\r\n * ```\r\n */\r\nexport function parseLookup(\r\n response: Record<string, unknown>,\r\n navigationProperty: string,\r\n): { id: string; name: string; entityType: string } | null {\r\n const key = `_${navigationProperty}_value`;\r\n const id = response[key] as string | undefined;\r\n if (!id) return null;\r\n\r\n return {\r\n id,\r\n name: (response[`${key}@OData.Community.Display.V1.FormattedValue`] as string) ?? '',\r\n entityType: (response[`${key}@Microsoft.Dynamics.CRM.lookuplogicalname`] as string) ?? '',\r\n };\r\n}\r\n\r\n/**\r\n * Parse multiple lookup fields from a Dataverse Web API response at once.\r\n *\r\n * @param response - The raw Web API response object\r\n * @param navigationProperties - Navigation property names to parse\r\n * @returns Map of navigation property name to LookupValue (null entries omitted)\r\n *\r\n * @example\r\n * ```typescript\r\n * const lookups = parseLookups(result, ['markant_address1_countryid', 'parentaccountid']);\r\n * formContext.getAttribute(Fields.Country).setValue(\r\n * lookups.markant_address1_countryid ? [lookups.markant_address1_countryid] : null\r\n * );\r\n * ```\r\n */\r\nexport function parseLookups(\r\n response: Record<string, unknown>,\r\n navigationProperties: string[],\r\n): Record<string, { id: string; name: string; entityType: string } | null> {\r\n const result: Record<string, { id: string; name: string; entityType: string } | null> = {};\r\n for (const prop of navigationProperties) {\r\n result[prop] = parseLookup(response, prop);\r\n }\r\n return result;\r\n}\r\n\r\n/**\r\n * Get the formatted (display) value of any field from a Web API response.\r\n *\r\n * Works for OptionSets, Lookups, DateTimes, Money, and other formatted fields.\r\n *\r\n * @param response - The raw Web API response object\r\n * @param fieldName - The field logical name (e.g. \"statecode\", \"createdon\")\r\n * @returns The formatted string value, or null if not available\r\n *\r\n * @example\r\n * ```typescript\r\n * const status = parseFormattedValue(result, 'statecode');\r\n * // \"Active\" (instead of 0)\r\n * ```\r\n */\r\nexport function parseFormattedValue(\r\n response: Record<string, unknown>,\r\n fieldName: string,\r\n): string | null {\r\n return (response[`${fieldName}@OData.Community.Display.V1.FormattedValue`] as string) ?? null;\r\n}\r\n\r\n/**\r\n * Build an OData $select and $expand query string.\r\n *\r\n * @param fields - Field names to select\r\n * @param expand - Navigation property to expand (optional)\r\n * @returns OData query string\r\n *\r\n * @example\r\n * ```typescript\r\n * Xrm.WebApi.retrieveRecord(\"account\", id, selectExpand(\r\n * [AccountFields.Name, AccountFields.WebsiteUrl],\r\n * \"primarycontactid($select=fullname,emailaddress1)\"\r\n * ));\r\n * ```\r\n */\r\nexport function selectExpand(fields: string[], expand: string): string {\r\n const parts: string[] = [];\r\n if (fields.length > 0) parts.push(`$select=${fields.join(',')}`);\r\n if (expand) parts.push(`$expand=${expand}`);\r\n return parts.length > 0 ? `?${parts.join('&')}` : '';\r\n}\r\n\r\n// ─── Form Lookup Helpers ────────────────────────────────────────────────────\r\n\r\n/**\r\n * Extract the first lookup value from a FormContext lookup attribute.\r\n *\r\n * Centralizes the common pattern of reading a lookup from a form field,\r\n * handling null/empty arrays, and normalizing the GUID (removing braces).\r\n *\r\n * @param attr - A lookup attribute from formContext.getAttribute()\r\n * @returns Xrm.LookupValue with normalized id (no braces), or null if empty\r\n *\r\n * @example\r\n * ```typescript\r\n * import { formLookup } from '@xrmforge/helpers';\r\n * const customer = formLookup(form.getAttribute(Fields.CustomerId));\r\n * if (customer) {\r\n * console.log(customer.id, customer.name, customer.entityType);\r\n * }\r\n * ```\r\n */\r\nexport function formLookup(\r\n attr: { getValue(): { id: string; name?: string; entityType: string }[] | null },\r\n): { id: string; name: string; entityType: string } | null {\r\n const values = attr.getValue();\r\n if (!values || values.length === 0) return null;\r\n const first = values[0]!;\r\n return {\r\n id: first.id.replace(/[{}]/g, ''),\r\n name: first.name ?? '',\r\n entityType: first.entityType,\r\n };\r\n}\r\n\r\n/**\r\n * Extract just the normalized GUID from a FormContext lookup attribute.\r\n *\r\n * Shorthand for the most common lookup use case: getting the record ID\r\n * for a Web API call or comparison.\r\n *\r\n * @param attr - A lookup attribute from formContext.getAttribute()\r\n * @returns Normalized GUID string (no braces), or null if empty\r\n *\r\n * @example\r\n * ```typescript\r\n * import { formLookupId } from '@xrmforge/helpers';\r\n * const accountId = formLookupId(form.getAttribute(Fields.AccountId));\r\n * if (accountId) {\r\n * await Xrm.WebApi.retrieveRecord(EntityNames.Account, accountId, select(...));\r\n * }\r\n * ```\r\n */\r\nexport function formLookupId(\r\n attr: { getValue(): { id: string }[] | null },\r\n): string | null {\r\n const values = attr.getValue();\r\n if (!values || values.length === 0) return null;\r\n return values[0]!.id.replace(/[{}]/g, '');\r\n}\r\n","/**\r\n * @xrmforge/helpers - Xrm API Constants\r\n *\r\n * Const enums for all common Xrm string/number constants.\r\n * Eliminates raw strings in D365 form scripts.\r\n *\r\n * @types/xrm defines these as string literal types for compile-time checking,\r\n * but does NOT provide runtime constants (XrmEnum is not available at runtime).\r\n * These const enums are erased at compile time (zero runtime overhead).\r\n *\r\n * @example\r\n * ```typescript\r\n * import { DisplayState } from '@xrmforge/helpers';\r\n *\r\n * if (tab.getDisplayState() === DisplayState.Expanded) { ... }\r\n * ```\r\n */\r\n\r\n/** Tab/Section display state */\r\nexport const enum DisplayState {\r\n Expanded = 'expanded',\r\n Collapsed = 'collapsed',\r\n}\r\n\r\n/**\r\n * Form type (formContext.ui.getFormType()).\r\n *\r\n * WARNING: XrmEnum.FormType from @types/xrm is a const enum that does NOT exist\r\n * at runtime. esbuild does not resolve const enums from .d.ts files. Using\r\n * XrmEnum.FormType.Create in code produces \"XrmEnum is not defined\" at runtime.\r\n * Use this FormType enum instead (same values, zero runtime overhead).\r\n */\r\nexport const enum FormType {\r\n Undefined = 0,\r\n Create = 1,\r\n Update = 2,\r\n ReadOnly = 3,\r\n Disabled = 4,\r\n BulkEdit = 6,\r\n}\r\n\r\n/**\r\n * True when the form is currently shown in the given {@link FormType}.\r\n *\r\n * `formContext.ui.getFormType()` is typed as `XrmEnum.FormType` (from\r\n * @types/xrm), which is a nominally distinct type from the {@link FormType}\r\n * const enum above. A direct `getFormType() === FormType.Create` therefore\r\n * fails to compile under `strict` with TS2367 (\"This comparison appears to be\r\n * unintentional because the types have no overlap\"). Relational operators\r\n * (`>`/`<`) slip past TS2367 but cannot express an exact match. This helper\r\n * bridges both numeric enums for the equality case without a hand-written cast.\r\n *\r\n * @example\r\n * if (isFormType(form.$context, FormType.Create)) {\r\n * // only on create\r\n * }\r\n */\r\nexport function isFormType(formContext: Xrm.FormContext, formType: FormType): boolean {\r\n return (formContext.ui.getFormType() as number) === (formType as number);\r\n}\r\n\r\n/** Form notification level (formContext.ui.setFormNotification) */\r\nexport const enum FormNotificationLevel {\r\n Error = 'ERROR',\r\n Warning = 'WARNING',\r\n Info = 'INFO',\r\n}\r\n\r\n/** Attribute required level (attribute.setRequiredLevel) */\r\nexport const enum RequiredLevel {\r\n None = 'none',\r\n Required = 'required',\r\n Recommended = 'recommended',\r\n}\r\n\r\n/** Attribute submit mode (attribute.setSubmitMode) */\r\nexport const enum SubmitMode {\r\n Always = 'always',\r\n Never = 'never',\r\n Dirty = 'dirty',\r\n}\r\n\r\n/** Save mode (eventArgs.getSaveMode()) */\r\nexport const enum SaveMode {\r\n Save = 1,\r\n SaveAndClose = 2,\r\n Deactivate = 5,\r\n Reactivate = 6,\r\n Send = 7,\r\n Disqualify = 15,\r\n Qualify = 16,\r\n Assign = 47,\r\n SaveAsCompleted = 58,\r\n SaveAndNew = 59,\r\n AutoSave = 70,\r\n}\r\n\r\n/** Client type (Xrm.Utility.getGlobalContext().client.getClient()) */\r\nexport const enum ClientType {\r\n Web = 'Web',\r\n Outlook = 'Outlook',\r\n Mobile = 'Mobile',\r\n}\r\n\r\n/** Client state (Xrm.Utility.getGlobalContext().client.getClientState()) */\r\nexport const enum ClientState {\r\n Online = 'Online',\r\n Offline = 'Offline',\r\n}\r\n\r\n// WebApi Execute Constants\r\n\r\n/** Operation type for Xrm.WebApi.execute getMetadata().operationType */\r\nexport const enum OperationType {\r\n /** Custom Action or OOB Action (POST) */\r\n Action = 0,\r\n /** Custom Function or OOB Function (GET) */\r\n Function = 1,\r\n /** CRUD operation (Create, Retrieve, Update, Delete) */\r\n CRUD = 2,\r\n}\r\n\r\n/** Structural property for getMetadata().parameterTypes[].structuralProperty */\r\nexport const enum StructuralProperty {\r\n Unknown = 0,\r\n PrimitiveType = 1,\r\n ComplexType = 2,\r\n EnumerationType = 3,\r\n Collection = 4,\r\n EntityType = 5,\r\n}\r\n\r\n/** Binding type for Custom API definitions */\r\nexport const enum BindingType {\r\n /** Not bound to an entity (globally callable) */\r\n Global = 0,\r\n /** Bound to a single entity record */\r\n Entity = 1,\r\n /** Bound to an entity collection */\r\n EntityCollection = 2,\r\n}\r\n","/**\r\n * @xrmforge/helpers - Action/Function Runtime Helpers\r\n *\r\n * Factory functions for type-safe Custom API execution.\r\n * These are imported by generated action/function modules.\r\n *\r\n * Design:\r\n * - `createBoundAction` / `createUnboundAction`: Produce executor objects\r\n * with `.execute()` (calls Xrm.WebApi) and `.request()` (for executeMultiple)\r\n * - `executeRequest`: Central execute wrapper (single place for the `as any` cast)\r\n * - `withProgress`: Convenience wrapper with progress indicator (errors propagate to the handler wrapper)\r\n *\r\n * @example\r\n * ```typescript\r\n * // Generated code (in generated/actions/quote.ts):\r\n * import { createBoundAction } from '@xrmforge/helpers';\r\n * export const WinQuote = createBoundAction('markant_winquote', 'quote');\r\n *\r\n * // Developer code (in quote-form.ts):\r\n * import { WinQuote } from '../generated/actions/quote';\r\n * const response = await WinQuote.execute(recordId);\r\n * ```\r\n */\r\n\r\nimport { OperationType, StructuralProperty } from './xrm-constants.js';\r\n\r\n// Types\r\n\r\n/** Parameter metadata for getMetadata().parameterTypes */\r\nexport interface ParameterMeta {\r\n typeName: string;\r\n structuralProperty: number;\r\n}\r\n\r\n/** Map of parameter names to their OData metadata */\r\nexport type ParameterMetaMap = Record<string, ParameterMeta>;\r\n\r\n/** Executor for a bound action without additional parameters */\r\nexport interface BoundActionExecutor<TResult = void> {\r\n execute(recordId: string): Promise<TResult extends void ? Response : TResult>;\r\n request(recordId: string): Record<string, unknown>;\r\n}\r\n\r\n/** Executor for a bound action with typed parameters */\r\nexport interface BoundActionWithParamsExecutor<TParams, TResult = void> {\r\n execute(recordId: string, params: TParams): Promise<TResult extends void ? Response : TResult>;\r\n request(recordId: string, params: TParams): Record<string, unknown>;\r\n}\r\n\r\n/** Executor for an unbound action without parameters */\r\nexport interface UnboundActionExecutor<TResult = void> {\r\n execute(): Promise<TResult extends void ? Response : TResult>;\r\n request(): Record<string, unknown>;\r\n}\r\n\r\n/** Executor for an unbound action with typed parameters and optional typed response */\r\nexport interface UnboundActionWithParamsExecutor<TParams, TResult = void> {\r\n execute(params: TParams): Promise<TResult extends void ? Response : TResult>;\r\n request(params: TParams): Record<string, unknown>;\r\n}\r\n\r\n/** Executor for an unbound function with typed response */\r\nexport interface UnboundFunctionExecutor<TResult> {\r\n execute(): Promise<TResult>;\r\n request(): Record<string, unknown>;\r\n}\r\n\r\n/** Executor for a bound function with typed response */\r\nexport interface BoundFunctionExecutor<TResult> {\r\n execute(recordId: string): Promise<TResult>;\r\n request(recordId: string): Record<string, unknown>;\r\n}\r\n\r\n// Central Execute\r\n\r\n/**\r\n * Execute a single request via Xrm.WebApi.online.execute().\r\n *\r\n * This is the ONLY place in the entire framework where the `as any` cast happens.\r\n * All generated executors call this function internally.\r\n */\r\nexport function executeRequest(request: Record<string, unknown>): Promise<Response> {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return (Xrm.WebApi as any).online.execute(request) as Promise<Response>;\r\n}\r\n\r\n/**\r\n * Execute multiple requests via Xrm.WebApi.online.executeMultiple().\r\n *\r\n * @param requests - Array of request objects (from `.request()` factories).\r\n * Wrap a subset in an inner array for transactional changeset execution.\r\n */\r\nexport function executeMultiple(\r\n requests: Array<Record<string, unknown> | Array<Record<string, unknown>>>,\r\n): Promise<Response[]> {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return (Xrm.WebApi as any).online.executeMultiple(requests) as Promise<Response[]>;\r\n}\r\n\r\n// Request Builder (internal)\r\n\r\nfunction cleanRecordId(id: string): string {\r\n return id.replace(/[{}]/g, '');\r\n}\r\n\r\nfunction buildBoundRequest(\r\n operationName: string,\r\n entityLogicalName: string,\r\n operationType: OperationType,\r\n recordId: string,\r\n paramMeta?: ParameterMetaMap,\r\n params?: Record<string, unknown>,\r\n): Record<string, unknown> {\r\n const parameterTypes: Record<string, ParameterMeta> = {\r\n entity: {\r\n typeName: `mscrm.${entityLogicalName}`,\r\n structuralProperty: StructuralProperty.EntityType,\r\n },\r\n };\r\n\r\n if (paramMeta) {\r\n for (const [key, meta] of Object.entries(paramMeta)) {\r\n parameterTypes[key] = meta;\r\n }\r\n }\r\n\r\n const request: Record<string, unknown> = {\r\n getMetadata: () => ({\r\n boundParameter: 'entity',\r\n parameterTypes,\r\n operationName,\r\n operationType,\r\n }),\r\n entity: {\r\n id: cleanRecordId(recordId),\r\n entityType: entityLogicalName,\r\n },\r\n };\r\n\r\n if (params) {\r\n for (const [key, value] of Object.entries(params)) {\r\n request[key] = value;\r\n }\r\n }\r\n\r\n return request;\r\n}\r\n\r\nfunction buildUnboundRequest(\r\n operationName: string,\r\n operationType: OperationType,\r\n paramMeta?: ParameterMetaMap,\r\n params?: Record<string, unknown>,\r\n): Record<string, unknown> {\r\n const parameterTypes: Record<string, ParameterMeta> = {};\r\n\r\n if (paramMeta) {\r\n for (const [key, meta] of Object.entries(paramMeta)) {\r\n parameterTypes[key] = meta;\r\n }\r\n }\r\n\r\n const request: Record<string, unknown> = {\r\n getMetadata: () => ({\r\n boundParameter: null,\r\n parameterTypes,\r\n operationName,\r\n operationType,\r\n }),\r\n };\r\n\r\n if (params) {\r\n for (const [key, value] of Object.entries(params)) {\r\n request[key] = value;\r\n }\r\n }\r\n\r\n return request;\r\n}\r\n\r\n// Action Factories\r\n\r\n/**\r\n * Create an executor for a bound action (entity-bound) without parameters or typed response.\r\n *\r\n * @param operationName - Custom API unique name (e.g. \"markant_winquote\")\r\n * @param entityLogicalName - Entity logical name (e.g. \"quote\")\r\n */\r\nexport function createBoundAction(\r\n operationName: string,\r\n entityLogicalName: string,\r\n): BoundActionExecutor;\r\n\r\n/**\r\n * Create an executor for a bound action without parameters but with typed response.\r\n *\r\n * @param operationName - Custom API unique name\r\n * @param entityLogicalName - Entity logical name\r\n */\r\nexport function createBoundAction<TResult>(\r\n operationName: string,\r\n entityLogicalName: string,\r\n): BoundActionExecutor<TResult>;\r\n\r\n/**\r\n * Create an executor for a bound action with typed parameters and optional typed response.\r\n *\r\n * @param operationName - Custom API unique name\r\n * @param entityLogicalName - Entity logical name\r\n * @param paramMeta - Parameter metadata map (parameter name to OData type info)\r\n */\r\nexport function createBoundAction<\r\n TParams extends Record<string, unknown>,\r\n TResult = void,\r\n>(\r\n operationName: string,\r\n entityLogicalName: string,\r\n paramMeta: ParameterMetaMap,\r\n): BoundActionWithParamsExecutor<TParams, TResult>;\r\n\r\nexport function createBoundAction<\r\n TParams extends Record<string, unknown>,\r\n TResult = void,\r\n>(\r\n operationName: string,\r\n entityLogicalName: string,\r\n paramMeta?: ParameterMetaMap,\r\n): BoundActionExecutor<TResult> | BoundActionWithParamsExecutor<TParams, TResult> {\r\n return {\r\n async execute(recordId: string, params?: TParams): Promise<TResult extends void ? Response : TResult> {\r\n const req = buildBoundRequest(\r\n operationName, entityLogicalName, OperationType.Action,\r\n recordId, paramMeta, params,\r\n );\r\n const response = await executeRequest(req);\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(errorText);\r\n }\r\n // Parse JSON when response properties are defined (TResult is not void)\r\n if (response.status !== 204) {\r\n return response.json() as Promise<TResult extends void ? Response : TResult>;\r\n }\r\n return response as TResult extends void ? Response : TResult;\r\n },\r\n request(recordId: string, params?: TParams): Record<string, unknown> {\r\n return buildBoundRequest(\r\n operationName, entityLogicalName, OperationType.Action,\r\n recordId, paramMeta, params,\r\n );\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Create an executor for an unbound (global) action without parameters or typed response.\r\n *\r\n * @param operationName - Custom API unique name\r\n */\r\nexport function createUnboundAction(\r\n operationName: string,\r\n): UnboundActionExecutor;\r\n\r\n/**\r\n * Create an executor for an unbound action without parameters but with typed response.\r\n *\r\n * @param operationName - Custom API unique name\r\n */\r\nexport function createUnboundAction<TResult>(\r\n operationName: string,\r\n): UnboundActionExecutor<TResult>;\r\n\r\n/**\r\n * Create an executor for an unbound action with typed parameters and optional typed response.\r\n *\r\n * @param operationName - Custom API unique name\r\n * @param paramMeta - Parameter metadata map\r\n */\r\nexport function createUnboundAction<\r\n TParams extends Record<string, unknown>,\r\n TResult = void,\r\n>(\r\n operationName: string,\r\n paramMeta: ParameterMetaMap,\r\n): UnboundActionWithParamsExecutor<TParams, TResult>;\r\n\r\nexport function createUnboundAction<\r\n TParams extends Record<string, unknown>,\r\n TResult = void,\r\n>(\r\n operationName: string,\r\n paramMeta?: ParameterMetaMap,\r\n): UnboundActionExecutor | UnboundActionWithParamsExecutor<TParams, TResult> {\r\n return {\r\n async execute(params?: TParams): Promise<TResult extends void ? Response : TResult> {\r\n const req = buildUnboundRequest(\r\n operationName, OperationType.Action, paramMeta, params,\r\n );\r\n const response = await executeRequest(req);\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(errorText);\r\n }\r\n if (response.status !== 204) {\r\n return response.json() as Promise<TResult extends void ? Response : TResult>;\r\n }\r\n return response as TResult extends void ? Response : TResult;\r\n },\r\n request(params?: TParams): Record<string, unknown> {\r\n return buildUnboundRequest(\r\n operationName, OperationType.Action, paramMeta, params,\r\n );\r\n },\r\n };\r\n}\r\n\r\n// Function Factories\r\n\r\n/**\r\n * Create an executor for an unbound (global) function with typed response.\r\n *\r\n * @param operationName - Function name (e.g. \"WhoAmI\")\r\n */\r\nexport function createUnboundFunction<TResult>(\r\n operationName: string,\r\n): UnboundFunctionExecutor<TResult> {\r\n return {\r\n async execute(): Promise<TResult> {\r\n const req = buildUnboundRequest(operationName, OperationType.Function);\r\n const response = await executeRequest(req);\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(errorText);\r\n }\r\n return response.json() as Promise<TResult>;\r\n },\r\n request(): Record<string, unknown> {\r\n return buildUnboundRequest(operationName, OperationType.Function);\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Create an executor for a bound function with typed response.\r\n *\r\n * @param operationName - Function name\r\n * @param entityLogicalName - Entity logical name\r\n */\r\nexport function createBoundFunction<TResult>(\r\n operationName: string,\r\n entityLogicalName: string,\r\n): BoundFunctionExecutor<TResult> {\r\n return {\r\n async execute(recordId: string): Promise<TResult> {\r\n const req = buildBoundRequest(\r\n operationName, entityLogicalName, OperationType.Function, recordId,\r\n );\r\n const response = await executeRequest(req);\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(errorText);\r\n }\r\n return response.json() as Promise<TResult>;\r\n },\r\n request(recordId: string): Record<string, unknown> {\r\n return buildBoundRequest(\r\n operationName, entityLogicalName, OperationType.Function, recordId,\r\n );\r\n },\r\n };\r\n}\r\n\r\n// Convenience\r\n\r\n/**\r\n * Execute an async operation with an Xrm progress indicator.\r\n *\r\n * Shows a progress spinner before the operation and closes it afterwards\r\n * (success or failure). Errors are NOT displayed here; they propagate to the\r\n * caller so the single error UI is owned by the handler wrapper\r\n * (`wrapHandler`/`wrapCommand`). Showing an error dialog here too would produce\r\n * a duplicate error UI (dialog + form notification) when `withProgress` runs\r\n * inside a wrapped command (the common ribbon case).\r\n *\r\n * @param message - Progress indicator message (e.g. \"Processing quote...\")\r\n * @param operation - Async function to execute\r\n * @returns The result of the operation\r\n *\r\n * @example\r\n * ```typescript\r\n * // Inside a wrapCommand handler: the wrapper shows the error notification.\r\n * await withProgress('Processing quote...', () => WinQuote.execute(recordId));\r\n * ```\r\n */\r\nexport async function withProgress<T>(\r\n message: string,\r\n operation: () => Promise<T>,\r\n): Promise<T> {\r\n Xrm.Utility.showProgressIndicator(message);\r\n try {\r\n return await operation();\r\n } finally {\r\n Xrm.Utility.closeProgressIndicator();\r\n }\r\n}\r\n","/**\r\n * @xrmforge/helpers - TypedForm Proxy\r\n *\r\n * Creates a proxy around Xrm.FormContext that allows direct property access\r\n * to form fields. Instead of `form.getAttribute(\"name\").setValue(\"X\")`,\r\n * write `form.name.setValue(\"X\")`.\r\n *\r\n * Works with generated form types from @xrmforge/typegen. Since v0.9.2,\r\n * typegen generates a `FormTypeInfo` interface per form that bundles\r\n * Fields, AttributeMap, and ControlMap for reliable type extraction.\r\n *\r\n * @example\r\n * ```typescript\r\n * import { typedForm } from '@xrmforge/helpers';\r\n * import type { AccountLMFirmaFormTypeInfo } from '../../generated/forms/account.js';\r\n *\r\n * const form = typedForm<AccountLMFirmaFormTypeInfo>(ctx.getFormContext());\r\n * form.name.getValue(); // string | null (typed)\r\n * form.revenue.setValue(150000); // NumberAttribute (typed)\r\n * form.$context.ui.tabs.get(...); // Full FormContext access\r\n * form.controls.name; // Control access (typed)\r\n * form.$unsafe('off_form_field'); // Access fields not on the form\r\n * ```\r\n */\r\n\r\n// ─── FormTypeInfo Protocol ───────────────────────────────────────────────────\r\n\r\n/**\r\n * Protocol interface generated by typegen for each form.\r\n * Bundles Fields, AttributeMap, and ControlMap so typedForm can extract\r\n * them reliably without fragile Conditional Type inference on overloads.\r\n *\r\n * Generated as: `export interface MyFormTypeInfo { fields: ...; attributes: ...; controls: ...; form: ...; }`\r\n */\r\nexport interface FormTypeInfoProtocol {\r\n fields: string;\r\n attributes: Record<string, Xrm.Attributes.Attribute>;\r\n controls: Record<string, Xrm.Controls.Control>;\r\n form: object;\r\n}\r\n\r\n// ─── Type Extraction ─────────────────────────────────────────────────────────\r\n\r\n/**\r\n * Extract Fields from a Form interface.\r\n *\r\n * Strategy: Check if TForm has a companion TypeInfo interface (generated by\r\n * typegen >= 0.9.2). If so, extract fields directly. Otherwise, fall back\r\n * to Conditional Type inference on getAttribute (works in same compilation\r\n * unit but may fail across package boundaries in TS 5.9+).\r\n */\r\n/**\r\n * Type extraction uses duck typing: if TForm has a `fields` property,\r\n * it's a TypeInfo interface (from typegen >= 0.10.0). Otherwise, fall\r\n * back to Conditional Type inference on getAttribute overloads.\r\n *\r\n * Duck typing (`TForm extends { fields: infer F }`) is more robust than\r\n * matching against FormTypeInfoProtocol because it doesn't require\r\n * structural compatibility of attributes/controls/form across packages.\r\n */\r\ntype ExtractFields<TForm> =\r\n TForm extends { fields: infer F extends string } ? F :\r\n TForm extends { getAttribute<K extends infer F>(name: K): unknown }\r\n ? F extends string ? F : never\r\n : never;\r\n\r\ntype ExtractAttributeMap<TForm, TFields extends string> =\r\n TForm extends { attributes: infer A extends Record<string, Xrm.Attributes.Attribute> } ? A :\r\n { [K in TFields]: TForm extends { getAttribute(name: K): infer R }\r\n ? R extends Xrm.Attributes.Attribute ? R : Xrm.Attributes.Attribute\r\n : Xrm.Attributes.Attribute;\r\n };\r\n\r\ntype ExtractControlMap<TForm, TFields extends string> =\r\n TForm extends { controls: infer C extends Record<string, Xrm.Controls.Control> } ? C :\r\n { [K in TFields]: TForm extends { getControl(name: K): infer R }\r\n ? R extends Xrm.Controls.Control ? R : Xrm.Controls.Control\r\n : Xrm.Controls.Control;\r\n };\r\n\r\ntype ExtractFormContext<TForm> =\r\n TForm extends { form: infer FC } ? FC :\r\n TForm extends Xrm.FormContext ? TForm :\r\n Xrm.FormContext;\r\n\r\n// ─── TypedForm Type ──────────────────────────────────────────────────────────\r\n\r\n/**\r\n * TypedForm: proxy type that maps field names to their attribute types.\r\n *\r\n * Provides direct property access to form fields (e.g. `form.name` returns\r\n * the StringAttribute), plus:\r\n * - `$context` for full FormContext access (ui, data, tabs, getAttribute with addOnChange)\r\n * - `controls.fieldName` for typed control access\r\n * - `$unsafe(name)` for off-form field access (fields loaded by D365 but not on the form)\r\n */\r\nexport type TypedForm<\r\n TForm,\r\n TFields extends string = ExtractFields<TForm>,\r\n TAttrMap extends Record<string, Xrm.Attributes.Attribute> = ExtractAttributeMap<TForm, TFields>,\r\n TCtrlMap extends Record<string, Xrm.Controls.Control> = ExtractControlMap<TForm, TFields>,\r\n> = {\r\n /**\r\n * Direct field access: form.fieldName returns the typed Attribute.\r\n *\r\n * Non-nullable because the field is in the generated FormXml. If a field\r\n * is NOT in the generated interface, it won't compile, forcing you to use\r\n * $unsafe() which IS nullable. This is the compiler warning: a compile\r\n * error that says \"this field is not on the form, use $unsafe()\".\r\n */\r\n readonly [K in TFields]: K extends keyof TAttrMap\r\n ? TAttrMap[K]\r\n : Xrm.Attributes.Attribute;\r\n} & {\r\n /** Access the underlying FormContext for ui, data, tabs, etc. */\r\n readonly $context: ExtractFormContext<TForm>;\r\n\r\n /**\r\n * Typed control access via form.controls.fieldname.\r\n *\r\n * Returns the specific control type from the generated ControlMap\r\n * (LookupControl, NumberControl, etc.). No cast needed.\r\n *\r\n * @example\r\n * ```typescript\r\n * form.controls.customerid.setEntityTypes([EntityNames.Account]);\r\n * form.controls.revenue.setVisible(false);\r\n * form.controls.name.setDisabled(true);\r\n * ```\r\n */\r\n readonly controls: {\r\n readonly [K in TFields]: K extends keyof TCtrlMap\r\n ? TCtrlMap[K]\r\n : Xrm.Controls.Control;\r\n };\r\n\r\n /**\r\n * Access an off-form field (loaded by D365 but not on the current form layout).\r\n * Returns null if the attribute does not exist.\r\n *\r\n * @example\r\n * ```typescript\r\n * form.$unsafe(OpportunityFields.VslBeauftragung)?.setValue(closeDate);\r\n * ```\r\n */\r\n $unsafe(name: string): Xrm.Attributes.Attribute | null;\r\n};\r\n\r\n/**\r\n * Wraps an Xrm Attribute so that setValue() automatically calls setSubmitMode('always').\r\n *\r\n * D365 AutoSave only submits \"dirty\" fields. Programmatically set values via setValue()\r\n * are NOT marked dirty by default, causing silent data loss on AutoSave. This proxy\r\n * intercepts setValue() and automatically marks the field for submission.\r\n *\r\n * This is intentionally invisible to the developer: they write `form.name.setValue('X')`\r\n * and the framework handles the rest. No more forgotten setSubmitMode calls.\r\n */\r\nfunction wrapAttributeWithAutoSubmit(attr: Xrm.Attributes.Attribute): Xrm.Attributes.Attribute {\r\n return new Proxy(attr, {\r\n get(target, prop) {\r\n if (prop === 'setValue') {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Xrm.Attributes.Attribute.setValue has varying signatures per attribute type\r\n return (value: any) => {\r\n target.setValue(value);\r\n target.setSubmitMode('always');\r\n };\r\n }\r\n const val = (target as unknown as Record<string | symbol, unknown>)[prop];\r\n if (typeof val === 'function') return val.bind(target);\r\n return val;\r\n },\r\n });\r\n}\r\n\r\n/**\r\n * Create a typed form proxy around a FormContext.\r\n *\r\n * Pass the generated FormTypeInfo interface as type parameter (typegen >= 0.9.2).\r\n * It bundles the field/attribute/control maps so type extraction works across\r\n * package boundaries; the bare form interface resolves to `never` in consumer\r\n * projects (overload inference on getAttribute is unreliable across packages, TS 5.9+).\r\n *\r\n * @example\r\n * ```typescript\r\n * // Pass the generated <Form>TypeInfo type, not the bare form interface.\r\n * const form = typedForm<AccountLMFirmaFormTypeInfo>(ctx.getFormContext());\r\n * ```\r\n *\r\n * @param formContext - The Xrm.FormContext from executionContext.getFormContext()\r\n * @returns A proxy with direct typed property access to form fields\r\n */\r\nexport function typedForm<TForm>(\r\n formContext: Xrm.FormContext,\r\n): TypedForm<TForm> {\r\n return new Proxy(formContext as unknown as TypedForm<TForm>, {\r\n get(_target, prop) {\r\n if (typeof prop !== 'string') {\r\n return (formContext as unknown as Record<symbol, unknown>)[prop];\r\n }\r\n if (prop === '$context') return formContext;\r\n if (prop === 'controls') {\r\n return new Proxy({} as Record<string, Xrm.Controls.Control>, {\r\n get(_, controlName) {\r\n if (typeof controlName !== 'string') return undefined;\r\n return formContext.getControl(controlName);\r\n },\r\n });\r\n }\r\n if (prop === '$unsafe') {\r\n return (name: string) => formContext.getAttribute(name);\r\n }\r\n const attr = formContext.getAttribute(prop);\r\n if (attr) return wrapAttributeWithAutoSubmit(attr);\r\n return (formContext as unknown as Record<string, unknown>)[prop];\r\n },\r\n\r\n set(_target, prop, _value) {\r\n throw new TypeError(\r\n `Cannot assign to '${String(prop)}'. Use form.${String(prop)}.setValue() instead.`,\r\n );\r\n },\r\n\r\n has(_target, prop) {\r\n if (typeof prop !== 'string') return false;\r\n if (prop === '$context' || prop === 'controls' || prop === '$unsafe') return true;\r\n return formContext.getAttribute(prop) !== null;\r\n },\r\n });\r\n}\r\n\r\n// ─── normalizeGuid ───────────────────────────────────────────────────────────\r\n\r\n/**\r\n * Normalize a GUID: strip curly braces and lowercase.\r\n *\r\n * Use this for GUIDs from sources other than formLookupId():\r\n * - `formContext.data.entity.getId()` returns GUIDs with braces\r\n * - WebApi `_value` fields may have braces depending on annotations\r\n * - Custom API responses may return GUIDs in varying formats\r\n *\r\n * formLookupId() already normalizes internally, so this is NOT needed for\r\n * lookup field access. Only use for getId(), WebApi responses, and comparisons.\r\n *\r\n * @param guid - A GUID string, possibly with braces and mixed case\r\n * @returns Normalized GUID (lowercase, no braces), or empty string if null/empty\r\n *\r\n * @example\r\n * ```typescript\r\n * const recordId = normalizeGuid(form.$context.data.entity.getId());\r\n * // \"{A1B2C3D4-...}\" -> \"a1b2c3d4-...\"\r\n *\r\n * const currencyId = normalizeGuid(result._transactioncurrencyid_value as string);\r\n * ```\r\n */\r\nexport function normalizeGuid(guid: string | null | undefined): string {\r\n if (!guid) return '';\r\n return guid.replace(/[{}]/g, '').toLowerCase();\r\n}\r\n\r\n// ─── Legacy Exports ──────────────────────────────────────────────────────────\r\n\r\n/** @deprecated Use ExtractFields<TForm> instead */\r\nexport type FormFields<TForm> = ExtractFields<TForm>;\r\n","/**\n * @xrmforge/helpers - Power Automate Cloud Flow caller\n *\n * Browser-safe, typed wrapper around a Power Automate cloud flow triggered by an\n * HTTP request (\"When an HTTP request is received\"). Replaces the hand-written\n * fetch wrappers that legacy D365 form scripts use for cloud-flow calls.\n *\n * The trigger URL contains a SAS signature and is environment-specific: pass it in\n * as a parameter (e.g. read from configuration), never hard-code it in source.\n * Custom API / Dataverse-proxied calls are a different concern and are covered by\n * `createUnboundAction`; this helper is for the direct HTTP-trigger case. Because\n * the call runs in the browser, the flow's CORS settings must allow the Dynamics\n * origin.\n *\n * Zero Node.js dependencies (uses the global `fetch`). For a progress spinner,\n * compose with `withProgress`: `withProgress('...', () => callCloudFlow(url, body))`.\n *\n * @example\n * ```typescript\n * import { callCloudFlow } from '@xrmforge/helpers';\n *\n * interface PriceRequest { quoteId: string; }\n * interface PriceResponse { total: number; currency: string; }\n *\n * // FLOW_URL comes from configuration, never hard-coded in source.\n * const price = await callCloudFlow<PriceRequest, PriceResponse>(\n * FLOW_URL,\n * { quoteId },\n * );\n * console.log(price.total, price.currency);\n * ```\n */\n\n/** Options for {@link callCloudFlow}. */\nexport interface CloudFlowOptions {\n /** HTTP method (default `'POST'`; HTTP-trigger flows are usually POST). */\n method?: string;\n /** Extra request headers, merged over the defaults (the caller's values win). */\n headers?: Record<string, string>;\n /** AbortSignal to cancel the request (e.g. a timeout or form unload). */\n signal?: AbortSignal;\n}\n\n/**\n * Call a Power Automate cloud flow via its HTTP request trigger URL.\n *\n * Sends `body` as JSON for methods that carry a body (anything but GET/HEAD), and\n * returns the parsed response: parsed JSON when the flow responds with\n * `application/json`, the raw text for other content types, or `undefined` for an\n * empty / `204 No Content` response. Throws on any non-2xx HTTP status, with the\n * status code and the response body included in the error message.\n *\n * @typeParam TReq - Shape of the request body.\n * @typeParam TRes - Shape of the parsed response.\n * @param triggerUrl - The flow's HTTP trigger URL (contains a SAS signature; pass\n * from configuration, never hard-code it).\n * @param body - Request payload, JSON-serialized when present.\n * @param options - Optional HTTP method, extra headers, and abort signal.\n * @returns The parsed flow response.\n * @throws {Error} If the flow responds with a non-2xx status.\n */\nexport async function callCloudFlow<TReq = unknown, TRes = unknown>(\n triggerUrl: string,\n body?: TReq,\n options: CloudFlowOptions = {},\n): Promise<TRes> {\n const method = options.method ?? 'POST';\n const hasBody = body !== undefined && method !== 'GET' && method !== 'HEAD';\n\n const headers: Record<string, string> = {};\n if (hasBody) headers['Content-Type'] = 'application/json';\n if (options.headers) Object.assign(headers, options.headers);\n\n const response = await fetch(triggerUrl, {\n method,\n headers,\n body: hasBody ? JSON.stringify(body) : undefined,\n signal: options.signal,\n });\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => '');\n throw new Error(\n `Cloud flow call failed (HTTP ${response.status} ${response.statusText})` +\n (errorText ? `: ${errorText}` : ''),\n );\n }\n\n if (response.status === 204) {\n return undefined as TRes;\n }\n\n const contentType = response.headers.get('content-type') ?? '';\n if (contentType.includes('application/json')) {\n return (await response.json()) as TRes;\n }\n const text = await response.text();\n return (text === '' ? undefined : text) as TRes;\n}\n"],"mappings":";AAgCO,SAAS,UAAU,MAAqC;AAC7D,QAAM,SAAS,KAAK,WAAW,KAAK,MAAM,QAAQ,KAAK,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI;AACvE,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,SAAO,YAAY,OAAO,KAAK,GAAG,CAAC;AACrC;AAyBO,SAAS,YACd,UACA,oBACyD;AACzD,QAAM,MAAM,IAAI,kBAAkB;AAClC,QAAM,KAAK,SAAS,GAAG;AACvB,MAAI,CAAC,GAAI,QAAO;AAEhB,SAAO;AAAA,IACL;AAAA,IACA,MAAO,SAAS,GAAG,GAAG,4CAA4C,KAAgB;AAAA,IAClF,YAAa,SAAS,GAAG,GAAG,2CAA2C,KAAgB;AAAA,EACzF;AACF;AAiBO,SAAS,aACd,UACA,sBACyE;AACzE,QAAM,SAAkF,CAAC;AACzF,aAAW,QAAQ,sBAAsB;AACvC,WAAO,IAAI,IAAI,YAAY,UAAU,IAAI;AAAA,EAC3C;AACA,SAAO;AACT;AAiBO,SAAS,oBACd,UACA,WACe;AACf,SAAQ,SAAS,GA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AAc,MAAyC;AACrE,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,KAAK,QAAQ,SAAS,EAAE,EAAE,YAAY;AAC/C;;;ACrMA,eAAsB,cACpB,YACA,MACA,UAA4B,CAAC,GACd;AACf,QAAM,SAAS,QAAQ,UAAU;AACjC,QAAM,UAAU,SAAS,UAAa,WAAW,SAAS,WAAW;AAErE,QAAM,UAAkC,CAAC;AACzC,MAAI,QAAS,SAAQ,cAAc,IAAI;AACvC,MAAI,QAAQ,QAAS,QAAO,OAAO,SAAS,QAAQ,OAAO;AAE3D,QAAM,WAAW,MAAM,MAAM,YAAY;AAAA,IACvC;AAAA,IACA;AAAA,IACA,MAAM,UAAU,KAAK,UAAU,IAAI,IAAI;AAAA,IACvC,QAAQ,QAAQ;AAAA,EAClB,CAAC;AAED,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,YAAY,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,EAAE;AACtD,UAAM,IAAI;AAAA,MACR,gCAAgC,SAAS,MAAM,IAAI,SAAS,UAAU,OACrE,YAAY,KAAK,SAAS,KAAK;AAAA,IAClC;AAAA,EACF;AAEA,MAAI,SAAS,WAAW,KAAK;AAC3B,WAAO;AAAA,EACT;AAEA,QAAM,cAAc,SAAS,QAAQ,IAAI,cAAc,KAAK;AAC5D,MAAI,YAAY,SAAS,kBAAkB,GAAG;AAC5C,WAAQ,MAAM,SAAS,KAAK;AAAA,EAC9B;AACA,QAAM,OAAO,MAAM,SAAS,KAAK;AACjC,SAAQ,SAAS,KAAK,SAAY;AACpC;","names":["DisplayState","FormType","FormNotificationLevel","RequiredLevel","SubmitMode","SaveMode","ClientType","ClientState","OperationType","StructuralProperty","BindingType"]}
1
+ {"version":3,"sources":["../src/webapi-helpers.ts","../src/xrm-constants.ts","../src/action-runtime.ts","../src/typed-form.ts","../src/cloud-flow.ts","../src/form-submit.ts","../src/app-notification.ts"],"sourcesContent":["/**\r\n * @xrmforge/helpers - Web API Helper Functions\r\n *\r\n * Lightweight utility functions for building OData query strings\r\n * with type-safe field names from generated Fields enums.\r\n *\r\n * Zero runtime overhead when used with const enums (values are inlined).\r\n *\r\n * @example\r\n * ```typescript\r\n * import { select } from '@xrmforge/helpers';\r\n *\r\n * Xrm.WebApi.retrieveRecord(ref.entityType, ref.id, select(\r\n * AccountFields.Name,\r\n * AccountFields.WebsiteUrl,\r\n * AccountFields.Address1Line1,\r\n * ));\r\n * ```\r\n */\r\n\r\n/**\r\n * Build an OData $select query string from field names.\r\n *\r\n * Accepts either variadic arguments or a single array:\r\n * - `select(Fields.Name, Fields.Email)` (variadic)\r\n * - `select([Fields.Name, Fields.Email])` (array)\r\n *\r\n * @param fields - Field names (use generated Fields enum for type safety)\r\n * @returns OData query string (e.g. \"?$select=name,websiteurl,address1_line1\")\r\n */\r\nexport function select(fields: string[]): string;\r\nexport function select(...fields: string[]): string;\r\nexport function select(...args: string[] | [string[]]): string {\r\n const fields = args.length === 1 && Array.isArray(args[0]) ? args[0] : args as string[];\r\n if (fields.length === 0) return '';\r\n return `?$select=${fields.join(',')}`;\r\n}\r\n\r\n/**\r\n * Parse a lookup field from a Dataverse Web API response into a LookupValue.\r\n *\r\n * Dataverse returns lookups as `_fieldname_value` with OData annotations:\r\n * - `_fieldname_value` (GUID)\r\n * - `_fieldname_value@OData.Community.Display.V1.FormattedValue` (display name)\r\n * - `_fieldname_value@Microsoft.Dynamics.CRM.lookuplogicalname` (entity type)\r\n *\r\n * This function extracts all three into an `Xrm.LookupValue` object.\r\n *\r\n * @param response - The raw Web API response object\r\n * @param navigationProperty - Navigation property name (use NavigationProperties enum for type safety)\r\n * @returns Xrm.LookupValue or null if the lookup is empty\r\n *\r\n * @example\r\n * ```typescript\r\n * // With NavigationProperties enum (recommended):\r\n * parseLookup(result, AccountNav.Country);\r\n *\r\n * // Or with navigation property name directly:\r\n * parseLookup(result, 'markant_address1_countryid');\r\n * ```\r\n */\r\nexport function parseLookup(\r\n response: Record<string, unknown>,\r\n navigationProperty: string,\r\n): { id: string; name: string; entityType: string } | null {\r\n const key = `_${navigationProperty}_value`;\r\n const id = response[key] as string | undefined;\r\n if (!id) return null;\r\n\r\n return {\r\n id,\r\n name: (response[`${key}@OData.Community.Display.V1.FormattedValue`] as string) ?? '',\r\n entityType: (response[`${key}@Microsoft.Dynamics.CRM.lookuplogicalname`] as string) ?? '',\r\n };\r\n}\r\n\r\n/**\r\n * Parse multiple lookup fields from a Dataverse Web API response at once.\r\n *\r\n * @param response - The raw Web API response object\r\n * @param navigationProperties - Navigation property names to parse\r\n * @returns Map of navigation property name to LookupValue (null entries omitted)\r\n *\r\n * @example\r\n * ```typescript\r\n * const lookups = parseLookups(result, ['markant_address1_countryid', 'parentaccountid']);\r\n * formContext.getAttribute(Fields.Country).setValue(\r\n * lookups.markant_address1_countryid ? [lookups.markant_address1_countryid] : null\r\n * );\r\n * ```\r\n */\r\nexport function parseLookups(\r\n response: Record<string, unknown>,\r\n navigationProperties: string[],\r\n): Record<string, { id: string; name: string; entityType: string } | null> {\r\n const result: Record<string, { id: string; name: string; entityType: string } | null> = {};\r\n for (const prop of navigationProperties) {\r\n result[prop] = parseLookup(response, prop);\r\n }\r\n return result;\r\n}\r\n\r\n/**\r\n * Get the formatted (display) value of any field from a Web API response.\r\n *\r\n * Works for OptionSets, Lookups, DateTimes, Money, and other formatted fields.\r\n *\r\n * @param response - The raw Web API response object\r\n * @param fieldName - The field logical name (e.g. \"statecode\", \"createdon\")\r\n * @returns The formatted string value, or null if not available\r\n *\r\n * @example\r\n * ```typescript\r\n * const status = parseFormattedValue(result, 'statecode');\r\n * // \"Active\" (instead of 0)\r\n * ```\r\n */\r\nexport function parseFormattedValue(\r\n response: Record<string, unknown>,\r\n fieldName: string,\r\n): string | null {\r\n return (response[`${fieldName}@OData.Community.Display.V1.FormattedValue`] as string) ?? null;\r\n}\r\n\r\n/**\r\n * Parse a MultiSelect OptionSet value into a number array.\r\n *\r\n * MultiSelect OptionSets come back in different shapes: the Web API returns a\r\n * comma-separated string (`\"595300000,595300001\"`), a form attribute returns a\r\n * `number[]`. This normalizes all shapes (comma string, number[], single number,\r\n * null/undefined) to a clean `number[]` (empty/whitespace parts dropped).\r\n *\r\n * @param value - The raw value (comma string, number[], number, or null)\r\n * @param emptyAsNull - When `true`, an empty result yields `null` instead of `[]`\r\n * (handy for `setValue`, which treats `null` as \"clear\")\r\n * @returns The parsed option values\r\n *\r\n * @example\r\n * // Web API response -> number[] for comparison:\r\n * const types = parseMultiSelect(account.markant_customertypemulticode);\r\n * if (types.includes(CustomerType.Industry)) { ... }\r\n *\r\n * // Writing back to a form field (empty -> null clears it):\r\n * form.markant_customertypemulticode.setValue(parseMultiSelect(raw, true));\r\n */\r\nexport function parseMultiSelect(value: unknown): number[];\r\nexport function parseMultiSelect(value: unknown, emptyAsNull: false): number[];\r\nexport function parseMultiSelect(value: unknown, emptyAsNull: true): number[] | null;\r\nexport function parseMultiSelect(value: unknown, emptyAsNull = false): number[] | null {\r\n let nums: number[];\r\n if (value == null) {\r\n nums = [];\r\n } else if (Array.isArray(value)) {\r\n nums = value.map((v) => Number(v)).filter(Number.isFinite);\r\n } else if (typeof value === 'number') {\r\n nums = [value];\r\n } else if (typeof value === 'string') {\r\n // Drop empty parts BEFORE Number(): Number('') is 0, not NaN, which would\r\n // otherwise sneak a spurious 0 in from a trailing comma.\r\n nums = value\r\n .split(',')\r\n .map((s) => s.trim())\r\n .filter((s) => s !== '')\r\n .map(Number)\r\n .filter(Number.isFinite);\r\n } else {\r\n nums = [];\r\n }\r\n return nums.length === 0 && emptyAsNull ? null : nums;\r\n}\r\n\r\n/**\r\n * Build an OData $select and $expand query string.\r\n *\r\n * @param fields - Field names to select\r\n * @param expand - Navigation property to expand (optional)\r\n * @returns OData query string\r\n *\r\n * @example\r\n * ```typescript\r\n * Xrm.WebApi.retrieveRecord(\"account\", id, selectExpand(\r\n * [AccountFields.Name, AccountFields.WebsiteUrl],\r\n * \"primarycontactid($select=fullname,emailaddress1)\"\r\n * ));\r\n * ```\r\n */\r\nexport function selectExpand(fields: string[], expand: string): string {\r\n const parts: string[] = [];\r\n if (fields.length > 0) parts.push(`$select=${fields.join(',')}`);\r\n if (expand) parts.push(`$expand=${expand}`);\r\n return parts.length > 0 ? `?${parts.join('&')}` : '';\r\n}\r\n\r\n// ─── Form Lookup Helpers ────────────────────────────────────────────────────\r\n\r\n/**\r\n * Extract the first lookup value from a FormContext lookup attribute.\r\n *\r\n * Centralizes the common pattern of reading a lookup from a form field,\r\n * handling null/empty arrays, and normalizing the GUID (removing braces).\r\n *\r\n * @param attr - A lookup attribute from formContext.getAttribute()\r\n * @returns Xrm.LookupValue with normalized id (no braces), or null if empty\r\n *\r\n * @example\r\n * ```typescript\r\n * import { formLookup } from '@xrmforge/helpers';\r\n * const customer = formLookup(form.getAttribute(Fields.CustomerId));\r\n * if (customer) {\r\n * console.log(customer.id, customer.name, customer.entityType);\r\n * }\r\n * ```\r\n */\r\nexport function formLookup(\r\n attr: { getValue(): { id: string; name?: string; entityType: string }[] | null },\r\n): { id: string; name: string; entityType: string } | null {\r\n const values = attr.getValue();\r\n if (!values || values.length === 0) return null;\r\n const first = values[0]!;\r\n return {\r\n id: first.id.replace(/[{}]/g, ''),\r\n name: first.name ?? '',\r\n entityType: first.entityType,\r\n };\r\n}\r\n\r\n/**\r\n * Extract just the normalized GUID from a FormContext lookup attribute.\r\n *\r\n * Shorthand for the most common lookup use case: getting the record ID\r\n * for a Web API call or comparison.\r\n *\r\n * @param attr - A lookup attribute from formContext.getAttribute()\r\n * @returns Normalized GUID string (no braces), or null if empty\r\n *\r\n * @example\r\n * ```typescript\r\n * import { formLookupId } from '@xrmforge/helpers';\r\n * const accountId = formLookupId(form.getAttribute(Fields.AccountId));\r\n * if (accountId) {\r\n * await Xrm.WebApi.retrieveRecord(EntityNames.Account, accountId, select(...));\r\n * }\r\n * ```\r\n */\r\nexport function formLookupId(\r\n attr: { getValue(): { id: string }[] | null },\r\n): string | null {\r\n const values = attr.getValue();\r\n if (!values || values.length === 0) return null;\r\n return values[0]!.id.replace(/[{}]/g, '');\r\n}\r\n","/**\r\n * @xrmforge/helpers - Xrm API Constants\r\n *\r\n * Const enums for all common Xrm string/number constants.\r\n * Eliminates raw strings in D365 form scripts.\r\n *\r\n * @types/xrm defines these as string literal types for compile-time checking,\r\n * but does NOT provide runtime constants (XrmEnum is not available at runtime).\r\n * These const enums are erased at compile time (zero runtime overhead).\r\n *\r\n * @example\r\n * ```typescript\r\n * import { DisplayState } from '@xrmforge/helpers';\r\n *\r\n * if (tab.getDisplayState() === DisplayState.Expanded) { ... }\r\n * ```\r\n */\r\n\r\n/** Tab/Section display state */\r\nexport const enum DisplayState {\r\n Expanded = 'expanded',\r\n Collapsed = 'collapsed',\r\n}\r\n\r\n/**\r\n * Form type (formContext.ui.getFormType()).\r\n *\r\n * WARNING: XrmEnum.FormType from @types/xrm is a const enum that does NOT exist\r\n * at runtime. esbuild does not resolve const enums from .d.ts files. Using\r\n * XrmEnum.FormType.Create in code produces \"XrmEnum is not defined\" at runtime.\r\n * Use this FormType enum instead (same values, zero runtime overhead).\r\n */\r\nexport const enum FormType {\r\n Undefined = 0,\r\n Create = 1,\r\n Update = 2,\r\n ReadOnly = 3,\r\n Disabled = 4,\r\n BulkEdit = 6,\r\n}\r\n\r\n/**\r\n * True when the form is currently shown in the given {@link FormType}.\r\n *\r\n * `formContext.ui.getFormType()` is typed as `XrmEnum.FormType` (from\r\n * @types/xrm), which is a nominally distinct type from the {@link FormType}\r\n * const enum above. A direct `getFormType() === FormType.Create` therefore\r\n * fails to compile under `strict` with TS2367 (\"This comparison appears to be\r\n * unintentional because the types have no overlap\"). Relational operators\r\n * (`>`/`<`) slip past TS2367 but cannot express an exact match. This helper\r\n * bridges both numeric enums for the equality case without a hand-written cast.\r\n *\r\n * @example\r\n * if (isFormType(form.$context, FormType.Create)) {\r\n * // only on create\r\n * }\r\n */\r\nexport function isFormType(formContext: Xrm.FormContext, formType: FormType): boolean {\r\n return (formContext.ui.getFormType() as number) === (formType as number);\r\n}\r\n\r\n/** Form notification level (formContext.ui.setFormNotification) */\r\nexport const enum FormNotificationLevel {\r\n Error = 'ERROR',\r\n Warning = 'WARNING',\r\n Info = 'INFO',\r\n}\r\n\r\n/**\r\n * App-level (global) notification level for Xrm.App.addGlobalNotification.\r\n *\r\n * Mirrors XrmEnum.AppNotificationLevel, which (like all XrmEnum const enums) does\r\n * NOT exist at runtime. Use this enum; {@link addAppNotification} applies the cast\r\n * to the @types/xrm typings at a single boundary.\r\n */\r\nexport const enum AppNotificationLevel {\r\n Success = 1,\r\n Error = 2,\r\n Warning = 3,\r\n Information = 4,\r\n}\r\n\r\n/** Attribute required level (attribute.setRequiredLevel) */\r\nexport const enum RequiredLevel {\r\n None = 'none',\r\n Required = 'required',\r\n Recommended = 'recommended',\r\n}\r\n\r\n/** Attribute submit mode (attribute.setSubmitMode) */\r\nexport const enum SubmitMode {\r\n Always = 'always',\r\n Never = 'never',\r\n Dirty = 'dirty',\r\n}\r\n\r\n/** Save mode (eventArgs.getSaveMode()) */\r\nexport const enum SaveMode {\r\n Save = 1,\r\n SaveAndClose = 2,\r\n Deactivate = 5,\r\n Reactivate = 6,\r\n Send = 7,\r\n Disqualify = 15,\r\n Qualify = 16,\r\n Assign = 47,\r\n SaveAsCompleted = 58,\r\n SaveAndNew = 59,\r\n AutoSave = 70,\r\n}\r\n\r\n/** Client type (Xrm.Utility.getGlobalContext().client.getClient()) */\r\nexport const enum ClientType {\r\n Web = 'Web',\r\n Outlook = 'Outlook',\r\n Mobile = 'Mobile',\r\n}\r\n\r\n/** Client state (Xrm.Utility.getGlobalContext().client.getClientState()) */\r\nexport const enum ClientState {\r\n Online = 'Online',\r\n Offline = 'Offline',\r\n}\r\n\r\n// WebApi Execute Constants\r\n\r\n/** Operation type for Xrm.WebApi.execute getMetadata().operationType */\r\nexport const enum OperationType {\r\n /** Custom Action or OOB Action (POST) */\r\n Action = 0,\r\n /** Custom Function or OOB Function (GET) */\r\n Function = 1,\r\n /** CRUD operation (Create, Retrieve, Update, Delete) */\r\n CRUD = 2,\r\n}\r\n\r\n/** Structural property for getMetadata().parameterTypes[].structuralProperty */\r\nexport const enum StructuralProperty {\r\n Unknown = 0,\r\n PrimitiveType = 1,\r\n ComplexType = 2,\r\n EnumerationType = 3,\r\n Collection = 4,\r\n EntityType = 5,\r\n}\r\n\r\n/** Binding type for Custom API definitions */\r\nexport const enum BindingType {\r\n /** Not bound to an entity (globally callable) */\r\n Global = 0,\r\n /** Bound to a single entity record */\r\n Entity = 1,\r\n /** Bound to an entity collection */\r\n EntityCollection = 2,\r\n}\r\n","/**\r\n * @xrmforge/helpers - Action/Function Runtime Helpers\r\n *\r\n * Factory functions for type-safe Custom API execution.\r\n * These are imported by generated action/function modules.\r\n *\r\n * Design:\r\n * - `createBoundAction` / `createUnboundAction`: Produce executor objects\r\n * with `.execute()` (calls Xrm.WebApi) and `.request()` (for executeMultiple)\r\n * - `executeRequest`: Central execute wrapper (single place for the `as any` cast)\r\n * - `withProgress`: Convenience wrapper with progress indicator (errors propagate to the handler wrapper)\r\n *\r\n * @example\r\n * ```typescript\r\n * // Generated code (in generated/actions/quote.ts):\r\n * import { createBoundAction } from '@xrmforge/helpers';\r\n * export const WinQuote = createBoundAction('markant_winquote', 'quote');\r\n *\r\n * // Developer code (in quote-form.ts): void action throws on failure, so just await it\r\n * import { WinQuote } from '../generated/actions/quote';\r\n * await WinQuote.execute(recordId);\r\n * ```\r\n */\r\n\r\nimport { OperationType, StructuralProperty } from './xrm-constants.js';\r\n\r\n// Types\r\n\r\n/** Parameter metadata for getMetadata().parameterTypes */\r\nexport interface ParameterMeta {\r\n typeName: string;\r\n structuralProperty: number;\r\n}\r\n\r\n/** Map of parameter names to their OData metadata */\r\nexport type ParameterMetaMap = Record<string, ParameterMeta>;\r\n\r\n/** Executor for a bound action without additional parameters */\r\nexport interface BoundActionExecutor<TResult = void> {\r\n execute(recordId: string): Promise<TResult extends void ? void : TResult>;\r\n request(recordId: string): Record<string, unknown>;\r\n}\r\n\r\n/** Executor for a bound action with typed parameters */\r\nexport interface BoundActionWithParamsExecutor<TParams, TResult = void> {\r\n execute(recordId: string, params: TParams): Promise<TResult extends void ? void : TResult>;\r\n request(recordId: string, params: TParams): Record<string, unknown>;\r\n}\r\n\r\n/** Executor for an unbound action without parameters */\r\nexport interface UnboundActionExecutor<TResult = void> {\r\n execute(): Promise<TResult extends void ? void : TResult>;\r\n request(): Record<string, unknown>;\r\n}\r\n\r\n/** Executor for an unbound action with typed parameters and optional typed response */\r\nexport interface UnboundActionWithParamsExecutor<TParams, TResult = void> {\r\n execute(params: TParams): Promise<TResult extends void ? void : TResult>;\r\n request(params: TParams): Record<string, unknown>;\r\n}\r\n\r\n/** Executor for an unbound function with typed response */\r\nexport interface UnboundFunctionExecutor<TResult> {\r\n execute(): Promise<TResult>;\r\n request(): Record<string, unknown>;\r\n}\r\n\r\n/** Executor for a bound function with typed response */\r\nexport interface BoundFunctionExecutor<TResult> {\r\n execute(recordId: string): Promise<TResult>;\r\n request(recordId: string): Record<string, unknown>;\r\n}\r\n\r\n// Central Execute\r\n\r\n/**\r\n * Execute a single request via Xrm.WebApi.online.execute().\r\n *\r\n * This is the ONLY place in the entire framework where the `as any` cast happens.\r\n * All generated executors call this function internally.\r\n */\r\nexport function executeRequest(request: Record<string, unknown>): Promise<Response> {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return (Xrm.WebApi as any).online.execute(request) as Promise<Response>;\r\n}\r\n\r\n/**\r\n * Execute multiple requests via Xrm.WebApi.online.executeMultiple().\r\n *\r\n * @param requests - Array of request objects (from `.request()` factories).\r\n * Wrap a subset in an inner array for transactional changeset execution.\r\n */\r\nexport function executeMultiple(\r\n requests: Array<Record<string, unknown> | Array<Record<string, unknown>>>,\r\n): Promise<Response[]> {\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n return (Xrm.WebApi as any).online.executeMultiple(requests) as Promise<Response[]>;\r\n}\r\n\r\n// Request Builder (internal)\r\n\r\nfunction cleanRecordId(id: string): string {\r\n return id.replace(/[{}]/g, '');\r\n}\r\n\r\nfunction buildBoundRequest(\r\n operationName: string,\r\n entityLogicalName: string,\r\n operationType: OperationType,\r\n recordId: string,\r\n paramMeta?: ParameterMetaMap,\r\n params?: Record<string, unknown>,\r\n): Record<string, unknown> {\r\n const parameterTypes: Record<string, ParameterMeta> = {\r\n entity: {\r\n typeName: `mscrm.${entityLogicalName}`,\r\n structuralProperty: StructuralProperty.EntityType,\r\n },\r\n };\r\n\r\n if (paramMeta) {\r\n for (const [key, meta] of Object.entries(paramMeta)) {\r\n parameterTypes[key] = meta;\r\n }\r\n }\r\n\r\n const request: Record<string, unknown> = {\r\n getMetadata: () => ({\r\n boundParameter: 'entity',\r\n parameterTypes,\r\n operationName,\r\n operationType,\r\n }),\r\n entity: {\r\n id: cleanRecordId(recordId),\r\n entityType: entityLogicalName,\r\n },\r\n };\r\n\r\n if (params) {\r\n for (const [key, value] of Object.entries(params)) {\r\n request[key] = value;\r\n }\r\n }\r\n\r\n return request;\r\n}\r\n\r\nfunction buildUnboundRequest(\r\n operationName: string,\r\n operationType: OperationType,\r\n paramMeta?: ParameterMetaMap,\r\n params?: Record<string, unknown>,\r\n): Record<string, unknown> {\r\n const parameterTypes: Record<string, ParameterMeta> = {};\r\n\r\n if (paramMeta) {\r\n for (const [key, meta] of Object.entries(paramMeta)) {\r\n parameterTypes[key] = meta;\r\n }\r\n }\r\n\r\n const request: Record<string, unknown> = {\r\n getMetadata: () => ({\r\n boundParameter: null,\r\n parameterTypes,\r\n operationName,\r\n operationType,\r\n }),\r\n };\r\n\r\n if (params) {\r\n for (const [key, value] of Object.entries(params)) {\r\n request[key] = value;\r\n }\r\n }\r\n\r\n return request;\r\n}\r\n\r\n// Action Factories\r\n\r\n/**\r\n * Create an executor for a bound action (entity-bound) without parameters or typed response.\r\n *\r\n * @param operationName - Custom API unique name (e.g. \"markant_winquote\")\r\n * @param entityLogicalName - Entity logical name (e.g. \"quote\")\r\n */\r\nexport function createBoundAction(\r\n operationName: string,\r\n entityLogicalName: string,\r\n): BoundActionExecutor;\r\n\r\n/**\r\n * Create an executor for a bound action without parameters but with typed response.\r\n *\r\n * @param operationName - Custom API unique name\r\n * @param entityLogicalName - Entity logical name\r\n */\r\nexport function createBoundAction<TResult>(\r\n operationName: string,\r\n entityLogicalName: string,\r\n): BoundActionExecutor<TResult>;\r\n\r\n/**\r\n * Create an executor for a bound action with typed parameters and optional typed response.\r\n *\r\n * @param operationName - Custom API unique name\r\n * @param entityLogicalName - Entity logical name\r\n * @param paramMeta - Parameter metadata map (parameter name to OData type info)\r\n */\r\nexport function createBoundAction<\r\n TParams extends Record<string, unknown>,\r\n TResult = void,\r\n>(\r\n operationName: string,\r\n entityLogicalName: string,\r\n paramMeta: ParameterMetaMap,\r\n): BoundActionWithParamsExecutor<TParams, TResult>;\r\n\r\nexport function createBoundAction<\r\n TParams extends Record<string, unknown>,\r\n TResult = void,\r\n>(\r\n operationName: string,\r\n entityLogicalName: string,\r\n paramMeta?: ParameterMetaMap,\r\n): BoundActionExecutor<TResult> | BoundActionWithParamsExecutor<TParams, TResult> {\r\n return {\r\n async execute(recordId: string, params?: TParams): Promise<TResult extends void ? void : TResult> {\r\n const req = buildBoundRequest(\r\n operationName, entityLogicalName, OperationType.Action,\r\n recordId, paramMeta, params,\r\n );\r\n const response = await executeRequest(req);\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(errorText);\r\n }\r\n // Parse JSON when response properties are defined (TResult is not void)\r\n if (response.status !== 204) {\r\n return response.json() as Promise<TResult extends void ? void : TResult>;\r\n }\r\n return undefined as TResult extends void ? void : TResult;\r\n },\r\n request(recordId: string, params?: TParams): Record<string, unknown> {\r\n return buildBoundRequest(\r\n operationName, entityLogicalName, OperationType.Action,\r\n recordId, paramMeta, params,\r\n );\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Create an executor for an unbound (global) action without parameters or typed response.\r\n *\r\n * @param operationName - Custom API unique name\r\n */\r\nexport function createUnboundAction(\r\n operationName: string,\r\n): UnboundActionExecutor;\r\n\r\n/**\r\n * Create an executor for an unbound action without parameters but with typed response.\r\n *\r\n * @param operationName - Custom API unique name\r\n */\r\nexport function createUnboundAction<TResult>(\r\n operationName: string,\r\n): UnboundActionExecutor<TResult>;\r\n\r\n/**\r\n * Create an executor for an unbound action with typed parameters and optional typed response.\r\n *\r\n * @param operationName - Custom API unique name\r\n * @param paramMeta - Parameter metadata map\r\n */\r\nexport function createUnboundAction<\r\n TParams extends Record<string, unknown>,\r\n TResult = void,\r\n>(\r\n operationName: string,\r\n paramMeta: ParameterMetaMap,\r\n): UnboundActionWithParamsExecutor<TParams, TResult>;\r\n\r\nexport function createUnboundAction<\r\n TParams extends Record<string, unknown>,\r\n TResult = void,\r\n>(\r\n operationName: string,\r\n paramMeta?: ParameterMetaMap,\r\n): UnboundActionExecutor | UnboundActionWithParamsExecutor<TParams, TResult> {\r\n return {\r\n async execute(params?: TParams): Promise<TResult extends void ? void : TResult> {\r\n const req = buildUnboundRequest(\r\n operationName, OperationType.Action, paramMeta, params,\r\n );\r\n const response = await executeRequest(req);\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(errorText);\r\n }\r\n if (response.status !== 204) {\r\n return response.json() as Promise<TResult extends void ? void : TResult>;\r\n }\r\n return undefined as TResult extends void ? void : TResult;\r\n },\r\n request(params?: TParams): Record<string, unknown> {\r\n return buildUnboundRequest(\r\n operationName, OperationType.Action, paramMeta, params,\r\n );\r\n },\r\n };\r\n}\r\n\r\n// Function Factories\r\n\r\n/**\r\n * Create an executor for an unbound (global) function with typed response.\r\n *\r\n * @param operationName - Function name (e.g. \"WhoAmI\")\r\n */\r\nexport function createUnboundFunction<TResult>(\r\n operationName: string,\r\n): UnboundFunctionExecutor<TResult> {\r\n return {\r\n async execute(): Promise<TResult> {\r\n const req = buildUnboundRequest(operationName, OperationType.Function);\r\n const response = await executeRequest(req);\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(errorText);\r\n }\r\n return response.json() as Promise<TResult>;\r\n },\r\n request(): Record<string, unknown> {\r\n return buildUnboundRequest(operationName, OperationType.Function);\r\n },\r\n };\r\n}\r\n\r\n/**\r\n * Create an executor for a bound function with typed response.\r\n *\r\n * @param operationName - Function name\r\n * @param entityLogicalName - Entity logical name\r\n */\r\nexport function createBoundFunction<TResult>(\r\n operationName: string,\r\n entityLogicalName: string,\r\n): BoundFunctionExecutor<TResult> {\r\n return {\r\n async execute(recordId: string): Promise<TResult> {\r\n const req = buildBoundRequest(\r\n operationName, entityLogicalName, OperationType.Function, recordId,\r\n );\r\n const response = await executeRequest(req);\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(errorText);\r\n }\r\n return response.json() as Promise<TResult>;\r\n },\r\n request(recordId: string): Record<string, unknown> {\r\n return buildBoundRequest(\r\n operationName, entityLogicalName, OperationType.Function, recordId,\r\n );\r\n },\r\n };\r\n}\r\n\r\n// Convenience\r\n\r\n/**\r\n * Execute an async operation with an Xrm progress indicator.\r\n *\r\n * Shows a progress spinner before the operation and closes it afterwards\r\n * (success or failure). Errors are NOT displayed here; they propagate to the\r\n * caller so the single error UI is owned by the handler wrapper\r\n * (`wrapHandler`/`wrapCommand`). Showing an error dialog here too would produce\r\n * a duplicate error UI (dialog + form notification) when `withProgress` runs\r\n * inside a wrapped command (the common ribbon case).\r\n *\r\n * @param message - Progress indicator message (e.g. \"Processing quote...\")\r\n * @param operation - Async function to execute\r\n * @returns The result of the operation\r\n *\r\n * @example\r\n * ```typescript\r\n * // Inside a wrapCommand handler: the wrapper shows the error notification.\r\n * await withProgress('Processing quote...', () => WinQuote.execute(recordId));\r\n * ```\r\n */\r\nexport async function withProgress<T>(\r\n message: string,\r\n operation: () => Promise<T>,\r\n): Promise<T> {\r\n Xrm.Utility.showProgressIndicator(message);\r\n try {\r\n return await operation();\r\n } finally {\r\n Xrm.Utility.closeProgressIndicator();\r\n }\r\n}\r\n","/**\n * @xrmforge/helpers - TypedForm Proxy\n *\n * Creates a proxy around Xrm.FormContext that allows direct property access\n * to form fields. Instead of `form.getAttribute(\"name\").setValue(\"X\")`,\n * write `form.name.setValue(\"X\")`.\n *\n * Works with generated form types from @xrmforge/typegen. Since v0.9.2,\n * typegen generates a `FormTypeInfo` interface per form that bundles\n * Fields, AttributeMap, and ControlMap for reliable type extraction.\n *\n * @example\n * ```typescript\n * import { typedForm } from '@xrmforge/helpers';\n * import type { AccountLMFirmaFormTypeInfo } from '../../generated/forms/account.js';\n *\n * const form = typedForm<AccountLMFirmaFormTypeInfo>(ctx.getFormContext());\n * form.name.getValue(); // string | null (typed)\n * form.revenue.setValue(150000); // NumberAttribute (typed)\n * form.$context.ui.tabs.get(...); // Full FormContext access\n * form.controls.name; // Control access (typed)\n * form.$unsafe('off_form_field'); // Access fields not on the form\n * ```\n */\n\n// ─── FormTypeInfo Protocol ───────────────────────────────────────────────────\n\n/**\n * Protocol interface generated by typegen for each form.\n * Bundles Fields, AttributeMap, and ControlMap so typedForm can extract\n * them reliably without fragile Conditional Type inference on overloads.\n *\n * Generated as: `export interface MyFormTypeInfo { fields: ...; attributes: ...; controls: ...; form: ...; }`\n */\nexport interface FormTypeInfoProtocol {\n fields: string;\n attributes: Record<string, Xrm.Attributes.Attribute>;\n controls: Record<string, Xrm.Controls.Control>;\n form: object;\n}\n\n// ─── Type Extraction ─────────────────────────────────────────────────────────\n\n/**\n * Extract Fields from a Form interface.\n *\n * Strategy: Check if TForm has a companion TypeInfo interface (generated by\n * typegen >= 0.9.2). If so, extract fields directly. Otherwise, fall back\n * to Conditional Type inference on getAttribute (works in same compilation\n * unit but may fail across package boundaries in TS 5.9+).\n */\n/**\n * Type extraction uses duck typing: if TForm has a `fields` property,\n * it's a TypeInfo interface (from typegen >= 0.10.0). Otherwise, fall\n * back to Conditional Type inference on getAttribute overloads.\n *\n * Duck typing (`TForm extends { fields: infer F }`) is more robust than\n * matching against FormTypeInfoProtocol because it doesn't require\n * structural compatibility of attributes/controls/form across packages.\n */\ntype ExtractFields<TForm> =\n TForm extends { fields: infer F extends string } ? F :\n TForm extends { getAttribute<K extends infer F>(name: K): unknown }\n ? F extends string ? F : never\n : never;\n\ntype ExtractAttributeMap<TForm, TFields extends string> =\n TForm extends { attributes: infer A extends Record<string, Xrm.Attributes.Attribute> } ? A :\n { [K in TFields]: TForm extends { getAttribute(name: K): infer R }\n ? R extends Xrm.Attributes.Attribute ? R : Xrm.Attributes.Attribute\n : Xrm.Attributes.Attribute;\n };\n\ntype ExtractControlMap<TForm, TFields extends string> =\n TForm extends { controls: infer C extends Record<string, Xrm.Controls.Control> } ? C :\n { [K in TFields]: TForm extends { getControl(name: K): infer R }\n ? R extends Xrm.Controls.Control ? R : Xrm.Controls.Control\n : Xrm.Controls.Control;\n };\n\ntype ExtractFormContext<TForm> =\n TForm extends { form: infer FC } ? FC :\n TForm extends Xrm.FormContext ? TForm :\n Xrm.FormContext;\n\n// ─── TypedForm Type ──────────────────────────────────────────────────────────\n\n/**\n * TypedForm: proxy type that maps field names to their attribute types.\n *\n * Provides direct property access to form fields (e.g. `form.name` returns\n * the StringAttribute), plus:\n * - `$context` for full FormContext access (ui, data, tabs, getAttribute with addOnChange)\n * - `controls.fieldName` for typed control access\n * - `$unsafe(name)` for off-form field access (fields loaded by D365 but not on the form)\n */\nexport type TypedForm<\n TForm,\n TFields extends string = ExtractFields<TForm>,\n TAttrMap extends Record<string, Xrm.Attributes.Attribute> = ExtractAttributeMap<TForm, TFields>,\n TCtrlMap extends Record<string, Xrm.Controls.Control> = ExtractControlMap<TForm, TFields>,\n> = {\n /**\n * Direct field access: form.fieldName returns the typed Attribute.\n *\n * Non-nullable because the field is in the generated FormXml. If a field\n * is NOT in the generated interface, it won't compile, forcing you to use\n * $unsafe() which IS nullable. This is the compiler warning: a compile\n * error that says \"this field is not on the form, use $unsafe()\".\n */\n readonly [K in TFields]: K extends keyof TAttrMap\n ? TAttrMap[K]\n : Xrm.Attributes.Attribute;\n} & {\n /** Access the underlying FormContext for ui, data, tabs, etc. */\n readonly $context: ExtractFormContext<TForm>;\n\n /**\n * Typed control access via form.controls.fieldname.\n *\n * Returns the specific control type from the generated ControlMap\n * (LookupControl, NumberControl, etc.). No cast needed.\n *\n * @example\n * ```typescript\n * form.controls.customerid.setEntityTypes([EntityNames.Account]);\n * form.controls.revenue.setVisible(false);\n * form.controls.name.setDisabled(true);\n * ```\n */\n readonly controls: {\n readonly [K in TFields]: K extends keyof TCtrlMap\n ? TCtrlMap[K]\n : Xrm.Controls.Control;\n };\n\n /**\n * Access an off-form field (loaded by D365 but not on the current form layout).\n * Returns null if the attribute does not exist.\n *\n * @example\n * ```typescript\n * form.$unsafe(OpportunityFields.VslBeauftragung)?.setValue(closeDate);\n * ```\n */\n $unsafe(name: string): Xrm.Attributes.Attribute | null;\n};\n\n/**\n * Wraps an Xrm Attribute so that setValue() automatically calls setSubmitMode('always').\n *\n * D365 AutoSave only submits \"dirty\" fields. Programmatically set values via setValue()\n * are NOT marked dirty by default, causing silent data loss on AutoSave. This proxy\n * intercepts setValue() and automatically marks the field for submission.\n *\n * This is intentionally invisible to the developer: they write `form.name.setValue('X')`\n * and the framework handles the rest. No more forgotten setSubmitMode calls.\n */\nfunction wrapAttributeWithAutoSubmit(attr: Xrm.Attributes.Attribute): Xrm.Attributes.Attribute {\n return new Proxy(attr, {\n get(target, prop) {\n if (prop === 'setValue') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Xrm.Attributes.Attribute.setValue has varying signatures per attribute type\n return (value: any) => {\n target.setValue(value);\n target.setSubmitMode('always');\n };\n }\n const val = (target as unknown as Record<string | symbol, unknown>)[prop];\n if (typeof val === 'function') return val.bind(target);\n return val;\n },\n });\n}\n\n/**\n * Create a typed form proxy around a FormContext.\n *\n * Pass the generated FormTypeInfo interface as type parameter (typegen >= 0.9.2).\n * It bundles the field/attribute/control maps so type extraction works across\n * package boundaries; the bare form interface resolves to `never` in consumer\n * projects (overload inference on getAttribute is unreliable across packages, TS 5.9+).\n *\n * @example\n * ```typescript\n * // Pass the generated <Form>TypeInfo type, not the bare form interface.\n * const form = typedForm<AccountLMFirmaFormTypeInfo>(ctx.getFormContext());\n * ```\n *\n * @param formContext - The Xrm.FormContext from executionContext.getFormContext()\n * @returns A proxy with direct typed property access to form fields\n */\nexport function typedForm<TForm>(\n formContext: Xrm.FormContext,\n): TypedForm<TForm> {\n return new Proxy(formContext as unknown as TypedForm<TForm>, {\n get(_target, prop) {\n if (typeof prop !== 'string') {\n return (formContext as unknown as Record<symbol, unknown>)[prop];\n }\n if (prop === '$context') return formContext;\n if (prop === 'controls') {\n return new Proxy({} as Record<string, Xrm.Controls.Control>, {\n get(_, controlName) {\n if (typeof controlName !== 'string') return undefined;\n return formContext.getControl(controlName);\n },\n });\n }\n if (prop === '$unsafe') {\n return (name: string) => formContext.getAttribute(name);\n }\n const attr = formContext.getAttribute(prop);\n if (attr) return wrapAttributeWithAutoSubmit(attr);\n return (formContext as unknown as Record<string, unknown>)[prop];\n },\n\n set(_target, prop, _value) {\n throw new TypeError(\n `Cannot assign to '${String(prop)}'. Use form.${String(prop)}.setValue() instead.`,\n );\n },\n\n has(_target, prop) {\n if (typeof prop !== 'string') return false;\n if (prop === '$context' || prop === 'controls' || prop === '$unsafe') return true;\n return formContext.getAttribute(prop) !== null;\n },\n });\n}\n\n// ─── normalizeGuid ───────────────────────────────────────────────────────────\n\n/**\n * Normalize a GUID: strip curly braces and lowercase.\n *\n * Use this for GUIDs from sources other than formLookupId():\n * - `formContext.data.entity.getId()` returns GUIDs with braces\n * - WebApi `_value` fields may have braces depending on annotations\n * - Custom API responses may return GUIDs in varying formats\n *\n * formLookupId() already normalizes internally, so this is NOT needed for\n * lookup field access. Only use for getId(), WebApi responses, and comparisons.\n *\n * @param guid - A GUID string, possibly with braces and mixed case\n * @returns Normalized GUID (lowercase, no braces), or empty string if null/empty\n *\n * @example\n * ```typescript\n * const recordId = normalizeGuid(form.$context.data.entity.getId());\n * // \"{A1B2C3D4-...}\" -> \"a1b2c3d4-...\"\n *\n * const currencyId = normalizeGuid(result._transactioncurrencyid_value as string);\n * ```\n */\nexport function normalizeGuid(guid: string | null | undefined): string {\n if (!guid) return '';\n return guid.replace(/[{}]/g, '').toLowerCase();\n}\n\n// ─── Legacy Exports ──────────────────────────────────────────────────────────\n\n/** @deprecated Use ExtractFields<TForm> instead */\nexport type FormFields<TForm> = ExtractFields<TForm>;\n","/**\r\n * @xrmforge/helpers - Power Automate Cloud Flow caller\r\n *\r\n * Browser-safe, typed wrapper around a Power Automate cloud flow triggered by an\r\n * HTTP request (\"When an HTTP request is received\"). Replaces the hand-written\r\n * fetch wrappers that legacy D365 form scripts use for cloud-flow calls.\r\n *\r\n * The trigger URL contains a SAS signature and is environment-specific: pass it in\r\n * as a parameter (e.g. read from configuration), never hard-code it in source.\r\n * Custom API / Dataverse-proxied calls are a different concern and are covered by\r\n * `createUnboundAction`; this helper is for the direct HTTP-trigger case. Because\r\n * the call runs in the browser, the flow's CORS settings must allow the Dynamics\r\n * origin.\r\n *\r\n * Zero Node.js dependencies (uses the global `fetch`). For a progress spinner,\r\n * compose with `withProgress`: `withProgress('...', () => callCloudFlow(url, body))`.\r\n *\r\n * @example\r\n * ```typescript\r\n * import { callCloudFlow } from '@xrmforge/helpers';\r\n *\r\n * interface PriceRequest { quoteId: string; }\r\n * interface PriceResponse { total: number; currency: string; }\r\n *\r\n * // FLOW_URL comes from configuration, never hard-coded in source.\r\n * const price = await callCloudFlow<PriceRequest, PriceResponse>(\r\n * FLOW_URL,\r\n * { quoteId },\r\n * );\r\n * console.log(price.total, price.currency);\r\n * ```\r\n */\r\n\r\n/** Options for {@link callCloudFlow}. */\r\nexport interface CloudFlowOptions {\r\n /** HTTP method (default `'POST'`; HTTP-trigger flows are usually POST). */\r\n method?: string;\r\n /** Extra request headers, merged over the defaults (the caller's values win). */\r\n headers?: Record<string, string>;\r\n /** AbortSignal to cancel the request (e.g. a timeout or form unload). */\r\n signal?: AbortSignal;\r\n}\r\n\r\n/**\r\n * Call a Power Automate cloud flow via its HTTP request trigger URL.\r\n *\r\n * Sends `body` as JSON for methods that carry a body (anything but GET/HEAD), and\r\n * returns the parsed response: parsed JSON when the flow responds with\r\n * `application/json`, the raw text for other content types, or `undefined` for an\r\n * empty / `204 No Content` response. Throws on any non-2xx HTTP status, with the\r\n * status code and the response body included in the error message.\r\n *\r\n * @typeParam TReq - Shape of the request body.\r\n * @typeParam TRes - Shape of the parsed response.\r\n * @param triggerUrl - The flow's HTTP trigger URL (contains a SAS signature; pass\r\n * from configuration, never hard-code it).\r\n * @param body - Request payload, JSON-serialized when present.\r\n * @param options - Optional HTTP method, extra headers, and abort signal.\r\n * @returns The parsed flow response.\r\n * @throws {Error} If the flow responds with a non-2xx status.\r\n */\r\nexport async function callCloudFlow<TReq = unknown, TRes = unknown>(\r\n triggerUrl: string,\r\n body?: TReq,\r\n options: CloudFlowOptions = {},\r\n): Promise<TRes> {\r\n const method = options.method ?? 'POST';\r\n const hasBody = body !== undefined && method !== 'GET' && method !== 'HEAD';\r\n\r\n const headers: Record<string, string> = {};\r\n if (hasBody) headers['Content-Type'] = 'application/json';\r\n if (options.headers) Object.assign(headers, options.headers);\r\n\r\n const response = await fetch(triggerUrl, {\r\n method,\r\n headers,\r\n body: hasBody ? JSON.stringify(body) : undefined,\r\n signal: options.signal,\r\n });\r\n\r\n if (!response.ok) {\r\n const errorText = await response.text().catch(() => '');\r\n throw new Error(\r\n `Cloud flow call failed (HTTP ${response.status} ${response.statusText})` +\r\n (errorText ? `: ${errorText}` : ''),\r\n );\r\n }\r\n\r\n if (response.status === 204) {\r\n return undefined as TRes;\r\n }\r\n\r\n const contentType = response.headers.get('content-type') ?? '';\r\n if (contentType.includes('application/json')) {\r\n return (await response.json()) as TRes;\r\n }\r\n const text = await response.text();\r\n return (text === '' ? undefined : text) as TRes;\r\n}\r\n","/**\n * @xrmforge/helpers - Attribute submit helpers\n *\n * Set or clear an attribute and force it to be submitted (SubmitMode.Always).\n * D365 AutoSave only submits dirty attributes; programmatically set values on\n * locked/calculated or off-form fields can otherwise be silently dropped.\n */\n\nimport { SubmitMode } from './xrm-constants.js';\n\n/**\n * Clear an attribute (`setValue(null)`) and force it to be submitted.\n *\n * Prefer this over a generic `setAndSubmit(attr, null)`: passing a literal `null`\n * as the value makes TypeScript infer the value type as `null` and fights the\n * attribute's real value type (F-LMA7-09). A dedicated clear helper has no value\n * parameter, so there is nothing to mis-infer.\n *\n * @param attr - A settable attribute (e.g. `form.revenue` from the typedForm proxy)\n */\nexport function clearAndSubmit(attr: {\n setValue(value: null): void;\n setSubmitMode(mode: Xrm.SubmitMode): void;\n}): void {\n attr.setValue(null);\n attr.setSubmitMode(SubmitMode.Always);\n}\n\n/**\n * Set an off-form attribute (loaded by D365 but not on the current form layout,\n * reached via the typedForm `$unsafe` proxy) and force submit.\n *\n * The typedForm proxy only exposes on-form fields; off-form fields go through\n * `$unsafe()`, which returns `Attribute | null`. This helper bundles the null\n * check, `setValue` and `setSubmitMode(Always)` (F-LMA7-07). For on-form fields\n * use the typed proxy directly (`form.field.setValue(v)` + `setSubmitMode`).\n *\n * @param form - The typedForm proxy (anything exposing `$unsafe`)\n * @param field - The off-form attribute logical name (use an entity Fields enum, never a raw string)\n * @param value - The value to set (off-form fields are untyped)\n * @returns `true` if the field existed and was set, `false` if it was absent\n */\nexport function setUnsafeAndSubmit(\n form: { $unsafe(name: string): Xrm.Attributes.Attribute | null },\n field: string,\n value: unknown,\n): boolean {\n const attr = form.$unsafe(field);\n if (attr == null) return false;\n (attr as { setValue(value: unknown): void }).setValue(value);\n attr.setSubmitMode(SubmitMode.Always);\n return true;\n}\n","/**\n * @xrmforge/helpers - App-level (global) notification helper\n *\n * Wraps Xrm.App.addGlobalNotification and hides the XrmEnum.AppNotificationLevel\n * runtime gap (XrmEnum const enums do not exist at runtime; see AGENT.md pitfall).\n */\n\nimport type { AppNotificationLevel } from './xrm-constants.js';\n\n/** Banner is the only supported global-notification type. */\nconst NOTIFICATION_TYPE_BANNER = 2;\n\n/** Options for {@link addAppNotification}. */\nexport interface AppNotificationOptions {\n /** Show a close (X) button on the banner (default: false). */\n showCloseButton?: boolean;\n /** Optional action button. */\n action?: Xrm.App.Action;\n}\n\n/**\n * Show a global app-level notification banner and return its id.\n *\n * Pass an {@link AppNotificationLevel} (Success/Error/Warning/Information). The\n * cast to the @types/xrm `XrmEnum.AppNotificationLevel` (which has no runtime\n * representation) happens here, once, instead of at every call site.\n *\n * @param message - The banner message\n * @param level - The notification level\n * @param options - Optional banner settings\n * @returns The created notification id (pass to `Xrm.App.clearGlobalNotification`)\n *\n * @example\n * const id = await addAppNotification(lang.saved, AppNotificationLevel.Success, { showCloseButton: true });\n */\nexport async function addAppNotification(\n message: string,\n level: AppNotificationLevel,\n options: AppNotificationOptions = {},\n): Promise<string> {\n const notification: Xrm.App.Notification = {\n type: NOTIFICATION_TYPE_BANNER as Xrm.App.Notification['type'],\n // XrmEnum.AppNotificationLevel has no runtime value; AppNotificationLevel carries\n // the same numbers. Cast at this single boundary to satisfy the typings.\n level: level as unknown as XrmEnum.AppNotificationLevel,\n message,\n showCloseButton: options.showCloseButton ?? false,\n ...(options.action ? { action: options.action } : {}),\n };\n return Xrm.App.addGlobalNotification(notification);\n}\n"],"mappings":";AAgCO,SAAS,UAAU,MAAqC;AAC7D,QAAM,SAAS,KAAK,WAAW,KAAK,MAAM,QAAQ,KAAK,CAAC,CAAC,IAAI,KAAK,CAAC,IAAI;AACvE,MAAI,OAAO,WAAW,EAAG,QAAO;AAChC,SAAO,YAAY,OAAO,KAAK,GAAG,CAAC;AACrC;AAyBO,SAAS,YACd,UACA,oBACyD;AACzD,QAAM,MAAM,IAAI,kBAAkB;AAClC,QAAM,KAAK,SAAS,GAAG;AACvB,MAAI,CAAC,GAAI,QAAO;AAEhB,SAAO;AAAA,IACL;AAAA,IACA,MAAO,SAAS,GAAG,GAAG,4CAA4C,KAAgB;AAAA,IAClF,YAAa,SAA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,CAAC;AAAA,EACrD;AACA,SAAO,IAAI,IAAI,sBAAsB,YAAY;AACnD;","names":["DisplayState","FormType","FormNotificationLevel","AppNotificationLevel","RequiredLevel","SubmitMode","SaveMode","ClientType","ClientState","OperationType","StructuralProperty","BindingType"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xrmforge/helpers",
3
- "version": "0.10.0",
3
+ "version": "0.10.1",
4
4
  "description": "Browser-safe runtime helpers for Dynamics 365 form scripts: select(), parseLookup(), typedForm(), Xrm constants, Action/Function executors",
5
5
  "keywords": [
6
6
  "dynamics-365",