@uipath/uipath-typescript 1.1.0 → 1.1.2

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/dist/index.umd.js CHANGED
@@ -3887,6 +3887,16 @@
3887
3887
  * Checks if code is running in a browser environment
3888
3888
  */
3889
3889
  const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
3890
+ const isInActionCenter = isBrowser && window.self != window.top && window.location.href.includes('source=ActionCenter');
3891
+
3892
+ /**
3893
+ * Session storage keys used by the auth module
3894
+ */
3895
+ const AUTH_STORAGE_KEYS = {
3896
+ TOKEN_PREFIX: 'uipath_sdk_user_token-',
3897
+ OAUTH_CONTEXT: 'uipath_sdk_oauth_context',
3898
+ CODE_VERIFIER: 'uipath_sdk_code_verifier',
3899
+ };
3890
3900
 
3891
3901
  // Type guard to check if config has OAuth credentials
3892
3902
  function hasOAuthConfig(config) {
@@ -4194,6 +4204,102 @@
4194
4204
  };
4195
4205
  }
4196
4206
 
4207
+ var ActionCenterEventNames;
4208
+ (function (ActionCenterEventNames) {
4209
+ ActionCenterEventNames["TOKENREFRESHED"] = "AC.tokenRefreshed";
4210
+ ActionCenterEventNames["REFRESHTOKEN"] = "AC.refreshToken";
4211
+ })(ActionCenterEventNames || (ActionCenterEventNames = {}));
4212
+
4213
+ const AUTHENTICATION_TIMEOUT = 8000;
4214
+ class ActionCenterTokenManager {
4215
+ constructor(config, onTokenRefreshed) {
4216
+ this.config = config;
4217
+ this.onTokenRefreshed = onTokenRefreshed;
4218
+ this.parentOrigin = new URLSearchParams(window.location.search).get('basedomain');
4219
+ this.refreshPromise = null;
4220
+ }
4221
+ async refreshAccessToken(tokenInfo) {
4222
+ if (!this.isTokenExpired(tokenInfo)) {
4223
+ return tokenInfo.token;
4224
+ }
4225
+ if (this.refreshPromise) {
4226
+ return this.refreshPromise;
4227
+ }
4228
+ this.refreshPromise = new Promise((resolve, reject) => {
4229
+ const content = {
4230
+ clientId: this.config.clientId,
4231
+ scope: this.config.scope,
4232
+ };
4233
+ this.sendMessageToParent(ActionCenterEventNames.REFRESHTOKEN, content);
4234
+ const messageListener = (event) => {
4235
+ if (event.origin !== this.parentOrigin)
4236
+ return;
4237
+ if (event.data?.eventType !== ActionCenterEventNames.TOKENREFRESHED)
4238
+ return;
4239
+ clearTimeout(timer);
4240
+ if (event.data?.content?.token) {
4241
+ const { accessToken, expiresAt } = event.data.content.token;
4242
+ this.onTokenRefreshed({ token: accessToken, type: 'secret', expiresAt });
4243
+ resolve(accessToken);
4244
+ }
4245
+ else {
4246
+ reject(new AuthenticationError({
4247
+ message: 'Failed to fetch access token',
4248
+ statusCode: HttpStatus.UNAUTHORIZED,
4249
+ }));
4250
+ }
4251
+ this.refreshPromise = null;
4252
+ this.cleanup(messageListener);
4253
+ };
4254
+ const timer = setTimeout(() => {
4255
+ reject(new AuthenticationError({
4256
+ message: 'Failed to fetch access token',
4257
+ statusCode: HttpStatus.UNAUTHORIZED,
4258
+ }));
4259
+ this.refreshPromise = null;
4260
+ this.cleanup(messageListener);
4261
+ }, AUTHENTICATION_TIMEOUT);
4262
+ window.addEventListener('message', messageListener);
4263
+ });
4264
+ return this.refreshPromise;
4265
+ }
4266
+ isTokenExpired(tokenInfo) {
4267
+ if (!tokenInfo?.expiresAt) {
4268
+ return true;
4269
+ }
4270
+ return new Date() >= tokenInfo.expiresAt;
4271
+ }
4272
+ sendMessageToParent(eventType, content) {
4273
+ if (window.parent && this.isValidOrigin(this.parentOrigin)) {
4274
+ try {
4275
+ window.parent.postMessage({ eventType, content }, this.parentOrigin);
4276
+ }
4277
+ catch (error) {
4278
+ console.warn('Failed to send message to Action Center', JSON.stringify(error));
4279
+ }
4280
+ }
4281
+ }
4282
+ cleanup(messageListener) {
4283
+ window.removeEventListener('message', messageListener);
4284
+ }
4285
+ isValidOrigin(origin) {
4286
+ const ALLOWED_ORIGINS = ['https://alpha.uipath.com', 'https://staging.uipath.com', 'https://cloud.uipath.com'];
4287
+ if (!origin) {
4288
+ return false;
4289
+ }
4290
+ if (ALLOWED_ORIGINS.includes(origin)) {
4291
+ return true;
4292
+ }
4293
+ try {
4294
+ const url = new URL(origin);
4295
+ return url.hostname === 'localhost';
4296
+ }
4297
+ catch {
4298
+ return false;
4299
+ }
4300
+ }
4301
+ }
4302
+
4197
4303
  /**
4198
4304
  * TokenManager is responsible for managing authentication tokens.
4199
4305
  * It provides token operations for a specific client ID.
@@ -4211,8 +4317,12 @@
4211
4317
  this.executionContext = executionContext;
4212
4318
  this.config = config;
4213
4319
  this.isOAuth = isOAuth;
4214
- this.STORAGE_KEY_PREFIX = 'uipath_sdk_user_token-';
4215
4320
  this.refreshPromise = null;
4321
+ this.actionCenterTokenManager = null;
4322
+ if (isInActionCenter) {
4323
+ this.actionCenterTokenManager = new ActionCenterTokenManager(config, (tokenInfo) => this.setToken(tokenInfo));
4324
+ this.isOAuth = false;
4325
+ }
4216
4326
  }
4217
4327
  /**
4218
4328
  * Checks if a token is expired
@@ -4240,6 +4350,9 @@
4240
4350
  message: 'No authentication token available. Make sure to initialize the SDK first.'
4241
4351
  });
4242
4352
  }
4353
+ if (this.actionCenterTokenManager) {
4354
+ return await this.actionCenterTokenManager.refreshAccessToken(tokenInfo);
4355
+ }
4243
4356
  // For secret-based tokens, they never expire
4244
4357
  if (tokenInfo.type === 'secret') {
4245
4358
  return tokenInfo.token;
@@ -4265,7 +4378,7 @@
4265
4378
  * Gets the storage key for this TokenManager instance
4266
4379
  */
