@jarwizz/create-jarshop 0.1.8 → 0.3.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 (116) hide show
  1. package/README.md +15 -0
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.js +1 -0
  4. package/dist/cli.js.map +1 -1
  5. package/dist/generator.d.ts +11 -1
  6. package/dist/generator.js +45 -11
  7. package/dist/generator.js.map +1 -1
  8. package/dist/presets.d.ts +26 -0
  9. package/dist/presets.js +94 -0
  10. package/dist/presets.js.map +1 -0
  11. package/dist/template/CONTEXT.md +4 -2
  12. package/dist/template/README.md +255 -3
  13. package/dist/template/env.example.template +19 -0
  14. package/dist/template/gitignore.template +1 -0
  15. package/dist/template/jarshop.config.ts +31 -0
  16. package/dist/template/package.json +5 -0
  17. package/dist/template/pnpm-lock.yaml +3291 -1809
  18. package/dist/template/pnpm-workspace.yaml +6 -1
  19. package/dist/template/src/client/features.ts +41 -0
  20. package/dist/template/src/client/invoicing.ts +29 -0
  21. package/dist/template/src/dev-storefront-environment.test.ts +45 -0
  22. package/dist/template/src/dev-storefront-environment.ts +32 -0
  23. package/dist/template/src/dev-storefront.ts +3 -12
  24. package/dist/template/src/environment.d.ts +8 -0
  25. package/dist/template/src/invoice-email-recover.ts +59 -0
  26. package/dist/template/src/jarshop-config-loader.ts +118 -0
  27. package/dist/template/src/jarshop-config.test.ts +335 -0
  28. package/dist/template/src/jarshop-config.ts +439 -0
  29. package/dist/template/src/jarshop-features.test.ts +222 -0
  30. package/dist/template/src/jarshop-features.ts +112 -0
  31. package/dist/template/src/operation-codes.ts +34 -0
  32. package/dist/template/src/packeta-config.test.ts +95 -0
  33. package/dist/template/src/packeta-countries.test.ts +161 -0
  34. package/dist/template/src/packeta-countries.ts +120 -0
  35. package/dist/template/src/packeta-validation.test.ts +35 -0
  36. package/dist/template/src/packeta-validation.ts +52 -0
  37. package/dist/template/src/payment-return-url.test.ts +57 -0
  38. package/dist/template/src/payment-return-url.ts +34 -0
  39. package/dist/template/src/plugins/jarshop-checkout/confirmation-view.test.ts +79 -0
  40. package/dist/template/src/plugins/jarshop-checkout/confirmation.ts +51 -0
  41. package/dist/template/src/plugins/jarshop-checkout/dashboard/index.tsx +1 -0
  42. package/dist/template/src/plugins/jarshop-checkout/invoice-delivery.plugin.ts +79 -0
  43. package/dist/template/src/plugins/jarshop-checkout/invoice-email-events.ts +35 -0
  44. package/dist/template/src/plugins/jarshop-checkout/invoice-email-lifecycle.ts +235 -0
  45. package/dist/template/src/plugins/jarshop-checkout/invoice-email-worker.test.ts +426 -0
  46. package/dist/template/src/plugins/jarshop-checkout/invoice-email.test.ts +107 -0
  47. package/dist/template/src/plugins/jarshop-checkout/jarshop-checkout.plugin.ts +161 -57
  48. package/dist/template/src/plugins/jarshop-checkout/market-channels.test.ts +58 -0
  49. package/dist/template/src/plugins/jarshop-checkout/market-channels.ts +87 -0
  50. package/dist/template/src/plugins/jarshop-checkout/operation-code-check.ts +36 -0
  51. package/dist/template/src/plugins/jarshop-checkout/order-email-configuration.entity.ts +1 -1
  52. package/dist/template/src/plugins/jarshop-checkout/order-email-configuration.ts +1 -0
  53. package/dist/template/src/plugins/jarshop-checkout/order-email-delivery-core.ts +94 -1
  54. package/dist/template/src/plugins/jarshop-checkout/order-email-delivery.entity.ts +1 -0
  55. package/dist/template/src/plugins/jarshop-checkout/order-email-outbox.ts +83 -1
  56. package/dist/template/src/plugins/jarshop-checkout/order-email-worker.ts +136 -1
  57. package/dist/template/src/plugins/jarshop-checkout/shipping-tax.test.ts +109 -0
  58. package/dist/template/src/plugins/jarshop-checkout/shipping.test.ts +156 -0
  59. package/dist/template/src/plugins/jarshop-checkout/shipping.ts +75 -11
  60. package/dist/template/src/seed.ts +427 -184
  61. package/dist/template/src/vendure-config.ts +258 -113
  62. package/dist/template/storefront/README.md +7 -0
  63. package/dist/template/storefront/app/[locale]/[slug]/page.tsx +3 -2
  64. package/dist/template/storefront/app/[locale]/account/login/page.tsx +3 -2
  65. package/dist/template/storefront/app/[locale]/account/page.tsx +10 -4
  66. package/dist/template/storefront/app/[locale]/account/password-reset/callback/route.ts +4 -2
  67. package/dist/template/storefront/app/[locale]/account/password-reset/complete/page.tsx +3 -2
  68. package/dist/template/storefront/app/[locale]/account/password-reset/page.tsx +3 -2
  69. package/dist/template/storefront/app/[locale]/account/register/page.tsx +3 -2
  70. package/dist/template/storefront/app/[locale]/account/verify/complete/route.ts +4 -2
  71. package/dist/template/storefront/app/[locale]/account/verify/page.tsx +3 -2
  72. package/dist/template/storefront/app/[locale]/cart/page.tsx +3 -2
  73. package/dist/template/storefront/app/[locale]/checkout/actions.ts +43 -0
  74. package/dist/template/storefront/app/[locale]/checkout/checkout-form.tsx +188 -36
  75. package/dist/template/storefront/app/[locale]/checkout/confirmation/route.ts +2 -2
  76. package/dist/template/storefront/app/[locale]/checkout/packeta-chooser.tsx +96 -0
  77. package/dist/template/storefront/app/[locale]/checkout/page.tsx +60 -2
  78. package/dist/template/storefront/app/[locale]/checkout/payment-return/actions.ts +55 -0
  79. package/dist/template/storefront/app/[locale]/checkout/payment-return/page.tsx +32 -0
  80. package/dist/template/storefront/app/[locale]/checkout/payment-return/payment-return.tsx +84 -0
  81. package/dist/template/storefront/app/[locale]/checkout/success/page.tsx +32 -2
  82. package/dist/template/storefront/app/[locale]/layout.tsx +3 -2
  83. package/dist/template/storefront/app/[locale]/page.tsx +3 -2
  84. package/dist/template/storefront/app/globals.css +16 -0
  85. package/dist/template/storefront/app/layout.tsx +6 -2
  86. package/dist/template/storefront/lib/cart.ts +2 -4
  87. package/dist/template/storefront/lib/checkout-contract.test.ts +18 -1
  88. package/dist/template/storefront/lib/checkout-contract.ts +8 -0
  89. package/dist/template/storefront/lib/checkout-countries.test.ts +61 -0
  90. package/dist/template/storefront/lib/checkout-countries.ts +67 -0
  91. package/dist/template/storefront/lib/checkout.ts +22 -11
  92. package/dist/template/storefront/lib/commerce.ts +262 -2
  93. package/dist/template/storefront/lib/confirmation.test.ts +116 -0
  94. package/dist/template/storefront/lib/confirmation.ts +13 -7
  95. package/dist/template/storefront/lib/i18n.test.ts +32 -12
  96. package/dist/template/storefront/lib/i18n.ts +29 -8
  97. package/dist/template/storefront/lib/market-config.ts +40 -0
  98. package/dist/template/storefront/lib/market-routing.test.ts +107 -0
  99. package/dist/template/storefront/lib/market-routing.ts +57 -0
  100. package/dist/template/storefront/lib/market.ts +51 -0
  101. package/dist/template/storefront/lib/packeta-selection.test.ts +141 -0
  102. package/dist/template/storefront/lib/packeta-selection.ts +98 -0
  103. package/dist/template/storefront/lib/payment-return-actions.test.ts +61 -0
  104. package/dist/template/storefront/lib/payment-return-page.test.ts +30 -0
  105. package/dist/template/storefront/lib/payment-return-polling.test.ts +37 -0
  106. package/dist/template/storefront/lib/payment-return-polling.ts +58 -0
  107. package/dist/template/storefront/messages/en.json +13 -1
  108. package/dist/template/storefront/messages/sk.json +13 -1
  109. package/dist/template/storefront/package.json +2 -1
  110. package/dist/template/storefront/proxy.ts +35 -0
  111. package/dist/template/turbo.json +5 -1
  112. package/dist/template/vite.config.mts +13 -2
  113. package/dist/template-manifest.json +1 -1
  114. package/dist/template.js +1 -0
  115. package/dist/template.js.map +1 -1
  116. package/package.json +1 -1
