@graphcommerce/next-config 11.0.0-canary.49 → 11.0.0-canary.50

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/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Change Log
2
2
 
3
+ ## 11.0.0-canary.50
4
+
5
+ ### Major Changes
6
+
7
+ - [#2707](https://github.com/graphcommerce-org/graphcommerce/pull/2707) [`abcfce1`](https://github.com/graphcommerce-org/graphcommerce/commit/abcfce130beaf5544a6ceec794fdeb99e4b3e3ba) - **Breaking change:** configuration fields are server-only, unless their definition in `Config.graphqls` has `@public`. In the browser, `@graphcommerce/next-config/config` resolves to a file with only the `@public` fields, so secrets such as `previewSecret` and `hygraphSecret` stay out of the client JavaScript and its source maps. Turbopack stops the build on a browser import of a server-only field. See [docs/upgrading/graphcommerce-10-to-11.md](docs/upgrading/graphcommerce-10-to-11.md). ([@paales](https://github.com/paales))
8
+
9
+ ### Patch Changes
10
+
11
+ - [#2707](https://github.com/graphcommerce-org/graphcommerce/pull/2707) [`d17e00b`](https://github.com/graphcommerce-org/graphcommerce/commit/d17e00b0553402cd956c0b93c32979b1ef89f0c7) - A configuration field without a value has the default from `Config.graphqls`, such as `containerSizingShell: 'FULL_WIDTH'`. ([@paales](https://github.com/paales))
12
+
13
+ - [#2707](https://github.com/graphcommerce-org/graphcommerce/pull/2707) [`6f3fcab`](https://github.com/graphcommerce-org/graphcommerce/commit/6f3fcab35fe9b7ab58825ed0ee0c2663bb28e918) - `findParentPath()` returns a parent `@graphcommerce` package only when its `workspaces` contain the directory. Codegen in a checkout inside another GraphCommerce repository, such as a git worktree in `.tmp`, changes only the files of that checkout. ([@paales](https://github.com/paales))
14
+
3
15
  ## 11.0.0-canary.49
4
16
 
5
17
  ## 11.0.0-canary.48
package/Config.graphqls CHANGED
@@ -40,6 +40,20 @@ You can also use the configuration in your `.meshrc.yml` by accessing
40
40
  endpoint: '{graphCommerce.magentoEndpoint}'
41
41
  ```
42
42
 
43
+ ## Public and server-only configuration
44
+
45
+ A field with `@public` is available in the browser. A field without `@public` is server-only:
46
+ code that runs in the browser cannot read it.
47
+
48
+ - Turbopack stops the build when browser code imports a server-only field from
49
+ `@graphcommerce/next-config/config`.
50
+ - A server-only field of a storefront, such as `useStorefrontConfig().myServerField`, throws in
51
+ development and returns `undefined` in production.
52
+ - A server-only field of a section, such as `algolia.searchOnlyApiKey`, is `undefined`.
53
+
54
+ Put `@public` on fields with a scalar or enum type. In the browser, a field with an input type, such
55
+ as `debug: GraphCommerceDebugConfig`, contains only the `@public` fields of that input.
56
+
43
57
  ## Environment variables to override configuration
44
58
 
45
59
  Configuration values can be overwriten by environment variables, with the following rules:
@@ -64,10 +78,11 @@ Create a graphql/Config.graphqls file in your project and extend the GraphCommer
64
78
 
65
79
  ```graphql
66
80
  extend input GraphCommerceConfig {
67
- myConfig: String # or Boolean, or Int, or Float, make required with `!`
81
+ myConfig: String @public # or Boolean, or Int, or Float, make required with `!`
82
+ myApiSecret: String
68
83
  }
69
84
  extend input GraphCommerceStorefrontConfig {
70
- myField: Boolean
85
+ myField: Boolean @public
71
86
  }
72
87
  ```
73
88
 
@@ -102,7 +117,7 @@ input GraphCommerceConfig {
102
117
  - https://example.com/en
103
118
  - https://example.com/en-US
104
119
  """
105
- canonicalBaseUrl: String!
120
+ canonicalBaseUrl: String! @public
106
121
 
107
122
  """
108
123
  To enable next.js' preview mode, configure the secret you'd like to use.
@@ -124,19 +139,19 @@ input GraphCommerceStorefrontConfig {
124
139
  - If there are more, the first one is used.
125
140
  - If there is none, the first entry is used.
126
141
  """
127
- defaultLocale: Boolean
142
+ defaultLocale: Boolean @public
128
143
 
129
144
  """
130
145
  Domain configuration, must be a domain https://tools.ietf.org/html/rfc3986
131
146
  """
132
- domain: String
147
+ domain: String @public
133
148
 
134
149
  """
135
150
  Must be a [locale string](https://www.unicode.org/reports/tr35/tr35-59/tr35.html#Identifiers) for automatic redirects to work.
136
151
 
137
152
  This value can be used as a sub-path identifier only, make sure linguiLocale is configured for each URL.
138
153
  """
139
- locale: String!
154
+ locale: String! @public
140
155
 
141
156
  """
142
157
  Allow the site to be indexed by search engines.
@@ -152,7 +167,7 @@ input GraphCommerceStorefrontConfig {
152
167
  - https://example.com/en
153
168
  - https://example.com/en-US
154
169
  """
155
- canonicalBaseUrl: String
170
+ canonicalBaseUrl: String @public
156
171
  }
157
172
 
158
173
  """
@@ -181,3 +196,5 @@ input GraphCommerceDebugConfig {
181
196
  """
182
197
  pluginStatus: Boolean
183
198
  }
199
+
200
+ directive @public on INPUT_FIELD_DEFINITION
@@ -0,0 +1,8 @@
1
+ import { GraphCommerceConfigSchema } from '../../src/generated/config'
2
+
3
+ it('applies the GraphQL default to a field without a value', () => {
4
+ const { shape } = GraphCommerceConfigSchema()
5
+ expect(shape.containerSizingShell.parse(undefined)).toBe('FULL_WIDTH')
6
+ expect(shape.containerSizingShell.parse(null)).toBeNull()
7
+ expect(shape.containerSizingShell.parse('BREAKPOINT')).toBe('BREAKPOINT')
8
+ })
@@ -0,0 +1,36 @@
1
+ import fs from 'fs'
2
+ import os from 'os'
3
+ import path from 'path'
4
+ import { findParentPath } from '../../src/utils/findParentPath'
5
+
6
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'find-parent-path-'))
7
+
8
+ const write = (dir: string, packageJson: object) => {
9
+ fs.mkdirSync(path.join(root, dir), { recursive: true })
10
+ fs.writeFileSync(path.join(root, dir, 'package.json'), JSON.stringify(packageJson))
11
+ }
12
+
13
+ write('.', {
14
+ name: '@graphcommerce/private',
15
+ workspaces: ['graphcommerce', 'graphcommerce/examples/*'],
16
+ })
17
+ write('graphcommerce', { name: '@graphcommerce/graphcommerce', workspaces: ['examples/*'] })
18
+ write('graphcommerce/examples/shop', { name: '@graphcommerce/shop' })
19
+ write('.tmp/worktree', { name: '@graphcommerce/private', workspaces: ['graphcommerce'] })
20
+ write('.tmp/worktree/graphcommerce', { name: '@graphcommerce/graphcommerce' })
21
+
22
+ afterAll(() => fs.rmSync(root, { recursive: true, force: true }))
23
+
24
+ it('returns the parent that has the directory as a workspace', () => {
25
+ expect(findParentPath(path.join(root, 'graphcommerce/examples/shop'))).toBe(
26
+ path.join(root, 'graphcommerce'),
27
+ )
28
+ expect(findParentPath(path.join(root, 'graphcommerce'))).toBe(root)
29
+ expect(findParentPath(path.join(root, '.tmp/worktree/graphcommerce'))).toBe(
30
+ path.join(root, '.tmp/worktree'),
31
+ )
32
+ })
33
+
34
+ it('returns null for a checkout inside another repository', () => {
35
+ expect(findParentPath(path.join(root, '.tmp/worktree'))).toBeNull()
36
+ })
@@ -22,17 +22,17 @@ function DatalayerConfigSchema() {
22
22
  }
23
23
  function GraphCommerceConfigSchema() {
24
24
  return z.object({
25
- breadcrumbs: z.boolean().default(false).nullish(),
25
+ breadcrumbs: z.boolean().nullish().default(false),
26
26
  canonicalBaseUrl: z.string().min(1),
27
27
  cartDisplayPricesInclTax: z.boolean().nullish(),
28
28
  compare: z.boolean().nullish(),
29
- compareVariant: CompareVariantSchema.default("ICON").nullish(),
30
- configurableVariantForSimple: z.boolean().default(false).nullish(),
29
+ compareVariant: CompareVariantSchema.nullish().default("ICON"),
30
+ configurableVariantForSimple: z.boolean().nullish().default(false),
31
31
  configurableVariantValues: z.lazy(() => MagentoConfigurableVariantValuesSchema().nullish()),
32
- containerSizingContent: ContainerSizingSchema.default("FULL_WIDTH").nullish(),
33
- containerSizingShell: ContainerSizingSchema.default("FULL_WIDTH").nullish(),
34
- crossSellsHideCartItems: z.boolean().default(false).nullish(),
35
- crossSellsRedirectItems: z.boolean().default(false).nullish(),
32
+ containerSizingContent: ContainerSizingSchema.nullish().default("FULL_WIDTH"),
33
+ containerSizingShell: ContainerSizingSchema.nullish().default("FULL_WIDTH"),
34
+ crossSellsHideCartItems: z.boolean().nullish().default(false),
35
+ crossSellsRedirectItems: z.boolean().nullish().default(false),
36
36
  customerAddressNoteEnable: z.boolean().nullish(),
37
37
  customerCompanyFieldsEnable: z.boolean().nullish(),
38
38
  customerDeleteEnabled: z.boolean().nullish(),
@@ -44,7 +44,7 @@ function GraphCommerceConfigSchema() {
44
44
  googlePlaystore: z.lazy(() => GraphCommerceGooglePlaystoreConfigSchema().nullish()),
45
45
  googleRecaptchaKey: z.string().nullish(),
46
46
  googleTagmanagerId: z.string().nullish(),
47
- graphqlMeshEditMode: z.boolean().default(false).nullish(),
47
+ graphqlMeshEditMode: z.boolean().nullish().default(false),
48
48
  hygraphManagementApi: z.string().nullish(),
49
49
  hygraphProjectId: z.string().nullish(),
50
50
  hygraphWriteAccessToken: z.string().nullish(),
@@ -53,9 +53,9 @@ function GraphCommerceConfigSchema() {
53
53
  magentoVersion: z.number(),
54
54
  permissions: z.lazy(() => GraphCommercePermissionsSchema().nullish()),
55
55
  previewSecret: z.string().nullish(),
56
- productFiltersLayout: ProductFiltersLayoutSchema.default("DEFAULT").nullish(),
56
+ productFiltersLayout: ProductFiltersLayoutSchema.nullish().default("DEFAULT"),
57
57
  productFiltersPro: z.boolean().nullish(),
58
- productListPaginationVariant: PaginationVariantSchema.default("COMPACT").nullish(),
58
+ productListPaginationVariant: PaginationVariantSchema.nullish().default("COMPACT"),
59
59
  productRoute: z.string().nullish(),
60
60
  recentlyViewedProducts: z.lazy(() => RecentlyViewedProductsConfigSchema().nullish()),
61
61
  robotsAllow: z.boolean().nullish(),
package/dist/index.js CHANGED
@@ -7,7 +7,7 @@ import { spawn } from 'child_process';
7
7
  import { l as loadConfig, t as toEnvStr } from './loadConfig-S8JJz4LU.js';
8
8
  export { r as replaceConfigInString } from './loadConfig-S8JJz4LU.js';
9
9
  import { parseFileSync, parseSync as parseSync$1, transformFileSync } from '@swc/core';
10
- import fs$1, { writeFileSync, readFileSync, existsSync, rmSync, mkdirSync } from 'fs';
10
+ import fs$1, { writeFileSync, readFileSync, rmSync, mkdirSync, existsSync } from 'fs';
11
11
  import { resolve as resolve$2 } from 'import-meta-resolve';
12
12
  import assert from 'assert';
13
13
  import crypto from 'crypto';
@@ -17,8 +17,8 @@ import prettierConf from '@graphcommerce/prettier-config-pwa';
17
17
  import prettier from 'prettier';
18
18
  import fg from 'fast-glob';
19
19
  import { generate } from '@graphql-codegen/cli';
20
- import { GraphCommerceConfigSchema } from './generated/config.js';
21
- export { GraphCommerceDebugConfigSchema, GraphCommerceStorefrontConfigSchema } from './generated/config.js';
20
+ import { parse, Kind } from 'graphql';
21
+ export { GraphCommerceConfigSchema, GraphCommerceDebugConfigSchema, GraphCommerceStorefrontConfigSchema } from './generated/config.js';
22
22
  import 'cosmiconfig';
23
23
  import 'node:fs';
24
24
  import 'node:module';
@@ -1395,6 +1395,10 @@ async function exportConfig() {
1395
1395
  }
1396
1396
 
1397
1397
  const packages = [...resolveDependenciesSync().values()].filter((p) => p !== ".");
1398
+ const configSchemaLocations = [
1399
+ "graphql/Config.graphqls",
1400
+ ...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`])
1401
+ ];
1398
1402
  const resolve$1 = resolveDependency();
