@weaverse/hydrogen 5.7.1 → 5.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/dist/index.d.mts CHANGED
@@ -74,7 +74,92 @@ declare class WeaverseClient {
74
74
  env: WeaverseClientArgs['env'];
75
75
  cache: WeaverseClientArgs['cache'];
76
76
  waitUntil: WeaverseClientArgs['waitUntil'];
77
+ private readonly parsedUrl;
78
+ private readonly componentsByType;
79
+ private readonly fetchTimeoutMs;
77
80
  constructor(args: WeaverseClientArgs);
81
+ /**
82
+ * Initialize Hydrogen cache with proper configuration.
83
+ * Logs warning if waitUntil is missing.
84
+ */
85
+ private initializeCache;
86
+ /**
87
+ * Initialize configs with projectId resolution and fail-fast validation.
88
+ * Throws WeaverseError if projectId cannot be resolved.
89
+ */
90
+ private initializeConfigs;
91
+ /**
92
+ * Build component lookup map for O(1) access by type.
93
+ * Significantly improves performance for large component lists.
94
+ */
95
+ private buildComponentLookupMap;
96
+ /**
97
+ * Extract comprehensive error information from unknown error type.
98
+ * Preserves error context, codes, and stack traces for debugging.
99
+ *
100
+ * @param error - Unknown error to extract information from
101
+ * @returns Structured error information with message, code, stack, and context
102
+ *
103
+ * @example
104
+ * ```typescript
105
+ * try {
106
+ * // ... operation
107
+ * } catch (error) {
108
+ * const errorInfo = this.extractErrorInfo(error)
109
+ * console.error('Operation failed:', errorInfo.message, errorInfo.context)
110
+ * }
111
+ * ```
112
+ */
113
+ private extractErrorInfo;
114
+ /**
115
+ * Extract error message only (for backward compatibility).
116
+ * Use extractErrorInfo() for more detailed error information.
117
+ *
118
+ * @deprecated Use extractErrorInfo() instead to preserve error context
119
+ */
120
+ private extractErrorMessage;
121
+ /**
122
+ * Validates projectId format (alphanumeric, hyphens, underscores only).
123
+ * Returns detailed validation result with error message.
124
+ *
125
+ * @param projectId - Project identifier to validate
126
+ * @returns Validation result with error message if invalid
127
+ */
128
+ private validateProjectId;
129
+ /**
130
+ * Resolves projectId with multi-project architecture support.
131
+ * Uses priority chain to determine the correct project ID.
132
+ *
133
+ * @param projectId - Project identifier (string, function, or undefined)
134
+ * @param request - HTTP request for context access
135
+ * @param env - Hydrogen environment with variables
136
+ * @param baseConfigs - Pre-fetched base configs to avoid duplicate calls
137
+ * @returns Resolved project ID string (empty string if none found)
138
+ */
139
+ private resolveProjectIdSync;
140
+ /**
141
+ * Priority 1: Resolve projectId from URL query parameters.
142
+ * Used for design mode and preview mode overrides.
143
+ */
144
+ private resolveFromQueryParams;
145
+ /**
146
+ * Priority 2: Resolve projectId from function parameter.
147
+ * Detects and rejects async functions with helpful error.
148
+ */
149
+ private resolveFromFunction;
150
+ /**
151
+ * Priority 3: Resolve projectId from explicit string parameter.
152
+ */
153
+ private resolveFromString;
154
+ /**
155
+ * Priority 4: Resolve projectId from environment variables.
156
+ */
157
+ private resolveFromEnvironment;
158
+ /**
159
+ * Helper method for direct fetching in design mode.
160
+ * Returns same format as withCache.fetch for consistency.
161
+ * Includes 10-second timeout to prevent hanging requests.
162
+ */
78
163
  private readonly directFetch;
79
164
  private isLocalhost;
80
165
  private getApiUrl;
@@ -83,12 +168,7 @@ declare class WeaverseClient {
83
168
  }) => Promise<T>;
84
169
  loadThemeSettings: (strategy?: AllCacheOptions) => Promise<ThemeSettingsResponse>;
85
170
  generateFallbackPage: (message: string) => HydrogenPageData;
86
- loadPage: (params?: {
87
- type?: PageType;
88
- locale?: string;
89
- handle?: string;
90
- strategy?: AllCacheOptions;
91
- }) => Promise<WeaverseLoaderData | null>;
171
+ loadPage: (params?: LoadPageParams) => Promise<WeaverseLoaderData | null>;
92
172
  execComponentLoader: (item: HydrogenComponentData) => Promise<HydrogenComponentData>;
