-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathconfig.ts
689 lines (570 loc) · 17.3 KB
/
config.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
import { mergeSchemas } from '@graphql-tools/schema'
import fs from 'fs-extra'
import { glob } from 'glob'
import * as graphql from 'graphql'
import os from 'os'
import path from 'path'
import { promisify } from 'util'
import * as url from 'url'
// locals
import { computeID, ConfigFile, defaultConfigValues, keyFieldsForType } from '../runtime/lib'
import { CachePolicy } from '../runtime/lib/types'
import { KitConfig } from '@sveltejs/kit'
// a place to hold conventions and magic strings
export class Config {
filepath: string
rootDir: string
projectRoot: string
schema: graphql.GraphQLSchema
apiUrl?: string
schemaPath?: string
persistedQueryPath?: string
sourceGlob: string
static?: boolean
scalars?: ConfigFile['scalars']
framework: 'sapper' | 'kit' | 'svelte' = 'kit'
module: 'commonjs' | 'esm' = 'esm'
cacheBufferSize?: number
defaultCachePolicy: CachePolicy
defaultPartial: boolean
definitionsFolder?: string
newSchema: string = ''
newDocuments: string = ''
defaultKeys: string[] = ['id']
typeConfig: ConfigFile['types']
configFile: ConfigFile
logLevel: LogLevel
disableMasking: boolean
configIsRoute: ((filepath: string) => boolean) | null = null
routesDir: string | null
constructor({
filepath,
loadFrameworkConfig,
...configFile
}: ConfigFile & { filepath: string; loadFrameworkConfig?: boolean }) {
this.configFile = defaultConfigValues(configFile)
// apply defaults and pull out the values
let {
schema,
schemaPath,
sourceGlob,
apiUrl,
quiet = false,
framework = 'kit',
module = 'esm',
static: staticSite,
scalars,
cacheBufferSize,
definitionsPath,
defaultCachePolicy = CachePolicy.CacheOrNetwork,
defaultPartial = false,
defaultKeys,
types = {},
logLevel,
disableMasking = false,
routesDir = null,
} = this.configFile
// make sure we got some kind of schema
if (!schema) {
throw {
filepath,
message:
'Invalid config file: please provide one of schema or schemaPath. Also, export default config',
}
}
// if we're given a schema string
if (typeof schema === 'string') {
this.schema = graphql.buildSchema(schema)
} else {
this.schema = schema!
}
// validate the log level value
if (logLevel && !Object.values(LogLevel).includes(logLevel.toLowerCase() as LogLevel)) {
console.warn(
`⚠️ Invalid log level provided. Valid values are: ${JSON.stringify(
Object.values(LogLevel)
)}`
)
logLevel = LogLevel.Summary
}
if (framework === 'sapper') {
console.warn(
`⚠️ Support for sapper will be dropped in 0.16.0. ⚠️
If that's going to be a problem, please open a discussion on GitHub.`
)
}
// save the values we were given
this.schemaPath = schemaPath
this.apiUrl = apiUrl
this.filepath = filepath
this.sourceGlob = sourceGlob
this.framework = framework
this.module = module
this.projectRoot = path.dirname(filepath)
this.static = staticSite
this.scalars = scalars
this.cacheBufferSize = cacheBufferSize
this.defaultCachePolicy = defaultCachePolicy
this.defaultPartial = defaultPartial
this.definitionsFolder = definitionsPath
this.logLevel = ((logLevel as LogLevel) || LogLevel.Summary).toLowerCase() as LogLevel
this.disableMasking = disableMasking
this.routesDir = routesDir
// if the user asked for `quiet` logging notify them its been deprecated
if (quiet) {
console.warn(
`⚠️ The quiet configuration parameter has been deprecated. ⚠️
You should update your config to look like this:
export default {
// ...
logLevel: 'quiet'
}
For more information, visit this link: https://www.houdinigraphql.com/guides/migrating-to-0.15.0#config-values
`
)
this.logLevel = LogLevel.Summary
}
// hold onto the key config
if (defaultKeys) {
this.defaultKeys = defaultKeys
}
if (types) {
this.typeConfig = {
...this.typeConfig,
...types,
}
}
// if we are building a sapper project, we want to put the runtime in
// src/node_modules so that we can access @sapper/app and interact
// with the application stores directly
this.rootDir =
framework === 'sapper'
? path.join(this.projectRoot, 'src', 'node_modules', '$houdini')
: path.join(this.projectRoot, '$houdini')
// if the config file specified an isRoute, use that
if (configFile.routes) {
this.configIsRoute = configFile.routes
}
}
// compute if a path points to a component query or not
isRoute(filepath: string): boolean {
// a vanilla svelte app is never considered in a route
if (this.framework === 'svelte' || this.static) {
return false
}
// only consider filepaths in src/routes
const routesDir = this.routesDir || 'src/routes'
if (!posixify(filepath).startsWith(posixify(path.join(this.projectRoot, routesDir)))) {
return false
}
// always consider layouts as routes
if (layout_pattern.test(path.parse(filepath).name)) {
return true
}
// if there is a route function from the config
if (this.configIsRoute) {
return this.configIsRoute(filepath)
}
// there is no special filter to apply. anything this far is a route
return true
}
async loadKitConfig({
isRoute,
configFilePath,
}: {
isRoute: boolean
configFilePath?: string
}) {
// if we fail to load
try {
// so far, all this does is load the route function so if we don't
// have to do that, we're done
if (!isRoute) {
return
}
// import the user's kit config file, and look for a custom isRoute function
const configFile = path.join(process.cwd(), configFilePath || 'svelte.config.js')
const config: KitConfig = await import(url.pathToFileURL(configFile).href)
// if there is a custom route function, use it
if (config.routes) {
this.configIsRoute = config.routes
}
} catch {}
// if its not in the route directory, its not a
// if we didn't assign an isRoute function, use the default kit one
if (!this.configIsRoute) {
// copied from here: https://github.com/sveltejs/kit/blob/28139749c4bf056d1e04f55e7f955da33770750d/packages/kit/src/core/config/options.js#L250
this.configIsRoute = (filepath) =>
!/(?:(?:^_|\/_)|(?:^\.|\/\.)(?!well-known))/.test(filepath)
}
}
/*
Directory structure
*/
// the directory where we put all of the artifacts
get artifactDirectory() {
return path.join(this.rootDir, this.artifactDirectoryName)
}
private get artifactDirectoryName() {
return 'artifacts'
}
// the directory where artifact types live
get artifactTypeDirectory() {
return this.artifactDirectory
}
// the directory where we put all of the stores
get storesDirectory() {
return path.join(this.rootDir, this.storesDirectoryName)
}
get metaFilePath() {
return path.join(this.rootDir, 'meta.json')
}
private get storesDirectoryName() {
return 'stores'
}
// where we will place the runtime
get runtimeDirectory() {
return path.join(this.rootDir, 'runtime')
}
// Default to => $houdini/graphql
get definitionsDirectory() {
return this.definitionsFolder
? path.join(this.projectRoot, this.definitionsFolder)
: path.join(this.rootDir, 'graphql')
}
get enumRuntimeDefinitionsPath() {
return path.join(this.definitionsDirectory, 'enums.js')
}
get enumTypesDefinitionsPath() {
return path.join(this.definitionsDirectory, 'enums.d.ts')
}
get definitionsSchemaPath() {
return path.join(this.definitionsDirectory, 'schema.graphql')
}
get definitionsDocumentsPath() {
return path.join(this.definitionsDirectory, 'documents.gql')
}
get typeIndexPath() {
return path.join(this.rootDir, 'index.d.ts')
}
artifactTypePath(document: graphql.DocumentNode) {
return path.join(this.artifactTypeDirectory, `${this.documentName(document)}.d.ts`)
}
// the location of the artifact generated corresponding to the provided documents
artifactPath(document: graphql.DocumentNode): string {
// use the operation name for the artifact
// make sure to mark artifacts as .js in sveltekit
return path.join(this.artifactDirectory, this.documentName(document) + '.js')
}
// the path that the runtime can use to import an artifact
artifactImportPath(name: string): string {
return `$houdini/${this.artifactDirectoryName}/${name}`
}
// the path that the runtime can use to import a store
storeImportPath(name: string): string {
return `$houdini/${this.storesDirectoryName}/${name}`
}
storeName({ name }: { name: string }) {
return `GQL_${name}`
}
storeFactoryName(name: string): string {
return name + 'Store'
}
keyFieldsForType(type: string) {
return keyFieldsForType(this.configFile, type)
}
computeID(type: string, data: any): string {
return computeID(this.configFile, type, data)
}
// a string identifier for the document (must be unique)
documentName(document: graphql.DocumentNode): string {
// if there is an operation in the document
const operation = document.definitions.find(
({ kind }) => graphql.Kind.OPERATION_DEFINITION
) as graphql.OperationDefinitionNode
if (operation) {
// if the operation does not have a name
if (!operation.name) {
// we can't give them a file
throw new Error('encountered operation with no name: ' + graphql.print(document))
}
// use the operation name for the artifact
return operation.name.value
}
// look for a fragment definition
const fragmentDefinitions = document.definitions.filter(
({ kind }) => kind === graphql.Kind.FRAGMENT_DEFINITION
) as graphql.FragmentDefinitionNode[]
if (fragmentDefinitions.length) {
// join all of the fragment definitions into one
return fragmentDefinitions.map((fragment) => fragment.name).join('_')
}
// we don't know how to generate a name for this document
throw new Error('Could not generate artifact name for document: ' + graphql.print(document))
}
isSelectionScalar(type: string) {
return ['String', 'Boolean', 'Float', 'ID', 'Int']
.concat(Object.keys(this.scalars || {}))
.includes(type)
}
async createDirectories(): Promise<void> {
await Promise.all([
fs.mkdirp(this.artifactDirectory),
fs.mkdirp(this.artifactTypeDirectory),
fs.mkdirp(this.runtimeDirectory),
fs.mkdirp(this.storesDirectory),
fs.mkdirp(this.definitionsDirectory),
])
}
/*
GraphqQL conventions
*/
get listDirective() {
return 'list'
}
get listPrependDirective() {
return 'prepend'
}
get listAppendDirective() {
return 'append'
}
get listParentDirective() {
return this.listDirectiveParentIDArg
}
get listDirectiveParentIDArg() {
return 'parentID'
}
get listNameArg() {
return 'name'
}
get insertFragmentSuffix() {
return `_insert`
}
get removeFragmentSuffix() {
return `_remove`
}
get toggleFragmentSuffix() {
return `_toggle`
}
get deleteDirectiveSuffix() {
return `_delete`
}
get whenDirective() {
return 'when'
}
get whenNotDirective() {
return this.whenDirective + '_not'
}
get argumentsDirective() {
return 'arguments'
}
get withDirective() {
return 'with'
}
get paginateDirective() {
return 'paginate'
}
get paginateNameArg() {
return 'name'
}
get cacheDirective() {
return 'cache'
}
get cachePartialArg() {
return 'partial'
}
get cachePolicyArg() {
return 'policy'
}
paginationQueryName(documentName: string) {
return documentName + '_Pagination_Query'
}
isDeleteDirective(name: string) {
return name.endsWith(this.deleteDirectiveSuffix)
}
listDeleteDirective(name: string): string {
return name + this.deleteDirectiveSuffix
}
deleteDirectiveType(name: string) {
return name.slice(0, name.length - this.deleteDirectiveSuffix.length)
}
isInsertFragment(name: string) {
return name.endsWith(this.insertFragmentSuffix)
}
listInsertFragment(name: string): string {
return name + this.insertFragmentSuffix
}
listToggleFragment(name: string): string {
return name + this.toggleFragmentSuffix
}
isRemoveFragment(name: string) {
return name.endsWith(this.removeFragmentSuffix)
}
isToggleFragment(name: string) {
return name.endsWith(this.toggleFragmentSuffix)
}
listRemoveFragment(name: string): string {
return name + this.removeFragmentSuffix
}
isInternalEnum(node: graphql.EnumTypeDefinitionNode): boolean {
// if we are looking at an enum, it could be CachePolicy
return node.name.value === 'CachePolicy'
}
isInternalDirective({ name }: graphql.DirectiveNode): boolean {
return (
[
this.listDirective,
this.listPrependDirective,
this.listAppendDirective,
this.listDirectiveParentIDArg,
this.whenDirective,
this.whenNotDirective,
this.argumentsDirective,
this.withDirective,
this.paginateDirective,
this.cacheDirective,
].includes(name.value) || this.isDeleteDirective(name.value)
)
}
isListFragment(name: string): boolean {
return (
name.endsWith(this.insertFragmentSuffix) ||
name.endsWith(this.removeFragmentSuffix) ||
name.endsWith(this.toggleFragmentSuffix)
)
}
isListOperationDirective(name: string): boolean {
return name.endsWith(this.deleteDirectiveSuffix)
}
isFragmentForList(listName: string, fragmentName: string) {
return fragmentName.startsWith(listName)
}
// return 'insert' for All_Users_insert
listOperationFromFragment(fragmentName: string): 'insert' | 'remove' | 'toggle' {
// check the name against the fragment patterns
if (this.isInsertFragment(fragmentName)) {
return 'insert'
} else if (this.isRemoveFragment(fragmentName)) {
return 'remove'
} else if (this.isToggleFragment(fragmentName)) {
return 'toggle'
}
throw new Error('Could not determine list operation from fragment name: ' + fragmentName)
}
listNameFromDirective(directiveName: string): string {
try {
return this.listNameFromFragment(directiveName)
} catch (e) {
throw new Error('Could not find list name from directive: ' + directiveName)
}
}
listNameFromFragment(fragmentName: string): string {
// starting at the end of the fragment name going left, look for a _
for (let i = fragmentName.length - 1; i >= 0; i--) {
// if we hit a _
if (fragmentName[i] === '_') {
return fragmentName.substr(0, i)
}
}
throw new Error('Could not find list name from fragment: ' + fragmentName)
}
}
const DEFAULT_CONFIG_PATH = path.join(process.cwd(), 'houdini.config.js')
// helper function to load the config file
export async function readConfigFile(
configPath: string = DEFAULT_CONFIG_PATH
): Promise<ConfigFile> {
// on windows, we need to prepend the right protocol before we
// can import from an absolute path
let importPath = configPath
if (os.platform() === 'win32') {
importPath = 'file:///' + importPath
}
const imported = await import(importPath)
// if this is wrapped in a default, use it
const config = imported.default || imported
return config
}
// a place to store the current configuration
let _config: Config
async function loadSchemaFile(schemaPath: string): Promise<graphql.GraphQLSchema> {
// if the schema is not a relative path, the config file is out of date
if (path.isAbsolute(schemaPath)) {
// compute the new value for schema
const relPath = path.relative(process.cwd(), schemaPath)
// build up an error with no stack trace so the message isn't so noisy
const error = new Error(
`Invalid config value: 'schemaPath' must now be passed as a relative directory. Please change ` +
`its value to "./${relPath}".`
)
error.stack = ''
// don't let anything continue
throw error
}
// if the path is a glob, load each file
if (glob.hasMagic(schemaPath)) {
// the first step we have to do is grab a list of every file in the source tree
const sourceFiles = await promisify(glob)(schemaPath)
return mergeSchemas({
typeDefs: await Promise.all(
sourceFiles.map(async (filepath) => fs.readFile(filepath, 'utf-8'))
),
})
}
// the path has no glob magic, make sure its a real file
if (!fs.stat(schemaPath)) {
throw new Error(`Schema file does not exist! Create it using houdini generate -p`)
}
const contents = await fs.readFile(schemaPath, 'utf-8')
// if the schema points to an sdl file
if (schemaPath.endsWith('gql') || schemaPath.endsWith('graphql')) {
return graphql.buildSchema(contents)
}
// the schema must point to a json blob (with data level or content of data directly)
const jsonContents = JSON.parse(contents)
if (jsonContents.data) {
return graphql.buildClientSchema(jsonContents.data)
}
return graphql.buildClientSchema(jsonContents)
}
// get the project's current configuration
export async function getConfig({
configFile,
...extraConfig
}: { configFile?: string } & Partial<ConfigFile> = {}): Promise<Config> {
if (_config) {
return _config
}
// add the filepath and save the result
const configPath = configFile || DEFAULT_CONFIG_PATH
const config = await readConfigFile(configPath)
// look up the schema
let schema = config.schema
if (config.schemaPath) {
schema = await loadSchemaFile(config.schemaPath)
}
_config = new Config({
schema,
...config,
...extraConfig,
filepath: configPath,
})
// if we are loading a sveltekit project, we might be able to grab the isRoute
// from the config (if it exists)
if (config.framework === 'kit') {
// only load the route config if the user didn't specify one explicitly
await _config.loadKitConfig({
isRoute: !config.routes,
configFilePath: config.frameworkConfigFile,
})
}
return _config
}
export enum LogLevel {
Full = 'full',
Summary = 'summary',
ShortSummary = 'short-summary',
Quiet = 'quiet',
}
const posixify = (str: string) => str.replace(/\\/g, '/')
const layout_pattern = /^__layout(?:-([a-zA-Z0-9_-]+))?(?:@([a-zA-Z0-9_-]+))?$/