4267
4380
  _getStorageKey() {
4268
- return `${this.STORAGE_KEY_PREFIX}${this.config.clientId}`;
4381
+ return `${AUTH_STORAGE_KEYS.TOKEN_PREFIX}${this.config.clientId}`;
4269
4382
  }
4270
4383
  /**
4271
4384
  * Loads token from session storage if available
@@ -4384,9 +4497,6 @@
4384
4497
  clearToken() {
4385
4498
  this.currentToken = undefined;
4386
4499
  this.executionContext.set('tokenInfo', undefined);
4387
- const headers = this.executionContext.getHeaders();
4388
- delete headers['Authorization'];
4389
- this.executionContext.setHeaders(headers);
4390
4500
  // Remove from session storage if this is an OAuth token
4391
4501
  if (isBrowser && this.isOAuth) {
4392
4502
  try {
@@ -4402,10 +4512,6 @@
4402
4512
  */
4403
4513
  _updateExecutionContext(tokenInfo) {
4404
4514
  this.executionContext.set('tokenInfo', tokenInfo);
4405
- // Update authorization header
4406
- this.executionContext.setHeaders({
4407
- 'Authorization': `Bearer ${tokenInfo.token}`
4408
- });
4409
4515
  }
4410
4516
  /**
4411
4517
  * Refreshes the access token using the stored refresh token.
@@ -4609,8 +4715,15 @@
4609
4715
 
4610
4716
  class AuthService {
4611
4717
  constructor(config, executionContext) {
4612
- // Check if we should use stored OAuth context instead of provided config
4613
- const storedContext = AuthService.getStoredOAuthContext();
4718
+ // Only use stored OAuth context when completing an active callback (URL has ?code=).
4719
+ // If stored context exists but we're NOT in a callback, it's stale from a
4720
+ // failed/abandoned flow (e.g. scope mismatch, invalid redirect URI) and must
4721
+ // be cleared so the fresh config takes effect.
4722
+ const isCallback = AuthService.isInOAuthCallback();
4723
+ const storedContext = isCallback ? AuthService.getStoredOAuthContext() : null;
4724
+ if (!isCallback) {
4725
+ AuthService._clearStoredOAuthContext();
4726
+ }
4614
4727
  const effectiveConfig = storedContext ? AuthService._mergeConfigWithContext(config, storedContext) : config;
4615
4728
  this.config = effectiveConfig;
4616
4729
  const isOAuth = hasOAuthConfig(effectiveConfig);
@@ -4627,7 +4740,7 @@
4627
4740
  return false;
4628
4741
  const urlParams = new URLSearchParams(window.location.search);
4629
4742
  const code = urlParams.get('code');
4630
- const hasCodeVerifier = sessionStorage.getItem('uipath_sdk_code_verifier');
4743
+ const hasCodeVerifier = sessionStorage.getItem(AUTH_STORAGE_KEYS.CODE_VERIFIER);
4631
4744
  return !!(code && hasCodeVerifier);
4632
4745
  }
4633
4746
  /**
@@ -4638,7 +4751,7 @@
4638
4751
  return null;
4639
4752
  }
4640
4753
  try {
4641
- const stored = sessionStorage.getItem('uipath_sdk_oauth_context');
4754
+ const stored = sessionStorage.getItem(AUTH_STORAGE_KEYS.OAUTH_CONTEXT);
4642
4755
  if (!stored) {
4643
4756
  return null;
4644
4757
  }
@@ -4646,17 +4759,33 @@
4646
4759
  // Validate required fields
4647
4760
  if (!context.codeVerifier || !context.clientId || !context.redirectUri ||
4648
4761
  !context.baseUrl || !context.orgName) {
4649
- sessionStorage.removeItem('uipath_sdk_oauth_context');
4762
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.OAUTH_CONTEXT);
4650
4763
  return null;
4651
4764
  }
4652
4765
  return context;
4653
4766
  }
4654
4767
  catch (error) {
4655
- sessionStorage.removeItem('uipath_sdk_oauth_context');
4768
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.OAUTH_CONTEXT);
4656
4769
  console.warn('Failed to parse stored OAuth context from session storage', error);
4657
4770
  return null;
4658
4771
  }
4659
4772
  }
4773
+ /**
4774
+ * Clear stale OAuth context from session storage.
4775
+ * Called when there is no active OAuth callback, meaning any stored context
4776
+ * is left over from a failed or abandoned flow.
4777
+ */
4778
+ static _clearStoredOAuthContext() {
4779
+ if (!isBrowser)
4780
+ return;
4781
+ try {
4782
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.OAUTH_CONTEXT);
4783
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.CODE_VERIFIER);
4784
+ }
4785
+ catch {
4786
+ // Ignore storage errors
4787
+ }
4788
+ }
4660
4789
  /**
4661
4790
  * Merges provided config with stored OAuth context, prioritizing stored values
4662
4791
  */