@@ -0,0 +1,439 @@
1
+ /**
2
+ * The JarShop market contract shared by the Vendure server and the storefront.
3
+ *
4
+ * A Client Project describes its markets in the client-owned
5
+ * `jarshop.config.ts` at the project root. This platform-managed module only
6
+ * reads that data: it declares the shape, validates it with readable errors and
7
+ * resolves a market from a host, a channel token or a language. It imports
8
+ * nothing, so the storefront bundle, the Vendure build and Node's own type
9
+ * stripping can all load it.
10
+ *
11
+ * One market is one Vendure Channel with its own currency, prices, tax zone
12
+ * and carts. Customer accounts are shared across those channels.
13
+ */
14
+
15
+ /** An upper-case ISO 4217 currency code, such as `EUR`. */
16
+ export type JarShopCurrencyCode = string;
17
+ /** An upper-case ISO 3166-1 alpha-2 country code, such as `SK`. */
18
+ export type JarShopCountryCode = string;
19
+ /** A lower-case ISO 639-1 language code, such as `sk`. */
20
+ export type JarShopLanguageCode = string;
21
+
22
+ export interface JarShopMarket {
23
+ /** Stable lower-case identifier, also sent as the checkout `marketCode`. */
24
+ readonly code: string;
25
+ /** Token of the Vendure Channel that holds this market's prices and carts. */
26
+ readonly channelToken: string;
27
+ readonly defaultLanguage: JarShopLanguageCode;
28
+ /** Path-prefix languages served on this market's domains. */
29
+ readonly languages: readonly JarShopLanguageCode[];
30
+ readonly currency: JarShopCurrencyCode;
31
+ /** Countries this market ships to. The first one is the checkout default. */
32
+ readonly countries: readonly JarShopCountryCode[];
33
+ /** Host names, without scheme or port, that serve this market. */
34
+ readonly domains: readonly string[];
35
+ }
36
+
37
+ export interface JarShopConfig {
38
+ /** Code of the market served when a request host matches no domain. */
39
+ readonly defaultMarket: string;
40
+ readonly markets: readonly JarShopMarket[];
41
+ }
42
+
43
+ export class JarShopConfigError extends Error {
44
+ readonly issues: readonly string[];
45
+
46
+ constructor(source: string, issues: readonly string[]) {
47
+ super(
48
+ `Invalid ${source}:\n${issues.map((issue) => ` - ${issue}`).join("\n")}`,
49
+ );
50
+ this.name = "JarShopConfigError";
51
+ this.issues = issues;
52
+ }
53
+ }
54
+
55
+ // Active ISO 4217 codes accepted by Vendure's CurrencyCode enum.
56
+ const currencyCodes = new Set(
57
+ (
58
+ "AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BHD BIF BMD BND " +
59
+ "BOB BRL BSD BTN BWP BYN BZD CAD CDF CHF CLP CNY COP CRC CUC CUP CVE CZK " +
60
+ "DJF DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD " +
61
+ "HKD HNL HRK HTG HUF IDR ILS INR IQD IRR ISK JMD JOD JPY KES KGS KHR KMF " +
62
+ "KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL MGA MKD MMK MNT MOP " +
63
+ "MRU MUR MVR MWK MXN MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN PGK PHP " +
64
+ "PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLL SOS SRD " +
65
+ "SSP STN SVC SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD UYU " +
66
+ "UZS VES VND VUV WST XAF XCD XOF XPF YER ZAR ZMW ZWL"
67
+ ).split(" "),
68
+ );
69
+
70
+ // The two-letter ISO 639-1 codes in Vendure's LanguageCode enum. A path
71
+ // language is also the commerce `languageCode`, so Vendure must know it; the
72
+ // regional variants (`en_GB`, `pt_BR`, ...) cannot be a path prefix.
73
+ const languageCodes = new Set(
74
+ (
75
+ "af ak am ar as az be bg bm bn bo br bs ca ce co cs cu cy da de dz ee el " +
76
+ "en eo es et eu fa ff fi fo fr fy ga gd gl gu gv ha he hi hr ht hu hy ia " +
77
+ "id ig ii is it ja jv ka ki kk kl km kn ko ks ku kw ky la lb lg ln lo lt " +
78
+ "lu lv mg mi mk ml mn mr ms mt my nb nd ne nl nn ny om or os pa pl ps pt " +
79
+ "qu rm rn ro ru rw sa sd se sg si sk sl sm sn so sq sr st su sv sw ta te " +
80
+ "tg th ti tk to tr tt ug uk ur uz vi vo wo xh yi yo zh zu"
81
+ ).split(" "),
82
+ );
83
+
84
+ /** Currencies a market may declare: Vendure's `CurrencyCode` values. */
85
+ export const supportedCurrencyCodes: ReadonlySet<string> = currencyCodes;
86
+ /** Path languages a market may declare: Vendure's two-letter `LanguageCode` values. */
87
+ export const supportedLanguageCodes: ReadonlySet<string> = languageCodes;
88
+
89
+ // Officially assigned ISO 3166-1 alpha-2 codes.
90
+ const countryCodes = new Set(
91
+ (
92
+ "AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI " +
93
+ "BJ BL BM BN BO BQ BR BS BT BV BW BY BZ CA CC CD CF CG CH CI CK CL CM CN " +
94
+ "CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK " +
95
+ "FM FO FR GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM " +
96
+ "HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO JP KE KG KH KI KM KN " +
97
+ "KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK " +
98
+ "ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP " +
99
+ "NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO RS RU RW " +
100
+ "SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF " +
101
+ "TG TH TJ TK TL TM TN TO TR TT TV TW TZ UA UG UM US UY UZ VA VC VE VG VI " +
102
+ "VN VU WF WS YE YT ZA ZM ZW"
103
+ ).split(" "),
104
+ );
105
+
106
+ const marketCodePattern = /^[a-z][a-z0-9-]{0,31}$/u;
107
+ const channelTokenPattern = /^[A-Za-z0-9_-]{1,64}$/u;
108
+ const domainPattern =
109
+ /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/u;
110
+
111
+ function isRecord(value: unknown): value is Record<string, unknown> {
112
+ return typeof value === "object" && value !== null && !Array.isArray(value);
113
+ }
114
+
115
+ function stringList(value: unknown, label: string, issues: string[]): string[] {
116
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
117
+ issues.push(`${label} must be an array of strings`);
118
+ return [];
119
+ }
120
+ const items = value as string[];
121
+ const duplicates = items.filter(
122
+ (item, index) => items.indexOf(item) !== index,
123
+ );
124
+ if (duplicates.length > 0) {
125
+ issues.push(`${label} contains duplicate "${duplicates[0]}"`);
126
+ }
127
+ return items;
128
+ }
129
+
130
+ /**
131
+ * Validates untrusted configuration data and returns it as a typed, frozen
132
+ * value. Every problem is reported at once so a broken configuration can be
133
+ * fixed in one pass.
134
+ */
135
+ export function parseJarShopConfig(
136
+ value: unknown,
137
+ source = "jarshop.config.ts",
138
+ ): JarShopConfig {
139
+ const issues: string[] = [];
140
+ if (!isRecord(value)) {
141
+ throw new JarShopConfigError(source, [
142
+ "the default export must be an object",
143
+ ]);
144
+ }
145
+ if (!Array.isArray(value.markets) || value.markets.length === 0) {
146
+ throw new JarShopConfigError(source, ["markets must be a non-empty array"]);
147
+ }
148
+
149
+ const markets: JarShopMarket[] = [];
150
+ const seenCodes = new Set<string>();
151
+ const seenTokens = new Set<string>();
152
+ const domainOwners = new Map<string, string>();
153
+ value.markets.forEach((candidate: unknown, index: number) => {
154
+ const label = `markets[${index}]`;
155
+ if (!isRecord(candidate)) {
156
+ issues.push(`${label} must be an object`);
157
+ return;
158
+ }
159
+ const code = candidate.code;
160
+ const marketLabel =
161
+ typeof code === "string" && code ? `market "${code}"` : label;
162
+ if (typeof code !== "string" || !marketCodePattern.test(code)) {
163
+ issues.push(
164
+ `${label}.code must be a lower-case identifier such as "sk" (got ${JSON.stringify(code)})`,
165
+ );
166
+ } else if (seenCodes.has(code)) {
167
+ issues.push(`market code "${code}" is declared more than once`);
168
+ } else {
169
+ seenCodes.add(code);
170
+ }
171
+
172
+ const channelToken = candidate.channelToken;
173
+ if (
174
+ typeof channelToken !== "string" ||
175
+ !channelTokenPattern.test(channelToken)
176
+ ) {
177
+ issues.push(
178
+ `${marketLabel} channelToken must be 1-64 letters, digits, "-" or "_"`,
179
+ );
180
+ } else if (seenTokens.has(channelToken)) {
181
+ issues.push(
182
+ `${marketLabel} reuses channelToken "${channelToken}"; every market needs its own Vendure Channel`,
183
+ );
184
+ } else {
185
+ seenTokens.add(channelToken);
186
+ }
187
+
188
+ const currency = candidate.currency;
189
+ if (typeof currency !== "string" || !currencyCodes.has(currency)) {
190
+ issues.push(
191
+ `${marketLabel} currency ${JSON.stringify(currency)} is not a supported upper-case ISO 4217 code`,
192
+ );
193
+ }
194
+
195
+ const languages = stringList(
196
+ candidate.languages,
197
+ `${marketLabel} languages`,
198
+ issues,
199
+ );
200
+ if (languages.length === 0) {
201
+ issues.push(`${marketLabel} must serve at least one language`);
202
+ }
203
+ for (const language of languages) {
204
+ if (!languageCodes.has(language)) {
205
+ issues.push(
206
+ `${marketLabel} language "${language}" must be a lower-case ISO 639-1 code that Vendure supports`,
207
+ );
208
+ }
209
+ }
210
+ const defaultLanguage = candidate.defaultLanguage;
211
+ if (
212
+ typeof defaultLanguage !== "string" ||
213
+ !languages.includes(defaultLanguage)
214
+ ) {
215
+ issues.push(
216
+ `${marketLabel} defaultLanguage ${JSON.stringify(defaultLanguage)} must be one of its languages`,
217
+ );
218
+ }
219
+
220
+ const countries = stringList(
221
+ candidate.countries,
222
+ `${marketLabel} countries`,
223
+ issues,
224
+ );
225
+ if (countries.length === 0) {
226
+ issues.push(`${marketLabel} must ship to at least one country`);
227
+ }
228
+ for (const country of countries) {
229
+ if (!countryCodes.has(country)) {
230
+ issues.push(
231
+ `${marketLabel} country "${country}" is not an upper-case ISO 3166-1 alpha-2 code`,
232
+ );
233
+ }
234
+ }
235
+
236
+ const domains = stringList(
237
+ candidate.domains,
238
+ `${marketLabel} domains`,
239
+ issues,
240
+ );
241
+ for (const domain of domains) {
242
+ if (!domainPattern.test(domain)) {
243
+ issues.push(
244
+ `${marketLabel} domain "${domain}" must be a lower-case host name without scheme, port or path`,
245
+ );
246
+ continue;
247
+ }
248
+ const owner = domainOwners.get(domain);
249
+ if (owner !== undefined && owner !== marketLabel) {
250
+ issues.push(
251
+ `domain "${domain}" is declared by both ${owner} and ${marketLabel}`,
252
+ );
253
+ }
254
+ domainOwners.set(domain, marketLabel);
255
+ }
256
+
257
+ markets.push(
258
+ Object.freeze({
259
+ code: String(code),
260
+ channelToken: String(channelToken),
261
+ defaultLanguage: String(defaultLanguage),
262
+ languages: Object.freeze([...languages]),
263
+ currency: String(currency),
264
+ countries: Object.freeze([...countries]),
265
+ domains: Object.freeze([...domains]),
266
+ }),
267
+ );
268
+ });
269
+
270
+ if (markets.length > 1) {
271
+ for (const market of markets) {
272
+ if (market.domains.length === 0) {
273
+ issues.push(
274
+ `market "${market.code}" needs at least one domain when a project has several markets`,
275
+ );
276
+ }
277
+ }
278
+ }
279
+
280
+ const defaultMarket = value.defaultMarket;
281
+ if (typeof defaultMarket !== "string" || !seenCodes.has(defaultMarket)) {
282
+ issues.push(
283
+ `defaultMarket ${JSON.stringify(defaultMarket)} must name one of the markets (${[...seenCodes].join(", ")})`,
284
+ );
285
+ }
286
+
287
+ if (issues.length > 0) throw new JarShopConfigError(source, issues);
288
+ return Object.freeze({
289
+ defaultMarket: String(defaultMarket),
290
+ markets: Object.freeze(markets),
291
+ });
292
+ }
293
+
294
+ export function findMarket(
295
+ config: JarShopConfig,
296
+ code: string,
297
+ ): JarShopMarket | undefined {
298
+ return config.markets.find((market) => market.code === code);
299
+ }
300
+
301
+ export function defaultMarket(config: JarShopConfig): JarShopMarket {
302
+ const market = findMarket(config, config.defaultMarket);
303
+ if (!market) {
304
+ throw new Error(`Default market "${config.defaultMarket}" is not declared`);
305
+ }
306
+ return market;
307
+ }
308
+
309
+ /** Every language any market serves, default market languages first. */
310
+ export function configuredLanguages(config: JarShopConfig): string[] {
311
+ const ordered = [defaultMarket(config), ...config.markets];
312
+ return [...new Set(ordered.flatMap((market) => market.languages))];
313
+ }
314
+
315
+ export function marketForChannelToken(
316
+ config: JarShopConfig,
317
+ channelToken: string | undefined,
318
+ ): JarShopMarket | undefined {
319
+ return config.markets.find((market) => market.channelToken === channelToken);
320
+ }
321
+
322
+ /**
323
+ * Reduces a `Host` or `X-Forwarded-Host` value to a comparable host name:
324
+ * the first listed host, lower-cased, without port or trailing dot.
325
+ */
326
+ export function normalizeHost(host: string | null | undefined): string {
327
+ const first = host?.split(",")[0]?.trim().toLowerCase() ?? "";
328
+ const withoutPort = first.startsWith("[")
329
+ ? first.slice(0, first.indexOf("]") + 1)
330
+ : first.replace(/:\d+$/u, "");
331
+ return withoutPort.replace(/\.$/u, "");
332
+ }
333
+
334
+ export interface MarketHostOptions {
335
+ /** `JARSHOP_DEV_MARKET`: the market a development host that no market lists serves. */
336
+ readonly fallbackMarket?: string;
337
+ /**
338
+ * In production a project with several markets serves a market only on its
339
+ * own domains: an unknown host gets no market, and `fallbackMarket` is
340
+ * ignored. A single-market project keeps serving its one market.
341
+ */
342
+ readonly production?: boolean;
343
+ }
344
+
345
+ /**
346
+ * Selects the market whose domains contain the request host. A host that no
347
+ * market declares, such as `localhost` in development, falls back to the
348
+ * explicitly named development market and otherwise to the default market.
349
+ * In production with several markets an unknown host resolves to `undefined`,
350
+ * so the storefront answers 404 instead of serving the default market on a
351
+ * domain that was never configured for it.
352
+ */
353
+ export function resolveMarketForHost(
354
+ config: JarShopConfig,
355
+ host: string | null | undefined,
356
+ options: MarketHostOptions = {},
357
+ ): JarShopMarket | undefined {
358
+ const hostname = normalizeHost(host);
359
+ const matched = config.markets.find((market) =>
360
+ market.domains.includes(hostname),
361
+ );
362
+ if (matched) return matched;
363
+ if (options.production) {
364
+ return config.markets.length === 1 ? defaultMarket(config) : undefined;
365
+ }
366
+ const fallback = options.fallbackMarket?.trim();
367
+ if (fallback) {
368
+ const market = findMarket(config, fallback);
369
+ if (!market) {
370
+ throw new Error(
371
+ `JARSHOP_DEV_MARKET "${fallback}" is not a market in jarshop.config.ts (${config.markets
372
+ .map((item) => item.code)
373
+ .join(", ")})`,
374
+ );
375
+ }
376
+ return market;
377
+ }
378
+ return defaultMarket(config);
379
+ }
380
+
381
+ /**
382
+ * Restricts a requested path language to the market. A regional tag keeps its
383
+ * primary language; anything the market does not serve becomes its default.
384
+ */
385
+ export function resolveMarketLanguage(
386
+ market: JarShopMarket,
387
+ requested: string | null | undefined,
388
+ ): string {
389
+ const language = requested?.trim().toLowerCase().split(/[-_]/u)[0] ?? "";
390
+ return market.languages.includes(language)
391
+ ? language
392
+ : market.defaultLanguage;
393
+ }
394
+
395
+ export type MarketPathRoute =
396
+ | { readonly kind: "serve" }
397
+ | { readonly kind: "redirect"; readonly pathname: string }
398
+ | { readonly kind: "not-found" };
399
+
400
+ /**
401
+ * Decides how a market answers a storefront path whose first segment is the
402
+ * language. A language the market serves is rendered; a regional or
403
+ * differently cased tag of it, or a real language the market does not serve,
404
+ * redirects to the market's language so no page renders under two URLs; a
405
+ * segment that is no language at all is not found.
406
+ */
407
+ export function routeMarketPath(
408
+ market: JarShopMarket,
409
+ pathname: string,
410
+ ): MarketPathRoute {
411
+ const [, first = "", ...rest] = pathname.split("/");
412
+ const tail = rest.length > 0 ? `/${rest.join("/")}` : "";
413
+ if (first === "") {
414
+ return { kind: "redirect", pathname: `/${market.defaultLanguage}` };
415
+ }
416
+ if (market.languages.includes(first)) return { kind: "serve" };
417
+ const parts = first.toLowerCase().split(/[-_]/u);
418
+ const language = parts[0] ?? "";
419
+ const region = parts[1];
420
+ if (
421
+ !languageCodes.has(language) ||
422
+ parts.length > 2 ||
423
+ (region !== undefined && !/^[a-z0-9]{2,8}$/u.test(region))
424
+ ) {
425
+ return { kind: "not-found" };
426
+ }
427
+ const target = market.languages.includes(language)
428
+ ? language
429
+ : market.defaultLanguage;
430
+ return { kind: "redirect", pathname: `/${target}${tail}` };
431
+ }
432
+
433
+ /** Whether a market ships courier deliveries to the given country. */
434
+ export function marketServesCountry(
435
+ market: JarShopMarket,
436
+ countryCode: string,
437
+ ): boolean {
438
+ return market.countries.includes(countryCode);
439
+ }
@@ -0,0 +1,222 @@
1
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
2
+ import {
3
+ LanguageCode,
4
+ PaymentMethodHandler,
5
+ PluginCommonModule,
6
+ VendurePlugin,
7
+ defaultShippingCalculator,
8
+ defaultShippingEligibilityChecker,
9
+ defaultConfig,
10
+ mergeConfig,
11
+ runPluginConfigurations,
12
+ type ConfigService,
13
+ type RuntimeVendureConfig,
14
+ type VendureConfig,
15
+ } from "@vendure/core";
16
+ import type { MigrationInterface } from "typeorm";
17
+ import { jarShopKitMigrations } from "@jarwizz/feature-adapter-kit/server";
18
+ import { JarShopPacketaPlugin } from "@jarwizz/feature-packeta/server";
19
+ import {
20
+ JarShopInvoicingPlugin,
21
+ jarShopInvoicingMigrations,
22
+ } from "@jarwizz/jarshop-invoicing/server";
23
+
24
+ import type { JarShopFeatures } from "./jarshop-features.js";
25
+ import { JarShopInvoiceDeliveryPlugin } from "./plugins/jarshop-checkout/invoice-delivery.plugin.js";
26
+ import { JarShopCheckoutPlugin } from "./plugins/jarshop-checkout/index.js";
27
+ import { JarShopOperationCodeCheck } from "./plugins/jarshop-checkout/operation-code-check.js";
28
+
29
+ let createVendureConfig: (
30
+ features: JarShopFeatures,
31
+ environment?: NodeJS.ProcessEnv,
32
+ ) => VendureConfig;
33
+ let config: VendureConfig;
34
+ let clientFeatures: JarShopFeatures;
35
+ const originalAppEnvironment = process.env.APP_ENV;
36
+ const originalPacketaApiKey = process.env.PACKETA_API_KEY;
37
+
38
+ beforeAll(async () => {
39
+ process.env.APP_ENV = "test";
40
+ process.env.PACKETA_API_KEY = "0000000000000000";
41
+ ({ createVendureConfig, config } = await import("./vendure-config.js"));
42
+ ({ default: clientFeatures } = await import("./client/features.js"));
43
+ });
44
+
45
+ afterAll(() => {
46
+ if (originalAppEnvironment === undefined) delete process.env.APP_ENV;
47
+ else process.env.APP_ENV = originalAppEnvironment;
48
+ if (originalPacketaApiKey === undefined) delete process.env.PACKETA_API_KEY;
49
+ else process.env.PACKETA_API_KEY = originalPacketaApiKey;
50
+ });
51
+
52
+ const dummyPaymentHandler = new PaymentMethodHandler({
53
+ code: "dummy-payment",
54
+ description: [{ languageCode: LanguageCode.en, value: "Dummy payment" }],
55
+ args: {},
56
+ createPayment: (_ctx, _order, amount) => ({
57
+ amount,
58
+ state: "Settled" as const,
59
+ }),
60
+ settlePayment: () => ({ success: true }),
61
+ });
62
+
63
+ @VendurePlugin({ imports: [PluginCommonModule] })
64
+ class DummyClientPlugin {}
65
+
66
+ class DummyClientMigration1790000000000 implements MigrationInterface {
67
+ async up(): Promise<void> {}
68
+ async down(): Promise<void> {}
69
+ }
70
+
71
+ const codes = (operations: readonly { code: string }[] | undefined) =>
72
+ (operations ?? []).map((operation) => operation.code);
73
+
74
+ describe("the client-owned features slot", () => {
75
+ it("composes today's starter behaviour from the default features", () => {
76
+ expect(codes(config.paymentOptions.paymentMethodHandlers)).toEqual([
77
+ "jarshop-cod-handler",
78
+ "reference-redirect",
79
+ ]);
80
+ expect(config.plugins).toEqual(
81
+ expect.arrayContaining([
82
+ JarShopCheckoutPlugin,
83
+ JarShopInvoicingPlugin,
84
+ JarShopInvoiceDeliveryPlugin,
85
+ JarShopPacketaPlugin,
86
+ ]),
87
+ );
88
+ expect(config.dbConnectionOptions.migrations).toEqual(
89
+ expect.arrayContaining([
90
+ ...jarShopKitMigrations,
91
+ ...jarShopInvoicingMigrations,
92
+ ]),
93
+ );
94
+ });
95
+
96
+ it("switches invoicing off and adds a client payment handler, plugin and migration", () => {
97
+ const composed = createVendureConfig({
98
+ ...clientFeatures,
99
+ paymentMethodHandlers: [
100
+ ...clientFeatures.paymentMethodHandlers,
101
+ dummyPaymentHandler,
102
+ ],
103
+ invoicing: false,
104
+ plugins: [DummyClientPlugin],
105
+ migrations: [DummyClientMigration1790000000000],
106
+ });
107
+
108
+ expect(codes(composed.paymentOptions.paymentMethodHandlers)).toEqual([
109
+ "jarshop-cod-handler",
110
+ "reference-redirect",
111
+ "dummy-payment",
112
+ ]);
113
+ expect(composed.plugins).toContain(DummyClientPlugin);
114
+ expect(composed.plugins).toContain(JarShopCheckoutPlugin);
115
+ expect(composed.plugins).not.toContain(JarShopInvoicingPlugin);
116
+ expect(composed.plugins).not.toContain(JarShopInvoiceDeliveryPlugin);
117
+ const migrations = composed.dbConnectionOptions.migrations as unknown[];
118
+ expect(migrations).toContain(DummyClientMigration1790000000000);
119
+ expect(migrations).toEqual(
120
+ expect.arrayContaining([...jarShopKitMigrations]),
121
+ );
122
+ for (const migration of jarShopInvoicingMigrations)
123
+ expect(migrations).not.toContain(migration);
124
+ });
125
+
126
+ it("lets the features and the environment each switch Packeta off", () => {
127
+ const disabledInFeatures = createVendureConfig({
128
+ ...clientFeatures,
129
+ packeta: false,
130
+ });
131
+ const disabledByEnvironment = createVendureConfig(clientFeatures, {
132
+ ...process.env,
133
+ JARSHOP_PACKETA_ENABLED: "0",
134
+ });
135
+ for (const composed of [disabledInFeatures, disabledByEnvironment]) {
136
+ expect(composed.plugins).not.toContain(JarShopPacketaPlugin);
137
+ expect(
138
+ codes(composed.shippingOptions?.shippingCalculators),
139
+ ).not.toContain("packeta-calculator");
140
+ expect(
141
+ codes(composed.shippingOptions?.shippingEligibilityCheckers),
142
+ ).not.toContain("packeta-eligibility");
143
+ }
144
+ });
145
+
146
+ it("replaces the shipping operations with the client's own list", () => {
147
+ const composed = createVendureConfig({
148
+ ...clientFeatures,
149
+ packeta: false,
150
+ shippingEligibilityCheckers: [defaultShippingEligibilityChecker],
151
+ shippingCalculators: [],
152
+ });
153
+ expect(codes(composed.shippingOptions?.shippingCalculators)).toEqual([]);
154
+ expect(
155
+ codes(composed.shippingOptions?.shippingEligibilityCheckers),
156
+ ).toEqual(["default-shipping-eligibility-checker"]);
157
+ });
158
+
159
+ it("rejects two operations of one kind with the same code", () => {
160
+ expect(() =>
161
+ createVendureConfig({
162
+ ...clientFeatures,
163
+ paymentMethodHandlers: [dummyPaymentHandler, dummyPaymentHandler],
164
+ shippingCalculators: [
165
+ defaultShippingCalculator,
166
+ defaultShippingCalculator,
167
+ ],
168
+ }),
169
+ ).toThrow(
170
+ /Payment method handler code "dummy-payment"[\s\S]*Shipping calculator code "default-shipping-calculator"/,
171
+ );
172
+ });
173
+
174
+ it("detects a code a plugin adds in its own configuration hook", async () => {
175
+ @VendurePlugin({
176
+ imports: [PluginCommonModule],
177
+ configuration: (pluginConfig) => {
178
+ pluginConfig.paymentOptions.paymentMethodHandlers.push(
179
+ dummyPaymentHandler,
180
+ );
181
+ return pluginConfig;
182
+ },
183
+ })
184
+ class PaymentContributingPlugin {}
185
+
186
+ const check = async (features: JarShopFeatures) => {
187
+ const composed = createVendureConfig(features);
188
+ // Vendure's bootstrap order: defaults merged with the project
189
+ // configuration, then every plugin's configuration hook.
190
+ const runtime = await runPluginConfigurations(
191
+ mergeConfig(defaultConfig, {
192
+ ...composed,
193
+ paymentOptions: {
194
+ ...composed.paymentOptions,
195
+ paymentMethodHandlers: [
196
+ ...composed.paymentOptions.paymentMethodHandlers,
197
+ ],
198
+ },
199
+ }) as RuntimeVendureConfig,
200
+ );
201
+ new JarShopOperationCodeCheck(
202
+ runtime as unknown as ConfigService,
203
+ ).onApplicationBootstrap();
204
+ };
205
+
206
+ // The starter's own composition passes once every plugin hook has run.
207
+ await expect(check(clientFeatures)).resolves.toBeUndefined();
208
+ // createVendureConfig cannot see this clash; the startup check can.
209
+ await expect(
210
+ check({
211
+ ...clientFeatures,
212
+ paymentMethodHandlers: [
213
+ ...clientFeatures.paymentMethodHandlers,
214
+ dummyPaymentHandler,
215
+ ],
216
+ plugins: [PaymentContributingPlugin],
217
+ }),
218
+ ).rejects.toThrow(
219
+ /including operations added by plugins:\n- Payment method handler code "dummy-payment"/,
220
+ );
221
+ });
222
+ });