1399
1403
  dotenv.config({ quiet: true });
1400
1404
  async function generateConfig() {
@@ -1402,13 +1406,9 @@ async function generateConfig() {
1402
1406
  if (!resolved) throw Error("Could not resolve @graphcommerce/next-config");
1403
1407
  const targetTs = `${resolved.root}/src/generated/config.ts`;
1404
1408
  const targetJs = `${resolved.root}/dist/generated/config.js`;
1405
- const schemaLocations = [
1406
- "graphql/Config.graphqls",
1407
- ...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`])
1408
- ];
1409
1409
  await generate({
1410
1410
  silent: true,
1411
- schema: schemaLocations,
1411
+ schema: configSchemaLocations,
1412
1412
  generates: {
1413
1413
  [targetTs]: {
1414
1414
  plugins: ["typescript", "typescript-validation-schema"],
@@ -1434,13 +1434,21 @@ async function generateConfig() {
1434
1434
  });
1435
1435
  writeFileSync(
1436
1436
  targetTs,
1437
- await prettier.format(readFileSync(targetTs, "utf-8"), {
1438
- ...prettierConf,
1439
- parser: "typescript",
1440
- plugins: prettierConf.plugins?.filter(
1441
- (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1442
- )
1443
- })
1437
+ // typescript-validation-schema writes `.default(x).nullish()`: `.nullish()` returns undefined
1438
+ // before `.default()` runs.
1439
+ await prettier.format(
1440
+ readFileSync(targetTs, "utf-8").replace(
1441
+ /\.default\(([^()]+)\)\.nullish\(\)/g,
1442
+ ".nullish().default($1)"
1443
+ ),
1444
+ {
1445
+ ...prettierConf,
1446
+ parser: "typescript",
1447
+ plugins: prettierConf.plugins?.filter(
1448
+ (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1449
+ )
1450
+ }
1451
+ )
1444
1452
  );
1445
1453
  const result = transformFileSync(targetTs, {
1446
1454
  module: { type: "nodenext" },
@@ -1451,155 +1459,152 @@ async function generateConfig() {
1451
1459
 
1452
1460
  dotenv.config({ quiet: true });
1453
1461
  const resolve = resolveDependency();
1454
- function toFileName(key) {
1455
- return key;
1456
- }
1457
- function generateValueLiteral(value) {
1458
- if (value === null) return "null";
1459
- if (value === void 0) return "undefined";
1460
- if (typeof value === "string") return JSON.stringify(value);
1461
- if (typeof value === "boolean" || typeof value === "number") return String(value);
1462
- if (Array.isArray(value) || typeof value === "object" && value !== null) {
1463
- return JSON.stringify(value, null, 2);
1464
- }
1465
- return JSON.stringify(value);
1466
- }
1467
- function shouldCreateFile(value) {
1468
- return typeof value === "object" && value !== null && !Array.isArray(value);
1469
- }
1470
- function getSectionSchemaKeys(configKey) {
1471
- try {
1472
- const mainSchema = GraphCommerceConfigSchema();
1473
- const sectionSchema = mainSchema.shape[configKey];
1474
- if (!sectionSchema) return [];
1475
- let unwrappedSchema = sectionSchema;
1476
- while (true) {
1477
- if (!unwrappedSchema || typeof unwrappedSchema !== "object") break;
1478
- if (!("_def" in unwrappedSchema)) break;
1479
- const def = unwrappedSchema._def;
1480
- const typeName = def?.typeName;
1481
- if (typeName === "ZodLazy" && def.getter) {
1482
- unwrappedSchema = def.getter();
1483
- continue;
1484
- }
1485
- if (def.innerType) {
1486
- unwrappedSchema = def.innerType;
1487
- continue;
1488
- }
1489
- if (typeName === "ZodObject" && def.shape) {
1490
- const shape = typeof def.shape === "function" ? def.shape() : def.shape;
1491
- return Object.keys(shape || {});
1492
- }
1493
- break;
1494
- }
1495
- if (unwrappedSchema && "shape" in unwrappedSchema) {
1496
- const shape = typeof unwrappedSchema.shape === "function" ? unwrappedSchema.shape() : unwrappedSchema.shape;
1497
- return Object.keys(shape || {});
1498
- }
1499
- } catch {
1500
- }
1501
- return [];
1502
- }
1503
- async function createConfigSectionFile(sectionName, sectionValue, targetDir, targetDistDir, configKey) {
1504
- const fileName = `${toFileName(sectionName)}.ts`;
1505
- const filePath = path.join(targetDir, fileName);
1506
- const distFileName = `${toFileName(sectionName)}.js`;
1507
- const distFilePath = path.join(targetDistDir, distFileName);
1508
- const schemaKeys = getSectionSchemaKeys(configKey);
1509
- const completeSectionValue = {};
1510
- for (const key of schemaKeys) {
1511
- completeSectionValue[key] = sectionValue[key];
1512
- }
1513
- const exports = Object.entries(completeSectionValue).map(([key, value]) => {
1514
- const valueStr = generateValueLiteral(value);
1515
- const propertyPath = `'${sectionName}.${key}'`;
1516
- const typeAnnotation = `: Get<GraphCommerceConfig, ${propertyPath}>`;
1517
- return `export const ${key}${typeAnnotation} = ${valueStr}`;
1518
- }).join("\n\n");
1519
- const imports = `import type { GraphCommerceConfig } from '../config'
1520
- import type { Get } from 'type-fest'` ;
1521
- const content = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
1522
- ${imports}
1523
-
1524
- ${exports}
1525
- `;
1526
- const formattedContent = await prettier.format(content, {
1527
- ...prettierConf,
1528
- parser: "typescript",
1529
- plugins: prettierConf.plugins?.filter(
1530
- (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1531
- )
1532
- });
1533
- writeFileSync(filePath, formattedContent);
1534
- const result = transformFileSync(filePath, {
1535
- module: { type: "nodenext" },
1536
- env: { targets: { node: "18" } }
1537
- });
1538
- writeFileSync(distFilePath, result.code);
1539
- }
1462
+ const header = `// Auto-generated by 'yarn graphcommerce codegen-config-values'`;
1463
+ const typeImports = `import type { GraphCommerceConfig } from '../config'
1464
+ import type { Get } from 'type-fest'`;
1465
+ const literal = (value) => value === void 0 ? "undefined" : JSON.stringify(value, null, 2);
1466
+ const namedType = (type) => type.kind === Kind.NAMED_TYPE ? type.name.value : namedType(type.type);
1467
+ const isPublic = (field) => Boolean(field.directives?.some((directive) => directive.name.value === "public"));
1468
+ const isSection = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1540
1469
  async function generateConfigValues() {
1541
1470
  const resolved = resolve("@graphcommerce/next-config");
1542
1471
  if (!resolved) throw Error("Could not resolve @graphcommerce/next-config");
1543
1472
  const config = loadConfig(process.cwd());
1544
- const targetDir = `${resolved.root}/src/generated/configValues`;
1545
- const targetDistDir = `${resolved.root}/dist/generated/configValues`;
1546
- if (existsSync(targetDir)) {
1547
- rmSync(targetDir, { recursive: true, force: true });
1548
- }
1549
- if (existsSync(targetDistDir)) {
1550
- rmSync(targetDistDir, { recursive: true, force: true });
1473
+ const srcDir = `${resolved.root}/src/generated/configValues`;
1474
+ const distDir = `${resolved.root}/dist/generated/configValues`;
1475
+ const publicOnlyDir = `${distDir}/publicOnly`;
1476
+ rmSync(srcDir, { recursive: true, force: true });
1477
+ rmSync(distDir, { recursive: true, force: true });
1478
+ mkdirSync(srcDir, { recursive: true });
1479
+ mkdirSync(publicOnlyDir, { recursive: true });
1480
+ const inputs = /* @__PURE__ */ new Map();
1481
+ for (const location of configSchemaLocations.filter((l) => existsSync(l))) {
1482
+ for (const def of parse(readFileSync(location, "utf-8")).definitions) {
1483
+ if (def.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION && def.kind !== Kind.INPUT_OBJECT_TYPE_EXTENSION)
1484
+ continue;
1485
+ const typeName = def.name.value;
1486
+ inputs.set(typeName, [...inputs.get(typeName) ?? [], ...def.fields ?? []]);
1487
+ }
1551
1488
  }
1552
- mkdirSync(targetDir, { recursive: true });
1553
- mkdirSync(targetDistDir, { recursive: true });
1554
- const schema = GraphCommerceConfigSchema();
1555
- const schemaKeys = Object.keys(schema.shape);
1556
- const completeConfig = {};
1557
- for (const key of schemaKeys) {
1558
- completeConfig[key] = config[key];
1489
+ for (const [typeName, fields] of inputs) {
1490
+ const misplaced = fields.find((f) => isPublic(f) && inputs.has(namedType(f.type)));
1491
+ if (misplaced) {
1492
+ throw Error(
1493
+ `@public on ${typeName}.${misplaced.name.value}: add @public to the fields of ${namedType(misplaced.type)}.`
1494
+ );
1495
+ }
1559
1496
  }
1560
- const configEntries = Object.entries(completeConfig);
1561
- const nestedObjects = [];
1562
- const rootExports = [];
1563
- for (const [key, value] of configEntries) {
1564
- if (shouldCreateFile(value)) {
1565
- nestedObjects.push([key, value, key]);
1566
- rootExports.push(`export * as ${key} from './${toFileName(key)}'`);
1497
+ const hasPublic = (typeName) => (inputs.get(typeName) ?? []).some(
1498
+ (f) => inputs.has(namedType(f.type)) ? hasPublic(namedType(f.type)) : isPublic(f)
1499
+ );
1500
+ const browserLiteral = (value, typeName, valuePath) => {
1501
+ if (Array.isArray(value))
1502
+ return `[${value.map((item) => browserLiteral(item, typeName, `${valuePath}[]`)).join(",\n")}]`;
1503
+ if (!isSection(value)) return literal(value);
1504
+ const properties = [];
1505
+ const getters = [];
1506
+ for (const field of inputs.get(typeName) ?? []) {
1507
+ const name = field.name.value;
1508
+ const fieldType = namedType(field.type);
1509
+ const isInput = inputs.has(fieldType);
1510
+ if (!(isInput ? hasPublic(fieldType) : isPublic(field))) {
1511
+ const hint = isInput ? `the fields of ${fieldType}` : `${typeName}.${name}`;
1512
+ getters.push(`${name}: serverOnly('${valuePath}.${name}', '${hint}')`);
1513
+ } else if (value[name] !== void 0) {
1514
+ const fieldValue = isInput ? browserLiteral(value[name], fieldType, `${valuePath}.${name}`) : literal(value[name]);
1515
+ properties.push(`${JSON.stringify(name)}: ${fieldValue}`);
1516
+ }
1517
+ }
1518
+ const object = `{
1519
+ ${properties.join(",\n")}
1520
+ }`;
1521
+ return getters.length ? `Object.defineProperties(${object}, {
1522
+ ${getters.join(",\n")}
1523
+ })` : object;
1524
+ };
1525
+ const writeServerModule = async (name, content) => {
1526
+ const srcFile = path.join(srcDir, `${name}.ts`);
1527
+ writeFileSync(
1528
+ srcFile,
1529
+ await prettier.format(content, {
1530
+ ...prettierConf,
1531
+ parser: "typescript",
1532
+ plugins: prettierConf.plugins?.filter(
1533
+ (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1534
+ )
1535
+ })
1536
+ );
1537
+ const { code } = transformFileSync(srcFile, {
1538
+ module: { type: "nodenext" },
1539
+ env: { targets: { node: "20" } }
1540
+ });
1541
+ writeFileSync(path.join(distDir, `${name}.js`), code);
1542
+ };
1543
+ const writePublicOnlyModule = (name, serverOnlyNames, exports) => {
1544
+ const lines = [
1545
+ header,
1546
+ "// Browser build of @graphcommerce/next-config/config: only fields with @public in Config.graphqls.",
1547
+ "// Add @public to a field to read it in the browser. Keep secrets server-only.",
1548
+ ...serverOnlyNames.length ? [`// Server-only: ${serverOnlyNames.join(", ")}`] : []
1549
+ ];
1550
+ if (exports.some((e) => e.includes("serverOnly("))) {
1551
+ lines.push(`const serverOnly = (valuePath, hint) => ({
1552
+ get() {
1553
+ if (process.env.NODE_ENV !== 'production')
1554
+ throw Error(\`\${valuePath} is server-only. Read it on the server or add @public to \${hint} in Config.graphqls.\`)
1555
+ },
1556
+ })`);
1557
+ }
1558
+ writeFileSync(path.join(publicOnlyDir, `${name}.js`), [...lines, ...exports].join("\n"));
1559
+ };
1560
+ const serverExports = [];
1561
+ const browserExports = [];
1562
+ const serverOnlyKeys = [];
1563
+ let sectionCount = 0;
1564
+ for (const field of inputs.get("GraphCommerceConfig") ?? []) {
1565
+ const key = field.name.value;
1566
+ const value = config[key];
1567
+ const fieldType = namedType(field.type);
1568
+ const sectionFields = inputs.get(fieldType) ?? [];
1569
+ if (isSection(value)) {
1570
+ sectionCount++;
1571
+ const sectionExports = sectionFields.map(
1572
+ ({ name }) => `export const ${name.value}: Get<GraphCommerceConfig, '${key}.${name.value}'> = ${literal(value[name.value])}`
1573
+ );
1574
+ await writeServerModule(key, [header, typeImports, ...sectionExports].join("\n\n"));
1575
+ serverExports.push(`export * as ${key} from './${key}.js'`);
1576
+ } else {
1577
+ serverExports.push(
1578
+ `export const ${key}: Get<GraphCommerceConfig, '${key}'> = ${literal(value)}`
1579
+ );
1580
+ }
1581
+ if (!(inputs.has(fieldType) ? hasPublic(fieldType) : isPublic(field))) {
1582
+ serverOnlyKeys.push(key);
1583
+ } else if (isSection(value)) {
1584
+ const sectionServerOnly = [];
1585
+ const sectionPublic = [];
1586
+ for (const sectionField of sectionFields) {
1587
+ const name = sectionField.name.value;
1588
+ const nestedType = namedType(sectionField.type);
1589
+ if (!(inputs.has(nestedType) ? hasPublic(nestedType) : isPublic(sectionField)))
1590
+ sectionServerOnly.push(name);
1591
+ else
1592
+ sectionPublic.push(
1593
+ `export const ${name} = ${browserLiteral(value[name], nestedType, `${key}.${name}`)}`
1594
+ );
1595
+ }
1596
+ writePublicOnlyModule(key, sectionServerOnly, sectionPublic);
1597
+ browserExports.push(`export * as ${key} from './${key}.js'`);
1567
1598
  } else {
1568
- const valueStr = generateValueLiteral(value);
1569
- const typeAnnotation = `: Get<GraphCommerceConfig, '${key}'>`;
1570
- rootExports.push(`export const ${key}${typeAnnotation} = ${valueStr}`);
1599
+ browserExports.push(`export const ${key} = ${browserLiteral(value, fieldType, key)}`);
1571
1600
  }
1572
1601
  }
1573
- await Promise.all(
1574
- nestedObjects.map(
1575
- ([sectionName, sectionValue, configKey]) => createConfigSectionFile(sectionName, sectionValue, targetDir, targetDistDir, configKey)
1576
- )
1602
+ await writeServerModule("index", [header, typeImports, ...serverExports].join("\n"));
1603
+ writePublicOnlyModule("index", serverOnlyKeys, browserExports);
1604
+ console.log(`\u2705 Generated config values in ${srcDir} and ${distDir}`);
1605
+ console.log(
1606
+ `\u{1F4C1} ${sectionCount} sections, ${serverExports.length} server exports, ${browserExports.length} browser exports`
1577
1607
  );
1578
- const rootImports = `import type { GraphCommerceConfig } from '../config'
1579
- import type { Get } from 'type-fest'` ;
1580
- const indexContent = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
1581
- ${rootImports}
1582
-
1583
- ${rootExports.join("\n")}
1584
- `;
1585
- const formattedIndexContent = await prettier.format(indexContent, {
1586
- ...prettierConf,
1587
- parser: "typescript",
1588
- plugins: prettierConf.plugins?.filter(
1589
- (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
1590
- )
1591
- });
1592
- const indexPath = path.join(targetDir, "index.ts");
1593
- const distIndexPath = path.join(targetDistDir, "index.js");
1594
- writeFileSync(indexPath, formattedIndexContent);
1595
- const indexResult = transformFileSync(indexPath, {
1596
- module: { type: "nodenext" },
1597
- env: { targets: { node: "20" } }
1598
- });
1599
- writeFileSync(distIndexPath, indexResult.code);
1600
- console.log(`\u2705 Generated config values in ${targetDir} and ${targetDistDir}`);
1601
- console.log(`\u{1F4C1} Created ${nestedObjects.length} nested object files + index.ts/.js`);
1602
- console.log(`\u{1F4DD} Root exports: ${configEntries.length - nestedObjects.length}`);
1603
1608
  }
1604
1609
 
1605
1610
  let graphcommerceConfig;
@@ -1739,4 +1744,4 @@ function withGraphCommerce(nextConfig, cwd = process.cwd()) {
1739
1744
  };
1740
1745
  }
1741
1746
 
1742
- export { GraphCommerceConfigSchema, PackagesSort, TopologicalSort, cleanupInterceptors, codegen, codegenInterceptors, copyFiles, exportConfig, findParentPath, g, generateConfig, generateConfigValues, loadConfig, packageRoots, resolveDependenciesSync, resolveDependency, sig, sortDependencies, withGraphCommerce };
1747
+ export { PackagesSort, TopologicalSort, cleanupInterceptors, codegen, codegenInterceptors, configSchemaLocations, copyFiles, exportConfig, findParentPath, g, generateConfig, generateConfigValues, loadConfig, packageRoots, resolveDependenciesSync, resolveDependency, sig, sortDependencies, withGraphCommerce };
@@ -19,13 +19,15 @@ function findParentPath(directory) {
19
19
  log(`Looking for parent packages starting from: ${currentDir}`);
20
20
  while (currentDir !== path.parse(currentDir).root) {
21
21
  const packageJson = findPackageJson(currentDir);
22
- if (packageJson) {
23
- log(`Found package.json in: ${currentDir}`);
24
- log(`Package name: ${packageJson.name}`);
25
- if (packageJson.name.startsWith("@graphcommerce/")) {
22
+ if (packageJson?.name?.startsWith("@graphcommerce/")) {
23
+ log(`Found package ${packageJson.name} in: ${currentDir}`);
24
+ const workspaces = Array.isArray(packageJson.workspaces) ? packageJson.workspaces : packageJson.workspaces?.packages ?? [];
25
+ const relative = path.relative(currentDir, directory);
26
+ if (workspaces.some((workspace) => path.matchesGlob(relative, workspace))) {
26
27
  log(`Found parent @graphcommerce package at: ${currentDir}`);
27
28
  return currentDir;
28
29
  }
30
+ log(`${relative} is not a workspace of ${packageJson.name}`);
29
31
  }
30
32
  currentDir = path.dirname(currentDir);
31
33
  }
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@graphcommerce/next-config",
3
3
  "homepage": "https://www.graphcommerce.org/",
4
4
  "repository": "github:graphcommerce-org/graphcommerce",
5
- "version": "11.0.0-canary.49",
5
+ "version": "11.0.0-canary.50",
6
6
  "type": "module",
7
7
  "exports": {
8
8
  ".": {
@@ -15,6 +15,8 @@
15
15
  },
16
16
  "./config": {
17
17
  "types": "./src/generated/configValues/index.ts",
18
+ "edge-light": "./dist/generated/configValues/index.js",
19
+ "browser": "./dist/generated/configValues/publicOnly/index.js",
18
20
  "default": "./dist/generated/configValues/index.js"
19
21
  },
20
22
  "./loadConfig": {
@@ -63,7 +65,7 @@
63
65
  },
64
66
  "peerDependencies": {
65
67
  "@apollo/client": "*",
66
- "@graphcommerce/prettier-config-pwa": "^11.0.0-canary.49",
68
+ "@graphcommerce/prettier-config-pwa": "^11.0.0-canary.50",
67
69
  "@lingui/loader": "*",
68
70
  "@lingui/macro": "*",
69
71
  "@lingui/react": "*",
@@ -9,6 +9,12 @@ import { resolveDependenciesSync } from '../utils/resolveDependenciesSync'
9
9
  import { resolveDependency } from '../utils/resolveDependency'
10
10
 
11
11
  const packages = [...resolveDependenciesSync().values()].filter((p) => p !== '.')
12
+
13
+ // Use specific patterns instead of ** to avoid expensive directory traversal
14
+ export const configSchemaLocations = [
15
+ 'graphql/Config.graphqls',
16
+ ...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`]),
17
+ ]
12
18
  const resolve = resolveDependency()
13
19
 
14
20
  dotenv.config({ quiet: true })
@@ -20,15 +26,9 @@ export async function generateConfig() {
20
26
  const targetTs = `${resolved.root}/src/generated/config.ts`
21
27
  const targetJs = `${resolved.root}/dist/generated/config.js`
22
28
 
23
- // Use specific patterns instead of ** to avoid expensive directory traversal
24
- const schemaLocations = [
25
- 'graphql/Config.graphqls',
26
- ...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`]),
27
- ]
28
-
29
29
  await generate({
30
30
  silent: true,
31
- schema: schemaLocations,
31
+ schema: configSchemaLocations,
32
32
  generates: {
33
33
  [targetTs]: {
34
34
  plugins: ['typescript', 'typescript-validation-schema'],
@@ -55,13 +55,21 @@ export async function generateConfig() {
55
55
 
56
56
  writeFileSync(
57
57
  targetTs,
58
- await prettier.format(readFileSync(targetTs, 'utf-8'), {
59
- ...prettierConf,
60
- parser: 'typescript',
61
- plugins: prettierConf.plugins?.filter(
62
- (p) => typeof p === 'string' && !p.includes('prettier-plugin-sort-imports'),
58
+ // typescript-validation-schema writes `.default(x).nullish()`: `.nullish()` returns undefined
59
+ // before `.default()` runs.
60
+ await prettier.format(
61
+ readFileSync(targetTs, 'utf-8').replace(
62
+ /\.default\(([^()]+)\)\.nullish\(\)/g,
63
+ '.nullish().default($1)',
63
64
  ),
64
- }),
65
+ {
66
+ ...prettierConf,
67
+ parser: 'typescript',
68
+ plugins: prettierConf.plugins?.filter(
69
+ (p) => typeof p === 'string' && !p.includes('prettier-plugin-sort-imports'),
70
+ ),
71
+ },
72
+ ),
65
73
  )
66
74
 
67
75
  const result = transformFileSync(targetTs, {
@@ -1,264 +1,198 @@
1
- /* eslint-disable quotes */
2
- import { existsSync, mkdirSync, rmSync, writeFileSync } from 'fs'
1
+ /* eslint-disable no-console */
2
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'
3
3
  import path from 'path'
4
4
  import prettierConf from '@graphcommerce/prettier-config-pwa'
5
5
  import { transformFileSync } from '@swc/core'
6
6
  import dotenv from 'dotenv'
7
+ import type { InputValueDefinitionNode, TypeNode } from 'graphql'
8
+ import { Kind, parse } from 'graphql'
7
9
  import prettier from 'prettier'
8
10
  import { loadConfig } from '../config/loadConfig'
9
- import type { GraphCommerceConfig } from '../generated/config'
10
- import { GraphCommerceConfigSchema } from '../generated/config'
11
11
  import { resolveDependency } from '../utils/resolveDependency'
12
+ import { configSchemaLocations } from './generateConfig'
12
13
 
13
14
  dotenv.config({ quiet: true })
14
15
 
15
16
  const resolve = resolveDependency()
16
17
 
17
- /** Keeps camelCase for file names and export names */
18
- function toFileName(key: string): string {
19
- return key
20
- }
21
-
22
- /** Generates a TypeScript value literal for the given value */
23
- function generateValueLiteral(value: unknown): string {
24
- if (value === null) return 'null'
25
- if (value === undefined) return 'undefined'
26
- if (typeof value === 'string') return JSON.stringify(value)
27
- if (typeof value === 'boolean' || typeof value === 'number') return String(value)
28
- if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
29
- return JSON.stringify(value, null, 2)
30
- }
31
- return JSON.stringify(value)
32
- }
18
+ const header = `// Auto-generated by 'yarn graphcommerce codegen-config-values'`
19
+ const typeImports = `import type { GraphCommerceConfig } from '../config'\nimport type { Get } from 'type-fest'`
33
20
 
34
- /** Checks if a value should get its own file (non-null objects only, not arrays) */
35
- function shouldCreateFile(value: unknown): boolean {
36
- return typeof value === 'object' && value !== null && !Array.isArray(value)
37
- }
38
-
39
- /** Gets the schema keys for a specific config section */
40
- function getSectionSchemaKeys(configKey: keyof GraphCommerceConfig): string[] {
41
- try {
42
- const mainSchema = GraphCommerceConfigSchema()
43
- const sectionSchema = mainSchema.shape[configKey]
21
+ const literal = (value: unknown) =>
22
+ value === undefined ? 'undefined' : JSON.stringify(value, null, 2)
44
23
 
45
- if (!sectionSchema) return []
24
+ const namedType = (type: TypeNode): string =>
25
+ type.kind === Kind.NAMED_TYPE ? type.name.value : namedType(type.type)
46
26
 
47
- // Handle different schema wrapper types
48
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
- let unwrappedSchema: any = sectionSchema
27
+ const isPublic = (field: InputValueDefinitionNode) =>
28
+ Boolean(field.directives?.some((directive) => directive.name.value === 'public'))
50
29
 
51
- // Unwrap wrapper types in a loop to handle chained wrappers (e.g., ZodLazy containing ZodOptional)
52
- // eslint-disable-next-line no-constant-condition
53
- while (true) {
54
- if (!unwrappedSchema || typeof unwrappedSchema !== 'object') break
55
- if (!('_def' in unwrappedSchema)) break
30
+ const isSection = (value: unknown): value is Record<string, unknown> =>
31
+ typeof value === 'object' && value !== null && !Array.isArray(value)
56
32
 
57
- // eslint-disable-next-line no-underscore-dangle
58
- const def = unwrappedSchema._def
59
- const typeName = def?.typeName as string | undefined
60
-
61
- // Handle ZodLazy - need to evaluate the getter
62
- if (typeName === 'ZodLazy' && def.getter) {
63
- unwrappedSchema = def.getter()
64
- continue
65
- }
33
+ /**
34
+ * Writes `src/generated/configValues` and `dist/generated/configValues` with all values, for the
35
+ * server. Writes `dist/generated/configValues/publicOnly` with only the `@public` values, for the
36
+ * `browser` export condition, with a file per section for tree-shaking. A server-only field of an
37
+ * object in a list, such as `storefront[]`, is a getter that throws in development.
38
+ */
39
+ export async function generateConfigValues() {
40
+ const resolved = resolve('@graphcommerce/next-config')
41
+ if (!resolved) throw Error('Could not resolve @graphcommerce/next-config')
66
42
 
67
- // Handle ZodOptional, ZodNullable, ZodDefault
68
- if (def.innerType) {
69
- unwrappedSchema = def.innerType
43
+ const config = loadConfig(process.cwd()) as Record<string, unknown>
44
+ const srcDir = `${resolved.root}/src/generated/configValues`
45
+ const distDir = `${resolved.root}/dist/generated/configValues`
46
+ const publicOnlyDir = `${distDir}/publicOnly`
47
+
48
+ rmSync(srcDir, { recursive: true, force: true })
49
+ rmSync(distDir, { recursive: true, force: true })
50
+ mkdirSync(srcDir, { recursive: true })
51
+ mkdirSync(publicOnlyDir, { recursive: true })
52
+
53
+ const inputs = new Map<string, InputValueDefinitionNode[]>()
54
+ for (const location of configSchemaLocations.filter((l) => existsSync(l))) {
55
+ for (const def of parse(readFileSync(location, 'utf-8')).definitions) {
56
+ if (
57
+ def.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION &&
58
+ def.kind !== Kind.INPUT_OBJECT_TYPE_EXTENSION
59
+ )
70
60
  continue
71
- }
72
-
73
- // Handle ZodObject - this is what we want
74
- if (typeName === 'ZodObject' && def.shape) {
75
- const shape =
76
- typeof def.shape === 'function'
77
- ? (def.shape as () => Record<string, unknown>)()
78
- : (def.shape as Record<string, unknown>)
79
- return Object.keys(shape || {})
80
- }
81
-
82
- break
61
+ const typeName = def.name.value
62
+ inputs.set(typeName, [...(inputs.get(typeName) ?? []), ...(def.fields ?? [])])
83
63
  }
64
+ }
84
65
 
85
- // Direct ZodObject
86
- if (unwrappedSchema && 'shape' in unwrappedSchema) {
87
- const shape =
88
- typeof unwrappedSchema.shape === 'function'
89
- ? (unwrappedSchema.shape as () => Record<string, unknown>)()
90
- : (unwrappedSchema.shape as Record<string, unknown>)
91
- return Object.keys(shape || {})
66
+ for (const [typeName, fields] of inputs) {
67
+ const misplaced = fields.find((f) => isPublic(f) && inputs.has(namedType(f.type)))
68
+ if (misplaced) {
69
+ throw Error(
70
+ `@public on ${typeName}.${misplaced.name.value}: add @public to the fields of ${namedType(misplaced.type)}.`,
71
+ )
92
72
  }
93
- } catch {
94
- // Silently fail and return empty array
95
73
  }
96
74
 
97
- return []
98
- }
99
-
100
- /** Creates a configuration section file for nested objects */
101
- async function createConfigSectionFile(
102
- sectionName: string,
103
- sectionValue: Record<string, unknown>,
104
- targetDir: string,
105
- targetDistDir: string,
106
- configKey: keyof GraphCommerceConfig,
107
- ): Promise<void> {
108
- const fileName = `${toFileName(sectionName)}.ts`
109
- const filePath = path.join(targetDir, fileName)
110
- const distFileName = `${toFileName(sectionName)}.js`
111
- const distFilePath = path.join(targetDistDir, distFileName)
112
-
113
- // Get all schema keys for this section to include all properties, even undefined ones
114
- const schemaKeys = getSectionSchemaKeys(configKey)
115
-
116
- // Create complete section object with schema defaults
117
- const completeSectionValue: Record<string, unknown> = {}
118
- for (const key of schemaKeys) {
119
- completeSectionValue[key] = sectionValue[key] // Use actual value if present, undefined if not
75
+ const hasPublic = (typeName: string): boolean =>
76
+ (inputs.get(typeName) ?? []).some((f) =>
77
+ inputs.has(namedType(f.type)) ? hasPublic(namedType(f.type)) : isPublic(f),
78
+ )
79
+
80
+ const browserLiteral = (value: unknown, typeName: string, valuePath: string): string => {
81
+ if (Array.isArray(value))
82
+ return `[${value.map((item) => browserLiteral(item, typeName, `${valuePath}[]`)).join(',\n')}]`
83
+ if (!isSection(value)) return literal(value)
84
+
85
+ const properties: string[] = []
86
+ const getters: string[] = []
87
+ for (const field of inputs.get(typeName) ?? []) {
88
+ const name = field.name.value
89
+ const fieldType = namedType(field.type)
90
+ const isInput = inputs.has(fieldType)
91
+ if (!(isInput ? hasPublic(fieldType) : isPublic(field))) {
92
+ const hint = isInput ? `the fields of ${fieldType}` : `${typeName}.${name}`
93
+ getters.push(`${name}: serverOnly('${valuePath}.${name}', '${hint}')`)
94
+ } else if (value[name] !== undefined) {
95
+ const fieldValue = isInput
96
+ ? browserLiteral(value[name], fieldType, `${valuePath}.${name}`)
97
+ : literal(value[name])
98
+ properties.push(`${JSON.stringify(name)}: ${fieldValue}`)
99
+ }
100
+ }
101
+ const object = `{\n${properties.join(',\n')}\n}`
102
+ return getters.length
103
+ ? `Object.defineProperties(${object}, {\n${getters.join(',\n')}\n})`
104
+ : object
120
105
  }
121
106
 
122
- // Create individual exports for each property with proper typing
123
- const exports = Object.entries(completeSectionValue)
124
- .map(([key, value]) => {
125
- const valueStr = generateValueLiteral(value)
126
- const propertyPath = `'${sectionName}.${key}'`
127
-
128
- // Always include type annotation
129
- const typeAnnotation = `: Get<GraphCommerceConfig, ${propertyPath}>`
130
-
131
- return `export const ${key}${typeAnnotation} = ${valueStr}`
107
+ const writeServerModule = async (name: string, content: string) => {
108
+ const srcFile = path.join(srcDir, `${name}.ts`)
109
+ writeFileSync(
110
+ srcFile,
111
+ await prettier.format(content, {
112
+ ...prettierConf,
113
+ parser: 'typescript',
114
+ plugins: prettierConf.plugins?.filter(
115
+ (p) => typeof p === 'string' && !p.includes('prettier-plugin-sort-imports'),
116
+ ),
117
+ }),
118
+ )
119
+ const { code } = transformFileSync(srcFile, {
120
+ module: { type: 'nodenext' },
121
+ env: { targets: { node: '20' } },
132
122
  })
133
- .join('\n\n')
134
-
135
- // Always need the Get import since we always use type annotations
136
- const needsGetImport = true
137
-
138
- const imports = needsGetImport
139
- ? `import type { GraphCommerceConfig } from '../config'\nimport type { Get } from 'type-fest'`
140
- : `import type { GraphCommerceConfig } from '../config'`
141
-
142
- const content = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
143
- ${imports}
144
-
145
- ${exports}
146
- `
147
-
148
- const formattedContent = await prettier.format(content, {
149
- ...prettierConf,
150
- parser: 'typescript',
151
- plugins: prettierConf.plugins?.filter(
152
- (p) => typeof p === 'string' && !p.includes('prettier-plugin-sort-imports'),
153
- ),
154
- })
155
-
156
- // Write TypeScript file
157
- writeFileSync(filePath, formattedContent)
158
-
159
- // Transform and write JavaScript file
160
- const result = transformFileSync(filePath, {
161
- module: { type: 'nodenext' },
162
- env: { targets: { node: '18' } },
163
- })
164
-
165
- writeFileSync(distFilePath, result.code)
166
- }
167
-
168
- export async function generateConfigValues() {
169
- const resolved = resolve('@graphcommerce/next-config')
170
- if (!resolved) throw Error('Could not resolve @graphcommerce/next-config')
171
-
172
- const config = loadConfig(process.cwd())
173
- const targetDir = `${resolved.root}/src/generated/configValues`
174
- const targetDistDir = `${resolved.root}/dist/generated/configValues`
175
-
176
- // Clean up existing directories and recreate them
177
- if (existsSync(targetDir)) {
178
- rmSync(targetDir, { recursive: true, force: true })
123
+ writeFileSync(path.join(distDir, `${name}.js`), code)
179
124
  }
180
- if (existsSync(targetDistDir)) {
181
- rmSync(targetDistDir, { recursive: true, force: true })
182
- }
183
- mkdirSync(targetDir, { recursive: true })
184
- mkdirSync(targetDistDir, { recursive: true })
185
-
186
- // Get all schema keys to ensure we include everything, even undefined values
187
- const schema = GraphCommerceConfigSchema()
188
- const schemaKeys = Object.keys(schema.shape) as (keyof GraphCommerceConfig)[]
189
125
 
190
- // Create a complete config object with schema defaults
191
- const completeConfig: Record<string, unknown> = {}
192
- for (const key of schemaKeys) {
193
- completeConfig[key] = config[key] // Use actual value if present, undefined if not
126
+ const writePublicOnlyModule = (name: string, serverOnlyNames: string[], exports: string[]) => {
127
+ const lines = [
128
+ header,
129
+ '// Browser build of @graphcommerce/next-config/config: only fields with @public in Config.graphqls.',
130
+ '// Add @public to a field to read it in the browser. Keep secrets server-only.',
131
+ ...(serverOnlyNames.length ? [`// Server-only: ${serverOnlyNames.join(', ')}`] : []),
132
+ ]
133
+ if (exports.some((e) => e.includes('serverOnly('))) {
134
+ lines.push(`const serverOnly = (valuePath, hint) => ({
135
+ get() {
136
+ if (process.env.NODE_ENV !== 'production')
137
+ throw Error(\`\${valuePath} is server-only. Read it on the server or add @public to \${hint} in Config.graphqls.\`)
138
+ },
139
+ })`)
140
+ }
141
+ writeFileSync(path.join(publicOnlyDir, `${name}.js`), [...lines, ...exports].join('\n'))
194
142
  }
195
143
 
196
- const configEntries = Object.entries(completeConfig) as [keyof GraphCommerceConfig, unknown][]
197
- const nestedObjects: [string, Record<string, unknown>, keyof GraphCommerceConfig][] = []
198
- const rootExports: string[] = []
144
+ const serverExports: string[] = []
145
+ const browserExports: string[] = []
146
+ const serverOnlyKeys: string[] = []
147
+ let sectionCount = 0
148
+
149
+ for (const field of inputs.get('GraphCommerceConfig') ?? []) {
150
+ const key = field.name.value
151
+ const value = config[key]
152
+ const fieldType = namedType(field.type)
153
+ const sectionFields = inputs.get(fieldType) ?? []
154
+
155
+ if (isSection(value)) {
156
+ sectionCount++
157
+ const sectionExports = sectionFields.map(
158
+ ({ name }) =>
159
+ `export const ${name.value}: Get<GraphCommerceConfig, '${key}.${name.value}'> = ${literal(value[name.value])}`,
160
+ )
161
+ await writeServerModule(key, [header, typeImports, ...sectionExports].join('\n\n'))
162
+ serverExports.push(`export * as ${key} from './${key}.js'`)
163
+ } else {
164
+ serverExports.push(
165
+ `export const ${key}: Get<GraphCommerceConfig, '${key}'> = ${literal(value)}`,
166
+ )
167
+ }
199
168
 
200
- // Separate nested objects from root-level values
201
- for (const [key, value] of configEntries) {
202
- if (shouldCreateFile(value)) {
203
- // Create file for nested object
204
- nestedObjects.push([key, value as Record<string, unknown>, key])
205
- rootExports.push(`export * as ${key} from './${toFileName(key)}'`)
169
+ if (!(inputs.has(fieldType) ? hasPublic(fieldType) : isPublic(field))) {
170
+ serverOnlyKeys.push(key)
171
+ } else if (isSection(value)) {
172
+ const sectionServerOnly: string[] = []
173
+ const sectionPublic: string[] = []
174
+ for (const sectionField of sectionFields) {
175
+ const name = sectionField.name.value
176
+ const nestedType = namedType(sectionField.type)
177
+ if (!(inputs.has(nestedType) ? hasPublic(nestedType) : isPublic(sectionField)))
178
+ sectionServerOnly.push(name)
179
+ else
180
+ sectionPublic.push(
181
+ `export const ${name} = ${browserLiteral(value[name], nestedType, `${key}.${name}`)}`,
182
+ )
183
+ }
184
+ writePublicOnlyModule(key, sectionServerOnly, sectionPublic)
185
+ browserExports.push(`export * as ${key} from './${key}.js'`)
206
186
  } else {
207
- // Add to root exports (including undefined values)
208
- const valueStr = generateValueLiteral(value)
209
- // Always include type annotation
210
- const typeAnnotation = `: Get<GraphCommerceConfig, '${key}'>`
211
- rootExports.push(`export const ${key}${typeAnnotation} = ${valueStr}`)
187
+ browserExports.push(`export const ${key} = ${browserLiteral(value, fieldType, key)}`)
212
188
  }
213
189
  }
214
190
 
215
- // Create files for nested objects
216
- await Promise.all(
217
- nestedObjects.map(([sectionName, sectionValue, configKey]) =>
218
- createConfigSectionFile(sectionName, sectionValue, targetDir, targetDistDir, configKey),
219
- ),
220
- )
221
-
222
- // Always need the Get import since we always use type annotations
223
- const rootNeedsGetImport = true
224
-
225
- const rootImports = rootNeedsGetImport
226
- ? `import type { GraphCommerceConfig } from '../config'\nimport type { Get } from 'type-fest'`
227
- : `import type { GraphCommerceConfig } from '../config'`
228
-
229
- // Create the main index file
230
- const indexContent = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
231
- ${rootImports}
191
+ await writeServerModule('index', [header, typeImports, ...serverExports].join('\n'))
192
+ writePublicOnlyModule('index', serverOnlyKeys, browserExports)
232
193
 
233
- ${rootExports.join('\n')}
234
- `
235
-
236
- const formattedIndexContent = await prettier.format(indexContent, {
237
- ...prettierConf,
238
- parser: 'typescript',
239
- plugins: prettierConf.plugins?.filter(
240
- (p) => typeof p === 'string' && !p.includes('prettier-plugin-sort-imports'),
241
- ),
242
- })
243
-
244
- const indexPath = path.join(targetDir, 'index.ts')
245
- const distIndexPath = path.join(targetDistDir, 'index.js')
246
-
247
- // Write TypeScript index file
248
- writeFileSync(indexPath, formattedIndexContent)
249
-
250
- // Transform and write JavaScript index file
251
- const indexResult = transformFileSync(indexPath, {
252
- module: { type: 'nodenext' },
253
- env: { targets: { node: '20' } },
254
- })
255
-
256
- writeFileSync(distIndexPath, indexResult.code)
257
-
258
- // eslint-disable-next-line no-console
259
- console.log(`✅ Generated config values in ${targetDir} and ${targetDistDir}`)
260
- // eslint-disable-next-line no-console
261
- console.log(`📁 Created ${nestedObjects.length} nested object files + index.ts/.js`)
262
- // eslint-disable-next-line no-console
263
- console.log(`📝 Root exports: ${configEntries.length - nestedObjects.length}`)
194
+ console.log(`✅ Generated config values in ${srcDir} and ${distDir}`)
195
+ console.log(
196
+ `📁 ${sectionCount} sections, ${serverExports.length} server exports, ${browserExports.length} browser exports`,
197
+ )
264
198
  }
@@ -87,6 +87,20 @@ export type DatalayerConfig = {
87
87
  * endpoint: '{graphCommerce.magentoEndpoint}'
88
88
  * ```
89
89
  *
90
+ * ## Public and server-only configuration
91
+ *
92
+ * A field with `@public` is available in the browser. A field without `@public` is server-only:
93
+ * code that runs in the browser cannot read it.
94
+ *
95
+ * - Turbopack stops the build when browser code imports a server-only field from
96
+ * `@graphcommerce/next-config/config`.
97
+ * - A server-only field of a storefront, such as `useStorefrontConfig().myServerField`, throws in
98
+ * development and returns `undefined` in production.
99
+ * - A server-only field of a section, such as `algolia.searchOnlyApiKey`, is `undefined`.
100
+ *
101
+ * Put `@public` on fields with a scalar or enum type. In the browser, a field with an input type,
102
+ * such as `debug: GraphCommerceDebugConfig`, contains only the `@public` fields of that input.
103
+ *
90
104
  * ## Environment variables to override configuration
91
105
  *
92
106
  * Configuration values can be overwriten by environment variables, with the following rules:
@@ -113,10 +127,11 @@ export type DatalayerConfig = {
113
127
  *
114
128
  * ```graphql
115
129
  * extend input GraphCommerceConfig {
116
- * myConfig: String # or Boolean, or Int, or Float, make required with `!`
130
+ * myConfig: String @public # or Boolean, or Int, or Float, make required with `!`
131
+ * myApiSecret: String
117
132
  * }
118
133
  * extend input GraphCommerceStorefrontConfig {
119
- * myField: Boolean
134
+ * myField: Boolean @public
120
135
  * }
121
136
  * ```
122
137
  *
@@ -585,17 +600,17 @@ export function DatalayerConfigSchema(): z.ZodObject<Properties<DatalayerConfig>
585
600
 
586
601
  export function GraphCommerceConfigSchema(): z.ZodObject<Properties<GraphCommerceConfig>> {
587
602
  return z.object({
588
- breadcrumbs: z.boolean().default(false).nullish(),
603
+ breadcrumbs: z.boolean().nullish().default(false),
589
604
  canonicalBaseUrl: z.string().min(1),
590
605
  cartDisplayPricesInclTax: z.boolean().nullish(),
591
606
  compare: z.boolean().nullish(),
592
- compareVariant: CompareVariantSchema.default('ICON').nullish(),
593
- configurableVariantForSimple: z.boolean().default(false).nullish(),
607
+ compareVariant: CompareVariantSchema.nullish().default('ICON'),
608
+ configurableVariantForSimple: z.boolean().nullish().default(false),
594
609
  configurableVariantValues: z.lazy(() => MagentoConfigurableVariantValuesSchema().nullish()),
595
- containerSizingContent: ContainerSizingSchema.default('FULL_WIDTH').nullish(),
596
- containerSizingShell: ContainerSizingSchema.default('FULL_WIDTH').nullish(),
597
- crossSellsHideCartItems: z.boolean().default(false).nullish(),
598
- crossSellsRedirectItems: z.boolean().default(false).nullish(),
610
+ containerSizingContent: ContainerSizingSchema.nullish().default('FULL_WIDTH'),
611
+ containerSizingShell: ContainerSizingSchema.nullish().default('FULL_WIDTH'),
612
+ crossSellsHideCartItems: z.boolean().nullish().default(false),
613
+ crossSellsRedirectItems: z.boolean().nullish().default(false),
599
614
  customerAddressNoteEnable: z.boolean().nullish(),
600
615
  customerCompanyFieldsEnable: z.boolean().nullish(),
601
616
  customerDeleteEnabled: z.boolean().nullish(),
@@ -607,7 +622,7 @@ export function GraphCommerceConfigSchema(): z.ZodObject<Properties<GraphCommerc
607
622
  googlePlaystore: z.lazy(() => GraphCommerceGooglePlaystoreConfigSchema().nullish()),
608
623
  googleRecaptchaKey: z.string().nullish(),
609
624
  googleTagmanagerId: z.string().nullish(),
610
- graphqlMeshEditMode: z.boolean().default(false).nullish(),
625
+ graphqlMeshEditMode: z.boolean().nullish().default(false),
611
626
  hygraphManagementApi: z.string().nullish(),
612
627
  hygraphProjectId: z.string().nullish(),
613
628
  hygraphWriteAccessToken: z.string().nullish(),
@@ -616,9 +631,9 @@ export function GraphCommerceConfigSchema(): z.ZodObject<Properties<GraphCommerc
616
631
  magentoVersion: z.number(),
617
632
  permissions: z.lazy(() => GraphCommercePermissionsSchema().nullish()),
618
633
  previewSecret: z.string().nullish(),
619
- productFiltersLayout: ProductFiltersLayoutSchema.default('DEFAULT').nullish(),
634
+ productFiltersLayout: ProductFiltersLayoutSchema.nullish().default('DEFAULT'),
620
635
  productFiltersPro: z.boolean().nullish(),
621
- productListPaginationVariant: PaginationVariantSchema.default('COMPACT').nullish(),
636
+ productListPaginationVariant: PaginationVariantSchema.nullish().default('COMPACT'),
622
637
  productRoute: z.string().nullish(),
623
638
  recentlyViewedProducts: z.lazy(() => RecentlyViewedProductsConfigSchema().nullish()),
624
639
  robotsAllow: z.boolean().nullish(),
@@ -5,7 +5,9 @@ const debug = process.env.DEBUG === '1'
5
5
  // eslint-disable-next-line no-console
6
6
  const log = (message: string) => debug && console.log(`isMonorepo: ${message}`)
7
7
 
8
- function findPackageJson(directory: string): { name: string } | null {
8
+ type PackageJson = { name?: string; workspaces?: string[] | { packages?: string[] } }
9
+
10
+ function findPackageJson(directory: string): PackageJson | null {
9
11
  try {
10
12
  const packageJsonPath = path.join(directory, 'package.json')
11
13
  const content = fs.readFileSync(packageJsonPath, 'utf8')
@@ -16,8 +18,8 @@ function findPackageJson(directory: string): { name: string } | null {
16
18
  }
17
19
 
18
20
  /**
19
- * Finds the path of the parent @graphcommerce package if it exists Returns null if no parent
20
- * package is found
21
+ * Finds the path of the parent @graphcommerce package that has `directory` as a workspace. Returns
22
+ * null if no parent package is found
21
23
  */
22
24
  export function findParentPath(directory: string): string | null {
23
25
  let currentDir = directory
@@ -31,14 +33,18 @@ export function findParentPath(directory: string): string | null {
31
33
  while (currentDir !== path.parse(currentDir).root) {
32
34
  const packageJson = findPackageJson(currentDir)
33
35
 
34
- if (packageJson) {
35
- log(`Found package.json in: ${currentDir}`)
36
- log(`Package name: ${packageJson.name}`)
36
+ if (packageJson?.name?.startsWith('@graphcommerce/')) {
37
+ log(`Found package ${packageJson.name} in: ${currentDir}`)
38
+ const workspaces = Array.isArray(packageJson.workspaces)
39
+ ? packageJson.workspaces
40
+ : (packageJson.workspaces?.packages ?? [])
41
+ const relative = path.relative(currentDir, directory)
37
42
 
38
- if (packageJson.name.startsWith('@graphcommerce/')) {
43
+ if (workspaces.some((workspace) => path.matchesGlob(relative, workspace))) {
39
44
  log(`Found parent @graphcommerce package at: ${currentDir}`)
40
45
  return currentDir
41
46
  }
47
+ log(`${relative} is not a workspace of ${packageJson.name}`)
42
48
  }
43
49
 
44
50
  currentDir = path.dirname(currentDir)