@@ -4727,7 +4856,7 @@
4727
4856
  throw new Error('OAuth flow is only supported in browser environments');
4728
4857
  }
4729
4858
  // Check if we have a stored code verifier indicating we're in an OAuth flow
4730
- const codeVerifier = sessionStorage.getItem('uipath_sdk_code_verifier');
4859
+ const codeVerifier = sessionStorage.getItem(AUTH_STORAGE_KEYS.CODE_VERIFIER);
4731
4860
  const isInOAuthFlow = codeVerifier !== null;
4732
4861
  const urlParams = new URLSearchParams(window.location.search);
4733
4862
  const code = urlParams.get('code');
@@ -4736,7 +4865,7 @@
4736
4865
  // We're expecting a callback - validate parameters
4737
4866
  if (!code) {
4738
4867
  // Clear stored state on error
4739
- sessionStorage.removeItem('uipath_sdk_code_verifier');
4868
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.CODE_VERIFIER);
4740
4869
  throw new Error('Authorization code missing in OAuth callback');
4741
4870
  }
4742
4871
  // Validate the authorization code format before using it
@@ -4744,7 +4873,7 @@
4744
4873
  const codePattern = /^[A-Za-z0-9\-._~+/]+=*$/;
4745
4874
  if (!codePattern.test(code)) {
4746
4875
  // Clear stored state on error
4747
- sessionStorage.removeItem('uipath_sdk_code_verifier');
4876
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.CODE_VERIFIER);
4748
4877
  throw new Error('Invalid authorization code format');
4749
4878
  }
4750
4879
  // Authorization code is present and validated, so we can exchange it for a token.
@@ -4785,6 +4914,24 @@
4785
4914
  hasValidToken() {
4786
4915
  return this.tokenManager.hasValidToken();
4787
4916
  }
4917
+ /**
4918
+ * Clears all authentication state including tokens and stored OAuth context.
4919
+ */
4920
+ logout() {
4921
+ this.tokenManager.clearToken();
4922
+ // Clear OAuth context from session storage. These are normally cleaned up in _handleOAuthCallback after a successful
4923
+ // token exchange, but if a user calls logout() while an OAuth flow is
4924
+ // mid-redirect (before callback completes), they'd be left behind.
4925
+ if (isBrowser) {
4926
+ try {
4927
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.OAUTH_CONTEXT);
4928
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.CODE_VERIFIER);
4929
+ }
4930
+ catch (error) {
4931
+ console.warn('Failed to clear OAuth context from session storage', error);
4932
+ }
4933
+ }
4934
+ }
4788
4935
  /**
4789
4936
  * Get the current token
4790
4937
  */
@@ -4916,8 +5063,8 @@
4916
5063
  tenantName: this.config.tenantName,
4917
5064
  scope
4918
5065
  };
