@joy-loyalty/hydrogen 0.0.0-stage → 0.2.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.
Files changed (127) hide show
  1. package/LICENSE +3 -0
  2. package/README.md +134 -2
  3. package/dist/cache-control.d.ts +8 -0
  4. package/dist/cache-control.js +6 -0
  5. package/dist/csp.d.ts +14 -0
  6. package/dist/csp.js +33 -0
  7. package/dist/headless-host-adapter.d.ts +5 -0
  8. package/dist/headless-host-adapter.js +198 -0
  9. package/dist/host-adapter/capabilities.d.ts +4 -0
  10. package/dist/host-adapter/capabilities.js +15 -0
  11. package/dist/host-adapter/data-source.d.ts +3 -0
  12. package/dist/host-adapter/data-source.js +49 -0
  13. package/dist/host-adapter/product-fetcher.d.ts +2 -0
  14. package/dist/host-adapter/product-fetcher.js +38 -0
  15. package/dist/host-adapter/promoted-collections.d.ts +2 -0
  16. package/dist/host-adapter/promoted-collections.js +44 -0
  17. package/dist/host-adapter/types.d.ts +212 -0
  18. package/dist/host-adapter/types.js +1 -0
  19. package/dist/hydrogen-cart-port.d.ts +134 -0
  20. package/dist/hydrogen-cart-port.js +245 -0
  21. package/dist/index.d.ts +26 -0
  22. package/dist/index.js +15 -0
  23. package/dist/joy-widget.d.ts +29 -0
  24. package/dist/joy-widget.js +291 -0
  25. package/dist/lib/JoyProvider.d.ts +47 -0
  26. package/dist/lib/JoyProvider.js +95 -0
  27. package/dist/lib/account-links.d.ts +5 -0
  28. package/dist/lib/account-links.js +65 -0
  29. package/dist/lib/apply-behavior.d.ts +12 -0
  30. package/dist/lib/apply-behavior.js +26 -0
  31. package/dist/lib/core-loader.d.ts +63 -0
  32. package/dist/lib/core-loader.js +160 -0
  33. package/dist/lib/core-manifest.d.ts +7 -0
  34. package/dist/lib/core-manifest.js +54 -0
  35. package/dist/lib/core-preload-links.d.ts +8 -0
  36. package/dist/lib/core-preload-links.js +8 -0
  37. package/dist/lib/coupon-mapper.d.ts +95 -0
  38. package/dist/lib/coupon-mapper.js +167 -0
  39. package/dist/lib/custom-links.d.ts +22 -0
  40. package/dist/lib/custom-links.js +56 -0
  41. package/dist/lib/deeplink.d.ts +25 -0
  42. package/dist/lib/deeplink.js +92 -0
  43. package/dist/lib/earn-signup-gate.d.ts +3 -0
  44. package/dist/lib/earn-signup-gate.js +31 -0
  45. package/dist/lib/facebook-ref-link.d.ts +13 -0
  46. package/dist/lib/facebook-ref-link.js +31 -0
  47. package/dist/lib/headless-referral-origin.d.ts +2 -0
  48. package/dist/lib/headless-referral-origin.js +24 -0
  49. package/dist/lib/headless-source.d.ts +8 -0
  50. package/dist/lib/headless-source.js +71 -0
  51. package/dist/lib/image.d.ts +2 -0
  52. package/dist/lib/image.js +14 -0
  53. package/dist/lib/metafield-blob.d.ts +33 -0
  54. package/dist/lib/metafield-blob.js +76 -0
  55. package/dist/lib/money.d.ts +6 -0
  56. package/dist/lib/money.js +25 -0
  57. package/dist/lib/order-mapper.d.ts +44 -0
  58. package/dist/lib/order-mapper.js +141 -0
  59. package/dist/lib/place-order-scope.d.ts +6 -0
  60. package/dist/lib/place-order-scope.js +22 -0
  61. package/dist/lib/points.d.ts +5 -0
  62. package/dist/lib/points.js +10 -0
  63. package/dist/lib/recently-viewed-tracker.d.ts +1 -0
  64. package/dist/lib/recently-viewed-tracker.js +34 -0
  65. package/dist/lib/recommended-loader.d.ts +44 -0
  66. package/dist/lib/recommended-loader.js +113 -0
  67. package/dist/lib/referral-share.d.ts +4 -0
  68. package/dist/lib/referral-share.js +33 -0
  69. package/dist/lib/safe-navigation-url.d.ts +1 -0
  70. package/dist/lib/safe-navigation-url.js +9 -0
  71. package/dist/lib/server-token.d.ts +41 -0
  72. package/dist/lib/server-token.js +87 -0
  73. package/dist/lib/shop-locale.d.ts +1 -0
  74. package/dist/lib/shop-locale.js +21 -0
  75. package/dist/lib/social-earn.d.ts +11 -0
  76. package/dist/lib/social-earn.js +25 -0
  77. package/dist/lib/storefront-fonts.d.ts +5 -0
  78. package/dist/lib/storefront-fonts.js +52 -0
  79. package/dist/lib/token.d.ts +14 -0
  80. package/dist/lib/token.js +135 -0
  81. package/dist/lib/write-review.d.ts +2 -0
  82. package/dist/lib/write-review.js +44 -0
  83. package/dist/loyalty-page/JoyLoyaltyPage.d.ts +151 -0
  84. package/dist/loyalty-page/JoyLoyaltyPage.js +447 -0
  85. package/dist/loyalty-page/compose-home.d.ts +35 -0
  86. package/dist/loyalty-page/compose-home.js +177 -0
  87. package/dist/loyalty-page/skeleton.d.ts +11 -0
  88. package/dist/loyalty-page/skeleton.js +99 -0
  89. package/dist/orchestrator/context.d.ts +61 -0
  90. package/dist/orchestrator/context.js +64 -0
  91. package/dist/orchestrator/gated.d.ts +1 -0
  92. package/dist/orchestrator/gated.js +14 -0
  93. package/dist/orchestrator/handlers/account.d.ts +19 -0
  94. package/dist/orchestrator/handlers/account.js +266 -0
  95. package/dist/orchestrator/handlers/birthday.d.ts +6 -0
  96. package/dist/orchestrator/handlers/birthday.js +128 -0
  97. package/dist/orchestrator/handlers/earn.d.ts +5 -0
  98. package/dist/orchestrator/handlers/earn.js +267 -0
  99. package/dist/orchestrator/handlers/milestone-tier.d.ts +5 -0
  100. package/dist/orchestrator/handlers/milestone-tier.js +123 -0
  101. package/dist/orchestrator/handlers/profile.d.ts +5 -0
  102. package/dist/orchestrator/handlers/profile.js +262 -0
  103. package/dist/orchestrator/handlers/redeem.d.ts +6 -0
  104. package/dist/orchestrator/handlers/redeem.js +464 -0
  105. package/dist/orchestrator/handlers/referral.d.ts +5 -0
  106. package/dist/orchestrator/handlers/referral.js +218 -0
  107. package/dist/orchestrator/render.d.ts +2 -0
  108. package/dist/orchestrator/render.js +193 -0
  109. package/dist/render-adapter.d.ts +50 -0
  110. package/dist/render-adapter.js +422 -0
  111. package/dist/routes/joy-place-order-scope.d.ts +12 -0
  112. package/dist/routes/joy-place-order-scope.js +32 -0
  113. package/dist/routes/joy-products.d.ts +48 -0
  114. package/dist/routes/joy-products.js +338 -0
  115. package/dist/routes/joy-token.d.ts +16 -0
  116. package/dist/routes/joy-token.js +32 -0
  117. package/dist/server/get-joy-initial-data.d.ts +39 -0
  118. package/dist/server/get-joy-initial-data.js +65 -0
  119. package/dist/server/get-joy-loyalty-page-data.d.ts +28 -0
  120. package/dist/server/get-joy-loyalty-page-data.js +99 -0
  121. package/dist/server/index.d.ts +8 -0
  122. package/dist/server/index.js +4 -0
  123. package/dist/widget-controller.d.ts +2 -0
  124. package/dist/widget-controller.js +1 -0
  125. package/dist/widget-orchestrator.d.ts +89 -0
  126. package/dist/widget-orchestrator.js +504 -0
  127. package/package.json +121 -4