93
173
  }
94
174
 
@@ -221,7 +301,7 @@ type WeaverseLoaderData = {
221
301
  };
222
302
  page: HydrogenPageData;
223
303
  project: HydrogenProjectType;
224
- pageAssignment: HydrogenPageAssignment;
304
+ pageAssignment?: HydrogenPageAssignment;
225
305
  };
226
306
  interface HydrogenPageData extends WeaverseProjectDataType {
227
307
  id: string;
@@ -271,11 +351,131 @@ type FetchProjectPayload = {
271
351
  error?: string;
272
352
  [key: string]: any;
273
353
  };
354
+ /**
355
+ * Project identifier value - can be static string or dynamic function.
356
+ *
357
+ * **Static String**: Direct project ID reference
358
+ * ```ts
359
+ * 'project-abc-123'
360
+ * ```
361
+ *
362
+ * **Synchronous Function**: Returns project ID based on request context
363
+ * ```ts
364
+ * () => {
365
+ * const host = new URL(request.url).hostname
366
+ * return PROJECT_MAP[host] || 'default-project'
367
+ * }
368
+ * ```
369
+ *
370
+ * **Asynchronous Function**: Async project resolution (must be awaited before passing)
371
+ * ```ts
372
+ * async () => {
373
+ * return await database.getProjectId(userId)
374
+ * }
375
+ * ```
376
+ */
377
+ type ProjectIdValue = string | (() => string) | (() => Promise<string>);
378
+ /**
379
+ * Type guard for detecting function-based projectId.
380
+ *
381
+ * Used internally by WeaverseClient constructor to determine
382
+ * if projectId needs evaluation or can be used directly.
383
+ */
384
+ declare function isProjectIdFunction(projectId: ProjectIdValue | undefined): projectId is (() => string) | (() => Promise<string>);
385
+ /**
386
+ * Extended WeaverseClient constructor arguments supporting multi-project architecture.
387
+ *
388
+ * @example Static project (existing pattern - backward compatible)
389
+ * ```ts
390
+ * const weaverse = new WeaverseClient({
391
+ * ...hydrogenContext,
392
+ * projectId: 'project-default-123'
393
+ * })
394
+ * ```
395
+ *
396
+ * @example Dynamic project selection (new capability)
397
+ * ```ts
398
+ * const weaverse = new WeaverseClient({
399
+ * ...hydrogenContext,
400
+ * projectId: () => {
401
+ * const origin = new URL(request.url).origin
402
+ * if (origin === 'https://mystore.se') return process.env.WEAVERSE_PROJECT_SWEDEN!
403
+ * if (origin === 'https://mystore.fr') return process.env.WEAVERSE_PROJECT_FRANCE!
404
+ * return process.env.WEAVERSE_PROJECT_ID!
405
+ * }
406
+ * })
407
+ * ```
408
+ *
409
+ * **Priority Chain** (highest to lowest):
410
+ * 1. URL query parameter: `?weaverseProjectId=...` (design mode, preview mode)
411
+ * 2. Function result (if function provided)
412
+ * 3. Explicit string value (if string provided)
413
+ * 4. Environment variable: `WEAVERSE_PROJECT_ID` (Hydrogen env or process.env)
414
+ * 5. Empty string (triggers validation error in methods)
415
+ *
416
+ * **Function Requirements**:
417
+ * - Must return non-empty string
418
+ * - Can access request via closure for routing decisions
419
+ * - Evaluated once per WeaverseClient instance (request-scoped)
420
+ * - Async functions must be awaited before passing to constructor
421
+ * - Should handle edge cases (missing headers, invalid domains, etc.)
422
+ *
423
+ * **Request Context Access**:
424
+ * Functions access request via closure from constructor arguments.
425
+ */
274
426
  type WeaverseClientArgs = HydrogenContext & {
427
+ /**
428
+ * React components registered with Weaverse CMS.
429
+ * Each component must have a schema defining its properties and settings.
430
+ */
275
431
  components: HydrogenComponent[];
432
+ /**
433
+ * Theme schema defining global theme settings (colors, fonts, layouts).
434
+ * Used to generate default theme configuration and validate theme data.
435
+ */
276
436
  themeSchema: HydrogenThemeSchema;
437
+ /**
438
+ * Incoming HTTP request object from React Router loader.
439
+ * Provides access to URL, headers, cookies for dynamic routing decisions.
440
+ */
277
441
  request: Request;
442
+ /**
443
+ * Hydrogen cache instance for content caching.
444
+ *Supports multi-tenant caching with project-specific cache keys.
445
+ */
278
446
  cache: Cache;
447
+ /**
448
+ * Project identifier for loading content from Weaverse CMS.
449
+ *
450
+ * **Value Types**:
451
+ * - Static string: 'project-123' (existing usage)
452
+ * - Synchronous function: () => determineProject(request)
453
+ * - Asynchronous function: async () => await getProject(request) (must be awaited)
454
+ *
455
+ * **Backward Compatibility**:
456
+ * - Optional parameter (defaults to environment variable)
457
+ * - Existing code without projectId continues to work unchanged
458
+ *
459
+ * **Cache Isolation**:
460
+ * ProjectId is included in cache keys to prevent cross-project content pollution.
461
+ * Each project's content is cached separately, ensuring multi-tenant isolation.
462
+ */
463
+ projectId?: ProjectIdValue;
464
+ /**
465
+ * Fetch timeout in milliseconds for API requests.
466
+ * Defaults to 10000ms (10 seconds) if not specified.
467
+ * Useful for adjusting based on network conditions or deployment environment.
468
+ *
469
+ * @default 10000
470
+ * @example
471
+ * ```typescript
472
+ * new WeaverseClient({
473
+ * // ... other args
474
+ * fetchTimeoutMs: 5000 // 5 second timeout
475
+ * })
476
+ * ```
477
+ */
478
+ fetchTimeoutMs?: number;
279
479
  };
280
480
  type WeaverseProduct = WeaverseResourcePickerData;
281
481
  type WeaverseCollection = WeaverseResourcePickerData;
@@ -293,6 +493,8 @@ type ThemeSettingsResponse = {
293
493
  theme?: HydrogenThemeSettings;
294
494
  schema?: HydrogenThemeSchema;
295
495
  publicEnv?: PublicEnv;
496
+ _error?: string;
497
+ _loadFailed?: boolean;
296
498
  };
297
499
  type DirectFetchResponse<T = unknown> = {
298
500
  data?: T;
@@ -305,6 +507,14 @@ declare class WeaverseError extends Error {
305
507
  readonly context?: Record<string, unknown>;
306
508
  constructor(message: string, code?: string, statusCode?: number, context?: Record<string, unknown>);
307
509
  }
510
+ /**
511
+ * Validation result type for project ID validation.
512
+ * Returns validation status with optional error message.
513
+ */
514
+ type ProjectIdValidationResult = {
515
+ valid: boolean;
516
+ error?: string;
517
+ };
308
518
  /**
309
519
  * Type guards for response validation
310
520
  */
@@ -319,7 +529,20 @@ declare function isThemeSettingsResponse(data: unknown): data is ThemeSettingsRe
319
529
  */
320
530
  type HydrogenSchemaValidationResult = SchemaValidationResult<HydrogenComponentSchema>;
321
531
  /**
322
- * Type guard to check if a schema is valid
532
+ * Type guard to check if a schema is valid.
533
+ * Leverages validation from @weaverse/schema package which provides
534
+ * comprehensive Zod-based validation with the ElementSchema.
535
+ *
536
+ * @param schema - Unknown value to validate
537
+ * @returns True if schema is a valid HydrogenComponentSchema
538
+ *
539
+ * @example
540
+ * ```typescript
541
+ * if (isValidHydrogenSchema(userInput)) {
542
+ * // userInput is now typed as HydrogenComponentSchema
543
+ * console.log(userInput.type)
544
+ * }
545
+ * ```
323
546
  */
324
547
  declare function isValidHydrogenSchema(schema: unknown): schema is HydrogenComponentSchema;
325
548
  /**
@@ -370,6 +593,101 @@ declare module '@shopify/hydrogen' {
370
593
  PUBLIC_SHOPIFY_INBOX_SHOP_ID: string;
371
594
  }
372
595
  }
596
+ /**
597
+ * Parameters for loadPage method supporting route-level project override.
598
+ *
599
+ * @example Basic usage (uses client-level project)
600
+ * ```ts
601
+ * const weaverseData = await weaverse.loadPage({
602
+ * type: 'PRODUCT',
603
+ * handle: params.productHandle
604
+ * })
605
+ * ```
606
+ *
607
+ * @example Route-level project override
608
+ * ```ts
609
+ * export async function loader({ params, context }: LoaderFunctionArgs) {
610
+ * const { weaverse } = context
611
+ *
612
+ * // Use special campaign project for this route only
613
+ * const weaverseData = await weaverse.loadPage({
614
+ * type: 'PRODUCT',
615
+ * handle: params.productHandle,
616
+ * projectId: process.env.WEAVERSE_PROJECT_CAMPAIGN // Override
617
+ * })
618
+ *
619
+ * return { weaverseData }
620
+ * }
621
+ * ```
622
+ */
623
+ type LoadPageParams = {
624
+ /**
625
+ * Page type to load from Weaverse CMS.
626
+ *
627
+ * Determines which template to use for rendering the page.
628
+ * Falls back to 'INDEX' if not specified or if page type doesn't exist.
629
+ *
630
+ * @default 'INDEX'
631
+ */
632
+ type?: PageType;
633
+ /**
634
+ * Locale for internationalization.
635
+ *
636
+ * Format: IETF BCP 47 language tag (e.g., 'en-US', 'fr-FR', 'de-DE')
637
+ * Used to load locale-specific content and translations.
638
+ */
639
+ locale?: string;
640
+ /**
641
+ * Page handle for dynamic pages.
642
+ *
643
+ * Identifies specific resource within page type:
644
+ * - Product handle: 'red-sneakers'
645
+ * - Collection handle: 'summer-sale'
646
+ * - Page handle: 'about-us'
647
+ * - Article handle: 'how-to-style-sneakers'
648
+ */
649
+ handle?: string;
650
+ /**
651
+ * Cache strategy override for this specific page load.
652
+ *
653
+ * Overrides default cache strategy for special use cases:
654
+ * - Fresh content for checkout pages (no cache)
655
+ * - Long-lived cache for static pages (1 hour+)
656
+ * - Short-lived cache for frequently updated content (5 minutes)
657
+ */
658
+ strategy?: AllCacheOptions;
659
+ /**
660
+ * Optional project override for this specific page load.
661
+ *
662
+ * **Precedence**: Route-level projectId takes precedence over client-level projectId.
663
+ *
664
+ * **Use Cases**:
665
+ * - Campaign landing pages with custom content
666
+ * - VIP customer experiences with dedicated projects
667
+ * - A/B testing specific pages without changing global config
668
+ * - Seasonal promotions with limited-time content
669
+ *
670
+ * **Validation**:
671
+ * - Must be non-empty string
672
+ * - Validated before API call
673
+ * - Falls back to client-level projectId if undefined
674
+ * - Does NOT support function (string only)
675
+ *
676
+ * **Cache Isolation**:
677
+ * Override projectId is included in cache key, ensuring separate caches
678
+ * for different projects even on the same route.
679
+ *
680
+ * @example Campaign page override
681
+ * ```ts
682
+ * const campaignData = await weaverse.loadPage({
683
+ * type: 'PAGE',
684
+ * handle: 'summer-sale',
685
+ * projectId: process.env.WEAVERSE_PROJECT_CAMPAIGN
686
+ * })
687
+ * ```
688
+ */
689
+ projectId?: string;
690
+ };
373
691
 
374
692
  declare let defaultComponents: HydrogenComponent[];
375
693
 
@@ -390,8 +708,37 @@ declare function useWeaverseDataContext(): WeaverseDataContext;
390
708
  */
391
709
  declare function createWeaverseDataContext(matches: UIMatch<unknown, unknown>[]): WeaverseDataContext;
392
710
 
393
- declare function getRequestQueries<T = Record<string, string | boolean>>(request: Request): T;
711
+ /**
712
+ * Extract and parse query parameters from a request URL.
713
+ * Supports optional allowlist for security-sensitive applications.
714
+ *
715
+ * @param request - The incoming request
716
+ * @param options - Optional configuration
717
+ * @param options.allowedKeys - If provided, only these keys will be extracted
718
+ * @returns Parsed query parameters with type coercion for booleans
719
+ *
720
+ * @example
721
+ * ```typescript
722
+ * // Extract all params
723
+ * const queries = getRequestQueries(request)
724
+ *
725
+ * // Extract only allowed params (security-sensitive)
726
+ * const queries = getRequestQueries(request, {
727
+ * allowedKeys: ['weaverseProjectId', 'weaverseHost']
728
+ * })
729
+ * ```
730
+ */
731
+ declare function getRequestQueries<T = Record<string, string | boolean>>(request: Request, options?: {
732
+ allowedKeys?: string[];
733
+ }): T;
394
734
  declare function getWeaverseConfigs(request: Request, env: HydrogenEnv): WeaverseProjectConfigs;
735
+ /**
736
+ * Generate default data from component or theme schema.
737
+ * Results are memoized using WeakMap for performance.
738
+ *
739
+ * @param schema - Component or theme schema
740
+ * @returns Default data object extracted from schema inputs
741
+ */
395
742
  declare function generateDataFromSchema(schema: HydrogenComponentSchema | HydrogenThemeSchema): Record<string, any>;
396
743
  declare function getPreviewData(type: string, components: HydrogenComponent[], weaverseHost: string): WeaverseLoaderData;
397
744
 
@@ -428,4 +775,4 @@ declare const IMAGES_PLACEHOLDERS: {
428
775
  product_18: string;
429
776
  };
430
777
 
431
- export { type AllCacheOptions, type CacheResponseValidator, type ComponentLoaderArgs, type CreateHydrogenSchemaOptions, type DirectFetchResponse, type FetchProjectPayload, type FetchProjectRequestBody, type HydrogenComponent, type HydrogenComponentData, type HydrogenComponentPresets, type HydrogenComponentProps, type HydrogenComponentSchema, type HydrogenElement, type HydrogenPageAssignment, type HydrogenPageData, type HydrogenProjectType, type HydrogenSchemaValidationResult, type HydrogenThemeSchema, type HydrogenThemeSettings, IMAGES_PLACEHOLDERS, type PublicEnv, type RouteLoaderArgs, type ThemeSettingsResponse, type WeaverseArticle, type WeaverseBlog, WeaverseClient, type WeaverseClientArgs, type WeaverseCollection, type WeaverseDataContext, WeaverseError, WeaverseHydrogen, WeaverseHydrogenItem, type WeaverseHydrogenParams, WeaverseHydrogenRoot, type WeaverseI18n, type WeaverseInternal, type WeaverseLoaderData, type WeaverseLoaderRequestInfo, type WeaverseMetaObject, type WeaverseProduct, type WeaverseProjectConfigs, type WeaverseStudioQueries, type WithCacheFetchResponse, createWeaverseDataContext, defaultComponents, generateDataFromSchema, getPreviewData, getRequestQueries, getSelectedProductOptions, getWeaverseConfigs, hasError, isFetchProjectPayload, isThemeSettingsResponse, isValidHydrogenSchema, isWithCacheFetchResponse, registerComponent, useThemeSettings, useWeaverseDataContext, withWeaverse };
778
+ export { type AllCacheOptions, type CacheResponseValidator, type ComponentLoaderArgs, type CreateHydrogenSchemaOptions, type DirectFetchResponse, type FetchProjectPayload, type FetchProjectRequestBody, type HydrogenComponent, type HydrogenComponentData, type HydrogenComponentPresets, type HydrogenComponentProps, type HydrogenComponentSchema, type HydrogenElement, type HydrogenPageAssignment, type HydrogenPageData, type HydrogenProjectType, type HydrogenSchemaValidationResult, type HydrogenThemeSchema, type HydrogenThemeSettings, IMAGES_PLACEHOLDERS, type LoadPageParams, type ProjectIdValidationResult, type ProjectIdValue, type PublicEnv, type RouteLoaderArgs, type ThemeSettingsResponse, type WeaverseArticle, type WeaverseBlog, WeaverseClient, type WeaverseClientArgs, type WeaverseCollection, type WeaverseDataContext, WeaverseError, WeaverseHydrogen, WeaverseHydrogenItem, type WeaverseHydrogenParams, WeaverseHydrogenRoot, type WeaverseI18n, type WeaverseInternal, type WeaverseLoaderData, type WeaverseLoaderRequestInfo, type WeaverseMetaObject, type WeaverseProduct, type WeaverseProjectConfigs, type WeaverseStudioQueries, type WithCacheFetchResponse, createWeaverseDataContext, defaultComponents, generateDataFromSchema, getPreviewData, getRequestQueries, getSelectedProductOptions, getWeaverseConfigs, hasError, isFetchProjectPayload, isProjectIdFunction, isThemeSettingsResponse, isValidHydrogenSchema, isWithCacheFetchResponse, registerComponent, useThemeSettings, useWeaverseDataContext, withWeaverse };