4919
- sessionStorage.setItem('uipath_sdk_oauth_context', JSON.stringify(oauthContext));
4920
- sessionStorage.setItem('uipath_sdk_code_verifier', codeVerifier);
5066
+ sessionStorage.setItem(AUTH_STORAGE_KEYS.OAUTH_CONTEXT, JSON.stringify(oauthContext));
5067
+ sessionStorage.setItem(AUTH_STORAGE_KEYS.CODE_VERIFIER, codeVerifier);
4921
5068
  const authUrl = this.getAuthorizationUrl({
4922
5069
  clientId,
4923
5070
  redirectUri,
@@ -4927,7 +5074,7 @@
4927
5074
  window.location.href = authUrl;
4928
5075
  }
4929
5076
  async _handleOAuthCallback(code, clientId, redirectUri) {
4930
- const codeVerifier = sessionStorage.getItem('uipath_sdk_code_verifier');
5077
+ const codeVerifier = sessionStorage.getItem(AUTH_STORAGE_KEYS.CODE_VERIFIER);
4931
5078
  if (!codeVerifier) {
4932
5079
  throw new Error('Code verifier not found in session storage. Authentication may have been interrupted.');
4933
5080
  }
@@ -4938,8 +5085,8 @@
4938
5085
  codeVerifier
4939
5086
  });
4940
5087
  // Clear OAuth context and code verifier after successful token exchange
4941
- sessionStorage.removeItem('uipath_sdk_oauth_context');
4942
- sessionStorage.removeItem('uipath_sdk_code_verifier');
5088
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.OAUTH_CONTEXT);
5089
+ sessionStorage.removeItem(AUTH_STORAGE_KEYS.CODE_VERIFIER);
4943
5090
  const url = new URL(window.location.href);
4944
5091
  url.searchParams.delete('code');
4945
5092
  url.searchParams.delete('state');
@@ -4947,14 +5094,42 @@
4947
5094
  }
4948
5095
  }
4949
5096
 
5097
+ /**
5098
+ * Check if config has all required base fields
5099
+ */
5100
+ function hasRequiredBaseFields(config) {
5101
+ return Boolean(config.baseUrl && config.orgName && config.tenantName);
5102
+ }
5103
+ /**
5104
+ * Check if config has exactly one authentication method (secret XOR oauth)
5105
+ * Returns true if exactly one auth method is present, false otherwise
5106
+ */
5107
+ function hasValidAuthConfig(config) {
5108
+ const hasSecret = hasSecretConfig(config);
5109
+ const hasOAuth = hasOAuthConfig(config);
5110
+ // XOR: exactly one auth method, not both, not neither
5111
+ return hasSecret !== hasOAuth;
5112
+ }
4950
5113
  function validateConfig(config) {
4951
- if (!config.baseUrl || !config.orgName || !config.tenantName) {
5114
+ if (!hasRequiredBaseFields(config)) {
4952
5115
  throw new Error('Missing required configuration: baseUrl, orgName, and tenantName are required');
4953
5116
  }
4954
- if (!hasSecretConfig(config) && !hasOAuthConfig(config)) {
4955
- throw new Error('Invalid configuration: must provide either secret or (clientId, redirectUri, and scope)');
5117
+ const hasSecret = hasSecretConfig(config);
5118
+ const hasOAuth = hasOAuthConfig(config);
5119
+ if (hasSecret && hasOAuth) {
5120
+ throw new Error('Invalid configuration: cannot provide both secret and OAuth credentials. Choose one authentication method.');
5121
+ }
5122
+ if (!hasSecret && !hasOAuth) {
5123
+ throw new Error('Invalid configuration: must provide either secret or OAuth credentials (clientId, redirectUri, and scope)');
4956
5124
  }
4957
5125
  }
5126
+ /**
5127
+ * Check if partial config has all required fields for a complete SDK config
5128
+ * Requires base fields and exactly one authentication method (secret XOR oauth)
5129
+ */
5130
+ function isCompleteConfig(config) {
5131
+ return hasRequiredBaseFields(config) && hasValidAuthConfig(config);
5132
+ }
4958
5133
  function normalizeBaseUrl(url) {
4959
5134
  return url.endsWith('/') ? url.slice(0, -1) : url;
4960
5135
  }
@@ -8720,7 +8895,7 @@
8720
8895
  // Connection string placeholder that will be replaced during build
8721
8896
  const CONNECTION_STRING = "InstrumentationKey=a6efa11d-1feb-4508-9738-e13e12dcae5e;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/;LiveEndpoint=https://westeurope.livediagnostics.monitor.azure.com/;ApplicationId=7c58eb1c-9581-4ba6-839e-11725848a037";
8722
8897
  // SDK Version placeholder
8723
- const SDK_VERSION = "1.1.0";
8898
+ const SDK_VERSION = "1.1.2";
8724
8899
  const VERSION = "Version";
8725
8900
  const SERVICE = "Service";
8726
8901
  const CLOUD_ORGANIZATION_NAME = "CloudOrganizationName";
@@ -9049,19 +9224,71 @@
9049
9224
  }
9050
9225
  }
9051
9226
 
