@plyaz/core 1.11.0 → 1.11.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.mjs CHANGED
@@ -8,7 +8,7 @@ import { mergeConfigs, createApiClient, ApiPackageError, setDefaultApiClient, ev
8
8
  import { EventEmitter } from 'events';
9
9
  import { OBSERVABILITY_METRICS } from '@plyaz/types/observability';
10
10
  import { clearEventEmitter, setEventEmitter, initializeGlobalErrorHandler } from '@plyaz/errors/middleware';
11
- import { STORE_KEYS, useRootStore, createStandaloneFeatureFlagStore } from '@plyaz/store';
11
+ import { STORE_KEYS, createStandaloneFeatureFlagStore } from '@plyaz/store';
12
12
  import { CORE_EVENTS as CORE_EVENTS$1, FEATURE_FLAG_TABLE, FEATURE_FLAG_FIELD, SORT_DIRECTION, FEATURE_FLAG_RULE_FIELD, EVALUATION_REASONS, DATABASE_FIELDS, SYSTEM_USERS, FEATURE_FLAG_TYPES, SERVICE_KEYS, FEATURE_FLAG_PROVIDERS as FEATURE_FLAG_PROVIDERS$1, NODE_ENVIRONMENTS as NODE_ENVIRONMENTS$1, FEATURE_FLAG_DEFAULTS } from '@plyaz/types/core';
13
13
  import { uploadFile, uploadFiles, generateDocument, downloadFile, getSignedUrl, deleteFile, getFile } from '@plyaz/api';
14
14
  import { ENTITY_TYPE, FILE_CATEGORY } from '@plyaz/types/storage';
@@ -3001,6 +3001,24 @@ var Core = class _Core {
3001
3001
  */
3002
3002
  this._rootStore = null;
3003
3003
  }
3004
+ static {
3005
+ /**
3006
+ * Injected store hook for frontend (set via setRootStoreHook before initialize).
3007
+ * This is used instead of directly importing from @plyaz/store to prevent
3008
+ * duplicate store instances when bundlers create multiple module copies.
3009
+ */
3010
+ this._injectedStoreHook = null;
3011
+ }
3012
+ /**
3013
+ * Set the root store hook for frontend use.
3014
+ * Must be called before Core.initialize() when running in browser.
3015
+ * PlyazProvider calls this automatically with the store prop.
3016
+ *
3017
+ * @param store - The useRootStore hook from @plyaz/store
3018
+ */
3019
+ static setRootStoreHook(store) {
3020
+ _Core._injectedStoreHook = store;
3021
+ }
3004
3022
  /**
3005
3023
  * Setup environment and context
3006
3024
  */
@@ -3911,8 +3929,14 @@ var Core = class _Core {
3911
3929
  static async initializeRootStore(config, verbose) {
3912
3930
  const isFrontend = typeof window !== "undefined";
3913
3931
  if (isFrontend) {
3914
- _Core.log("Using frontend root store (Zustand)", verbose);
3915
- _Core._rootStore = useRootStore;
3932
+ if (!_Core._injectedStoreHook) {
3933
+ throw new CorePackageError(
3934
+ "Root store hook not set. Call Core.setRootStoreHook(useRootStore) before Core.initialize(), or use PlyazProvider with the store prop: <PlyazProvider store={useRootStore} ...>",
3935
+ ERROR_CODES.CLIENT_INITIALIZATION_FAILED
3936
+ );
3937
+ }
3938
+ _Core.log("Using frontend root store (Zustand) - injected via setRootStoreHook", verbose);
3939
+ _Core._rootStore = _Core._injectedStoreHook;
3916
3940
  } else {
3917
3941
  _Core.log("Creating backend composite store (in-memory)", verbose);
3918
3942
  const ServerErrorMiddleware = getCoreDependency("ServerErrorMiddleware");
@@ -12471,8 +12495,9 @@ function buildDatabaseProviderConfig(config) {
12471
12495
  __name(buildDatabaseProviderConfig, "buildDatabaseProviderConfig");
12472
12496
  function buildRedisProviderConfig(config) {
12473
12497
  if (!config.redis?.url) {
12474
- throw new Error(
12475
- 'Redis URL is required when using redis provider. Provide redis: { url: "redis://..." }'
12498
+ throw new CorePackageError(
12499
+ 'Redis URL is required when using redis provider. Provide redis: { url: "redis://..." }',
12500
+ ERROR_CODES.CORE_CONFIGURATION_INVALID
12476
12501
  );
12477
12502
  }
12478
12503
  return {
@@ -14062,7 +14087,10 @@ var FrontendExampleDomainService = class _FrontendExampleDomainService extends B
14062
14087
  const response = await this.apiClient.post(endpoint, data);
14063
14088
  if (!this.isResponseSuccess(response)) {
14064
14089
  const error = this.extractResponseError(response);
14065
- throw new Error(`Failed to send email: ${JSON.stringify(error)}`);
14090
+ throw new CorePackageError(
14091
+ `Failed to send email: ${JSON.stringify(error)}`,
14092
+ ERROR_CODES.CORE_OPERATION_FAILED
14093
+ );
14066
14094
  }
14067
14095
  const result = this.unwrapResponseData(response.data);
14068
14096
  CoreEventManager.emit(`${this.eventPrefix}:email:sent`, { result });
@@ -14707,8 +14735,9 @@ var BackendFilesDomainService = class _BackendFilesDomainService extends BaseBac
14707
14735
  try {
14708
14736
  await this.beforeDownloadFile?.(params);
14709
14737
  if (!this.storageService) {
14710
- throw new Error(
14711
- "Storage service not available. Ensure storage is configured in Core.initialize()."
14738
+ throw new CorePackageError(
14739
+ "Storage service not available. Ensure storage is configured in Core.initialize().",
14740
+ ERROR_CODES.CORE_PROVIDER_INITIALIZATION_FAILED
14712
14741
  );
14713
14742
  }
14714
14743
  const storage = this.storageService.getStorage();
@@ -14749,8 +14778,9 @@ var BackendFilesDomainService = class _BackendFilesDomainService extends BaseBac
14749
14778
  try {
14750
14779
  await this.beforeGetSignedUrl?.(params);
14751
14780
  if (!this.storageService) {
14752
- throw new Error(
14753
- "Storage service not available. Ensure storage is configured in Core.initialize()."
14781
+ throw new CorePackageError(
14782
+ "Storage service not available. Ensure storage is configured in Core.initialize().",
14783
+ ERROR_CODES.CORE_PROVIDER_INITIALIZATION_FAILED
14754
14784
  );
14755
14785
  }
14756
14786
  const storage = this.storageService.getStorage();
@@ -16958,7 +16988,6 @@ __export(frontend_exports, {
16958
16988
  useHasService: () => useHasService,
16959
16989
  usePlyaz: () => usePlyaz,
16960
16990
  usePlyazReady: () => usePlyazReady,
16961
- useRootStore: () => useRootStore,
16962
16991
  useService: () => useService,
16963
16992
  useServiceAsync: () => useServiceAsync,
16964
16993
  useServiceKeys: () => useServiceKeys,
@@ -17139,22 +17168,27 @@ async function initializeCore(config) {
17139
17168
  });
17140
17169
  }
17141
17170
  __name(initializeCore, "initializeCore");
17142
- function createStoreRegistry() {
17171
+ function createStoreRegistry(store) {
17143
17172
  return {
17144
17173
  getStore(key) {
17145
- const state = useRootStore.getState();
17174
+ const state = store.getState();
17146
17175
  if (!state) {
17147
17176
  logger8.warn(
17148
17177
  "Store state is undefined - store may not be hydrated yet. This can cause side effects if called during SSR or before initialization."
17149
17178
  );
17150
17179
  return void 0;
17151
17180
  }
17152
- return state[key];
17181
+ const slice = state[key];
17182
+ logger8.debug(`[StoreRegistry] getStore('${key}')`, {
17183
+ hasSlice: !!slice,
17184
+ sliceKeys: slice ? Object.keys(slice) : []
17185
+ });
17186
+ return slice;
17153
17187
  }
17154
17188
  };
17155
17189
  }
17156
17190
  __name(createStoreRegistry, "createStoreRegistry");
17157
- async function initializeServices(config) {
17191
+ async function initializeServices(config, store) {
17158
17192
  if (!config.services || config.services.length === 0) return;
17159
17193
  if (config.verbose) {
17160
17194
  globalThis.console.log("[PlyazProvider] Initializing domain services...");
@@ -17166,7 +17200,7 @@ async function initializeServices(config) {
17166
17200
  observability: config.observability,
17167
17201
  services: config.services,
17168
17202
  // Provide store registry for injecting stores into services
17169
- stores: createStoreRegistry()
17203
+ stores: createStoreRegistry(store)
17170
17204
  });
17171
17205
  if (config.verbose) {
17172
17206
  globalThis.console.log(
@@ -17203,6 +17237,7 @@ function createServicesObject(config, featureFlagStore) {
17203
17237
  __name(createServicesObject, "createServicesObject");
17204
17238
  function PlyazProvider({
17205
17239
  children,
17240
+ store,
17206
17241
  config,
17207
17242
  loading,
17208
17243
  error: errorComponent,
@@ -17216,8 +17251,9 @@ function PlyazProvider({
17216
17251
  const initialize = useCallback(async () => {
17217
17252
  try {
17218
17253
  setError(null);
17254
+ Core.setRootStoreHook(store);
17219
17255
  await initializeCore(config);
17220
- await initializeServices(config);
17256
+ await initializeServices(config, store);
17221
17257
  await initializeFeatureFlags(featureFlagStore);
17222
17258
  setIsReady(true);
17223
17259
  onReady?.(createServicesObject(config, featureFlagStore));
@@ -17227,7 +17263,7 @@ function PlyazProvider({
17227
17263
  onError?.(initError);
17228
17264
  globalThis.console.error("[PlyazProvider] Initialization failed:", initError);
17229
17265
  }
17230
- }, [config, featureFlagStore, onReady, onError]);
17266
+ }, [config, store, featureFlagStore, onReady, onError]);
17231
17267
  const reinitialize = useCallback(async () => {
17232
17268
  setIsReady(false);
17233
17269
  ServiceRegistry.disposeAll();
@@ -17276,8 +17312,9 @@ __name(PlyazProvider, "PlyazProvider");
17276
17312
  function usePlyaz() {
17277
17313
  const context = useContext(PlyazContext);
17278
17314
  if (!context) {
17279
- throw new Error(
17280
- "usePlyaz must be used within a PlyazProvider. Wrap your app with <PlyazProvider config={...}>...</PlyazProvider>"
17315
+ throw new CorePackageError(
17316
+ "usePlyaz must be used within a PlyazProvider. Wrap your app with <PlyazProvider config={...}>...</PlyazProvider>",
17317
+ ERROR_CODES.CORE_PROVIDER_NOT_FOUND
17281
17318
  );
17282
17319
  }
17283
17320
  return context;
@@ -17286,7 +17323,10 @@ __name(usePlyaz, "usePlyaz");
17286
17323
  function useApi() {
17287
17324
  const { api, isReady } = usePlyaz();
17288
17325
  if (!isReady || !api) {
17289
- throw new Error("API client is not ready. Make sure PlyazProvider has finished initializing.");
17326
+ throw new CorePackageError(
17327
+ "API client is not ready. Make sure PlyazProvider has finished initializing.",
17328
+ ERROR_CODES.CORE_PROVIDER_INITIALIZATION_FAILED
17329
+ );
17290
17330
  }
17291
17331
  return api;
17292
17332
  }
@@ -17329,7 +17369,10 @@ __name(useEnvironment, "useEnvironment");
17329
17369
  function useService(key) {
17330
17370
  const { getService, isReady } = usePlyaz();
17331
17371
  if (!isReady) {
17332
- throw new Error(`PlyazProvider not ready. Cannot get service '${key}'.`);
17372
+ throw new CorePackageError(
17373
+ `PlyazProvider not ready. Cannot get service '${key}'.`,
17374
+ ERROR_CODES.CORE_PROVIDER_INITIALIZATION_FAILED
17375
+ );
17333
17376
  }
17334
17377
  return useMemo(() => getService(key), [getService, key]);
17335
17378
  }