updates gquery to work in prod

This commit is contained in:
Scott Tolinski 2021-10-13 11:06:31 -06:00
parent 2de47b51a2
commit 9d51ed7b20
9 changed files with 275 additions and 229 deletions

View file

@ -44,7 +44,7 @@ docs coming soon
<script lang="ts"> <script lang="ts">
// Cache becomes populated with data available for SSR // Cache becomes populated with data available for SSR
import { gCache } from '@leveluptuts/gQuery' import { gCache } from '@leveluptuts/g-query'
// $: console.log($gCache.seriesList) // $: console.log($gCache.seriesList)
</script> </script>

View file

@ -1,22 +1,24 @@
import { visit, concatAST, Kind, } from "graphql";
import "@graphql-codegen/plugin-helpers";
import { ClientSideBaseVisitor, } from "@graphql-codegen/visitor-plugin-common"; import { ClientSideBaseVisitor, } from "@graphql-codegen/visitor-plugin-common";
import { concatAST, Kind, visit, } from "graphql";
import { pascalCase } from "pascal-case"; import { pascalCase } from "pascal-case";
module.exports = { console.log("codegen.ts");
plugin: (schema, documents, config) => { export const plugin = (schema, documents, config) => {
const allAst = concatAST(documents.map((d) => d.document)); console.log("config", config);
const allFragments = [ const allAst = concatAST(documents.map((d) => d.document));
...allAst.definitions.filter((d) => d.kind === Kind.FRAGMENT_DEFINITION).map((fragmentDef) => ({ const allFragments = [
node: fragmentDef, ...allAst.definitions.filter((d) => d.kind === Kind.FRAGMENT_DEFINITION).map((fragmentDef) => ({
name: fragmentDef.name.value, node: fragmentDef,
onType: fragmentDef.typeCondition.name.value, name: fragmentDef.name.value,
isExternal: false, onType: fragmentDef.typeCondition.name.value,
})), isExternal: false,
...(config.externalFragments || []), })),
]; ...(config.externalFragments || []),
const visitor = new ClientSideBaseVisitor(schema, allFragments, {}, { documentVariableSuffix: "Doc" }, documents); ];
const visitorResult = visit(allAst, { leave: visitor }); const visitor = new ClientSideBaseVisitor(schema, allFragments, {}, { documentVariableSuffix: "Doc" }, documents);
const operations = allAst.definitions.filter((d) => d.kind === Kind.OPERATION_DEFINITION); const visitorResult = visit(allAst, { leave: visitor });
const defaultTypes = ` const operations = allAst.definitions.filter((d) => d.kind === Kind.OPERATION_DEFINITION);
const defaultTypes = `
type FetchWrapperArgs<T> = { type FetchWrapperArgs<T> = {
fetch: typeof fetch, fetch: typeof fetch,
@ -26,39 +28,51 @@ type FetchWrapperArgs<T> = {
type SubscribeWrapperArgs<T> = { type SubscribeWrapperArgs<T> = {
variables?: T, variables?: T,
} }
interface CacheFunctionOptions {
update?: boolean
}
`; `;
const ops = operations const ops = operations
.map((o) => { .map((o) => {
var _a; var _a;
if (o) { if (o) {
const name = ((_a = o === null || o === void 0 ? void 0 : o.name) === null || _a === void 0 ? void 0 : _a.value) || ""; const name = ((_a = o === null || o === void 0 ? void 0 : o.name) === null || _a === void 0 ? void 0 : _a.value) || "";
// const dsl = `export const ${pascalCase(op.name.value)}Doc = gql\` // const dsl = `export const ${pascalCase(op.name.value)}Doc = gql\`
// ${documents.find((d) => d.rawSDL.includes(`${op.operation} ${op.name.value}`)).rawSDL}\`` // ${documents.find((d) => d.rawSDL.includes(`${op.operation} ${op.name.value}`)).rawSDL}\``
const op = `${pascalCase(name)}${pascalCase(o.operation)}`; const op = `${pascalCase(name)}${pascalCase(o.operation)}`;
const opv = `${op}Variables`; const opv = `${op}Variables`;
let operations = ""; let operations = "";
if (o.operation === "query") { if (o.operation === "query") {
operations += ` operations += `
export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>): export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>):
Promise<GFetchReturnWithErrors<${op}>> => Promise<GFetchReturnWithErrors<${op}>> =>
g.fetch<${op}>({ g.fetch<${op}>({
queries: [{ query: ${pascalCase(name)}Doc, variables }], queries: [{ query: ${pascalCase(name)}Doc, variables }],
fetch fetch
}) })
// Cached
export async function get${pascalCase(name)}(variables, options?: CacheFunctionOptions) {
await gQuery('user', { query: ${name}, variables }, options)
}
`; `;
// If config is set to have subscription query, also write the // If config is set to have subscription query, also write the
if (config.subscriptionQuery) { if (config.subscriptionQuery) {
operations += ` operations += `
export const ${name}Subscribe = ({ variables }: SubscribeWrapperArgs<${opv}>): export const ${name}Subscribe = ({ variables }: SubscribeWrapperArgs<${opv}>):
Readable<GFetchReturnWithErrors<${op}>> => Readable<GFetchReturnWithErrors<${op}>> =>
g.oFetch<${op}>({ g.oFetch<${op}>({
queries: [{ query: ${pascalCase(name)}Doc, variables }] queries: [{ query: ${pascalCase(name)}Doc, variables }]
}) })
`; `;
}
} }
else if (o.operation === "mutation") { }
operations += ` else if (o.operation === "mutation") {
operations += `
export const ${name} = ({ variables }: SubscribeWrapperArgs<${opv}>): export const ${name} = ({ variables }: SubscribeWrapperArgs<${opv}>):
Promise<GFetchReturnWithErrors<${op}>> => Promise<GFetchReturnWithErrors<${op}>> =>
g.fetch<${op}>({ g.fetch<${op}>({
@ -66,52 +80,52 @@ Promise<GFetchReturnWithErrors<${op}>> =>
fetch, fetch,
}) })
`; `;
}
return operations;
} }
}) return operations;
.join("\n"); }
const imports = [ })
`import type { Readable } from "svelte/store"`, .join("\n");
`import { g } from '${config.gFetchPath}'`, const imports = [
`import type { GFetchReturnWithErrors } from '$graphql/gfetchLib'`, `import type { Readable } from "svelte/store"`,
`import gql from "graphql-tag"`, `import { g } from '${config.gPath}'`,
]; `import type { GFetchReturnWithErrors } from '@leveluptuts/g-query'`,
// let schemaInputs = getCachedDocumentNodeFromSchema(schema).definitions.filter((d) => { `import { gQuery } from '@leveluptuts/g-query'`,
// return d.kind === 'InputObjectTypeDefinition' `import gql from "graphql-tag"`,
// }) ];
// let inputs = schemaInputs // let schemaInputs = getCachedDocumentNodeFromSchema(schema).definitions.filter((d) => {
// .map((d) => { // return d.kind === 'InputObjectTypeDefinition'
// console.log('/* START */') // })
// // @ts-ignore // let inputs = schemaInputs
// console.log('NAME: ', d.fields[0].name.value) // .map((d) => {
// // @ts-ignore // console.log('/* START */')
// let isReq = d.fields[0]?.type?.kind === 'NonNullType' // // @ts-ignore
// console.log('REQUIRED: ', isReq ? '✅' : '❌') // console.log('NAME: ', d.fields[0].name.value)
// // @ts-ignore // // @ts-ignore
// console.log('TYPE: ', isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value) // let isReq = d.fields[0]?.type?.kind === 'NonNullType'
// // @ts-ignore // console.log('REQUIRED: ', isReq ? '✅' : '❌')
// // @ts-ignore // // @ts-ignore
// console.log('d.fields[0]', d.fields[0]?.type) // console.log('TYPE: ', isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value)
// console.log('/* END */') // // @ts-ignore
// console.log('') // // @ts-ignore
// return ` // console.log('d.fields[0]', d.fields[0]?.type)
// const inputName = { // console.log('/* END */')
// ${d.fields[0].name.value}: ${isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value} // console.log('')
// } // return `
// ` // const inputName = {
// }) // ${d.fields[0].name.value}: ${isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value}
// .join('\n') // }
// console.log('inputs', inputs) // `
return { // })
prepend: imports, // .join('\n')
content: [ // console.log('inputs', inputs)
defaultTypes, return {
visitor.fragments, prepend: imports,
...visitorResult.definitions.filter((t) => typeof t == "string"), content: [
ops, defaultTypes,
].join("\n"), visitor.fragments,
}; ...visitorResult.definitions.filter((t) => typeof t == "string"),
}, ops,
].join("\n"),
};
}; };
//# sourceMappingURL=codegen.js.map //# sourceMappingURL=codegen.js.map

View file

@ -1 +1 @@
{"version":3,"file":"codegen.js","sourceRoot":"","sources":["codegen.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,qBAAqB,GACtB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,SAAS,EAET,IAAI,EAEJ,KAAK,GACN,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,CAAC,OAAO,GAAG;IACf,MAAM,EAAE,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE;QACpC,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC,CAA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
} from "graphql";
import {
Types,
PluginValidateFn,
PluginFunction,
} from "@graphql-codegen/plugin-helpers";
import type { CodegenPlugin } from "@graphql-codegen/plugin-helpers"; import type { CodegenPlugin } from "@graphql-codegen/plugin-helpers";
import { import {
LoadedFragment, LoadedFragment,
ClientSideBaseVisitor, ClientSideBaseVisitor,
} from "@graphql-codegen/visitor-plugin-common"; } from "@graphql-codegen/visitor-plugin-common";
import {
concatAST,
FragmentDefinitionNode,
Kind,
OperationDefinitionNode,
visit,
} from "graphql";
import { pascalCase } from "pascal-case"; import { pascalCase } from "pascal-case";
module.exports = { console.log("codegen.ts");
plugin: (schema, documents, config) => {
const allAst = concatAST(documents.map((d) => d.document));
const allFragments: LoadedFragment[] = [ export const plugin: PluginFunction<any> = (
...( schema: GraphQLSchema,
allAst.definitions.filter( documents: Types.DocumentFile[],
(d) => d.kind === Kind.FRAGMENT_DEFINITION config
) as FragmentDefinitionNode[] ) => {
).map((fragmentDef) => ({ console.log("config", config);
node: fragmentDef, const allAst = concatAST(documents.map((d) => d.document));
name: fragmentDef.name.value,
onType: fragmentDef.typeCondition.name.value,
isExternal: false,
})),
...(config.externalFragments || []),
];
const visitor = new ClientSideBaseVisitor( const allFragments: LoadedFragment[] = [
schema, ...(
allFragments, allAst.definitions.filter(
{}, (d) => d.kind === Kind.FRAGMENT_DEFINITION
{ documentVariableSuffix: "Doc" }, ) as FragmentDefinitionNode[]
documents ).map((fragmentDef) => ({
); node: fragmentDef,
const visitorResult = visit(allAst, { leave: visitor }); name: fragmentDef.name.value,
onType: fragmentDef.typeCondition.name.value,
isExternal: false,
})),
...(config.externalFragments || []),
];
const operations = allAst.definitions.filter( const visitor = new ClientSideBaseVisitor(
(d) => d.kind === Kind.OPERATION_DEFINITION schema,
) as OperationDefinitionNode[]; allFragments,
const defaultTypes = ` {},
{ documentVariableSuffix: "Doc" },
documents
);
const visitorResult = visit(allAst, { leave: visitor });
const operations = allAst.definitions.filter(
(d) => d.kind === Kind.OPERATION_DEFINITION
) as OperationDefinitionNode[];
const defaultTypes = `
type FetchWrapperArgs<T> = { type FetchWrapperArgs<T> = {
fetch: typeof fetch, fetch: typeof fetch,
@ -52,39 +65,53 @@ type FetchWrapperArgs<T> = {
type SubscribeWrapperArgs<T> = { type SubscribeWrapperArgs<T> = {
variables?: T, variables?: T,
} }
interface CacheFunctionOptions {
update?: boolean
}
`; `;
const ops = operations const ops = operations
.map((o) => { .map((o) => {
if (o) { if (o) {
const name = o?.name?.value || ""; const name = o?.name?.value || "";
// const dsl = `export const ${pascalCase(op.name.value)}Doc = gql\` // const dsl = `export const ${pascalCase(op.name.value)}Doc = gql\`
// ${documents.find((d) => d.rawSDL.includes(`${op.operation} ${op.name.value}`)).rawSDL}\`` // ${documents.find((d) => d.rawSDL.includes(`${op.operation} ${op.name.value}`)).rawSDL}\``
const op = `${pascalCase(name)}${pascalCase(o.operation)}`; const op = `${pascalCase(name)}${pascalCase(o.operation)}`;
const opv = `${op}Variables`; const opv = `${op}Variables`;
let operations = ""; let operations = "";
if (o.operation === "query") { if (o.operation === "query") {
operations += ` operations += `
export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>): export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>):
Promise<GFetchReturnWithErrors<${op}>> => Promise<GFetchReturnWithErrors<${op}>> =>
g.fetch<${op}>({ g.fetch<${op}>({
queries: [{ query: ${pascalCase(name)}Doc, variables }], queries: [{ query: ${pascalCase(name)}Doc, variables }],
fetch fetch
}) })
// Cached
export async function get${pascalCase(
name
)}(variables, options?: CacheFunctionOptions) {
await gQuery('user', { query: ${name}, variables }, options)
}
`; `;
// If config is set to have subscription query, also write the // If config is set to have subscription query, also write the
if (config.subscriptionQuery) { if (config.subscriptionQuery) {
operations += ` operations += `
export const ${name}Subscribe = ({ variables }: SubscribeWrapperArgs<${opv}>): export const ${name}Subscribe = ({ variables }: SubscribeWrapperArgs<${opv}>):
Readable<GFetchReturnWithErrors<${op}>> => Readable<GFetchReturnWithErrors<${op}>> =>
g.oFetch<${op}>({ g.oFetch<${op}>({
queries: [{ query: ${pascalCase(name)}Doc, variables }] queries: [{ query: ${pascalCase(name)}Doc, variables }]
}) })
`; `;
} }
} else if (o.operation === "mutation") { } else if (o.operation === "mutation") {
operations += ` operations += `
export const ${name} = ({ variables }: SubscribeWrapperArgs<${opv}>): export const ${name} = ({ variables }: SubscribeWrapperArgs<${opv}>):
Promise<GFetchReturnWithErrors<${op}>> => Promise<GFetchReturnWithErrors<${op}>> =>
g.fetch<${op}>({ g.fetch<${op}>({
@ -92,56 +119,56 @@ Promise<GFetchReturnWithErrors<${op}>> =>
fetch, fetch,
}) })
`; `;
}
return operations;
} }
})
.join("\n");
const imports = [ return operations;
`import type { Readable } from "svelte/store"`, }
`import { g } from '${config.gFetchPath}'`, })
`import type { GFetchReturnWithErrors } from '$graphql/gfetchLib'`, .join("\n");
`import gql from "graphql-tag"`,
];
// let schemaInputs = getCachedDocumentNodeFromSchema(schema).definitions.filter((d) => { const imports = [
// return d.kind === 'InputObjectTypeDefinition' `import type { Readable } from "svelte/store"`,
// }) `import { g } from '${config.gPath}'`,
// let inputs = schemaInputs `import type { GFetchReturnWithErrors } from '@leveluptuts/g-query'`,
// .map((d) => { `import { gQuery } from '@leveluptuts/g-query'`,
// console.log('/* START */') `import gql from "graphql-tag"`,
// // @ts-ignore ];
// console.log('NAME: ', d.fields[0].name.value)
// // @ts-ignore
// let isReq = d.fields[0]?.type?.kind === 'NonNullType'
// console.log('REQUIRED: ', isReq ? '✅' : '❌')
// // @ts-ignore
// console.log('TYPE: ', isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value)
// // @ts-ignore
// // @ts-ignore
// console.log('d.fields[0]', d.fields[0]?.type)
// console.log('/* END */')
// console.log('')
// return ` // let schemaInputs = getCachedDocumentNodeFromSchema(schema).definitions.filter((d) => {
// const inputName = { // return d.kind === 'InputObjectTypeDefinition'
// ${d.fields[0].name.value}: ${isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value} // })
// } // let inputs = schemaInputs
// ` // .map((d) => {
// }) // console.log('/* START */')
// .join('\n') // // @ts-ignore
// console.log('inputs', inputs) // console.log('NAME: ', d.fields[0].name.value)
// // @ts-ignore
// let isReq = d.fields[0]?.type?.kind === 'NonNullType'
// console.log('REQUIRED: ', isReq ? '✅' : '❌')
// // @ts-ignore
// console.log('TYPE: ', isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value)
// // @ts-ignore
// // @ts-ignore
// console.log('d.fields[0]', d.fields[0]?.type)
// console.log('/* END */')
// console.log('')
return { // return `
prepend: imports, // const inputName = {
content: [ // ${d.fields[0].name.value}: ${isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value}
defaultTypes, // }
visitor.fragments, // `
...visitorResult.definitions.filter((t) => typeof t == "string"), // })
ops, // .join('\n')
].join("\n"), // console.log('inputs', inputs)
};
}, return {
} as CodegenPlugin; prepend: imports,
content: [
defaultTypes,
visitor.fragments,
...visitorResult.definitions.filter((t) => typeof t == "string"),
ops,
].join("\n"),
};
};

View file

@ -31,8 +31,10 @@ export default function levelupViteCodegen(options) {
if (!options.output) { if (!options.output) {
throw new Error("No output directory specified"); throw new Error("No output directory specified");
} }
const { schema, output } = options; if (!options.gPath) {
console.log(`${process.cwd()}/${output}/${outputFile}`); throw new Error("No gPath directory specified. gPath is where you've initialized the 'g' client");
}
const { schema, output, gPath } = options;
return { return {
name: "levelup-vite-codegen", name: "levelup-vite-codegen",
async buildStart() { async buildStart() {
@ -44,23 +46,21 @@ export default function levelupViteCodegen(options) {
[`${process.cwd()}/${output}/gquery-types.generated.ts`]: { [`${process.cwd()}/${output}/gquery-types.generated.ts`]: {
plugins: ["typescript"], plugins: ["typescript"],
}, },
// [`${process.cwd()}/${output}/${outputFile}`]: { [`${process.cwd()}/${output}`]: {
// // preset: "import-types", config: {
// // presetConfig: { gPath,
// // typesPath: `${output}/${outputFile}`, },
// // }, preset: "near-operation-file",
// // preset: "near-operation-file", presetConfig: {
// // presetConfig: { extension: ".generated.ts",
// // extension: ".generated.ts", folder: "./",
// // folder: "./", baseTypesPath: `gquery-types.generated.ts`,
// // baseTypesPath: `${output}/${outputFile}`, },
// // }, plugins: [
// plugins: [ "typescript-operations",
// "typescript", "@leveluptuts/g-query/codegen-plugin",
// // "typescript-operations", ],
// "../packages/gQueryCodegen/codegen.js", },
// ],
// },
}, },
}, true); }, true);
} }

View file

@ -1 +1 @@
{"version":3,"file":"plugin.js","sourceRoot":"","sources":["plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,uCAAuC;AAEvC,4EAA4E;AAC5E,4BAA4B;AAC5B,gCAAgC;AAChC,mEAAmE;AAEnE,qDAAqD;AACrD,8CAA8C;AAE9C,wEAAwE;AACxE,MAAM,UAAU,GAAG,qBAAqB,CAAC;AACzC,mBAAmB;AACnB,mBAAmB;AACnB,wJAAwJ;AACxJ,0BAA0B;AAC1B,wCAAwC;AACxC,eAAe;AACf,yCAAyC;AACzC,QAAQ;AACR,yEAAyE;AACzE,SAAS;AACT,OAAO;AACP,iBAAiB;AACjB,oCAAoC;AACpC,OAAO;AACP,KAAK;AAEL,MAAM,SAAS,GAAG,cAAc,CAAC;AAEjC,MAAM,CAAC,OAAO,UAAU,kBAAkB,CAAC,OAAO;IAChD,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;KACvC;IACD,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;KAClD;IAED,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IACnC,OAAO,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,IAAI,MAAM,IAAI,UAAU,EAAE,CAAC,CAAC;IACxD,O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AAC,+CAA+C,CAAC,CAAC;gBAC7D,OAAO,CAAC,GAAG,CACT,0FAA0F,CAC3F,CAAC;gBACF,OAAO,CAAC,GAAG,CACT,uFAAuF,CACxF,CAAC;aACH;YACD,OAAO;QACT,CAAC;QAED,SAAS,CAAC,GAAG,EAAE,EAAE,IAAG,CAAC;KACtB,CAAC;AACJ,CAAC"}

View file

@ -36,9 +36,14 @@ export default function levelupViteCodegen(options) {
if (!options.output) { if (!options.output) {
throw new Error("No output directory specified"); throw new Error("No output directory specified");
} }
if (!options.gPath) {
throw new Error(
"No gPath directory specified. gPath is where you've initialized the 'g' client"
);
}
const { schema, output, gPath } = options;
const { schema, output } = options;
console.log(`${process.cwd()}/${output}/${outputFile}`);
return { return {
name: "levelup-vite-codegen", name: "levelup-vite-codegen",
@ -52,23 +57,21 @@ export default function levelupViteCodegen(options) {
[`${process.cwd()}/${output}/gquery-types.generated.ts`]: { [`${process.cwd()}/${output}/gquery-types.generated.ts`]: {
plugins: ["typescript"], plugins: ["typescript"],
}, },
// [`${process.cwd()}/${output}/${outputFile}`]: { [`${process.cwd()}/${output}`]: {
// // preset: "import-types", config: {
// // presetConfig: { gPath,
// // typesPath: `${output}/${outputFile}`, },
// // }, preset: "near-operation-file",
// // preset: "near-operation-file", presetConfig: {
// // presetConfig: { extension: ".generated.ts",
// // extension: ".generated.ts", folder: "./",
// // folder: "./", baseTypesPath: `gquery-types.generated.ts`,
// // baseTypesPath: `${output}/${outputFile}`, },
// // }, plugins: [
// plugins: [ "typescript-operations",
// "typescript", "@leveluptuts/g-query/codegen-plugin",
// // "typescript-operations", ],
// "../packages/gQueryCodegen/codegen.js", },
// ],
// },
}, },
}, },
true true

View file

@ -5,6 +5,7 @@
}, },
"dependencies": { "dependencies": {
"@graphql-codegen/cli": "^2.2.0", "@graphql-codegen/cli": "^2.2.0",
"@graphql-codegen/typescript-operations": "^2.1.6",
"camel-case": "^4.1.2", "camel-case": "^4.1.2",
"pascal-case": "^3.1.2", "pascal-case": "^3.1.2",
"svelte": "^3.43.1", "svelte": "^3.43.1",
@ -12,6 +13,8 @@
}, },
"description": "Not like jQuery. A GraphQL Fetcher & Cache for Svelte Kit", "description": "Not like jQuery. A GraphQL Fetcher & Cache for Svelte Kit",
"devDependencies": { "devDependencies": {
"@graphql-codegen/import-types-preset": "^2.1.4",
"@graphql-codegen/near-operation-file-preset": "^2.1.4",
"@graphql-codegen/plugin-helpers": "^2.1.1", "@graphql-codegen/plugin-helpers": "^2.1.1",
"@graphql-codegen/visitor-plugin-common": "^2.2.1", "@graphql-codegen/visitor-plugin-common": "^2.2.1",
"graphql": "^15.6.1", "graphql": "^15.6.1",
@ -19,7 +22,9 @@
}, },
"exports": { "exports": {
".": "./dist/index.js", ".": "./dist/index.js",
"./*": "./dist/index.js",
"./codegen": "./codegen/plugin.js", "./codegen": "./codegen/plugin.js",
"./codegen-plugin": "./codegen/codegen.js",
"./package.json": "./package.json" "./package.json": "./package.json"
}, },
"homepage": "https://github.com/leveluptuts/gQuery#readme", "homepage": "https://github.com/leveluptuts/gQuery#readme",
@ -27,7 +32,7 @@
"graphql" "graphql"
], ],
"license": "ISC", "license": "ISC",
"name": "@leveluptuts/gQuery", "name": "@leveluptuts/g-query",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/leveluptuts/gQuery.git" "url": "git+https://github.com/leveluptuts/gQuery.git"
@ -38,5 +43,5 @@
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"type": "module", "type": "module",
"version": "0.0.1" "version": "0.0.2"
} }

View file

@ -5,10 +5,6 @@
"lib": ["es2020", "DOM"], "lib": ["es2020", "DOM"],
"outDir": "./dist", "outDir": "./dist",
"target": "es2020", "target": "es2020",
/**
svelte-preprocess cannot figure out whether you have a value or a type, so tell TypeScript
to enforce using \`import type\` instead of \`import\` for Types.
*/
"importsNotUsedAsValues": "error", "importsNotUsedAsValues": "error",
"isolatedModules": true, "isolatedModules": true,
"resolveJsonModule": true, "resolveJsonModule": true,
@ -21,6 +17,7 @@
"skipLibCheck": true, "skipLibCheck": true,
"forceConsistentCasingInFileNames": true "forceConsistentCasingInFileNames": true
}, },
"exclude": ["node_modules"], "exclude": ["node_modules"],
"include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.ts", "src/codegen.ts"] "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.ts"]
} }