9052
- var _UiPath_config, _UiPath_authService, _UiPath_initialized;
9227
+ /**
9228
+ * UiPath meta tag names for runtime configuration.
9229
+ *
9230
+ * These meta tags are injected at deployment time by the Apps Service
9231
+ * to configure SDK authentication and asset resolution in production.
9232
+ */
9233
+ exports.UiPathMetaTags = void 0;
9234
+ (function (UiPathMetaTags) {
9235
+ // SDK/OAuth configuration
9236
+ UiPathMetaTags["CLIENT_ID"] = "uipath:client-id";
9237
+ UiPathMetaTags["SCOPE"] = "uipath:scope";
9238
+ UiPathMetaTags["ORG_NAME"] = "uipath:org-name";
9239
+ UiPathMetaTags["TENANT_NAME"] = "uipath:tenant-name";
9240
+ UiPathMetaTags["BASE_URL"] = "uipath:base-url";
9241
+ UiPathMetaTags["REDIRECT_URI"] = "uipath:redirect-uri";
9242
+ // Asset resolution and routing
9243
+ UiPathMetaTags["CDN_BASE"] = "uipath:cdn-base";
9244
+ UiPathMetaTags["APP_BASE"] = "uipath:app-base";
9245
+ })(exports.UiPathMetaTags || (exports.UiPathMetaTags = {}));
9246
+
9247
+ /**
9248
+ * Get the content of a meta tag by name.
9249
+ * Returns undefined if not in browser environment or meta tag is not found.
9250
+ */
9251
+ function getMetaTagContent(name) {
9252
+ if (!isBrowser)
9253
+ return undefined;
9254
+ return document.querySelector(`meta[name="${name}"]`)?.content;
9255
+ }
9256
+ /**
9257
+ * Load configuration from HTML meta tags injected at runtime.
9258
+ * These meta tags are injected by @uipath/coded-apps during build
9259
+ * or by the Apps service during deployment.
9260
+ *
9261
+ * Returns partial config with values found, or null if no meta tags present.
9262
+ */
9263
+ function loadFromMetaTags() {
9264
+ if (!isBrowser)
9265
+ return null;
9266
+ const config = {
9267
+ clientId: getMetaTagContent(exports.UiPathMetaTags.CLIENT_ID),
9268
+ scope: getMetaTagContent(exports.UiPathMetaTags.SCOPE),
9269
+ orgName: getMetaTagContent(exports.UiPathMetaTags.ORG_NAME),
9270
+ tenantName: getMetaTagContent(exports.UiPathMetaTags.TENANT_NAME),
9271
+ baseUrl: getMetaTagContent(exports.UiPathMetaTags.BASE_URL),
9272
+ redirectUri: getMetaTagContent(exports.UiPathMetaTags.REDIRECT_URI),
9273
+ };
9274
+ const hasAnyValue = Object.values(config).some(Boolean);
9275
+ return hasAnyValue ? config : null;
9276
+ }
9277
+
9278
+ var _UiPath_instances, _UiPath_config, _UiPath_authService, _UiPath_initialized, _UiPath_partialConfig, _UiPath_initializeWithConfig, _UiPath_loadConfig;
9053
9279
  /**
9054
9280
  * UiPath - Core SDK class for authentication and configuration management.
9055
9281
  *
9056
9282
  * Handles authentication, configuration, and provides access to SDK internals
9057
9283
  * for service instantiation in the modular pattern.
9058
9284
  *
9285
+ * Supports two usage patterns:
9286
+ * 1. Full config in constructor — for server-side or explicit configuration
9287
+ * 2. No config / partial config — loads from meta tags injected by @uipath/coded-apps plugin
9288
+ *
9059
9289
  * @example
9060
9290
  * ```typescript
9061
- * // Modular pattern
9062
- * import { UiPath } from '@uipath/uipath-typescript/core';
9063
- * import { Entities } from '@uipath/uipath-typescript/entities';
9064
- *
9291
+ * // Explicit config
9065
9292
  * const sdk = new UiPath({
9066
9293
  * baseUrl: 'https://cloud.uipath.com',
9067
9294
  * orgName: 'myorg',
@@ -9070,70 +9297,47 @@
9070
9297
  * redirectUri: 'http://localhost:3000/callback',
9071
9298
  * scope: 'OR.Users OR.Robots'
9072
9299
  * });
9073
- *
9074
9300
  * await sdk.initialize();
9301
+ * ```
9075
9302
  *
9076
- * const entitiesService = new Entities(sdk);
9077
- * const allEntities = await entitiesService.getAll();
9303
+ * @example
9304
+ * ```typescript
9305
+ * // Auto-load from meta tags (coded apps)
9306
+ * const sdk = new UiPath();
9307
+ * await sdk.initialize();
9078
9308
  * ```
9079
9309
  */
