@shopify/hydrogen-codegen 0.2.0 → 0.2.2

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.
@@ -1,108 +1,336 @@
1
- import { Types, PluginFunction } from '@graphql-codegen/plugin-helpers';
1
+ import { PluginFunction, Types } from '@graphql-codegen/plugin-helpers';
2
2
  import { Source } from '@graphql-tools/utils';
3
- import { OperationDefinitionNode, FragmentDefinitionNode, ExecutionArgs } from 'graphql';
4
- import { IsNever, SetOptional } from 'type-fest';
5
-
6
- type HydrogenPresetConfig = {
7
- /**
8
- * Name for the variable that contains the imported types.
9
- * @default 'StorefrontAPI'
10
- */
11
- namespacedImportName?: string;
12
- /**
13
- * Module to import the types from.
14
- * @default '@shopify/hydrogen/storefront-api-types'
15
- */
16
- importTypesFrom?: string;
17
- /**
18
- * Whether types should be imported from the `importTypesFrom` module, or generated inline.
19
- * @default true
20
- */
21
- importTypes?: boolean;
22
- /**
23
- * Whether to skip adding `__typename` to generated operation types.
24
- * @default true
25
- */
26
- skipTypenameInOperations?: boolean;
27
- /**
28
- * Override the default interface extension.
29
- */
30
- interfaceExtension?: (options: {
31
- queryType: string;
32
- mutationType: string;
33
- }) => string;
3
+ import { ExecutionArgs, FragmentDefinitionNode, OperationDefinitionNode } from 'graphql';
4
+
5
+ /**
6
+ Returns a boolean for whether the two given types are equal.
7
+
8
+ @link https://github.com/microsoft/TypeScript/issues/27024#issuecomment-421529650
9
+ @link https://stackoverflow.com/questions/68961864/how-does-the-equals-work-in-typescript/68963796#68963796
10
+
11
+ Use-cases:
12
+ - If you want to make a conditional branch based on the result of a comparison of two types.
13
+
14
+ @example
15
+ ```
16
+ import type {IsEqual} from 'type-fest';
17
+
18
+ // This type returns a boolean for whether the given array includes the given item.
19
+ // `IsEqual` is used to compare the given array at position 0 and the given item and then return true if they are equal.
20
+ type Includes<Value extends readonly any[], Item> =
21
+ Value extends readonly [Value[0], ...infer rest]
22
+ ? IsEqual<Value[0], Item> extends true
23
+ ? true
24
+ : Includes<rest, Item>
25
+ : false;
26
+ ```
27
+
28
+ @category Type Guard
29
+ @category Utilities
30
+ */
31
+ export type IsEqual<A, B> = (<G>() => G extends A ? 1 : 2) extends (<G>() => G extends B ? 1 : 2) ? true : false;
32
+ /**
33
+ Filter out keys from an object.
34
+
35
+ Returns `never` if `Exclude` is strictly equal to `Key`.
36
+ Returns `never` if `Key` extends `Exclude`.
37
+ Returns `Key` otherwise.
38
+
39
+ @example
40
+ ```
41
+ type Filtered = Filter<'foo', 'foo'>;
42
+ //=> never
43
+ ```
44
+
45
+ @example
46
+ ```
47
+ type Filtered = Filter<'bar', string>;
48
+ //=> never
49
+ ```
50
+
51
+ @example
52
+ ```
53
+ type Filtered = Filter<'bar', 'foo'>;
54
+ //=> 'bar'
55
+ ```
56
+
57
+ @see {Except}
58
+ */
59
+ export type Filter<KeyType, ExcludeType> = IsEqual<KeyType, ExcludeType> extends true ? never : (KeyType extends ExcludeType ? never : KeyType);
60
+ export type ExceptOptions = {
61
+ /**
62
+ Disallow assigning non-specified properties.
63
+
64
+ Note that any omitted properties in the resulting type will be present in autocomplete as `undefined`.
65
+
66
+ @default false
67
+ */
68
+ requireExactProps?: boolean;
34
69
  };
35
- declare const preset: Types.OutputPreset<HydrogenPresetConfig>;
70
+ /**
71
+ Create a type from an object type without certain keys.
36
72
 
37
- type OperationOrFragment = {
38
- initialName: string;
39
- definition: OperationDefinitionNode | FragmentDefinitionNode;
73
+ We recommend setting the `requireExactProps` option to `true`.
74
+
75
+ This type is a stricter version of [`Omit`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-5.html#the-omit-helper-type). The `Omit` type does not restrict the omitted keys to be keys present on the given type, while `Except` does. The benefits of a stricter type are avoiding typos and allowing the compiler to pick up on rename refactors automatically.
76
+
77
+ This type was proposed to the TypeScript team, which declined it, saying they prefer that libraries implement stricter versions of the built-in types ([microsoft/TypeScript#30825](https://github.com/microsoft/TypeScript/issues/30825#issuecomment-523668235)).
78
+
79
+ @example
80
+ ```
81
+ import type {Except} from 'type-fest';
82
+
83
+ type Foo = {
84
+ a: number;
85
+ b: string;
40
86
  };
41
- type SourceWithOperations = {
42
- source: Source;
43
- operations: Array<OperationOrFragment>;
87
+
88
+ type FooWithoutA = Except<Foo, 'a'>;
89
+ //=> {b: string}
90
+
91
+ const fooWithoutA: FooWithoutA = {a: 1, b: '2'};
92
+ //=> errors: 'a' does not exist in type '{ b: string; }'
93
+
94
+ type FooWithoutB = Except<Foo, 'b', {requireExactProps: true}>;
95
+ //=> {a: number} & Partial<Record<"b", never>>
96
+
97
+ const fooWithoutB: FooWithoutB = {a: 1, b: '2'};
98
+ //=> errors at 'b': Type 'string' is not assignable to type 'undefined'.
99
+ ```
100
+
101
+ @category Object
102
+ */
103
+ export type Except<ObjectType, KeysType extends keyof ObjectType, Options extends ExceptOptions = {
104
+ requireExactProps: false;
105
+ }> = {
106
+ [KeyType in keyof ObjectType as Filter<KeyType, KeysType>]: ObjectType[KeyType];
107
+ } & (Options["requireExactProps"] extends true ? Partial<Record<KeysType, never>> : {});
108
+ /**
109
+ Useful to flatten the type output to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.
110
+
111
+ @example
112
+ ```
113
+ import type {Simplify} from 'type-fest';
114
+
115
+ type PositionProps = {
116
+ top: number;
117
+ left: number;
44
118
  };
45
- declare const plugin: PluginFunction<{
46
- sourcesWithOperations: Array<SourceWithOperations>;
47
- interfaceExtensionCode: string;
48
- }>;
49
119
 
120
+ type SizeProps = {
121
+ width: number;
122
+ height: number;
123
+ };
124
+
125
+ // In your editor, hovering over `Props` will show a flattened object with all the properties.
126
+ type Props = Simplify<PositionProps & SizeProps>;
127
+ ```
128
+
129
+ Sometimes it is desired to pass a value as a function argument that has a different type. At first inspection it may seem assignable, and then you discover it is not because the `value`'s type definition was defined as an interface. In the following example, `fn` requires an argument of type `Record<string, unknown>`. If the value is defined as a literal, then it is assignable. And if the `value` is defined as type using the `Simplify` utility the value is assignable. But if the `value` is defined as an interface, it is not assignable because the interface is not sealed and elsewhere a non-string property could be added to the interface.
130
+
131
+ If the type definition must be an interface (perhaps it was defined in a third-party npm package), then the `value` can be defined as `const value: Simplify<SomeInterface> = ...`. Then `value` will be assignable to the `fn` argument. Or the `value` can be cast as `Simplify<SomeInterface>` if you can't re-declare the `value`.
132
+
133
+ @example
134
+ ```
135
+ import type {Simplify} from 'type-fest';
136
+
137
+ interface SomeInterface {
138
+ foo: number;
139
+ bar?: string;
140
+ baz: number | undefined;
141
+ }
142
+
143
+ type SomeType = {
144
+ foo: number;
145
+ bar?: string;
146
+ baz: number | undefined;
147
+ };
148
+
149
+ const literal = {foo: 123, bar: 'hello', baz: 456};
150
+ const someType: SomeType = literal;
151
+ const someInterface: SomeInterface = literal;
152
+
153
+ function fn(object: Record<string, unknown>): void {}
154
+
155
+ fn(literal); // Good: literal object type is sealed
156
+ fn(someType); // Good: type is sealed
157
+ fn(someInterface); // Error: Index signature for type 'string' is missing in type 'someInterface'. Because `interface` can be re-opened
158
+ fn(someInterface as Simplify<SomeInterface>); // Good: transform an `interface` into a `type`
159
+ ```
160
+
161
+ @link https://github.com/microsoft/TypeScript/issues/15300
162
+
163
+ @category Object
164
+ */
165
+ export type Simplify<T> = {
166
+ [KeyType in keyof T]: T[KeyType];
167
+ } & {};
50
168
  /**
51
- * Resolves a schema path for the provided API type. Only the API types currently
52
- * bundled in Hydrogen are allowed: "storefront" and "customer".
53
- * @param api
54
- * @returns
55
- */
56
- declare const getSchema: (api?: "storefront" | "customer-account") => string;
169
+ Returns a boolean for whether the given type is `never`.
170
+
171
+ @link https://github.com/microsoft/TypeScript/issues/31751#issuecomment-498526919
172
+ @link https://stackoverflow.com/a/53984913/10292952
173
+ @link https://www.zhenghao.io/posts/ts-never
174
+
175
+ Useful in type utilities, such as checking if something does not occur.
176
+
177
+ @example
178
+ ```
179
+ import type {IsNever} from 'type-fest';
180
+
181
+ type And<A, B> =
182
+ A extends true
183
+ ? B extends true
184
+ ? true
185
+ : false
186
+ : false;
187
+
188
+ // https://github.com/andnp/SimplyTyped/blob/master/src/types/strings.ts
189
+ type AreStringsEqual<A extends string, B extends string> =
190
+ And<
191
+ IsNever<Exclude<A, B>> extends true ? true : false,
192
+ IsNever<Exclude<B, A>> extends true ? true : false
193
+ >;
194
+
195
+ type EndIfEqual<I extends string, O extends string> =
196
+ AreStringsEqual<I, O> extends true
197
+ ? never
198
+ : void;
199
+
200
+ function endIfEqual<I extends string, O extends string>(input: I, output: O): EndIfEqual<I, O> {
201
+ if (input === output) {
202
+ process.exit(0);
203
+ }
204
+ }
205
+
206
+ endIfEqual('abc', 'abc');
207
+ //=> never
208
+
209
+ endIfEqual('abc', '123');
210
+ //=> void
211
+ ```
212
+
213
+ @category Type Guard
214
+ @category Utilities
215
+ */
216
+ export type IsNever<T> = [
217
+ T
218
+ ] extends [
219
+ never
220
+ ] ? true : false;
57
221
  /**
58
- * The resolved schema path for the Storefront API.
59
- */
60
- declare const schema: string;
222
+ Create a type that makes the given keys optional. The remaining keys are kept as is. The sister of the `SetRequired` type.
223
+
224
+ Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are optional.
61
225
 
62
- declare function processSources(sources: Array<Source>, buildName?: (node: OperationDefinitionNode | FragmentDefinitionNode) => string): SourceWithOperations[];
226
+ @example
227
+ ```
228
+ import type {SetOptional} from 'type-fest';
63
229
 
230
+ type Foo = {
231
+ a: number;
232
+ b?: string;
233
+ c: boolean;
234
+ }
235
+
236
+ type SomeOptional = SetOptional<Foo, 'b' | 'c'>;
237
+ // type SomeOptional = {
238
+ // a: number;
239
+ // b?: string; // Was already optional and still is.
240
+ // c?: boolean; // Is now optional.
241
+ // }
242
+ ```
243
+
244
+ @category Object
245
+ */
246
+ export type SetOptional<BaseType, Keys extends keyof BaseType> = Simplify<
247
+ // Pick just the keys that are readonly from the base type.
248
+ Except<BaseType, Keys> &
249
+ // Pick the keys that should be mutable from the base type and make them mutable.
250
+ Partial<Pick<BaseType, Keys>>>;
251
+ type PresetConfig = {
252
+ /**
253
+ * Whether types should be imported or generated inline.
254
+ */
255
+ importTypes?: {
256
+ /**
257
+ * Name for the variable that contains the imported types.
258
+ * @example 'StorefrontAPI'
259
+ */
260
+ namespace: string;
261
+ /**
262
+ * Module to import the types from.
263
+ * @example '@shopify/hydrogen/storefront-api-types'
264
+ */
265
+ from: string;
266
+ };
267
+ /**
268
+ * Whether to skip adding `__typename` to generated operation types.
269
+ * @default true
270
+ */
271
+ skipTypenameInOperations?: boolean;
272
+ /**
273
+ * Override the default interface extension.
274
+ * @example ({queryType}) => `declare module 'my-api' { interface Queries extends ${queryType} {} }`
275
+ */
276
+ interfaceExtension: (options: {
277
+ queryType: string;
278
+ mutationType: string;
279
+ }) => string;
280
+ };
281
+ export type OperationOrFragment = {
282
+ initialName: string;
283
+ definition: OperationDefinitionNode | FragmentDefinitionNode;
284
+ };
285
+ export type SourceWithOperations = {
286
+ source: Source;
287
+ operations: Array<OperationOrFragment>;
288
+ };
289
+ export declare const plugin: PluginFunction<{
290
+ sourcesWithOperations: Array<SourceWithOperations>;
291
+ interfaceExtensionCode: string;
292
+ }>;
293
+ export declare function processSources(sources: Array<Source>, buildName?: (node: OperationDefinitionNode | FragmentDefinitionNode) => string): SourceWithOperations[];
64
294
  /**
65
295
  * This is a modified version of graphql-tag-pluck's default config.
66
296
  * https://github.com/ardatan/graphql-tools/issues/5127
67
297
  */
68
- declare const pluckConfig: {
69
- /**
70
- * Hook to determine if a node is a gql template literal.
71
- * By default, graphql-tag-pluck only looks for leading comments or `gql` tag.
72
- */
73
- isGqlTemplateLiteral: (node: any, options: any) => boolean;
74
- /**
75
- * Instruct how to extract the gql template literal from the code.
76
- * By default, embedded expressions in template literals (e.g. ${foo})
77
- * are removed from the template string. This hook allows us to annotate
78
- * the template string with the required embedded expressions instead of
79
- * removing them. Later, we can use this information to reconstruct the
80
- * embedded expressions.
81
- */
82
- pluckStringFromFile: (code: string, { start, end, leadingComments }: any) => string;
298
+ export declare const pluckConfig: {
299
+ /**
300
+ * Hook to determine if a node is a gql template literal.
301
+ * By default, graphql-tag-pluck only looks for leading comments or `gql` tag.
302
+ */
303
+ isGqlTemplateLiteral: (node: any, options: any) => boolean;
304
+ /**
305
+ * Instruct how to extract the gql template literal from the code.
306
+ * By default, embedded expressions in template literals (e.g. ${foo})
307
+ * are removed from the template string. This hook allows us to annotate
308
+ * the template string with the required embedded expressions instead of
309
+ * removing them. Later, we can use this information to reconstruct the
310
+ * embedded expressions.
311
+ */
312
+ pluckStringFromFile: (code: string, { start, end, leadingComments }: any) => string;
83
313
  };
84
-
85
314
  /**
86
315
  * This file has utilities to create GraphQL clients
87
- * that consume the types generated by the Hydrogen preset.
316
+ * that consume the types generated by the preset.
88
317
  */
89
-
90
318
  /**
91
319
  * A generic type for `variables` in GraphQL clients
92
320
  */
93
- type GenericVariables = ExecutionArgs['variableValues'];
321
+ export type GenericVariables = ExecutionArgs["variableValues"];
94
322
  /**
95
323
  * Use this type to make parameters optional in GraphQL clients
96
324
  * when no variables need to be passed.
97
325
  */
98
- type EmptyVariables = {
99
- [key: string]: never;
326
+ export type EmptyVariables = {
327
+ [key: string]: never;
100
328
  };
101
329
  /**
102
330
  * GraphQL client's generic operation interface.
103
331
  */
104
- interface CodegenOperations {
105
- [key: string]: any;
332
+ export interface CodegenOperations {
333
+ [key: string]: any;
106
334
  }
107
335
  /**
108
336
  * Used as the return type for GraphQL clients. It picks
@@ -111,12 +339,12 @@ interface CodegenOperations {
111
339
  * graphqlQuery: (...) => Promise<ClientReturn<...>>
112
340
  * graphqlQuery: (...) => Promise<{data: ClientReturn<...>}>
113
341
  */
114
- type ClientReturn<GeneratedOperations extends CodegenOperations, RawGqlString extends string, OverrideReturnType extends any = never> = IsNever<OverrideReturnType> extends true ? RawGqlString extends keyof GeneratedOperations ? GeneratedOperations[RawGqlString]['return'] : any : OverrideReturnType;
342
+ export type ClientReturn<GeneratedOperations extends CodegenOperations, RawGqlString extends string, OverrideReturnType extends any = never> = IsNever<OverrideReturnType> extends true ? RawGqlString extends keyof GeneratedOperations ? GeneratedOperations[RawGqlString]["return"] : any : OverrideReturnType;
115
343
  /**
116
344
  * Checks if the generated variables for an operation
117
345
  * are optional or required.
118
346
  */
119
- type IsOptionalVariables<VariablesParam, OptionalVariableNames extends string = never, VariablesWithoutOptionals = Omit<VariablesParam, OptionalVariableNames>> = VariablesWithoutOptionals extends EmptyVariables ? true : GenericVariables extends VariablesParam ? true : Partial<VariablesWithoutOptionals> extends VariablesWithoutOptionals ? true : false;
347
+ export type IsOptionalVariables<VariablesParam, OptionalVariableNames extends string = never, VariablesWithoutOptionals = Omit<VariablesParam, OptionalVariableNames>> = VariablesWithoutOptionals extends EmptyVariables ? true : GenericVariables extends VariablesParam ? true : Partial<VariablesWithoutOptionals> extends VariablesWithoutOptionals ? true : false;
120
348
  /**
121
349
  * Used as the type for the GraphQL client's variables. It checks
122
350
  * the generated operation types to see if variables are optional.
@@ -124,19 +352,36 @@ type IsOptionalVariables<VariablesParam, OptionalVariableNames extends string =
124
352
  * graphqlQuery: (query: string, param: ClientVariables<...>) => Promise<...>
125
353
  * Where `param` is required.
126
354
  */
127
- type ClientVariables<GeneratedOperations extends CodegenOperations, RawGqlString extends string, OptionalVariableNames extends string = never, VariablesKey extends string = 'variables', GeneratedVariables = RawGqlString extends keyof GeneratedOperations ? SetOptional<GeneratedOperations[RawGqlString]['variables'], Extract<keyof GeneratedOperations[RawGqlString]['variables'], OptionalVariableNames>> : GenericVariables, VariablesWrapper = Record<VariablesKey, GeneratedVariables>> = IsOptionalVariables<GeneratedVariables, OptionalVariableNames> extends true ? Partial<VariablesWrapper> : VariablesWrapper;
355
+ export type ClientVariables<GeneratedOperations extends CodegenOperations, RawGqlString extends string, OptionalVariableNames extends string = never, VariablesKey extends string = "variables", GeneratedVariables = RawGqlString extends keyof GeneratedOperations ? SetOptional<GeneratedOperations[RawGqlString]["variables"], Extract<keyof GeneratedOperations[RawGqlString]["variables"], OptionalVariableNames>> : GenericVariables, VariablesWrapper = Record<VariablesKey, GeneratedVariables>> = IsOptionalVariables<GeneratedVariables, OptionalVariableNames> extends true ? Partial<VariablesWrapper> : VariablesWrapper;
128
356
  /**
129
357
  * Similar to ClientVariables, but makes the whole wrapper optional:
130
358
  * @example
131
359
  * graphqlQuery: (query: string, ...params: ClientVariablesInRestParams<...>) => Promise<...>
132
360
  * Where the first item in `params` might be optional depending on the query.
133
361
  */
134
- type ClientVariablesInRestParams<GeneratedOperations extends CodegenOperations, RawGqlString extends string, OtherParams extends Record<string, any> = {}, OptionalVariableNames extends string = never, ProcessedVariables = OtherParams & ClientVariables<GeneratedOperations, RawGqlString, OptionalVariableNames>> = Partial<OtherParams> extends OtherParams ? IsOptionalVariables<GeneratedOperations[RawGqlString]['variables'], OptionalVariableNames> extends true ? [
135
- ProcessedVariables?
362
+ export type ClientVariablesInRestParams<GeneratedOperations extends CodegenOperations, RawGqlString extends string, OtherParams extends Record<string, any> = {}, OptionalVariableNames extends string = never, ProcessedVariables = OtherParams & ClientVariables<GeneratedOperations, RawGqlString, OptionalVariableNames>> = Partial<OtherParams> extends OtherParams ? IsOptionalVariables<GeneratedOperations[RawGqlString]["variables"], OptionalVariableNames> extends true ? [
363
+ ProcessedVariables?
136
364
  ] : [
137
- ProcessedVariables
365
+ ProcessedVariables
138
366
  ] : [
139
- ProcessedVariables
367
+ ProcessedVariables
140
368
  ];
369
+ type PresetConfig$1 = Partial<PresetConfig>;
370
+ export declare const preset: Types.OutputPreset<PresetConfig$1>;
371
+ /**
372
+ * Resolves a schema path for the provided API type. Only the API types currently
373
+ * bundled in Hydrogen are allowed: "storefront" and "customer".
374
+ * @param api
375
+ * @returns
376
+ */
377
+ export declare const getSchema: (api?: "storefront" | "customer-account") => string;
378
+ /**
379
+ * The resolved schema path for the Storefront API.
380
+ */
381
+ export declare const schema: string;
382
+
383
+ export {
384
+ PresetConfig$1 as PresetConfig,
385
+ };
141
386
 
142
- export { ClientReturn, ClientVariables, ClientVariablesInRestParams, EmptyVariables, GenericVariables, IsOptionalVariables, getSchema, pluckConfig, plugin, preset, processSources, schema };
387
+ export {};
package/dist/esm/index.js CHANGED
@@ -1,7 +1,5 @@
1
1
  export { preset } from './preset.js';
2
- export { plugin } from './plugin.js';
3
2
  export { getSchema, schema } from './schema.js';
4
- export { processSources } from './sources.js';
5
- export { pluckConfig } from './pluck.js';
3
+ export { pluckConfig, plugin, processSources } from '@shopify/graphql-codegen';
6
4
  //# sourceMappingURL=out.js.map
7
5
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,SAAQ,cAAa;AACrB,SAAQ,cAAa;AACrB,SAAQ,QAAQ,iBAAgB;AAChC,SAAQ,sBAAqB;AAC7B,SAAQ,mBAAkB","sourcesContent":["export {preset} from './preset.js';\nexport {plugin} from './plugin.js';\nexport {schema, getSchema} from './schema.js';\nexport {processSources} from './sources.js';\nexport {pluckConfig} from './pluck.js';\nexport type * from './client.js';\n"]}
1
+ {"version":3,"sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,SAAQ,cAAgC;AACxC,SAAQ,QAAQ,iBAAgB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAOK","sourcesContent":["export {preset, type PresetConfig} from './preset.js';\nexport {schema, getSchema} from './schema.js';\nexport {\n plugin,\n pluckConfig,\n processSources,\n type GenericVariables,\n type EmptyVariables,\n type ClientReturn,\n type IsOptionalVariables,\n type ClientVariables,\n type ClientVariablesInRestParams,\n} from '@shopify/graphql-codegen';\n"]}
@@ -1,95 +1,30 @@
1
- import * as addPlugin from '@graphql-codegen/add';
2
- import * as typescriptPlugin from '@graphql-codegen/typescript';
3
- import * as typescriptOperationPlugin from '@graphql-codegen/typescript-operations';
4
- import { processSources } from './sources.js';
1
+ import { preset as preset$1 } from '@shopify/graphql-codegen';
5
2
  import { getDefaultOptions } from './defaults.js';
6
- import { GENERATED_QUERY_INTERFACE_NAME, GENERATED_MUTATION_INTERFACE_NAME, plugin } from './plugin.js';
7
3
 
8
4
  const preset = {
9
5
  [Symbol.for("name")]: "hydrogen",
10
6
  buildGeneratesSection: (options) => {
11
- if (!options.baseOutputDir.endsWith(".d.ts")) {
12
- throw new Error("[hydrogen-preset] target output should be a .d.ts file");
13
- }
14
- if (options.plugins?.length > 0 && Object.keys(options.plugins).some((p) => p.startsWith("typescript"))) {
15
- throw new Error(
16
- "[hydrogen-preset] providing additional typescript-based `plugins` leads to duplicated generated types"
7
+ try {
8
+ const defaultOptions = getDefaultOptions(options.baseOutputDir);
9
+ return preset$1.buildGeneratesSection({
10
+ ...options,
11
+ presetConfig: {
12
+ importTypes: {
13
+ namespace: defaultOptions.namespacedImportName,
14
+ from: defaultOptions.importTypesFrom
15
+ },
16
+ interfaceExtension: defaultOptions.interfaceExtensionCode,
17
+ ...options.presetConfig
18
+ }
19
+ });
20
+ } catch (err) {
21
+ const error = err;
22
+ error.message = error.message.replace(
23
+ "[@shopify/graphql-codegen]",
24
+ "[hydrogen-preset]"
17
25
  );
26
+ throw error;
18
27
  }
19
- const sourcesWithOperations = processSources(options.documents);
20
- const sources = sourcesWithOperations.map(({ source }) => source);
21
- const defaultOptions = getDefaultOptions(options.baseOutputDir);
22
- const importTypes = options.presetConfig.importTypes ?? true;
23
- const namespacedImportName = options.presetConfig.namespacedImportName ?? defaultOptions.namespacedImportName;
24
- const importTypesFrom = options.presetConfig.importTypesFrom ?? defaultOptions.importTypesFrom;
25
- const interfaceExtensionCode = options.presetConfig.interfaceExtension?.({
26
- queryType: GENERATED_QUERY_INTERFACE_NAME,
27
- mutationType: GENERATED_MUTATION_INTERFACE_NAME
28
- }) ?? defaultOptions.interfaceExtensionCode;
29
- const pluginMap = {
30
- ...options.pluginMap,
31
- [`add`]: addPlugin,
32
- [`typescript`]: typescriptPlugin,
33
- [`typescript-operations`]: typescriptOperationPlugin,
34
- [`gen-dts`]: { plugin: plugin }
35
- };
36
- const plugins = [
37
- // 1. Disable eslint for the generated file
38
- {
39
- [`add`]: {
40
- content: `/* eslint-disable eslint-comments/disable-enable-pair */
41
- /* eslint-disable eslint-comments/no-unlimited-disable */
42
- /* eslint-disable */`
43
- }
44
- },
45
- // 2. Import all the generated API types from Hydrogen or generate all the types from the schema.
46
- importTypes ? {
47
- [`add`]: {
48
- content: `import * as ${namespacedImportName} from '${importTypesFrom}';
49
- `
50
- }
51
- } : {
52
- [`typescript`]: {
53
- useTypeImports: true,
54
- useImplementingTypes: true,
55
- enumsAsTypes: true
56
- }
57
- },
58
- // 3. Generate the operations (i.e. queries, mutations, and fragments types)
59
- {
60
- [`typescript-operations`]: {
61
- useTypeImports: true,
62
- // Use `import type` instead of `import`
63
- preResolveTypes: false,
64
- // Use Pick<...> instead of primitives
65
- mergeFragmentTypes: true,
66
- // Merge equal fragment interfaces. Avoids adding `| {}` to Metaobject
67
- skipTypename: options.presetConfig.skipTypenameInOperations ?? true,
68
- // Skip __typename fields
69
- namespacedImportName: importTypes ? namespacedImportName : void 0
70
- }
71
- },
72
- // 4. Augment Hydrogen query/mutation interfaces with the generated operations
73
- { [`gen-dts`]: { sourcesWithOperations, interfaceExtensionCode } },
74
- // 5. Custom plugins from the user
75
- ...options.plugins
76
- ];
77
- return [
78
- {
79
- filename: options.baseOutputDir,
80
- plugins,
81
- pluginMap,
82
- schema: options.schema,
83
- config: {
84
- // For the TS plugin:
85
- defaultScalarType: "unknown",
86
- // Allow overwriting defaults:
87
- ...options.config
88
- },
89
- documents: sources,
90
- documentTransforms: options.documentTransforms
91
- }
92
- ];
93
28
  }
94
29
  };
95
30
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/preset.ts"],"names":[],"mappings":"AACA,YAAY,eAAe;AAC3B,YAAY,sBAAsB;AAClC,YAAY,+BAA+B;AAC3C,SAAQ,sBAAqB;AAC7B,SAAQ,yBAAwB;AAChC;AAAA,EACE,UAAU;AAAA,EACV;AAAA,EACA;AAAA,OACK;AAgCA,MAAM,SAAmD;AAAA,EAC9D,CAAC,OAAO,IAAI,MAAM,CAAC,GAAG;AAAA,EACtB,uBAAuB,CAAC,YAAY;AAClC,QAAI,CAAC,QAAQ,cAAc,SAAS,OAAO,GAAG;AAC5C,YAAM,IAAI,MAAM,wDAAwD;AAAA,IAC1E;AAEA,QACE,QAAQ,SAAS,SAAS,KAC1B,OAAO,KAAK,QAAQ,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,WAAW,YAAY,CAAC,GACnE;AACA,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,wBAAwB,eAAe,QAAQ,SAAS;AAC9D,UAAM,UAAU,sBAAsB,IAAI,CAAC,EAAC,OAAM,MAAM,MAAM;AAE9D,UAAM,iBAAiB,kBAAkB,QAAQ,aAAa;AAE9D,UAAM,cAAc,QAAQ,aAAa,eAAe;AACxD,UAAM,uBACJ,QAAQ,aAAa,wBACrB,eAAe;AACjB,UAAM,kBACJ,QAAQ,aAAa,mBAAmB,eAAe;AAEzD,UAAM,yBACJ,QAAQ,aAAa,qBAAqB;AAAA,MACxC,WAAW;AAAA,MACX,cAAc;AAAA,IAChB,CAAC,KAAK,eAAe;AAEvB,UAAM,YAAY;AAAA,MAChB,GAAG,QAAQ;AAAA,MACX,CAAC,KAAK,GAAG;AAAA,MACT,CAAC,YAAY,GAAG;AAAA,MAChB,CAAC,uBAAuB,GAAG;AAAA,MAC3B,CAAC,SAAS,GAAG,EAAC,QAAQ,UAAS;AAAA,IACjC;AAEA,UAAM,UAAyC;AAAA;AAAA,MAE7C;AAAA,QACE,CAAC,KAAK,GAAG;AAAA,UACP,SAAS;AAAA;AAAA;AAAA,QACX;AAAA,MACF;AAAA;AAAA,MAEA,cACI;AAAA,QACE,CAAC,KAAK,GAAG;AAAA,UACP,SAAS,eAAe,oBAAoB,UAAU,eAAe;AAAA;AAAA,QACvE;AAAA,MACF,IACA;AAAA,QACE,CAAC,YAAY,GAAG;AAAA,UACd,gBAAgB;AAAA,UAChB,sBAAsB;AAAA,UACtB,cAAc;AAAA,QAChB;AAAA,MACF;AAAA;AAAA,MAEJ;AAAA,QACE,CAAC,uBAAuB,GAAG;AAAA,UACzB,gBAAgB;AAAA;AAAA,UAChB,iBAAiB;AAAA;AAAA,UACjB,oBAAoB;AAAA;AAAA,UACpB,cAAc,QAAQ,aAAa,4BAA4B;AAAA;AAAA,UAC/D,sBAAsB,cAAc,uBAAuB;AAAA,QAC7D;AAAA,MACF;AAAA;AAAA,MAEA,EAAC,CAAC,SAAS,GAAG,EAAC,uBAAuB,uBAAsB,EAAC;AAAA;AAAA,MAE7D,GAAG,QAAQ;AAAA,IACb;AAEA,WAAO;AAAA,MACL;AAAA,QACE,UAAU,QAAQ;AAAA,QAClB;AAAA,QACA;AAAA,QACA,QAAQ,QAAQ;AAAA,QAChB,QAAQ;AAAA;AAAA,UAEN,mBAAmB;AAAA;AAAA,UAEnB,GAAG,QAAQ;AAAA,QACb;AAAA,QACA,WAAW;AAAA,QACX,oBAAoB,QAAQ;AAAA,MAC9B;AAAA,IACF;AAAA,EACF;AACF","sourcesContent":["import type {Types} from '@graphql-codegen/plugin-helpers';\nimport * as addPlugin from '@graphql-codegen/add';\nimport * as typescriptPlugin from '@graphql-codegen/typescript';\nimport * as typescriptOperationPlugin from '@graphql-codegen/typescript-operations';\nimport {processSources} from './sources.js';\nimport {getDefaultOptions} from './defaults.js';\nimport {\n plugin as dtsPlugin,\n GENERATED_MUTATION_INTERFACE_NAME,\n GENERATED_QUERY_INTERFACE_NAME,\n} from './plugin.js';\n\nexport type HydrogenPresetConfig = {\n /**\n * Name for the variable that contains the imported types.\n * @default 'StorefrontAPI'\n */\n namespacedImportName?: string;\n /**\n * Module to import the types from.\n * @default '@shopify/hydrogen/storefront-api-types'\n */\n importTypesFrom?: string;\n /**\n * Whether types should be imported from the `importTypesFrom` module, or generated inline.\n * @default true\n */\n importTypes?: boolean;\n /**\n * Whether to skip adding `__typename` to generated operation types.\n * @default true\n */\n skipTypenameInOperations?: boolean;\n /**\n * Override the default interface extension.\n */\n interfaceExtension?: (options: {\n queryType: string;\n mutationType: string;\n }) => string;\n};\n\nexport const preset: Types.OutputPreset<HydrogenPresetConfig> = {\n [Symbol.for('name')]: 'hydrogen',\n buildGeneratesSection: (options) => {\n if (!options.baseOutputDir.endsWith('.d.ts')) {\n throw new Error('[hydrogen-preset] target output should be a .d.ts file');\n }\n\n if (\n options.plugins?.length > 0 &&\n Object.keys(options.plugins).some((p) => p.startsWith('typescript'))\n ) {\n throw new Error(\n '[hydrogen-preset] providing additional typescript-based `plugins` leads to duplicated generated types',\n );\n }\n\n const sourcesWithOperations = processSources(options.documents);\n const sources = sourcesWithOperations.map(({source}) => source);\n\n const defaultOptions = getDefaultOptions(options.baseOutputDir);\n\n const importTypes = options.presetConfig.importTypes ?? true;\n const namespacedImportName =\n options.presetConfig.namespacedImportName ??\n defaultOptions.namespacedImportName;\n const importTypesFrom =\n options.presetConfig.importTypesFrom ?? defaultOptions.importTypesFrom;\n\n const interfaceExtensionCode =\n options.presetConfig.interfaceExtension?.({\n queryType: GENERATED_QUERY_INTERFACE_NAME,\n mutationType: GENERATED_MUTATION_INTERFACE_NAME,\n }) ?? defaultOptions.interfaceExtensionCode;\n\n const pluginMap = {\n ...options.pluginMap,\n [`add`]: addPlugin,\n [`typescript`]: typescriptPlugin,\n [`typescript-operations`]: typescriptOperationPlugin,\n [`gen-dts`]: {plugin: dtsPlugin},\n };\n\n const plugins: Array<Types.ConfiguredPlugin> = [\n // 1. Disable eslint for the generated file\n {\n [`add`]: {\n content: `/* eslint-disable eslint-comments/disable-enable-pair */\\n/* eslint-disable eslint-comments/no-unlimited-disable */\\n/* eslint-disable */`,\n },\n },\n // 2. Import all the generated API types from Hydrogen or generate all the types from the schema.\n importTypes\n ? {\n [`add`]: {\n content: `import * as ${namespacedImportName} from '${importTypesFrom}';\\n`,\n },\n }\n : {\n [`typescript`]: {\n useTypeImports: true,\n useImplementingTypes: true,\n enumsAsTypes: true,\n },\n },\n // 3. Generate the operations (i.e. queries, mutations, and fragments types)\n {\n [`typescript-operations`]: {\n useTypeImports: true, // Use `import type` instead of `import`\n preResolveTypes: false, // Use Pick<...> instead of primitives\n mergeFragmentTypes: true, // Merge equal fragment interfaces. Avoids adding `| {}` to Metaobject\n skipTypename: options.presetConfig.skipTypenameInOperations ?? true, // Skip __typename fields\n namespacedImportName: importTypes ? namespacedImportName : undefined,\n },\n },\n // 4. Augment Hydrogen query/mutation interfaces with the generated operations\n {[`gen-dts`]: {sourcesWithOperations, interfaceExtensionCode}},\n // 5. Custom plugins from the user\n ...options.plugins,\n ];\n\n return [\n {\n filename: options.baseOutputDir,\n plugins,\n pluginMap,\n schema: options.schema,\n config: {\n // For the TS plugin:\n defaultScalarType: 'unknown',\n // Allow overwriting defaults:\n ...options.config,\n },\n documents: sources,\n documentTransforms: options.documentTransforms,\n },\n ];\n },\n};\n"]}
1
+ {"version":3,"sources":["../../src/preset.ts"],"names":[],"mappings":"AACA;AAAA,EACE,UAAU;AAAA,OAEL;AACP,SAAQ,yBAAwB;AAIzB,MAAM,SAA2C;AAAA,EACtD,CAAC,OAAO,IAAI,MAAM,CAAC,GAAG;AAAA,EACtB,uBAAuB,CAAC,YAAY;AAClC,QAAI;AACF,YAAM,iBAAiB,kBAAkB,QAAQ,aAAa;AAE9D,aAAO,eAAe,sBAAsB;AAAA,QAC1C,GAAG;AAAA,QACH,cAAc;AAAA,UACZ,aAAa;AAAA,YACX,WAAW,eAAe;AAAA,YAC1B,MAAM,eAAe;AAAA,UACvB;AAAA,UACA,oBAAoB,eAAe;AAAA,UACnC,GAAG,QAAQ;AAAA,QACb;AAAA,MACF,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,YAAM,QAAQ;AAEd,YAAM,UAAU,MAAM,QAAQ;AAAA,QAC5B;AAAA,QACA;AAAA,MACF;AAEA,YAAM;AAAA,IACR;AAAA,EACF;AACF","sourcesContent":["import type {Types} from '@graphql-codegen/plugin-helpers';\nimport {\n preset as internalPreset,\n type PresetConfig as InternalPresetConfig,\n} from '@shopify/graphql-codegen';\nimport {getDefaultOptions} from './defaults.js';\n\nexport type PresetConfig = Partial<InternalPresetConfig>;\n\nexport const preset: Types.OutputPreset<PresetConfig> = {\n [Symbol.for('name')]: 'hydrogen',\n buildGeneratesSection: (options) => {\n try {\n const defaultOptions = getDefaultOptions(options.baseOutputDir);\n\n return internalPreset.buildGeneratesSection({\n ...options,\n presetConfig: {\n importTypes: {\n namespace: defaultOptions.namespacedImportName,\n from: defaultOptions.importTypesFrom,\n },\n interfaceExtension: defaultOptions.interfaceExtensionCode,\n ...options.presetConfig,\n } satisfies PresetConfig,\n });\n } catch (err) {\n const error = err as Error;\n\n error.message = error.message.replace(\n '[@shopify/graphql-codegen]',\n '[hydrogen-preset]',\n );\n\n throw error;\n }\n },\n};\n"]}