@@ -0,0 +1,193 @@
1
+ import { markEarnSignupSent, shouldSendEarnSignup } from '../lib/earn-signup-gate.js';
2
+ import { GUEST_INFO_SKIP } from '../lib/token.js';
3
+ import { buildHeadlessRenderProps, mergeInfoIntoBlob, resolveActiveTranslation, resolveContentLocale } from '../render-adapter.js';
4
+ import { buildProps, readCachedReferralLink, writeProps } from '../widget-orchestrator.js';
5
+ export function attachRenderCore(ctx) {
6
+ function buildRenderContext() {
7
+ const context = ctx.hostAdapter.context();
8
+ const locale = context.locale ?? ctx.initialData?.locale;
9
+ return {
10
+ login_url: ctx.initialData?.login_url ?? context.loginUrl,
11
+ register_url: ctx.initialData?.register_url ?? context.registerUrl,
12
+ account_url: ctx.initialData?.account_url ?? context.accountUrl,
13
+ page: ctx.initialData?.page ?? context.page,
14
+ locale,
15
+ contentLocale: context.contentLocale ?? resolveContentLocale(locale, ctx.activeBlob?.translation),
16
+ currency: context.currency,
17
+ currencyRate: context.currencyRate,
18
+ debug: context.debug,
19
+ viewport: context.viewport
20
+ };
21
+ }
22
+ function buildBlobProps(customer) {
23
+ return buildHeadlessRenderProps({
24
+ blob: ctx.activeBlob,
25
+ customer,
26
+ shopifyCustomer: ctx.initialData?.shopifyCustomer,
27
+ context: ctx.renderContext,
28
+ coreExports: ctx.coreExports
29
+ });
30
+ }
31
+ function applyStylePreset() {
32
+ const theme = ctx.activeBlob?.settings?.theme;
33
+ const style = theme?.style || 'default';
34
+ if (style !== 'default') {
35
+ document.documentElement.setAttribute('data-joy-style', style);
36
+ }
37
+ else {
38
+ document.documentElement.removeAttribute('data-joy-style');
39
+ }
40
+ }
41
+ function surface(work) {
42
+ work.catch((error) => {
43
+ const message = error instanceof Error ? error.message : String(error);
44
+ ctx.element.dispatchEvent(new CustomEvent('joy-error', { bubbles: true, composed: true, detail: { message } }));
45
+ });
46
+ }
47
+ function render(customer, programs) {
48
+ applyStylePreset();
49
+ if (ctx.useBlobPath) {
50
+ writeProps(ctx.element, { ...buildBlobProps(customer), ...ctx.appearanceOverrides, ...ctx.capabilityProps, 'cached-referral-link': readCachedReferralLink() });
51
+ return;
52
+ }
53
+ writeProps(ctx.element, {
54
+ ...buildProps(customer, programs, ctx.initialData?.tiers),
55
+ ...ctx.appearanceProps,
56
+ ...ctx.capabilityProps,
57
+ 'cached-referral-link': readCachedReferralLink()
58
+ });
59
+ }
60
+ async function runBeatTwo() {
61
+ const scActive = !!ctx.element.storeCreditLoading;
62
+ const blobTranslation = ctx.activeBlob?.translation;
63
+ const primary = typeof blobTranslation?.primaryLanguage === 'string' ? blobTranslation.primaryLanguage : 'en';
64
+ const allowGuest = primary.toLowerCase() !== 'en' || !!resolveContentLocale(ctx.renderContext?.locale, blobTranslation);
65
+ const earnSignupKey = isAuthed() ? earnSignupCustomerKey() : null;
66
+ const earnSignup = !!earnSignupKey && shouldSendEarnSignup(earnSignupKey);
67
+ const infoParams = {
68
+ ...(scActive ? { includeStoreCredit: true } : {}),
69
+ ...(earnSignup ? { earnSignup: true } : {}),
70
+ ...(allowGuest ? { allowGuest } : {})
71
+ };
72
+ let info;
73
+ try {
74
+ info = (await ctx.hostAdapter.data.getInfo(Object.keys(infoParams).length ? infoParams : undefined));
75
+ }
76
+ catch (error) {
77
+ if (error instanceof Error && error.message === GUEST_INFO_SKIP)
78
+ return;
79
+ if (scActive)
80
+ writeProps(ctx.element, { 'store-credit-loading': false });
81
+ surface(Promise.reject(error));
82
+ return;
83
+ }
84
+ ctx.activeBlob = mergeInfoIntoBlob(ctx.activeBlob, info, ctx.renderContext.locale);
85
+ const infoCustomer = info.customer;
86
+ if (infoCustomer && typeof infoCustomer === 'object') {
87
+ ctx.activeCustomer = infoCustomer;
88
+ }
89
+ if (earnSignup && earnSignupKey && infoCustomer && typeof infoCustomer === 'object')
90
+ markEarnSignupSent(earnSignupKey);
91
+ await filterSpendingEligibility();
92
+ render(ctx.activeCustomer, []);
93
+ if (ctx.activeCustomer && typeof ctx.activeCustomer === 'object' && ctx.activeCustomer.id) {
94
+ if (scActive)
95
+ ctx.applyStoreCreditFromInfo(info);
96
+ if (!ctx.panelOpened && hasLoyaltyPageOnScreen()) {
97
+ ctx.preloadDeferred = true;
98
+ return;
99
+ }
100
+ loadCustomerSections();
101
+ }
102
+ }
103
+ function loadCustomerSections() {
104
+ ctx.preloadDeferred = false;
105
+ ctx.loadRewards();
106
+ ctx.loadActivities();
107
+ ctx.loadReferral();
108
+ ctx.loadImpactHistory();
109
+ ctx.loadMilestone();
110
+ ctx.loadTierPerks();
111
+ }
112
+ function hasLoyaltyPageOnScreen() {
113
+ return typeof document !== 'undefined' && !!document.querySelector('joy-loyalty-page-v2');
114
+ }
115
+ async function filterSpendingEligibility() {
116
+ const filter = ctx.coreExports?.checkProgramRedeemAvailabilitySegmentFE;
117
+ if (typeof filter !== 'function' || !ctx.useBlobPath)
118
+ return;
119
+ const program = ctx.activeBlob?.program;
120
+ if (!Array.isArray(program?.spending) || !program.spending.length)
121
+ return;
122
+ const hostContext = ctx.hostAdapter.context();
123
+ const shopifyCustomerId = ctx.activeCustomer?.shopifyCustomerId ??
124
+ hostContext.shopifyCustomerId;
125
+ program.spending = await filter({
126
+ shopId: hostContext.shopId ?? '',
127
+ programsSpending: program.spending,
128
+ shopifyCustomerId,
129
+ post: async (_path, body) => ({
130
+ success: true,
131
+ data: await ctx.hostAdapter.data.checkSegmentPrograms((body.segmentPrograms ?? []))
132
+ })
133
+ });
134
+ }
135
+ async function refresh() {
136
+ if (ctx.useBlobPath) {
137
+ await runBeatTwo();
138
+ return;
139
+ }
140
+ const [customerResult, programsResult] = await Promise.allSettled([
141
+ ctx.hostAdapter.data.getCustomer(),
142
+ ctx.hostAdapter.data.getPrograms()
143
+ ]);
144
+ if (typeof ctx.hostAdapter.data.getTiers === 'function')
145
+ void ctx.hostAdapter.data.getTiers().catch(() => undefined);
146
+ const customer = customerResult.status === 'fulfilled' ? customerResult.value : ctx.initialData?.customer;
147
+ const programs = programsResult.status === 'fulfilled' ? programsResult.value : ctx.initialData?.programs ?? [];
148
+ render(customer, programs);
149
+ }
150
+ function patchCustomer(fields) {
151
+ const base = (ctx.activeCustomer && typeof ctx.activeCustomer === 'object' ? ctx.activeCustomer : {});
152
+ const next = { ...base, ...fields };
153
+ ctx.activeCustomer = next;
154
+ return next;
155
+ }
156
+ function tLabel(english, vars) {
157
+ const translation = resolveActiveTranslation(ctx.activeBlob?.translation, ctx.renderContext?.locale);
158
+ let label = translation[`[[WidgetV4]]${english}`] || translation[english] || english;
159
+ if (vars) {
160
+ for (const [key, value] of Object.entries(vars))
161
+ label = label.replaceAll(`{{${key}}}`, value);
162
+ }
163
+ return label;
164
+ }
165
+ function toast(english, vars) {
166
+ ctx.element.showToast?.(tLabel(english, vars));
167
+ }
168
+ function earnSignupCustomerKey() {
169
+ const joyId = ctx.activeCustomer?.id;
170
+ if (joyId)
171
+ return String(joyId);
172
+ const shopifyId = ctx.initialData?.shopifyCustomer?.id;
173
+ return shopifyId ? `shopify:${String(shopifyId)}` : 'member';
174
+ }
175
+ function isAuthed() {
176
+ const c = ctx.activeCustomer;
177
+ if (c && typeof c === 'object' && c.id)
178
+ return true;
179
+ return ctx.hostAdapter.auth.getState().status === 'authenticated';
180
+ }
181
+ ctx.buildRenderContext = buildRenderContext;
182
+ ctx.buildBlobProps = buildBlobProps;
183
+ ctx.applyStylePreset = applyStylePreset;
184
+ ctx.surface = surface;
185
+ ctx.render = render;
186
+ ctx.runBeatTwo = runBeatTwo;
187
+ ctx.refresh = refresh;
188
+ ctx.loadCustomerSections = loadCustomerSections;
189
+ ctx.patchCustomer = patchCustomer;
190
+ ctx.tLabel = tLabel;
191
+ ctx.toast = toast;
192
+ ctx.isAuthed = isAuthed;
193
+ }
@@ -0,0 +1,50 @@
1
+ import type { Customer, CustomerSocial } from '@joy-loyalty/sdk/client';
2
+ import type { WidgetCoreExports } from './lib/core-loader.js';
3
+ export type JoyMetafieldBlob = Record<string, unknown>;
4
+ export interface HeadlessRenderIdentity {
5
+ id?: string;
6
+ firstName?: string | null;
7
+ lastName?: string | null;
8
+ email?: string | null;
9
+ }
10
+ export interface HeadlessRenderContext {
11
+ login_url?: string;
12
+ register_url?: string;
13
+ account_url?: string;
14
+ page?: {
15
+ type: string;
16
+ resourceId: string;
17
+ handle: string;
18
+ };
19
+ locale?: string;
20
+ contentLocale?: string;
21
+ currency?: string;
22
+ currencyRate?: number;
23
+ debug?: boolean;
24
+ viewport?: {
25
+ width: number;
26
+ };
27
+ }
28
+ export interface BuildHeadlessRenderPropsParams {
29
+ blob: JoyMetafieldBlob;
30
+ customer?: Customer | Record<string, unknown> | null;
31
+ shopifyCustomer?: HeadlessRenderIdentity | null;
32
+ context: HeadlessRenderContext;
33
+ coreExports?: WidgetCoreExports;
34
+ }
35
+ export declare function buildHeadlessRenderProps(params: BuildHeadlessRenderPropsParams): Record<string, unknown>;
36
+ export declare function buildHeadlessFacade(params: BuildHeadlessRenderPropsParams): {
37
+ facade: Record<string, unknown>;
38
+ renderInput: Record<string, unknown>;
39
+ } | null;
40
+ export declare function mergeInfoIntoBlob(blob: JoyMetafieldBlob, info: Record<string, unknown>, locale?: string): JoyMetafieldBlob;
41
+ export declare const HEADLESS_FACEBOOK_PSID = "linked";
42
+ export declare function socialToFacebook(social: CustomerSocial | undefined, facebookPageId: string): {
43
+ psid: string;
44
+ pageId: string;
45
+ name: string;
46
+ } | undefined;
47
+ export declare function readFacebookPageId(blob: JoyMetafieldBlob | undefined): string;
48
+ export declare function matchLocaleKey(nested: unknown, locale?: string): string | undefined;
49
+ export declare function resolveContentLocale(locale: string | undefined, blobTranslation: unknown): string;
50
+ export declare function resolveActiveTranslation(nested: unknown, locale?: string): Record<string, string>;
@@ -0,0 +1,422 @@
1
+ import { buildWriteReviewProps } from './lib/write-review.js';
2
+ import { formatMoney } from './lib/money.js';
3
+ import { formatPointsNumber } from './lib/points.js';
4
+ const TYPE_BRANDING_DEFAULT = 'default';
5
+ const TYPE_BRANDING_IMAGE = 'image';
6
+ const TYPE_BRANDING_BLANK = 'blank';
7
+ const POINT_LABEL_MODE_TRANSLATION = 'translation';
8
+ const DISCOUNT_REFERRAL_TYPE_PERCENTAGE = 'percentage';
9
+ const DISCOUNT_REFERRAL_TYPE_AMOUNT = 'amount';
10
+ const REFERRAL_REWARD_TYPE_POINT = 'point';
11
+ const REFERRAL_REWARD_TYPE_STORE_CREDIT_ORDER_VALUE = 'store_credit_order_value';
12
+ const REFERRAL_REWARD_TYPE_STORE_CREDIT_FIXED = 'store_credit_fixed';
13
+ const REFERRAL_REWARD_TYPE_POINT_ORDER_VALUE = 'point_order_value';
14
+ const CAPABILITY_OVERRIDES = {
15
+ 'sso-multipass': false,
16
+ 'sso-google': false,
17
+ 'sso-facebook': false,
18
+ 'sso-shop-app': false,
19
+ 'hide-wishlist': true
20
+ };
21
+ export function buildHeadlessRenderProps(params) {
22
+ const built = assembleHeadlessFacade(params);
23
+ if (!built)
24
+ return {};
25
+ const { facade, renderInput, renderingProps, settings } = built;
26
+ const visibility = renderingProps.getMenuVisibility(facade, settings, renderInput);
27
+ const labels = renderingProps.buildLabels(facade, renderInput);
28
+ const referralProgram = asRecord(facade.data?.referralProgram);
29
+ const referralShareSocials = Array.isArray(referralProgram.shareSocials) ? referralProgram.shareSocials : [];
30
+ const referralAutomatedSharing = referralProgram.referralSharingMode === 'automated';
31
+ const referralRewardProps = buildReferralRewardProps({
32
+ referralProgram,
33
+ settingsReferral: asRecord(facade.data?.settingsReferral),
34
+ customer: asRecord(facade.data?.customer),
35
+ shop: asRecord(facade.data?.shop),
36
+ rawSettings: asRecord(facade._rawSettings),
37
+ translation: facade._translation || {},
38
+ context: params.context,
39
+ referralMenuVisible: Boolean(visibility._referralMenuVisible)
40
+ });
41
+ const props = {
42
+ ...renderingProps.buildCoreProps(facade, renderInput),
43
+ ...renderingProps.buildTierProps(facade, renderInput),
44
+ ...renderingProps.buildCustomerProps(facade, renderInput),
45
+ ...renderingProps.buildExpirationProps(facade, renderInput),
46
+ ...renderingProps.buildAppearanceProps(facade, renderInput),
47
+ ...renderingProps.buildVisibilityProps(facade, visibility, renderInput),
48
+ ...renderingProps.buildQrCodeProps(facade, renderInput),
49
+ ...renderingProps.buildWalletPassProps(facade, renderInput),
50
+ ...renderingProps.buildSectionConfigs(facade, settings, renderInput),
51
+ labels,
52
+ referralShareSocials,
53
+ referralAutomatedSharing,
54
+ ...referralRewardProps,
55
+ ...buildWriteReviewProps(asRecord(settings)),
56
+ ...CAPABILITY_OVERRIDES
57
+ };
58
+ if (Array.isArray(props.sectionOrder)) {
59
+ props.sectionOrder = props.sectionOrder.filter(id => id !== 'REVIEWS');
60
+ }
61
+ return props;
62
+ }
63
+ export function buildHeadlessFacade(params) {
64
+ const built = assembleHeadlessFacade(params);
65
+ if (!built)
66
+ return null;
67
+ const { facade, renderInput, renderingProps } = built;
68
+ renderingProps.buildTierProps(facade, renderInput);
69
+ return { facade, renderInput };
70
+ }
71
+ function assembleHeadlessFacade(params) {
72
+ const { blob, customer, shopifyCustomer, context, coreExports } = params;
73
+ const facebookPageId = readFacebookPageId(blob);
74
+ const renderingProps = coreExports?.renderingProps;
75
+ if (!renderingProps || typeof renderingProps.buildCoreProps !== 'function')
76
+ return null;
77
+ const resolveWidgetSettings = typeof coreExports?.resolveWidgetSettings === 'function'
78
+ ? coreExports.resolveWidgetSettings
79
+ : (settings) => settings;
80
+ const rawSettings0 = asRecord(blob.settings);
81
+ const activeTranslation = resolveActiveTranslation(blob.translation, context.locale);
82
+ const rawSettings = applyTranslatedPointLabel({ ...rawSettings0 }, activeTranslation);
83
+ const resolvedSettings = asRecord(resolveWidgetSettings(rawSettings0));
84
+ const clonedProgram = blob.program != null ? structuredClone(blob.program) : blob.program;
85
+ const data = {
86
+ ...blob,
87
+ program: clonedProgram,
88
+ translation: activeTranslation,
89
+ settings: {
90
+ ...resolvedSettings,
91
+ pointSingular: rawSettings.pointSingular,
92
+ pointPlural: rawSettings.pointPlural,
93
+ pointPosition: rawSettings.pointPosition,
94
+ pointLabelMode: rawSettings.pointLabelMode
95
+ },
96
+ _rawSettings: rawSettings,
97
+ login_url: context.login_url,
98
+ register_url: context.register_url,
99
+ account_url: context.account_url,
100
+ page: context.page
101
+ };
102
+ data.customer = assembleCustomer(customer, shopifyCustomer, facebookPageId) ?? {};
103
+ const thinProfile = identityToProfile(shopifyCustomer);
104
+ const renderInput = {
105
+ liquid: blob,
106
+ shopify: { currency: { active: context.currency, rate: context.currencyRate }, locale: context.locale },
107
+ viewport: context.viewport ?? { width: 0 },
108
+ currencyRate: context.currencyRate,
109
+ debug: context.debug,
110
+ customerProfile: thinProfile
111
+ };
112
+ const facade = createFacade(data, rawSettings, activeTranslation, context);
113
+ return { facade, renderInput, renderingProps, settings: data.settings };
114
+ }
115
+ export function mergeInfoIntoBlob(blob, info, locale) {
116
+ const merged = { ...blob };
117
+ const overrideShallow = (key) => {
118
+ if (isRecord(info[key]))
119
+ merged[key] = { ...asRecord(blob[key]), ...info[key] };
120
+ };
121
+ overrideShallow('settings');
122
+ overrideShallow('settingsReferral');
123
+ overrideShallow('referralProgram');
124
+ overrideShallow('tierProgram');
125
+ overrideShallow('settingWidgetQr');
126
+ if (Array.isArray(info.allTiers))
127
+ merged.allTiers = info.allTiers;
128
+ const freshFlat = isRecord(info.primaryTranslation)
129
+ ? info.primaryTranslation
130
+ : isRecord(info.translation)
131
+ ? resolveActiveTranslation(info.translation, locale)
132
+ : undefined;
133
+ if (freshFlat && Object.keys(freshFlat).length) {
134
+ const base = asRecord(blob.translation);
135
+ const primary = typeof base.primaryLanguage === 'string' ? base.primaryLanguage : undefined;
136
+ const key = matchLocaleKey(base, locale || primary) ?? (locale || primary || 'en').toLowerCase();
137
+ merged.translation = { ...base, [key]: { ...asRecord(base[key]), ...freshFlat } };
138
+ }
139
+ return merged;
140
+ }
141
+ function createFacade(data, rawSettings, translation, context) {
142
+ const contentLocale = context.contentLocale ?? '';
143
+ const resolvedLocale = context.locale || contentLocale || 'en';
144
+ return {
145
+ data,
146
+ _rawSettings: rawSettings,
147
+ _translation: translation,
148
+ _currentTierData: null,
149
+ _nextTierData: null,
150
+ _tierInfo: null,
151
+ hostAdapter: { context: () => ({ contentLocale }) },
152
+ get _program() {
153
+ return asRecord(data.program);
154
+ },
155
+ _getDetectLocale() {
156
+ return contentLocale;
157
+ },
158
+ _getResolvedLocale() {
159
+ return resolvedLocale;
160
+ },
161
+ _tLabel(key) {
162
+ return translation[`[[WidgetV4]]${key}`] || key;
163
+ },
164
+ _formatDisplayDate(value) {
165
+ return formatDisplayDate(value, resolvedLocale);
166
+ },
167
+ _getPointsLabel(points) {
168
+ return getPointsLabel(points, rawSettings);
169
+ },
170
+ _resolvePointsIcon(programObj) {
171
+ if (programObj?.pointsIconType === 'image')
172
+ return programObj.pointsIconUrl || '';
173
+ if (programObj?.pointsIconType === 'emoji')
174
+ return programObj.pointsIcon || '';
175
+ return '';
176
+ },
177
+ _resolveBalancePointIcon(s) {
178
+ if (s?.balancePointIconType === TYPE_BRANDING_IMAGE)
179
+ return s.balancePointIconUrl || '';
180
+ if (s?.balancePointIconType === TYPE_BRANDING_DEFAULT)
181
+ return '';
182
+ return TYPE_BRANDING_BLANK;
183
+ },
184
+ _resolveStoreCreditIcon(s) {
185
+ if (s?.storeCreditIconType === TYPE_BRANDING_IMAGE)
186
+ return s.storeCreditIconUrl || '';
187
+ if (s?.storeCreditIconType === TYPE_BRANDING_DEFAULT)
188
+ return '';
189
+ return TYPE_BRANDING_BLANK;
190
+ },
191
+ _shouldStartCollapsed() {
192
+ return true;
193
+ }
194
+ };
195
+ }
196
+ function assembleCustomer(customer, shopifyCustomer, facebookPageId) {
197
+ const rich = asRecord(customer);
198
+ const hasRich = Object.keys(rich).length > 0;
199
+ const hasThin = !!(shopifyCustomer?.firstName || shopifyCustomer?.lastName || shopifyCustomer?.email);
200
+ if (!hasRich && !hasThin)
201
+ return undefined;
202
+ const thin = shopifyCustomer
203
+ ? {
204
+ first_name: shopifyCustomer.firstName ?? '',
205
+ firstName: shopifyCustomer.firstName ?? '',
206
+ last_name: shopifyCustomer.lastName ?? '',
207
+ lastName: shopifyCustomer.lastName ?? '',
208
+ email: shopifyCustomer.email ?? ''
209
+ }
210
+ : {};
211
+ const merged = { ...thin, ...rich };
212
+ if (merged.point === undefined && rich.points !== undefined)
213
+ merged.point = rich.points;
214
+ if (merged.tierPoint === undefined && rich.tierPoint !== undefined)
215
+ merged.tierPoint = rich.tierPoint;
216
+ if (merged.phone === undefined && rich.phone != null)
217
+ merged.phone = rich.phone;
218
+ if (merged.tierId === undefined && isRecord(rich.tier))
219
+ merged.tierId = rich.tier.id;
220
+ if (merged.becomeMemberAt === undefined && rich.memberSince != null)
221
+ merged.becomeMemberAt = rich.memberSince;
222
+ if (merged.acceptsMarketing === undefined && typeof rich.marketingConsent === 'boolean') {
223
+ merged.acceptsMarketing = rich.marketingConsent;
224
+ }
225
+ if (merged.acceptsSmsMarketing === undefined && typeof rich.smsMarketingConsent === 'boolean') {
226
+ merged.acceptsSmsMarketing = rich.smsMarketingConsent;
227
+ }
228
+ if (merged.facebook === undefined) {
229
+ const facebook = socialToFacebook(rich.social, facebookPageId);
230
+ if (facebook)
231
+ merged.facebook = facebook;
232
+ }
233
+ if (merged.instagramUsername === undefined) {
234
+ const social = rich.social;
235
+ if (social?.instagramUsername)
236
+ merged.instagramUsername = social.instagramUsername;
237
+ }
238
+ return merged;
239
+ }
240
+ export const HEADLESS_FACEBOOK_PSID = 'linked';
241
+ export function socialToFacebook(social, facebookPageId) {
242
+ if (!social?.facebookConnected)
243
+ return undefined;
244
+ return { psid: HEADLESS_FACEBOOK_PSID, pageId: facebookPageId, name: social.facebookName ?? '' };
245
+ }
246
+ export function readFacebookPageId(blob) {
247
+ const pageId = asRecord(blob).facebookPageId;
248
+ return typeof pageId === 'string' ? pageId : '';
249
+ }
250
+ function identityToProfile(identity) {
251
+ if (!identity)
252
+ return undefined;
253
+ return { first_name: identity.firstName ?? '', last_name: identity.lastName ?? '' };
254
+ }
255
+ export function matchLocaleKey(nested, locale) {
256
+ if (!isRecord(nested) || !locale)
257
+ return undefined;
258
+ const norm = locale.replace(/_/g, '-').toLowerCase();
259
+ const localeKeys = Object.keys(nested).filter(k => isRecord(nested[k]));
260
+ return (localeKeys.find(k => k.toLowerCase() === norm) ??
261
+ localeKeys.find(k => norm.startsWith(`${k.toLowerCase()}-`)));
262
+ }
263
+ export function resolveContentLocale(locale, blobTranslation) {
264
+ if (!locale)
265
+ return '';
266
+ const primary = isRecord(blobTranslation) && typeof blobTranslation.primaryLanguage === 'string'
267
+ ? blobTranslation.primaryLanguage
268
+ : 'en';
269
+ const norm = locale.replace(/_/g, '-');
270
+ if (norm.toLowerCase() === primary.toLowerCase())
271
+ return '';
272
+ const exact = isRecord(blobTranslation)
273
+ ? Object.keys(blobTranslation).find(k => k.toLowerCase() === norm.toLowerCase())
274
+ : undefined;
275
+ if (exact)
276
+ return exact;
277
+ const [lang, region] = norm.split('-');
278
+ return region ? `${lang.toLowerCase()}-${region.toUpperCase()}` : lang.toLowerCase();
279
+ }
280
+ export function resolveActiveTranslation(nested, locale) {
281
+ if (!isRecord(nested))
282
+ return {};
283
+ const byLocale = (l) => {
284
+ const hit = matchLocaleKey(nested, l);
285
+ return hit ? nested[hit] : undefined;
286
+ };
287
+ const primary = typeof nested.primaryLanguage === 'string' ? nested.primaryLanguage : undefined;
288
+ const chosen = byLocale(locale) ??
289
+ byLocale(primary) ??
290
+ byLocale('en') ??
291
+ Object.values(nested).find(isRecord);
292
+ if (chosen)
293
+ return chosen;
294
+ const looksFlat = Object.values(nested).every(v => typeof v === 'string');
295
+ return looksFlat ? nested : {};
296
+ }
297
+ function applyTranslatedPointLabel(settings, translation) {
298
+ if (settings.pointLabelMode !== POINT_LABEL_MODE_TRANSLATION || !translation)
299
+ return settings;
300
+ return {
301
+ ...settings,
302
+ pointSingular: translation.point || settings.pointSingular,
303
+ pointPlural: translation.points || settings.pointPlural
304
+ };
305
+ }
306
+ function isSingularValue(num) {
307
+ const value = parseFloat(num);
308
+ return Number.isFinite(value) && Math.abs(Number(value.toFixed(2))) === 1;
309
+ }
310
+ function getPointsLabel(count, rawSettings) {
311
+ const singular = rawSettings.pointSingular || 'point';
312
+ const plural = rawSettings.pointPlural || 'points';
313
+ return count && isSingularValue(count) ? singular : plural;
314
+ }
315
+ function buildReferralRewardProps(input) {
316
+ const { referralProgram, settingsReferral, customer, shop, rawSettings, translation, context, referralMenuVisible } = input;
317
+ if (!referralProgram.status || !referralMenuVisible) {
318
+ return { referralRewardYou: '', referralRewardFriend: '', referralDescription: '' };
319
+ }
320
+ return {
321
+ referralRewardYou: buildReferralRewardText(referralProgram, true, customer, shop, rawSettings, translation, context),
322
+ referralRewardFriend: buildReferralRewardText(referralProgram, false, customer, shop, rawSettings, translation, context),
323
+ referralDescription: settingsReferral.description || ''
324
+ };
325
+ }
326
+ function buildReferralRewardText(program, isReferrer, customer, shop, rawSettings, translation, context) {
327
+ const prefix = isReferrer ? 'customerReward' : 'friendReward';
328
+ const discountType = program[`${prefix}DiscountType`] || '';
329
+ let earnAmount = Number(program[`${prefix}EarnAmount`]) || 0;
330
+ if (isReferrer && program.isAppliedVipTier && discountType !== REFERRAL_REWARD_TYPE_POINT_ORDER_VALUE) {
331
+ const earnPointsTiers = asRecord(program.earnPointsTiers);
332
+ const tierId = customer.tierId || '';
333
+ const tierEarnPoint = Number(asRecord(earnPointsTiers[tierId]).earnPoint) || 0;
334
+ const tierValues = Object.values(earnPointsTiers)
335
+ .map(tier => Number(asRecord(tier).earnPoint))
336
+ .filter(value => Number.isFinite(value));
337
+ const minEarnPoint = tierValues.length ? Math.min(...tierValues) : 0;
338
+ earnAmount = tierEarnPoint || minEarnPoint || 0;
339
+ }
340
+ const money = {
341
+ currency: context.currency || shop.currency || 'USD',
342
+ currencyFormat: shop.moneyFormat || '${{amount}}'
343
+ };
344
+ switch (discountType) {
345
+ case DISCOUNT_REFERRAL_TYPE_PERCENTAGE:
346
+ return i18nText('[[WidgetV4]]{{amount}}% off', translation, { amount: String(earnAmount) });
347
+ case DISCOUNT_REFERRAL_TYPE_AMOUNT:
348
+ return i18nText('[[WidgetV4]]{{amount}} off', translation, { amount: formatMoney(earnAmount, money) });
349
+ case REFERRAL_REWARD_TYPE_POINT:
350
+ return formatPointsAmount(earnAmount, rawSettings, context.locale);
351
+ case REFERRAL_REWARD_TYPE_STORE_CREDIT_ORDER_VALUE:
352
+ return i18nText('[[WidgetV4]]{{amount}}% of first order', translation, { amount: String(earnAmount) });
353
+ case REFERRAL_REWARD_TYPE_STORE_CREDIT_FIXED:
354
+ return i18nText('[[WidgetV4]]{{amount}} store credit', translation, { amount: formatMoney(earnAmount, money) });
355
+ case REFERRAL_REWARD_TYPE_POINT_ORDER_VALUE: {
356
+ const pointRate = resolveEffectivePointRate(program, customer, shop);
357
+ return i18nText('[[WidgetV4]]{{points}} points per {{amount}} your friend spends', translation, {
358
+ points: String(pointRate),
359
+ amount: formatMoney(1, money)
360
+ });
361
+ }
362
+ default:
363
+ return '';
364
+ }
365
+ }
366
+ function resolveEffectivePointRate(program, customer, shop) {
367
+ const fallbackRate = Number(shop.exchangeRatePoints) || 1;
368
+ if (!program.isAppliedVipTier) {
369
+ const rate = program.customerRewardPointExchangeRate;
370
+ return rate == null ? fallbackRate : Number(rate);
371
+ }
372
+ const tierId = customer.tierId || '';
373
+ const tierRate = asRecord(asRecord(program.earnPointsTiers)[tierId]).pointRate;
374
+ if (tierRate != null)
375
+ return Number(tierRate);
376
+ const nonTierRate = program.customerRewardPointNonTierRate;
377
+ return nonTierRate == null ? fallbackRate : Number(nonTierRate);
378
+ }
379
+ function i18nText(phrase, dict, variables = {}) {
380
+ const initial = (dict && Object.prototype.hasOwnProperty.call(dict, phrase) && dict[phrase]) ||
381
+ phrase.replace(/\[\[(.*?)\]\]/g, '');
382
+ return Object.keys(variables).reduce((text, key) => text.replace(new RegExp(`{{\\s*${key}\\s*}}`, 'g'), variables[key] ?? ''), initial);
383
+ }
384
+ function formatPointsAmount(count, rawSettings, locale) {
385
+ const unit = getPointsLabel(count, rawSettings);
386
+ const value = formatPointsNumber(count, locale);
387
+ const parts = rawSettings.pointPosition === 'before' ? [unit, value] : [value, unit];
388
+ return parts.filter(Boolean).join(' ');
389
+ }
390
+ function formatDisplayDate(value, locale) {
391
+ try {
392
+ if (!value)
393
+ return '';
394
+ let date = null;
395
+ if (value instanceof Date) {
396
+ date = value;
397
+ }
398
+ else if (typeof value === 'string' || typeof value === 'number') {
399
+ date = new Date(value);
400
+ }
401
+ else if (isRecord(value) && typeof value.toDate === 'function') {
402
+ date = value.toDate();
403
+ }
404
+ else if (isRecord(value)) {
405
+ const seconds = (value.seconds ?? value._seconds);
406
+ if (typeof seconds === 'number')
407
+ date = new Date(seconds * 1000);
408
+ }
409
+ if (!date || isNaN(date.getTime()))
410
+ return '';
411
+ return date.toLocaleDateString(locale || 'en', { month: 'short', day: 'numeric', year: 'numeric' });
412
+ }
413
+ catch {
414
+ return '';
415
+ }
416
+ }
417
+ function isRecord(value) {
418
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
419
+ }
420
+ function asRecord(value) {
421
+ return isRecord(value) ? value : {};
422
+ }
@@ -0,0 +1,12 @@
1
+ export interface JoyPlaceOrderScopeEnv {
2
+ JOY_API_URL?: string;
3
+ JOY_SHOP_DOMAIN?: string;
4
+ }
5
+ export interface JoyPlaceOrderScopeContext {
6
+ env: JoyPlaceOrderScopeEnv;
7
+ }
8
+ export interface JoyPlaceOrderScopeLoaderArgs {
9
+ context: JoyPlaceOrderScopeContext;
10
+ request: Request;
11
+ }
12
+ export declare function loader({ context, request }: JoyPlaceOrderScopeLoaderArgs): Promise<Response>;