9080
9310
  let UiPath$1 = class UiPath {
9081
9311
  constructor(config) {
9312
+ _UiPath_instances.add(this);
9082
9313
  // Private fields - true runtime privacy, not visible via Object.keys()
9083
9314
  _UiPath_config.set(this, void 0);
9084
9315
  _UiPath_authService.set(this, void 0);
9085
9316
  _UiPath_initialized.set(this, false);
9086
- // Validate and normalize the configuration
9087
- validateConfig(config);
9088
- const hasSecretAuth = hasSecretConfig(config);
9089
- const hasOAuthAuth = hasOAuthConfig(config);
9090
- // Initialize core components
9091
- const internalConfig = new UiPathConfig({
9092
- baseUrl: normalizeBaseUrl(config.baseUrl),
9093
- orgName: config.orgName,
9094
- tenantName: config.tenantName,
9095
- secret: hasSecretAuth ? config.secret : undefined,
9096
- clientId: hasOAuthAuth ? config.clientId : undefined,
9097
- redirectUri: hasOAuthAuth ? config.redirectUri : undefined,
9098
- scope: hasOAuthAuth ? config.scope : undefined
9099
- });
9100
- const executionContext = new ExecutionContext();
9101
- __classPrivateFieldSet(this, _UiPath_authService, new AuthService(internalConfig, executionContext), "f");
9102
- __classPrivateFieldSet(this, _UiPath_config, internalConfig, "f");
9103
- // Store internals in SDKInternalsRegistry (not visible on instance)
9104
- SDKInternalsRegistry.set(this, {
9105
- config: internalConfig,
9106
- context: executionContext,
9107
- tokenManager: __classPrivateFieldGet(this, _UiPath_authService, "f").getTokenManager()
9108
- });
9109
- // Expose read-only config for user convenience
9110
- this.config = {
9111
- baseUrl: internalConfig.baseUrl,
9112
- orgName: internalConfig.orgName,
9113
- tenantName: internalConfig.tenantName
9114
- };
9115
- // Initialize telemetry with SDK configuration
9116
- telemetryClient.initialize({
9117
- baseUrl: config.baseUrl,
9118
- orgName: config.orgName,
9119
- tenantName: config.tenantName,
9120
- clientId: hasOAuthAuth ? config.clientId : undefined,
9121
- redirectUri: hasOAuthAuth ? config.redirectUri : undefined
9122
- });
9123
- // Track SDK initialization
9124
- trackEvent('Sdk.Auth');
9125
- // Auto-initialize for secret-based auth
9126
- if (hasSecretAuth) {
9127
- __classPrivateFieldGet(this, _UiPath_authService, "f").authenticateWithSecret(config.secret);
9128
- __classPrivateFieldSet(this, _UiPath_initialized, true, "f");
9317
+ _UiPath_partialConfig.set(this, void 0);
9318
+ // Load configuration from meta tags
9319
+ const configFromMetaTags = loadFromMetaTags();
9320
+ // Merge configuration: constructor config overrides meta tags
9321
+ const mergedConfig = config ? { ...configFromMetaTags, ...config } : configFromMetaTags;
9322
+ if (mergedConfig && isCompleteConfig(mergedConfig)) {
9323
+ __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_initializeWithConfig).call(this, mergedConfig);
9324
+ }
9325
+ else if (config) {
9326
+ __classPrivateFieldSet(this, _UiPath_partialConfig, config, "f");
9129
9327
  }
9130
9328
  }
9131
9329
  /**
9132
9330
  * Initialize the SDK based on the provided configuration.
9133
9331
  * This method handles both OAuth flow initiation and completion automatically.
9134
9332
  * For secret-based authentication, initialization is automatic and this returns immediately.
9333
+ * If no config was provided in constructor, loads from meta tags.
9135
9334
  */
9136
9335
  async initialize() {
9336
+ // Load config from meta tags if not provided in constructor
9337
+ if (!__classPrivateFieldGet(this, _UiPath_config, "f")) {
9338
+ const loadedConfig = __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_loadConfig).call(this);
9339
+ __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_initializeWithConfig).call(this, loadedConfig);
9340
+ }
9137
9341
  // For secret-based auth, it's already initialized in constructor
