@hyphen/sdk 1.13.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -33,7 +33,6 @@ var index_exports = {};
33
33
  __export(index_exports, {
34
34
  Hyphen: () => Hyphen,
35
35
  Toggle: () => Toggle,
36
- ToggleHooks: () => ToggleHooks,
37
36
  env: () => env,
38
37
  loadEnv: () => loadEnv
39
38
  });
@@ -124,8 +123,7 @@ var BaseService = class extends import_hookified.Hookified {
124
123
  this._throwErrors = options.throwErrors;
125
124
  }
126
125
  this._net = new import_net.CacheableNet({
127
- cache: this._cache,
128
- useHttpCache: false
126
+ cache: this._cache
129
127
  });
130
128
  }
131
129
  get log() {
@@ -191,22 +189,12 @@ var BaseService = class extends import_hookified.Hookified {
191
189
  };
192
190
  }
193
191
  async put(url, data, config2) {
194
- const requestInit = {
195
- ...config2,
196
- method: "PUT",
197
- body: typeof data === "string" ? data : JSON.stringify(data),
198
- headers: {
199
- "Content-Type": "application/json",
200
- ...config2?.headers
201
- }
202
- };
203
- const response = await this._net.fetch(url, requestInit);
204
- const responseData = await response.json();
192
+ const response = await this._net.put(url, data, config2);
205
193
  return {
206
- data: responseData,
207
- status: response.status,
208
- statusText: response.statusText,
209
- headers: response.headers,
194
+ data: response.data,
195
+ status: response.response.status,
196
+ statusText: response.response.statusText,
197
+ headers: response.response.headers,
210
198
  config: config2,
211
199
  request: void 0
212
200
  };
@@ -221,7 +209,10 @@ var BaseService = class extends import_hookified.Hookified {
221
209
  const { data: configData, ...restConfig } = config2 || {};
222
210
  let body;
223
211
  if (configData) {
224
- body = typeof configData === "string" ? configData : JSON.stringify(configData);
212
+ body = typeof configData === "string" ? (
213
+ /* c8 ignore next */
214
+ configData
215
+ ) : JSON.stringify(configData);
225
216
  if (!headers["content-type"] && !headers["Content-Type"]) {
226
217
  headers["content-type"] = "application/json";
227
218
  }
@@ -777,365 +768,606 @@ var NetInfo = class extends BaseService {
777
768
  };
778
769
 
779
770
  // src/toggle.ts
780
- var import_node_process4 = __toESM(require("process"), 1);
781
- var import_openfeature_server_provider = require("@hyphen/openfeature-server-provider");
782
- var import_server_sdk = require("@openfeature/server-sdk");
783
- var import_dotenv2 = __toESM(require("dotenv"), 1);
771
+ var import_net2 = require("@cacheable/net");
784
772
  var import_hookified2 = require("hookified");
785
- import_dotenv2.default.config({
786
- quiet: true
787
- });
788
- var ToggleHooks = /* @__PURE__ */ (function(ToggleHooks2) {
789
- ToggleHooks2["beforeGetBoolean"] = "beforeGetBoolean";
790
- ToggleHooks2["afterGetBoolean"] = "afterGetBoolean";
791
- ToggleHooks2["beforeGetString"] = "beforeGetString";
792
- ToggleHooks2["afterGetString"] = "afterGetString";
793
- ToggleHooks2["beforeGetNumber"] = "beforeGetNumber";
794
- ToggleHooks2["afterGetNumber"] = "afterGetNumber";
795
- ToggleHooks2["beforeGetObject"] = "beforeGetObject";
796
- ToggleHooks2["afterGetObject"] = "afterGetObject";
797
- return ToggleHooks2;
798
- })({});
799
773
  var Toggle = class extends import_hookified2.Hookified {
800
774
  static {
801
775
  __name(this, "Toggle");
802
776
  }
803
- _applicationId = import_node_process4.default.env.HYPHEN_APPLICATION_ID;
804
- _publicApiKey = import_node_process4.default.env.HYPHEN_PUBLIC_API_KEY;
777
+ _publicApiKey;
778
+ _organizationId;
779
+ _applicationId;
805
780
  _environment;
806
- _client;
807
- _context;
808
- _throwErrors = false;
809
- _uris;
810
- _caching;
811
- /*
812
- * Create a new Toggle instance. This will create a new client and set the options.
813
- * @param {ToggleOptions}
781
+ _horizonUrls = [];
782
+ _net = new import_net2.CacheableNet();
783
+ _defaultContext;
784
+ _defaultTargetingKey = `${Math.random().toString(36).substring(7)}`;
785
+ /**
786
+ * Creates a new Toggle instance.
787
+ *
788
+ * @param options - Configuration options for the toggle client
789
+ *
790
+ * @example
791
+ * ```typescript
792
+ * // Minimal configuration
793
+ * const toggle = new Toggle({
794
+ * publicApiKey: 'public_your-key',
795
+ * applicationId: 'app-123'
796
+ * });
797
+ *
798
+ * // With full options
799
+ * const toggle = new Toggle({
800
+ * publicApiKey: 'public_your-key',
801
+ * applicationId: 'app-123',
802
+ * environment: 'production',
803
+ * defaultContext: { targetingKey: 'user-456' },
804
+ * horizonUrls: ['https://my-horizon.example.com']
805
+ * });
806
+ * ```
814
807
  */
815
808
  constructor(options) {
816
809
  super();
817
- this._throwErrors = options?.throwErrors ?? false;
818
- this._applicationId = options?.applicationId;
810
+ if (options?.applicationId) {
811
+ this._applicationId = options.applicationId;
812
+ }
813
+ if (options?.environment) {
814
+ this._environment = options.environment;
815
+ } else {
816
+ this._environment = "development";
817
+ }
818
+ if (options?.defaultContext) {
819
+ this._defaultContext = options.defaultContext;
820
+ }
819
821
  if (options?.publicApiKey) {
820
- this.setPublicApiKey(options.publicApiKey);
822
+ this._publicApiKey = options.publicApiKey;
823
+ this._organizationId = this.getOrgIdFromPublicKey(this._publicApiKey);
824
+ }
825
+ if (options?.horizonUrls) {
826
+ this._horizonUrls = options.horizonUrls;
827
+ } else {
828
+ this._horizonUrls = this.getDefaultHorizonUrls(this._publicApiKey);
829
+ }
830
+ if (options?.defaultTargetKey) {
831
+ this._defaultTargetingKey = options?.defaultTargetKey;
832
+ } else {
833
+ if (this._defaultContext) {
834
+ this._defaultTargetingKey = this.getTargetingKey(this._defaultContext);
835
+ } else {
836
+ this._defaultTargetingKey = this.generateTargetKey();
837
+ }
838
+ }
839
+ if (options?.cache) {
840
+ this._net.cache = options.cache;
821
841
  }
822
- this._environment = options?.environment ?? import_node_process4.default.env.NODE_ENV ?? "development";
823
- this._context = options?.context;
824
- this._uris = options?.uris;
825
- this._caching = options?.caching;
826
842
  }
827
843
  /**
828
- * Get the application ID
829
- * @returns {string | undefined}
844
+ * Gets the public API key used for authentication.
845
+ *
846
+ * @returns The current public API key or undefined if not set
830
847
  */
831
- get applicationId() {
832
- return this._applicationId;
848
+ get publicApiKey() {
849
+ return this._publicApiKey;
833
850
  }
834
851
  /**
835
- * Set the application ID
836
- * @param {string | undefined} value
852
+ * Sets the public API key used for authentication.
853
+ *
854
+ * @param value - The public API key string or undefined to clear
855
+ * @throws {Error} If the key doesn't start with "public_"
837
856
  */
838
- set applicationId(value) {
839
- this._applicationId = value;
857
+ set publicApiKey(value) {
858
+ this.setPublicKey(value);
840
859
  }
841
860
  /**
842
- * Get the public API key
843
- * @returns {string}
861
+ * Gets the default context used for toggle evaluations.
862
+ *
863
+ * @returns The current default ToggleContext
844
864
  */
845
- get publicApiKey() {
846
- return this._publicApiKey;
865
+ get defaultContext() {
866
+ return this._defaultContext;
847
867
  }
848
868
  /**
849
- * Set the public API key
850
- * @param {string} value
869
+ * Sets the default context used for toggle evaluations.
870
+ *
871
+ * @param value - The ToggleContext to use as default
851
872
  */
852
- set publicApiKey(value) {
853
- if (!value) {
854
- this._publicApiKey = void 0;
855
- this._client = void 0;
856
- return;
857
- }
858
- this.setPublicApiKey(value);
873
+ set defaultContext(value) {
874
+ this._defaultContext = value;
859
875
  }
860
876
  /**
861
- * Get the environment
862
- * @returns {string}
877
+ * Gets the organization ID extracted from the public API key.
878
+ *
879
+ * @returns The organization ID string or undefined if not available
863
880
  */
864
- get environment() {
865
- return this._environment;
881
+ get organizationId() {
882
+ return this._organizationId;
866
883
  }
867
884
  /**
868
- * Set the environment
869
- * @param {string} value
885
+ * Gets the Horizon endpoint URLs used for load balancing.
886
+ *
887
+ * These URLs are used to distribute requests across multiple Horizon endpoints.
888
+ * If endpoints fail, the system will attempt to use the default horizon endpoint service.
889
+ *
890
+ * @returns Array of Horizon endpoint URLs
891
+ * @see {@link https://hyphen.ai/horizon} for more information
870
892
  */
871
- set environment(value) {
872
- this._environment = value;
893
+ get horizonUrls() {
894
+ return this._horizonUrls;
873
895
  }
874
896
  /**
875
- * Get the throwErrors. If true, errors will be thrown in addition to being emitted.
876
- * @returns {boolean}
897
+ * Sets the Horizon endpoint URLs for load balancing.
898
+ *
899
+ * Configures multiple Horizon endpoints that will be used for load balancing.
900
+ * When endpoints fail, the system will fall back to the default horizon endpoint service.
901
+ *
902
+ * @param value - Array of Horizon endpoint URLs or empty array to clear
903
+ * @see {@link https://hyphen.ai/horizon} for more information
904
+ *
905
+ * @example
906
+ * ```typescript
907
+ * const toggle = new Toggle();
908
+ * toggle.horizonUrls = [
909
+ * 'https://org1.toggle.hyphen.cloud',
910
+ * 'https://org2.toggle.hyphen.cloud'
911
+ * ];
912
+ * ```
877
913
  */
878
- get throwErrors() {
879
- return this._throwErrors;
914
+ set horizonUrls(value) {
915
+ this._horizonUrls = value;
880
916
  }
881
917
  /**
882
- * Set the throwErrors. If true, errors will be thrown in addition to being emitted.
883
- * @param {boolean} value
918
+ * Gets the application ID used for toggle context.
919
+ *
920
+ * @returns The current application ID or undefined if not set
884
921
  */
885
- set throwErrors(value) {
886
- this._throwErrors = value;
922
+ get applicationId() {
923
+ return this._applicationId;
887
924
  }
888
925
  /**
889
- * Get the current context. This is the default context used. You can override this at the get function level.
890
- * @returns {ToggleContext}
926
+ * Sets the application ID used for toggle context.
927
+ *
928
+ * @param value - The application ID string or undefined to clear
891
929
  */
892
- get context() {
893
- return this._context;
930
+ set applicationId(value) {
931
+ this._applicationId = value;
894
932
  }
895
933
  /**
896
- * Set the context. This is the default context used. You can override this at the get function level.
897
- * @param {ToggleContext} value
934
+ * Gets the environment used for toggle context.
935
+ *
936
+ * @returns The current environment (defaults to 'development')
898
937
  */
899
- set context(value) {
900
- this._context = value;
938
+ get environment() {
939
+ return this._environment;
901
940
  }
902
941
  /**
903
- * Get the URIs. This is used to override the default URIs for testing or if you are using a self-hosted version.
904
- * @returns {Array<string>}
942
+ * Sets the environment used for toggle context.
943
+ *
944
+ * @param value - The environment string or undefined to clear
905
945
  */
906
- get uris() {
907
- return this._uris;
946
+ set environment(value) {
947
+ this._environment = value;
908
948
  }
909
949
  /**
910
- * Set the URIs. This is used to override the default URIs for testing or if you are using a self-hosted version.
911
- * @param {Array<string>} value
950
+ * Gets the default targeting key used for toggle evaluations.
951
+ *
952
+ * @returns The current default targeting key or undefined if not set
912
953
  */
913
- set uris(value) {
914
- this._uris = value;
954
+ get defaultTargetingKey() {
955
+ return this._defaultTargetingKey;
915
956
  }
916
957
  /**
917
- * Get the caching options.
918
- * @returns {ToggleCachingOptions | undefined}
958
+ * Sets the default targeting key used for toggle evaluations.
959
+ *
960
+ * @param value - The targeting key string or undefined to clear
919
961
  */
920
- get caching() {
921
- return this._caching;
962
+ set defaultTargetingKey(value) {
963
+ this._defaultTargetingKey = value;
922
964
  }
923
965
  /**
924
- * Set the caching options.
925
- * @param {ToggleCachingOptions | undefined} value
966
+ * Gets the Cacheable instance used for caching fetch operations.
967
+ *
968
+ * @returns The current Cacheable instance
926
969
  */
927
- set caching(value) {
928
- this._caching = value;
970
+ get cache() {
971
+ return this._net.cache;
929
972
  }
930
973
  /**
931
- * This is a helper function to set the public API key. It will check if the key starts with public_ and set it. If it
932
- * does set it will also set the client to undefined to force a new one to be created. If it does not,
933
- * it will emit an error and console warning and not set the key. Used by the constructor and publicApiKey setter.
934
- * @param key
935
- * @returns
974
+ * Sets the Cacheable instance for caching fetch operations.
975
+ *
976
+ * @param cache - The Cacheable instance to use for caching
936
977
  */
937
- setPublicApiKey(key) {
938
- if (!key.startsWith("public_")) {
939
- this.emit("error", new Error("Public API key should start with public_"));
940
- if (import_node_process4.default.env.NODE_ENV !== "production") {
941
- console.error("Public API key should start with public_");
978
+ set cache(cache) {
979
+ this._net.cache = cache;
980
+ }
981
+ /**
982
+ * Retrieves a toggle value with generic type support.
983
+ *
984
+ * This is the core method for fetching toggle values. All convenience methods
985
+ * (getBoolean, getString, getNumber, getObject) delegate to this method.
986
+ *
987
+ * @template T - The expected type of the toggle value
988
+ * @param toggleKey - The key of the toggle to retrieve
989
+ * @param defaultValue - The value to return if the toggle is not found or an error occurs
990
+ * @param options - Optional configuration including context override
991
+ * @returns Promise resolving to the toggle value or defaultValue
992
+ *
993
+ * @example
994
+ * ```typescript
995
+ * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' });
996
+ *
997
+ * // Get a boolean
998
+ * const enabled = await toggle.get<boolean>('feature-flag', false);
999
+ *
1000
+ * // Get an object with type safety
1001
+ * interface Config { theme: string; }
1002
+ * const config = await toggle.get<Config>('app-config', { theme: 'light' });
1003
+ *
1004
+ * // Override context for a single request
1005
+ * const value = await toggle.get('key', 'default', {
1006
+ * context: { targetingKey: 'user-456' }
1007
+ * });
1008
+ * ```
1009
+ */
1010
+ async get(toggleKey, defaultValue, options) {
1011
+ try {
1012
+ const context = {
1013
+ application: this._applicationId ?? "",
1014
+ environment: this._environment ?? "development"
1015
+ };
1016
+ if (options?.context) {
1017
+ context.targetingKey = options?.context.targetingKey;
1018
+ context.ipAddress = options?.context.ipAddress;
1019
+ context.user = options?.context.user;
1020
+ context.customAttributes = options?.context.customAttributes;
1021
+ } else {
1022
+ context.targetingKey = this._defaultContext?.targetingKey;
1023
+ context.ipAddress = this._defaultContext?.ipAddress;
1024
+ context.user = this._defaultContext?.user;
1025
+ context.customAttributes = this._defaultContext?.customAttributes;
942
1026
  }
943
- return;
1027
+ const fetchOptions = {
1028
+ headers: {}
1029
+ };
1030
+ if (!context.targetingKey) {
1031
+ context.targetingKey = this.getTargetingKey(context);
1032
+ }
1033
+ if (this._publicApiKey) {
1034
+ fetchOptions.headers["x-api-key"] = this._publicApiKey;
1035
+ } else {
1036
+ throw new Error("You must set the publicApiKey");
1037
+ }
1038
+ if (context.application === "") {
1039
+ throw new Error("You must set the applicationId");
1040
+ }
1041
+ const result = await this.fetch("/toggle/evaluate", context, fetchOptions);
1042
+ if (result?.toggles) {
1043
+ return result.toggles[toggleKey].value;
1044
+ }
1045
+ } catch (error) {
1046
+ this.emit("error", error);
944
1047
  }
945
- this._publicApiKey = key;
946
- this._client = void 0;
1048
+ return defaultValue;
947
1049
  }
948
1050
  /**
949
- * Set the context. This is the default context used. You can override this at the get function level.
950
- * @param {ToggleContext} context
1051
+ * Retrieves a boolean toggle value.
1052
+ *
1053
+ * This is a convenience method that wraps the generic get() method with boolean type safety.
1054
+ *
1055
+ * @param toggleKey - The key of the toggle to retrieve
1056
+ * @param defaultValue - The boolean value to return if the toggle is not found or an error occurs
1057
+ * @param options - Optional configuration including context for toggle evaluation
1058
+ * @returns Promise resolving to the boolean toggle value or defaultValue
1059
+ *
1060
+ * @example
1061
+ * ```typescript
1062
+ * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' });
1063
+ * const isFeatureEnabled = await toggle.getBoolean('feature-flag', false);
1064
+ * console.log(isFeatureEnabled); // true or false
1065
+ * ```
951
1066
  */
952
- setContext(context) {
953
- this._context = context;
954
- this._client = void 0;
1067
+ async getBoolean(toggleKey, defaultValue, options) {
1068
+ return this.get(toggleKey, defaultValue, options);
955
1069
  }
956
1070
  /**
957
- * Helper function to get the client. This will create a new client if one does not exist. It will also set the
958
- * application ID, environment, and URIs if they are not set. This is used by the get function to get the client.
959
- * This is normally only used internally.
960
- * @returns {Promise<Client>}
1071
+ * Retrieves a string toggle value.
1072
+ *
1073
+ * This is a convenience method that wraps the generic get() method with string type safety.
1074
+ *
1075
+ * @param toggleKey - The key of the toggle to retrieve
1076
+ * @param defaultValue - The string value to return if the toggle is not found or an error occurs
1077
+ * @param options - Optional configuration including context for toggle evaluation
1078
+ * @returns Promise resolving to the string toggle value or defaultValue
1079
+ *
1080
+ * @example
1081
+ * ```typescript
1082
+ * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' });
1083
+ * const message = await toggle.getString('welcome-message', 'Hello World');
1084
+ * console.log(message); // 'Welcome to our app!' or 'Hello World'
1085
+ * ```
961
1086
  */
962
- async getClient() {
963
- if (!this._client) {
964
- if (this._applicationId === void 0 || this._applicationId.length === 0) {
965
- const errorMessage = "Application ID is not set. You must set it before using the client or have the HYPHEN_APPLICATION_ID environment variable set.";
966
- this.emit("error", new Error(errorMessage));
967
- if (this._throwErrors) {
968
- throw new Error(errorMessage);
969
- }
970
- }
971
- const options = {
972
- application: this._applicationId,
973
- environment: this._environment,
974
- horizonUrls: this._uris,
975
- cache: this._caching
976
- };
977
- if (this._publicApiKey && this._publicApiKey.length > 0) {
978
- await import_server_sdk.OpenFeature.setProviderAndWait(new import_openfeature_server_provider.HyphenProvider(this._publicApiKey, options));
1087
+ async getString(toggleKey, defaultValue, options) {
1088
+ return this.get(toggleKey, defaultValue, options);
1089
+ }
1090
+ /**
1091
+ * Retrieves an object toggle value.
1092
+ *
1093
+ * This is a convenience method that wraps the generic get() method with object type safety.
1094
+ * Note that the toggle service may return JSON as a string, which should be parsed if needed.
1095
+ *
1096
+ * @template T - The expected object type
1097
+ * @param toggleKey - The key of the toggle to retrieve
1098
+ * @param defaultValue - The object value to return if the toggle is not found or an error occurs
1099
+ * @param options - Optional configuration including context for toggle evaluation
1100
+ * @returns Promise resolving to the object toggle value or defaultValue
1101
+ *
1102
+ * @example
1103
+ * ```typescript
1104
+ * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' });
1105
+ * const config = await toggle.getObject('app-config', { theme: 'light' });
1106
+ * console.log(config); // { theme: 'dark', features: ['a', 'b'] } or { theme: 'light' }
1107
+ * ```
1108
+ */
1109
+ async getObject(toggleKey, defaultValue, options) {
1110
+ return this.get(toggleKey, defaultValue, options);
1111
+ }
1112
+ /**
1113
+ * Retrieves a number toggle value.
1114
+ *
1115
+ * This is a convenience method that wraps the generic get() method with number type safety.
1116
+ *
1117
+ * @param toggleKey - The key of the toggle to retrieve
1118
+ * @param defaultValue - The number value to return if the toggle is not found or an error occurs
1119
+ * @param options - Optional configuration including context for toggle evaluation
1120
+ * @returns Promise resolving to the number toggle value or defaultValue
1121
+ *
1122
+ * @example
1123
+ * ```typescript
1124
+ * const toggle = new Toggle({ publicApiKey: 'public_key', applicationId: 'app-id' });
1125
+ * const maxRetries = await toggle.getNumber('max-retries', 3);
1126
+ * console.log(maxRetries); // 5 or 3
1127
+ * ```
1128
+ */
1129
+ async getNumber(toggleKey, defaultValue, options) {
1130
+ return this.get(toggleKey, defaultValue, options);
1131
+ }
1132
+ /**
1133
+ * Makes an HTTP POST request to the specified URL with automatic authentication.
1134
+ *
1135
+ * This method uses browser-compatible fetch and automatically includes the
1136
+ * public API key in the x-api-key header if available. It supports load
1137
+ * balancing across multiple horizon URLs with fallback behavior.
1138
+ *
1139
+ * @template T - The expected response type
1140
+ * @param path - The API path to request (e.g., '/api/toggles')
1141
+ * @param payload - The JSON payload to send in the request body
1142
+ * @param options - Optional fetch configuration. Cache is set at .cache
1143
+ * @returns Promise resolving to the parsed JSON response
1144
+ * @throws {Error} If no horizon URLs are configured or all requests fail
1145
+ *
1146
+ * @example
1147
+ * ```typescript
1148
+ * const toggle = new Toggle({
1149
+ * publicApiKey: 'public_your-key-here',
1150
+ * horizonUrls: ['https://api.hyphen.cloud']
1151
+ * });
1152
+ *
1153
+ * interface ToggleResponse {
1154
+ * enabled: boolean;
1155
+ * value: string;
1156
+ * }
1157
+ *
1158
+ * const result = await toggle.fetch<ToggleResponse>('/api/toggle/feature-flag', {
1159
+ * context: { targetingKey: 'user-123' }
1160
+ * });
1161
+ * console.log(result.enabled); // true/false
1162
+ * ```
1163
+ */
1164
+ async fetch(path2, payload, options) {
1165
+ if (this._horizonUrls.length === 0) {
1166
+ throw new Error("No horizon URLs configured. Set horizonUrls or provide a valid publicApiKey.");
1167
+ }
1168
+ const headers = {
1169
+ "Content-Type": "application/json"
1170
+ };
1171
+ if (options?.headers) {
1172
+ if (options.headers instanceof Headers) {
1173
+ options.headers.forEach((value, key) => {
1174
+ headers[key] = value;
1175
+ });
1176
+ } else if (Array.isArray(options.headers)) {
1177
+ options.headers.forEach(([key, value]) => {
1178
+ headers[key] = value;
1179
+ });
979
1180
  } else {
980
- this.emit("error", new Error("Public API key is not set. You must set it before using the client or have the HYPHEN_PUBLIC_API_KEY environment variable set."));
981
- if (this._throwErrors) {
982
- throw new Error("Public API key is not set");
1181
+ Object.assign(headers, options.headers);
1182
+ }
1183
+ }
1184
+ if (this._publicApiKey) {
1185
+ headers["x-api-key"] = this._publicApiKey;
1186
+ }
1187
+ const fetchOptions = {
1188
+ method: "POST",
1189
+ ...options,
1190
+ headers,
1191
+ body: payload ? JSON.stringify(payload) : options?.body
1192
+ };
1193
+ const errors = [];
1194
+ for (const baseUrl of this._horizonUrls) {
1195
+ try {
1196
+ const url = `${baseUrl.replace(/\/$/, "")}${path2.startsWith("/") ? path2 : `/${path2}`}`;
1197
+ const response = await this._net.fetch(url, fetchOptions);
1198
+ if (!response.ok) {
1199
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
1200
+ }
1201
+ const data = await response.json();
1202
+ return data;
1203
+ } catch (error) {
1204
+ const fetchError = error instanceof Error ? error : new Error("Unknown fetch error");
1205
+ const statusMatch = fetchError.message.match(/status (\d{3})/);
1206
+ if (statusMatch) {
1207
+ const status = statusMatch[1];
1208
+ errors.push(new Error(`HTTP ${status}: ${fetchError.message}`));
1209
+ } else {
1210
+ errors.push(fetchError);
983
1211
  }
984
1212
  }
985
- this._client = import_server_sdk.OpenFeature.getClient(this._context);
986
1213
  }
987
- return this._client;
1214
+ throw new Error(`All horizon URLs failed. Last errors: ${errors.map((e) => e.message).join(", ")}`);
988
1215
  }
989
1216
  /**
990
- * This is the main function to get a feature flag value. It will check the type of the default value and call the
991
- * appropriate function. It will also set the context if it is not set.
992
- * @param {string} key - The key of the feature flag
993
- * @param {T} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
994
- * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
995
- * @returns {Promise<T>}
1217
+ * Validates and sets the public API key.
1218
+ *
1219
+ * This method is used internally by the publicApiKey setter to validate
1220
+ * that the key starts with "public_" prefix. If the key is invalid,
1221
+ * an error is thrown.
1222
+ *
1223
+ * @param key - The public API key string or undefined to clear
1224
+ * @throws {Error} If the key doesn't start with "public_"
1225
+ *
1226
+ * @example
1227
+ * ```typescript
1228
+ * const toggle = new Toggle();
1229
+ *
1230
+ * // Valid key
1231
+ * toggle.setPublicKey('public_abc123'); // OK
1232
+ *
1233
+ * // Invalid key
1234
+ * toggle.setPublicKey('invalid_key'); // Throws error
1235
+ *
1236
+ * // Clear key
1237
+ * toggle.setPublicKey(undefined); // OK
1238
+ * ```
996
1239
  */
997
- async get(key, defaultValue, options) {
998
- switch (typeof defaultValue) {
999
- case "boolean": {
1000
- return this.getBoolean(key, defaultValue, options);
1001
- }
1002
- case "string": {
1003
- return this.getString(key, defaultValue, options);
1004
- }
1005
- case "number": {
1006
- return this.getNumber(key, defaultValue, options);
1007
- }
1008
- default: {
1009
- return this.getObject(key, defaultValue, options);
1010
- }
1240
+ setPublicKey(key) {
1241
+ if (key !== void 0 && !key.startsWith("public_")) {
1242
+ throw new Error("Public API key must start with 'public_'");
1011
1243
  }
1244
+ this._publicApiKey = key;
1012
1245
  }
1013
1246
  /**
1014
- * Get a boolean value from the feature flag. This will check the type of the default value and call the
1015
- * appropriate function. It will also set the context if it is not set.
1016
- * @param {string} key - The key of the feature flag
1017
- * @param {boolean} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
1018
- * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
1019
- * @returns {Promise<boolean>} - The value of the feature flag
1247
+ * Extracts the organization ID from a public API key.
1248
+ *
1249
+ * The public key format is: `public_<base64-encoded-data>`
1250
+ * The base64 data contains: `orgId:secretData`
1251
+ * Only alphanumeric characters, underscores, and hyphens are considered valid in org IDs.
1252
+ *
1253
+ * @param publicKey - The public API key to extract the organization ID from
1254
+ * @returns The organization ID if valid and extractable, undefined otherwise
1255
+ *
1256
+ * @example
1257
+ * ```typescript
1258
+ * const toggle = new Toggle();
1259
+ * const orgId = toggle.getOrgIdFromPublicKey('public_dGVzdC1vcmc6c2VjcmV0');
1260
+ * console.log(orgId); // 'test-org'
1261
+ * ```
1020
1262
  */
1021
- async getBoolean(key, defaultValue, options) {
1263
+ getOrgIdFromPublicKey(publicKey) {
1022
1264
  try {
1023
- const data = {
1024
- key,
1025
- defaultValue,
1026
- options
1027
- };
1028
- await this.hook("beforeGetBoolean", data);
1029
- const client = await this.getClient();
1030
- const result = await client.getBooleanValue(data.key, data.defaultValue, data.options?.context);
1031
- const resultData = {
1032
- key,
1033
- defaultValue,
1034
- options,
1035
- result
1036
- };
1037
- await this.hook("afterGetBoolean", resultData);
1038
- return resultData.result;
1039
- } catch (error) {
1040
- this.emit("error", error);
1041
- if (this._throwErrors) {
1042
- throw error;
1043
- }
1265
+ const keyWithoutPrefix = publicKey.replace(/^public_/, "");
1266
+ const decoded = globalThis.atob ? globalThis.atob(keyWithoutPrefix) : Buffer.from(keyWithoutPrefix, "base64").toString();
1267
+ const [orgId] = decoded.split(":");
1268
+ const isValidOrgId = /^[a-zA-Z0-9_-]+$/.test(orgId);
1269
+ return isValidOrgId ? orgId : void 0;
1270
+ } catch {
1271
+ return void 0;
1044
1272
  }
1045
- return defaultValue;
1046
1273
  }
1047
1274
  /**
1048
- * Get a string value from the feature flag.
1049
- * @param {string} key - The key of the feature flag
1050
- * @param {string} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
1051
- * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
1052
- * @returns {Promise<string>} - The value of the feature flag
1275
+ * Builds the default Horizon API URL for the given public key.
1276
+ *
1277
+ * If a valid organization ID can be extracted from the public key, returns an
1278
+ * organization-specific URL. Otherwise, returns the default fallback URL.
1279
+ *
1280
+ * @param publicKey - The public API key to build the URL for
1281
+ * @returns Organization-specific URL or default fallback URL
1282
+ *
1283
+ * @example
1284
+ * ```typescript
1285
+ * const toggle = new Toggle();
1286
+ *
1287
+ * // With valid org ID
1288
+ * const orgUrl = toggle.buildDefaultHorizonUrl('public_dGVzdC1vcmc6c2VjcmV0');
1289
+ * console.log(orgUrl); // 'https://test-org.toggle.hyphen.cloud'
1290
+ *
1291
+ * // With invalid key
1292
+ * const defaultUrl = toggle.buildDefaultHorizonUrl('invalid-key');
1293
+ * console.log(defaultUrl); // 'https://toggle.hyphen.cloud'
1294
+ * ```
1053
1295
  */
1054
- async getString(key, defaultValue, options) {
1055
- try {
1056
- const data = {
1057
- key,
1058
- defaultValue,
1059
- options
1060
- };
1061
- await this.hook("beforeGetString", data);
1062
- const client = await this.getClient();
1063
- const result = await client.getStringValue(data.key, data.defaultValue, data.options?.context);
1064
- const resultData = {
1065
- key,
1066
- defaultValue,
1067
- options,
1068
- result
1069
- };
1070
- await this.hook("afterGetString", resultData);
1071
- return resultData.result;
1072
- } catch (error) {
1073
- this.emit("error", error);
1074
- if (this._throwErrors) {
1075
- throw error;
1076
- }
1296
+ getDefaultHorizonUrl(publicKey) {
1297
+ if (publicKey) {
1298
+ const orgId = this.getOrgIdFromPublicKey(publicKey);
1299
+ return orgId ? `https://${orgId}.toggle.hyphen.cloud` : "https://toggle.hyphen.cloud";
1077
1300
  }
1078
- return defaultValue;
1301
+ return "https://toggle.hyphen.cloud";
1079
1302
  }
1080
- async getNumber(key, defaultValue, options) {
1081
- try {
1082
- const data = {
1083
- key,
1084
- defaultValue,
1085
- options
1086
- };
1087
- await this.hook("beforeGetNumber", data);
1088
- const client = await this.getClient();
1089
- const result = await client.getNumberValue(data.key, data.defaultValue, data.options?.context);
1090
- const resultData = {
1091
- key,
1092
- defaultValue,
1093
- options,
1094
- result
1095
- };
1096
- await this.hook("afterGetNumber", resultData);
1097
- return resultData.result;
1098
- } catch (error) {
1099
- this.emit("error", error);
1100
- if (this._throwErrors) {
1101
- throw error;
1303
+ /**
1304
+ * Gets the default Horizon URLs for load balancing and failover.
1305
+ *
1306
+ * If a public key is provided, returns an array with the organization-specific
1307
+ * URL as primary and the default Hyphen URL as fallback. Without a public key,
1308
+ * returns only the default Hyphen URL.
1309
+ *
1310
+ * @param publicKey - Optional public API key to derive organization-specific URL
1311
+ * @returns Array of Horizon URLs for load balancing
1312
+ *
1313
+ * @example
1314
+ * ```typescript
1315
+ * const toggle = new Toggle();
1316
+ *
1317
+ * // Without public key - returns default only
1318
+ * const defaultUrls = toggle.getDefaultHorizonUrls();
1319
+ * // ['https://toggle.hyphen.cloud']
1320
+ *
1321
+ * // With public key - returns org-specific + fallback
1322
+ * const urls = toggle.getDefaultHorizonUrls('public_dGVzdC1vcmc6c2VjcmV0');
1323
+ * // ['https://test-org.toggle.hyphen.cloud', 'https://toggle.hyphen.cloud']
1324
+ * ```
1325
+ */
1326
+ getDefaultHorizonUrls(publicKey) {
1327
+ let result = [
1328
+ this.getDefaultHorizonUrl()
1329
+ ];
1330
+ if (publicKey) {
1331
+ const defaultUrl = result[0];
1332
+ const orgUrl = this.getDefaultHorizonUrl(publicKey);
1333
+ result = [];
1334
+ if (orgUrl !== defaultUrl) {
1335
+ result.push(orgUrl);
1102
1336
  }
1337
+ result.push(defaultUrl);
1103
1338
  }
1104
- return defaultValue;
1339
+ return result;
1105
1340
  }
1106
1341
  /**
1107
- * Get an object value from the feature flag. This will check the type of the default value and call the
1108
- * appropriate function. It will also set the context if it is not set.
1109
- * @param {string} key - The key of the feature flag
1110
- * @param {T} defaultValue - The default value to return if the feature flag is not set or does not evaluate.
1111
- * @param {ToggleRequestOptions} options - The options to use for the request. This can be used to override the context.
1112
- * @returns {Promise<T>} - The value of the feature flag
1342
+ * Generates a unique targeting key based on available context.
1343
+ *
1344
+ * @returns A targeting key in the format: `[app]-[env]-[random]` or simplified versions
1113
1345
  */
1114
- async getObject(key, defaultValue, options) {
1115
- try {
1116
- const data = {
1117
- key,
1118
- defaultValue,
1119
- options
1120
- };
1121
- await this.hook("beforeGetObject", data);
1122
- const client = await this.getClient();
1123
- const result = await client.getObjectValue(key, defaultValue, data.options?.context);
1124
- const resultData = {
1125
- key,
1126
- defaultValue,
1127
- options,
1128
- result
1129
- };
1130
- await this.hook("afterGetObject", resultData);
1131
- return resultData.result;
1132
- } catch (error) {
1133
- this.emit("error", error);
1134
- if (this._throwErrors) {
1135
- throw error;
1136
- }
1346
+ generateTargetKey() {
1347
+ const randomSuffix = Math.random().toString(36).substring(7);
1348
+ const app = this._applicationId || "";
1349
+ const env2 = this._environment || "";
1350
+ const components = [
1351
+ app,
1352
+ env2,
1353
+ randomSuffix
1354
+ ].filter(Boolean);
1355
+ return components.join("-");
1356
+ }
1357
+ /**
1358
+ * Extracts targeting key from a toggle context with fallback logic.
1359
+ *
1360
+ * @param context - The toggle context to extract targeting key from
1361
+ * @returns The targeting key string
1362
+ */
1363
+ getTargetingKey(context) {
1364
+ if (context.targetingKey) {
1365
+ return context.targetingKey;
1137
1366
  }
1138
- return defaultValue;
1367
+ if (context.user) {
1368
+ return context.user.id;
1369
+ }
1370
+ return this._defaultTargetingKey;
1139
1371
  }
1140
1372
  };
1141
1373
 
@@ -1163,11 +1395,6 @@ var Hyphen = class extends import_hookified3.Hookified {
1163
1395
  netInfoOptions.apiKey = options.apiKey;
1164
1396
  linkOptions.apiKey = options.apiKey;
1165
1397
  }
1166
- if (options?.throwErrors !== void 0) {
1167
- toggleOptions.throwErrors = options.throwErrors;
1168
- netInfoOptions.throwErrors = options.throwErrors;
1169
- linkOptions.throwErrors = options.throwErrors;
1170
- }
1171
1398
  this._netInfo = new NetInfo(netInfoOptions);
1172
1399
  this._netInfo.on("error", (message, ...args) => this.emit("error", message, ...args));
1173
1400
  this._netInfo.on("info", (message, ...args) => this.emit("info", message, ...args));
@@ -1237,30 +1464,11 @@ var Hyphen = class extends import_hookified3.Hookified {
1237
1464
  this._netInfo.apiKey = value;
1238
1465
  this._link.apiKey = value;
1239
1466
  }
1240
- /**
1241
- * Get whether to throw errors or not.
1242
- * If set to true, errors will be thrown instead of logged.
1243
- * @returns {boolean} Whether to throw errors or not.
1244
- */
1245
- get throwErrors() {
1246
- return this._netInfo.throwErrors && this._toggle.throwErrors && this._link.throwErrors;
1247
- }
1248
- /**
1249
- * Set whether to throw errors or not. If set to true, errors will be thrown instead of logged.
1250
- * This will update the underlying services as well.
1251
- * @param {boolean} value - Whether to throw errors or not.
1252
- */
1253
- set throwErrors(value) {
1254
- this._netInfo.throwErrors = value;
1255
- this._toggle.throwErrors = value;
1256
- this._link.throwErrors = value;
1257
- }
1258
1467
  };
1259
1468
  // Annotate the CommonJS export names for ESM import in node:
1260
1469
  0 && (module.exports = {
1261
1470
  Hyphen,
1262
1471
  Toggle,
1263
- ToggleHooks,
1264
1472
  env,
1265
1473
  loadEnv
1266
1474
  });