@xrmforge/helpers 0.6.3 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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/dist/index.d.ts CHANGED
@@ -200,6 +200,23 @@ declare const enum FormType {
200
200
  Disabled = 4,
201
201
  BulkEdit = 6
202
202
  }
203
+ /**
204
+ * True when the form is currently shown in the given {@link FormType}.
205
+ *
206
+ * `formContext.ui.getFormType()` is typed as `XrmEnum.FormType` (from
207
+ * @types/xrm), which is a nominally distinct type from the {@link FormType}
208
+ * const enum above. A direct `getFormType() === FormType.Create` therefore
209
+ * fails to compile under `strict` with TS2367 ("This comparison appears to be
210
+ * unintentional because the types have no overlap"). Relational operators
211
+ * (`>`/`<`) slip past TS2367 but cannot express an exact match. This helper
212
+ * bridges both numeric enums for the equality case without a hand-written cast.
213
+ *
214
+ * @example
215
+ * if (isFormType(form.$context, FormType.Create)) {
216
+ * // only on create
217
+ * }
218
+ */
219
+ declare function isFormType(formContext: Xrm.FormContext, formType: FormType): boolean;
203
220
  /** Form notification level (formContext.ui.setFormNotification) */
204
221
  declare const enum FormNotificationLevel {
205
222
  Error = "ERROR",
@@ -281,7 +298,7 @@ declare const enum BindingType {
281
298
  * - `createBoundAction` / `createUnboundAction`: Produce executor objects
282
299
  * with `.execute()` (calls Xrm.WebApi) and `.request()` (for executeMultiple)
283
300
  * - `executeRequest`: Central execute wrapper (single place for the `as any` cast)
284
- * - `withProgress`: Convenience wrapper with progress indicator + error dialog
301
+ * - `withProgress`: Convenience wrapper with progress indicator (errors propagate to the handler wrapper)
285
302
  *
286
303
  * @example
287
304
  * ```typescript
@@ -400,10 +417,14 @@ declare function createUnboundFunction<TResult>(operationName: string): UnboundF
400
417
  */
401
418
  declare function createBoundFunction<TResult>(operationName: string, entityLogicalName: string): BoundFunctionExecutor<TResult>;
402
419
  /**
403
- * Execute an async operation with Xrm progress indicator.
420
+ * Execute an async operation with an Xrm progress indicator.
404
421
  *
405
- * Shows a progress spinner before the operation, closes it after,
406
- * and shows an error dialog on failure.
422
+ * Shows a progress spinner before the operation and closes it afterwards
423
+ * (success or failure). Errors are NOT displayed here; they propagate to the
424
+ * caller so the single error UI is owned by the handler wrapper
425
+ * (`wrapHandler`/`wrapCommand`). Showing an error dialog here too would produce
426
+ * a duplicate error UI (dialog + form notification) when `withProgress` runs
427
+ * inside a wrapped command (the common ribbon case).
407
428
  *
408
429
  * @param message - Progress indicator message (e.g. "Processing quote...")
409
430
  * @param operation - Async function to execute
@@ -411,6 +432,7 @@ declare function createBoundFunction<TResult>(operationName: string, entityLogic
411
432
  *
412
433
  * @example
413
434
  * ```typescript
435
+ * // Inside a wrapCommand handler: the wrapper shows the error notification.
414
436
  * await withProgress('Processing quote...', () => WinQuote.execute(recordId));
415
437
  * ```
416
438
  */
@@ -585,4 +607,65 @@ declare function normalizeGuid(guid: string | null | undefined): string;
585
607
  /** @deprecated Use ExtractFields<TForm> instead */
586
608
  type FormFields<TForm> = ExtractFields<TForm>;
587
609
 
588
- export { BindingType, type BoundActionExecutor, type BoundActionWithParamsExecutor, type BoundFunctionExecutor, ClientState, ClientType, DisplayState, type FormFields, FormNotificationLevel, FormType, type FormTypeInfoProtocol, OperationType, type ParameterMeta, type ParameterMetaMap, RequiredLevel, SaveMode, StructuralProperty, SubmitMode, type TypedForm, type UnboundActionExecutor, type UnboundActionWithParamsExecutor, type UnboundFunctionExecutor, createBoundAction, createBoundFunction, createUnboundAction, createUnboundFunction, executeMultiple, executeRequest, formLookup, formLookupId, normalizeGuid, parseFormattedValue, parseLookup, parseLookups, select, selectExpand, typedForm, withProgress };
610
+ /**
611
+ * @xrmforge/helpers - Power Automate Cloud Flow caller
612
+ *
613
+ * Browser-safe, typed wrapper around a Power Automate cloud flow triggered by an
614
+ * HTTP request ("When an HTTP request is received"). Replaces the hand-written
615
+ * fetch wrappers that legacy D365 form scripts use for cloud-flow calls.
616
+ *
617
+ * The trigger URL contains a SAS signature and is environment-specific: pass it in
618
+ * as a parameter (e.g. read from configuration), never hard-code it in source.
619
+ * Custom API / Dataverse-proxied calls are a different concern and are covered by
620
+ * `createUnboundAction`; this helper is for the direct HTTP-trigger case. Because
621
+ * the call runs in the browser, the flow's CORS settings must allow the Dynamics
622
+ * origin.
623
+ *
624
+ * Zero Node.js dependencies (uses the global `fetch`). For a progress spinner,
625
+ * compose with `withProgress`: `withProgress('...', () => callCloudFlow(url, body))`.
626
+ *
627
+ * @example
628
+ * ```typescript
629
+ * import { callCloudFlow } from '@xrmforge/helpers';
630
+ *
631
+ * interface PriceRequest { quoteId: string; }
632
+ * interface PriceResponse { total: number; currency: string; }
633
+ *
634
+ * // FLOW_URL comes from configuration, never hard-coded in source.
635
+ * const price = await callCloudFlow<PriceRequest, PriceResponse>(
636
+ * FLOW_URL,
637
+ * { quoteId },
638
+ * );
639
+ * console.log(price.total, price.currency);
640
+ * ```
641
+ */
642
+ /** Options for {@link callCloudFlow}. */
643
+ interface CloudFlowOptions {
644
+ /** HTTP method (default `'POST'`; HTTP-trigger flows are usually POST). */
645
+ method?: string;
646
+ /** Extra request headers, merged over the defaults (the caller's values win). */
647
+ headers?: Record<string, string>;
648
+ /** AbortSignal to cancel the request (e.g. a timeout or form unload). */
649
+ signal?: AbortSignal;
650
+ }
651
+ /**
652
+ * Call a Power Automate cloud flow via its HTTP request trigger URL.
653
+ *
654
+ * Sends `body` as JSON for methods that carry a body (anything but GET/HEAD), and
655
+ * returns the parsed response: parsed JSON when the flow responds with
656
+ * `application/json`, the raw text for other content types, or `undefined` for an
657
+ * empty / `204 No Content` response. Throws on any non-2xx HTTP status, with the
658
+ * status code and the response body included in the error message.
659
+ *
660
+ * @typeParam TReq - Shape of the request body.
661
+ * @typeParam TRes - Shape of the parsed response.
662
+ * @param triggerUrl - The flow's HTTP trigger URL (contains a SAS signature; pass
663
+ * from configuration, never hard-code it).
664
+ * @param body - Request payload, JSON-serialized when present.
665
+ * @param options - Optional HTTP method, extra headers, and abort signal.
666
+ * @returns The parsed flow response.
667
+ * @throws {Error} If the flow responds with a non-2xx status.
668
+ */
669
+ declare function callCloudFlow<TReq = unknown, TRes = unknown>(triggerUrl: string, body?: TReq, options?: CloudFlowOptions): Promise<TRes>;
670
+
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 };
package/dist/index.js CHANGED
@@ -61,6 +61,9 @@ var FormType = /* @__PURE__ */ ((FormType2) => {
61
61
  FormType2[FormType2["BulkEdit"] = 6] = "BulkEdit";
62
62
  return FormType2;
63
63
  })(FormType || {});
64
+ function isFormType(formContext, formType) {
65
+ return formContext.ui.getFormType() === formType;
66
+ }
64
67
  var FormNotificationLevel = /* @__PURE__ */ ((FormNotificationLevel2) => {
65
68
  FormNotificationLevel2["Error"] = "ERROR";
66
69
  FormNotificationLevel2["Warning"] = "WARNING";
@@ -297,10 +300,6 @@ async function withProgress(message, operation) {
297
300
  Xrm.Utility.showProgressIndicator(message);
298
301
  try {
299
302
  return await operation();
300
- } catch (error) {
301
- const msg = error instanceof Error ? error.message : String(error);
302
- Xrm.Navigation.openErrorDialog({ message: msg });
303
- throw error;
304
303
  } finally {
305
304
  Xrm.Utility.closeProgressIndicator();
306
305
  }
@@ -360,6 +359,36 @@ function normalizeGuid(guid) {
360
359
  if (!guid) return "";
361
360
  return guid.replace(/[{}]/g, "").toLowerCase();
362
361
  }
362
+
363
+ // src/cloud-flow.ts
364
+ async function callCloudFlow(triggerUrl, body, options = {}) {
365
+ const method = options.method ?? "POST";
366
+ const hasBody = body !== void 0 && method !== "GET" && method !== "HEAD";
367
+ const headers = {};
368
+ if (hasBody) headers["Content-Type"] = "application/json";
369
+ if (options.headers) Object.assign(headers, options.headers);
370
+ const response = await fetch(triggerUrl, {
371
+ method,
372
+ headers,
373
+ body: hasBody ? JSON.stringify(body) : void 0,
374
+ signal: options.signal
375
+ });
376
+ if (!response.ok) {
377
+ const errorText = await response.text().catch(() => "");
378
+ throw new Error(
379
+ `Cloud flow call failed (HTTP ${response.status} ${response.statusText})` + (errorText ? `: ${errorText}` : "")
380
+ );
381
+ }
382
+ if (response.status === 204) {
383
+ return void 0;
384
+ }
385
+ const contentType = response.headers.get("content-type") ?? "";
386
+ if (contentType.includes("application/json")) {
387
+ return await response.json();
388
+ }
389
+ const text = await response.text();
390
+ return text === "" ? void 0 : text;
391
+ }
363
392
  export {
364
393
  BindingType,
365
394
  ClientState,
@@ -372,6 +401,7 @@ export {
372
401
  SaveMode,
373
402
  StructuralProperty,
374
403
  SubmitMode,
404
+ callCloudFlow,
375
405
  createBoundAction,
376
406
  createBoundFunction,
377
407
  createUnboundAction,
@@ -380,6 +410,7 @@ export {
380
410
  executeRequest,
381
411
  formLookup,
382
412
  formLookupId,
413
+ isFormType,
383
414
  normalizeGuid,
384
415
  parseFormattedValue,
385
416
  parseLookup,
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"],"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/** 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 + error dialog\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 Xrm progress indicator.\r\n *\r\n * Shows a progress spinner before the operation, closes it after,\r\n * and shows an error dialog on failure.\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 * 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 } catch (error: unknown) {\r\n const msg = error instanceof Error ? error.message : String(error);\r\n Xrm.Navigation.openErrorDialog({ message: msg });\r\n throw error;\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"],"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,IA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SAAS,MAAM,QAAQ;AACzB,YAAM,IAAI;AAAA,QACR,qBAAqB,OAAO,IAAI,CAAC,eAAe,OAAO,IAAI,CAAC;AAAA,MAC9D;AAAA,IACF;AAAA,IAEA,IAAI,SAAS,MAAM;AACjB,UAAI,OAAO,SAAS,SAAU,QAAO;AACrC,UAAI,SAAS,cAAc,SAAS,cAAc,SAAS,UAAW,QAAO;AAC7E,aAAO,YAAY,aAAa,IAAI,MAAM;AAAA,IAC5C;AAAA,EACF,CAAC;AACH;AA0BO,SAAS,cAAc,MAAyC;AACrE,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,KAAK,QAAQ,SAAS,EAAE,EAAE,YAAY;AAC/C;","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"],"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,QA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;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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xrmforge/helpers",
3
- "version": "0.6.3",
3
+ "version": "0.8.0",
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",