9138
9342
  if (hasSecretConfig(__classPrivateFieldGet(this, _UiPath_config, "f"))) {
9139
9343
  return;
@@ -9180,6 +9384,11 @@
9180
9384
  if (!AuthService.isInOAuthCallback()) {
9181
9385
  throw new Error('Not in OAuth callback state. Call initialize() first to start OAuth flow.');
9182
9386
  }
9387
+ // Load config if not yet initialized
9388
+ if (!__classPrivateFieldGet(this, _UiPath_config, "f")) {
9389
+ const loadedConfig = __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_loadConfig).call(this);
9390
+ __classPrivateFieldGet(this, _UiPath_instances, "m", _UiPath_initializeWithConfig).call(this, loadedConfig);
9391
+ }
9183
9392
  try {
9184
9393
  const success = await __classPrivateFieldGet(this, _UiPath_authService, "f").authenticate(__classPrivateFieldGet(this, _UiPath_config, "f"));
9185
9394
  if (success && this.isAuthenticated()) {
@@ -9197,16 +9406,85 @@
9197
9406
  * Check if the user is authenticated (has valid token)
9198
9407
  */
9199
9408
  isAuthenticated() {
9200
- return __classPrivateFieldGet(this, _UiPath_authService, "f").hasValidToken();
9409
+ return __classPrivateFieldGet(this, _UiPath_authService, "f")?.hasValidToken() ?? false;
9201
9410
  }
9202
9411
  /**
9203
9412
  * Get the current authentication token
9204
9413
  */
9205
9414
  getToken() {
9206
- return __classPrivateFieldGet(this, _UiPath_authService, "f").getToken();
9415
+ return __classPrivateFieldGet(this, _UiPath_authService, "f")?.getToken();
9207
9416
  }
9417
+ /**
9418
+ * Logout from the SDK, clearing all authentication state.
9419
+ * After calling this method, the user will need to re-initialize to authenticate again.
9420
+ */
9421
+ logout() {
9422
+ // Secret-based auth has no session to end — skip silently
9423
+ if (__classPrivateFieldGet(this, _UiPath_config, "f") && hasSecretConfig(__classPrivateFieldGet(this, _UiPath_config, "f"))) {
9424
+ return;
9425
+ }
9426
+ __classPrivateFieldGet(this, _UiPath_authService, "f")?.logout();
9427
+ __classPrivateFieldSet(this, _UiPath_initialized, false, "f");
9428
+ }
9429
+ };
9430
+ _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_initialized = new WeakMap(), _UiPath_partialConfig = new WeakMap(), _UiPath_instances = new WeakSet(), _UiPath_initializeWithConfig = function _UiPath_initializeWithConfig(config) {
9431
+ // Validate and normalize the configuration
9432
+ validateConfig(config);
9433
+ const hasSecretAuth = hasSecretConfig(config);
9434
+ const hasOAuthAuth = hasOAuthConfig(config);
9435
+ // Initialize core components
9436
+ const internalConfig = new UiPathConfig({
9437
+ baseUrl: normalizeBaseUrl(config.baseUrl),
9438
+ orgName: config.orgName,
9439
+ tenantName: config.tenantName,
9440
+ secret: hasSecretAuth ? config.secret : undefined,
9441
+ clientId: hasOAuthAuth ? config.clientId : undefined,
9442
+ redirectUri: hasOAuthAuth ? config.redirectUri : undefined,
9443
+ scope: hasOAuthAuth ? config.scope : undefined
9444
+ });
9445
+ const executionContext = new ExecutionContext();
9446
+ __classPrivateFieldSet(this, _UiPath_authService, new AuthService(internalConfig, executionContext), "f");
9447
+ __classPrivateFieldSet(this, _UiPath_config, internalConfig, "f");
9448
+ // Store internals in SDKInternalsRegistry (not visible on instance)
9449
+ SDKInternalsRegistry.set(this, {
9450
+ config: internalConfig,
9451
+ context: executionContext,
9452
+ tokenManager: __classPrivateFieldGet(this, _UiPath_authService, "f").getTokenManager()
9453
+ });
9454
+ // Expose read-only config for user convenience
9455
+ this.config = {
9456
+ baseUrl: internalConfig.baseUrl,
9457
+ orgName: internalConfig.orgName,
9458
+ tenantName: internalConfig.tenantName
9459
+ };
9460
+ // Initialize telemetry with SDK configuration
9461
+ telemetryClient.initialize({
9462
+ baseUrl: config.baseUrl,
9463
+ orgName: config.orgName,
9464
+ tenantName: config.tenantName,
9465
+ clientId: hasOAuthAuth ? config.clientId : undefined,
9466
+ redirectUri: hasOAuthAuth ? config.redirectUri : undefined
9467
+ });
9468
+ // Track SDK initialization
9469
+ trackEvent('Sdk.Auth');
9470
+ /** Auto-initialize for secret-based auth
9471
+ * When viewed in Action Center, initialize tokenInfo with empty token. When an sdk call is made Action Center passes the token to sdk.
9472
+ */
9473
+ if (hasSecretAuth || isInActionCenter) {
9474
+ __classPrivateFieldGet(this, _UiPath_authService, "f").authenticateWithSecret(config.secret ?? '');
9475
+ __classPrivateFieldSet(this, _UiPath_initialized, true, "f");
9476
+ }
9477
+ }, _UiPath_loadConfig = function _UiPath_loadConfig() {
9478
+ // Load from meta tags
9479
+ const metaConfig = loadFromMetaTags();
9480
+ // Merge with any partial config from constructor (constructor overrides meta tags)
9481
+ const merged = { ...metaConfig, ...__classPrivateFieldGet(this, _UiPath_partialConfig, "f") };
9482
+ if (!isCompleteConfig(merged)) {
9483
+ throw new Error('UiPath SDK configuration not found. ' +
9484
+ 'Ensure @uipath/coded-apps plugin is set up in your bundler to inject configuration during development and build.');
9485
+ }
9486
+ return merged;
9208
9487
  };
9209
- _UiPath_config = new WeakMap(), _UiPath_authService = new WeakMap(), _UiPath_initialized = new WeakMap();
9210
9488
 
9211
9489
  /**
9212
9490
  * Type guards for error response types
@@ -9485,15 +9763,6 @@
9485
9763
  async getDefaultHeaders() {
9486
9764
  // Get headers from execution context first
9487
9765
  const contextHeaders = this.executionContext.getHeaders();
9488
- // If Authorization header is already set in context, use that
9489
- if (contextHeaders['Authorization']) {
9490
- return {
9491
- ...contextHeaders,
9492
- 'Content-Type': CONTENT_TYPES.JSON,
9493
- ...this.defaultHeaders,
9494
- ...this.clientConfig.headers
9495
- };
9496
- }
9497
9766
  const token = await this.getValidToken();
9498
9767
  return {
9499
9768
  ...contextHeaders,
@@ -14837,6 +15106,81 @@
14837
15106
  ...CommonFieldMap
14838
15107
  };
14839
15108
 
15109
+ /**
15110
+ * Asset resolution utilities for UiPath Coded Apps
15111
+ *
15112
+ * These helpers enable developers to write code that works identically
15113
+ * in local development and production environments.
15114
+ *
15115
+ * Values are read from meta tags injected at deployment:
15116
+ * - <meta name="uipath:cdn-base" content="https://cdn.example.com/appId/folder">
15117
+ * - <meta name="uipath:app-base" content="/org/apps_/.../public">
15118
+ */
15119
+ /**
15120
+ * Resolves an asset path to the CDN URL (if available)
15121
+ *
15122
+ * In local development: returns path as-is (loads from local dev server)
15123
+ * In production: prepends CDN base URL from meta tag
15124
+ *
15125
+ * @param path - The asset path (e.g., './assets/logo.png' or '/assets/logo.png')
15126
+ * @returns The resolved asset URL
15127
+ *
15128
+ * @example
15129
+ * ```tsx
15130
+ * import { getAsset } from '@uipath/uipath-typescript';
15131
+ * import logoPath from './assets/logo.png';
15132
+ *
15133
+ * function MyComponent() {
15134
+ * return <img src={getAsset(logoPath)} alt="Logo" />;
15135
+ * }
15136
+ * ```
15137
+ */
15138
+ function getAsset(path) {
15139
+ // If path is already an absolute URL, return as-is
15140
+ if (path.startsWith('http://') || path.startsWith('https://')) {
15141
+ return path;
15142
+ }
15143
+ const cdnBase = getMetaTagContent(exports.UiPathMetaTags.CDN_BASE);
15144
+ if (!cdnBase)
15145
+ return path;
15146
+ // Normalize CDN base URL to remove trailing slash
15147
+ const normalizedCdnBase = normalizeBaseUrl(cdnBase);
15148
+ // Normalize path to ensure it starts with /
15149
+ let normalizedPath = path;
15150
+ if (normalizedPath.startsWith('./')) {
15151
+ normalizedPath = normalizedPath.substring(1); // ./assets -> /assets
15152
+ }
15153
+ else if (!normalizedPath.startsWith('/')) {
15154
+ normalizedPath = '/' + normalizedPath; // assets -> /assets
15155
+ }
15156
+ return normalizedCdnBase + normalizedPath;
15157
+ }
15158
+ /**
15159
+ * Returns the app base path for router configuration
15160
+ *
15161
+ * In local development: returns '/'
15162
+ * In production: returns the deployed app path from meta tag
15163
+ *
15164
+ * @returns The app base path
15165
+ *
15166
+ * @example
15167
+ * ```tsx
15168
+ * import { getAppBase } from '@uipath/uipath-typescript';
15169
+ * import { BrowserRouter } from 'react-router-dom';
15170
+ *
15171
+ * function App() {
15172
+ * return (
15173
+ * <BrowserRouter basename={getAppBase()}>
15174
+ * {/* routes *\/}
15175
+ * </BrowserRouter>
15176
+ * );
15177
+ * }
15178
+ * ```
15179
+ */
15180
+ function getAppBase() {
15181
+ return getMetaTagContent(exports.UiPathMetaTags.APP_BASE) || '/';
15182
+ }
15183
+
14840
15184
  exports.APP_NAME = APP_NAME;
14841
15185
  exports.AgentMap = AgentMap;
14842
15186
  exports.AuthenticationError = AuthenticationError;
@@ -14879,6 +15223,8 @@
14879
15223
  exports.createProcessInstanceWithMethods = createProcessInstanceWithMethods;
14880
15224
  exports.createProcessWithMethods = createProcessWithMethods;
14881
15225
  exports.createTaskWithMethods = createTaskWithMethods;
15226
+ exports.getAppBase = getAppBase;
15227
+ exports.getAsset = getAsset;
14882
15228
  exports.getErrorDetails = getErrorDetails;
14883
15229
  exports.getLimitedPageSize = getLimitedPageSize;
14884
15230
  exports.isAuthenticationError = isAuthenticationError;
@@ -14889,6 +15235,7 @@
14889
15235
  exports.isServerError = isServerError;
14890
15236
  exports.isUiPathError = isUiPathError;
14891
15237
  exports.isValidationError = isValidationError;
15238
+ exports.loadFromMetaTags = loadFromMetaTags;
14892
15239
  exports.telemetryClient = telemetryClient;
14893
15240
  exports.track = track;
14894
15241
  exports.trackEvent = trackEvent;