From 639f56eaa1aeb1f25459820ee62cacd1039ff529 Mon Sep 17 00:00:00 2001 From: Josh GM Walker <56300765+Josh-Walker-GM@users.noreply.github.com> Date: Sun, 18 Aug 2024 00:03:50 +0100 Subject: [PATCH 1/8] temp: check in dist --- .gitignore | 2 + .../__snapshots__/graphqlCodeGen.test.ts.snap | 413 ++++++++++++++++++ .../__snapshots__/graphqlSchema.test.ts.snap | 130 ++++++ .../__snapshots__/possibleTypes.test.ts.snap | 17 + .../typeDefinitions.test.ts.snap | 36 ++ ...alidateSchemaForReservedNames.test.ts.snap | 19 + .../fixtures/.redwood/schema.graphql | 31 ++ .../bookshelf/api/db/schema.prisma | 21 + .../graphqlCodeGen/bookshelf/redwood.toml | 10 + .../invalidQueryType/.redwood/schema.graphql | 21 + .../invalidQueryType/redwood.toml | 2 + .../missingType/.redwood/schema.graphql | 25 ++ .../graphqlCodeGen/missingType/redwood.toml | 2 + .../nonExistingField/.redwood/schema.graphql | 31 ++ .../nonExistingField/redwood.toml | 2 + .../realtime/api/db/schema.prisma | 21 + .../graphqlCodeGen/realtime/redwood.toml | 10 + .../fixtures/nestedPages/redwood.toml | 16 + .../fixtures/nestedPages/web/src/index.html | 21 + .../__tests__/fixtures/redwood.empty.toml | 0 .../dist/__tests__/fixtures/redwood.toml | 2 + .../__tests__/fixtures/redwood.withEnv.toml | 9 + packages/internal/dist/ast.d.ts | 26 ++ packages/internal/dist/ast.d.ts.map | 1 + packages/internal/dist/ast.js | 186 ++++++++ packages/internal/dist/build/api.d.ts | 6 + packages/internal/dist/build/api.d.ts.map | 1 + packages/internal/dist/build/api.js | 82 ++++ packages/internal/dist/cliLogger.d.ts | 11 + packages/internal/dist/cliLogger.d.ts.map | 1 + packages/internal/dist/cliLogger.js | 20 + packages/internal/dist/dev.d.ts | 2 + packages/internal/dist/dev.d.ts.map | 1 + packages/internal/dist/dev.js | 13 + packages/internal/dist/files.d.ts | 51 +++ packages/internal/dist/files.d.ts.map | 1 + packages/internal/dist/files.js | 245 +++++++++++ .../internal/dist/generate/clientPreset.d.ts | 17 + .../dist/generate/clientPreset.d.ts.map | 1 + .../internal/dist/generate/clientPreset.js | 72 +++ packages/internal/dist/generate/generate.d.ts | 10 + .../internal/dist/generate/generate.d.ts.map | 1 + packages/internal/dist/generate/generate.js | 81 ++++ .../dist/generate/graphqlCodeGen.d.ts | 16 + .../dist/generate/graphqlCodeGen.d.ts.map | 1 + .../internal/dist/generate/graphqlCodeGen.js | 350 +++++++++++++++ .../internal/dist/generate/graphqlSchema.d.ts | 8 + .../dist/generate/graphqlSchema.d.ts.map | 1 + .../internal/dist/generate/graphqlSchema.js | 122 ++++++ .../rw-typescript-resolvers/index.d.ts | 6 + .../rw-typescript-resolvers/index.d.ts.map | 1 + .../plugins/rw-typescript-resolvers/index.js | 92 ++++ .../rw-typescript-resolvers/visitor.d.ts | 9 + .../rw-typescript-resolvers/visitor.d.ts.map | 1 + .../rw-typescript-resolvers/visitor.js | 101 +++++ .../internal/dist/generate/possibleTypes.d.ts | 36 ++ .../dist/generate/possibleTypes.d.ts.map | 1 + .../internal/dist/generate/possibleTypes.js | 107 +++++ .../internal/dist/generate/templates.d.ts | 6 + .../internal/dist/generate/templates.d.ts.map | 1 + packages/internal/dist/generate/templates.js | 26 ++ .../templates/all-currentUser.d.ts.template | 28 ++ .../templates/api-globImports.d.ts.template | 9 + .../templates/api-globalContext.d.ts.template | 7 + .../templates/api-scenarios.d.ts.template | 10 + .../templates/api-test-globals.d.ts.template | 5 + .../templates/mirror-cell.d.ts.template | 13 + .../mirror-directoryNamedModule.d.ts.template | 5 + .../templates/web-routerRoutes.d.ts.template | 20 + .../templates/web-routesPages.d.ts.template | 13 + .../templates/web-test-globals.d.ts.template | 7 + .../dist/generate/trustedDocuments.d.ts | 3 + .../dist/generate/trustedDocuments.d.ts.map | 1 + .../dist/generate/trustedDocuments.js | 72 +++ .../dist/generate/typeDefinitions.d.ts | 30 ++ .../dist/generate/typeDefinitions.d.ts.map | 1 + .../internal/dist/generate/typeDefinitions.js | 349 +++++++++++++++ packages/internal/dist/generate/types.d.ts | 6 + .../internal/dist/generate/types.d.ts.map | 1 + packages/internal/dist/generate/types.js | 6 + packages/internal/dist/generate/watch.d.ts | 3 + .../internal/dist/generate/watch.d.ts.map | 1 + packages/internal/dist/generate/watch.js | 109 +++++ packages/internal/dist/gql.d.ts | 14 + packages/internal/dist/gql.d.ts.map | 1 + packages/internal/dist/gql.js | 94 ++++ packages/internal/dist/index.d.ts | 11 + packages/internal/dist/index.d.ts.map | 1 + packages/internal/dist/index.js | 119 +++++ packages/internal/dist/jsx.d.ts | 16 + packages/internal/dist/jsx.d.ts.map | 1 + packages/internal/dist/jsx.js | 91 ++++ packages/internal/dist/jsxAttributeValue.d.ts | 2 + .../internal/dist/jsxAttributeValue.d.ts.map | 1 + packages/internal/dist/jsxAttributeValue.js | 127 ++++++ packages/internal/dist/project.d.ts | 8 + packages/internal/dist/project.d.ts.map | 1 + packages/internal/dist/project.js | 39 ++ packages/internal/dist/routes.d.ts | 42 ++ packages/internal/dist/routes.d.ts.map | 1 + packages/internal/dist/routes.js | 100 +++++ packages/internal/dist/ts2js.d.ts | 40 ++ packages/internal/dist/ts2js.d.ts.map | 1 + packages/internal/dist/ts2js.js | 156 +++++++ packages/internal/dist/validateSchema.d.ts | 14 + .../internal/dist/validateSchema.d.ts.map | 1 + packages/internal/dist/validateSchema.js | 158 +++++++ 107 files changed, 4293 insertions(+) create mode 100644 packages/internal/dist/__tests__/__snapshots__/graphqlCodeGen.test.ts.snap create mode 100644 packages/internal/dist/__tests__/__snapshots__/graphqlSchema.test.ts.snap create mode 100644 packages/internal/dist/__tests__/__snapshots__/possibleTypes.test.ts.snap create mode 100644 packages/internal/dist/__tests__/__snapshots__/typeDefinitions.test.ts.snap create mode 100644 packages/internal/dist/__tests__/__snapshots__/validateSchemaForReservedNames.test.ts.snap create mode 100644 packages/internal/dist/__tests__/fixtures/.redwood/schema.graphql create mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/api/db/schema.prisma create mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/redwood.toml create mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/.redwood/schema.graphql create mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/redwood.toml create mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/.redwood/schema.graphql create mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/redwood.toml create mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/.redwood/schema.graphql create mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/redwood.toml create mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/api/db/schema.prisma create mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/redwood.toml create mode 100644 packages/internal/dist/__tests__/fixtures/nestedPages/redwood.toml create mode 100644 packages/internal/dist/__tests__/fixtures/nestedPages/web/src/index.html create mode 100644 packages/internal/dist/__tests__/fixtures/redwood.empty.toml create mode 100644 packages/internal/dist/__tests__/fixtures/redwood.toml create mode 100644 packages/internal/dist/__tests__/fixtures/redwood.withEnv.toml create mode 100644 packages/internal/dist/ast.d.ts create mode 100644 packages/internal/dist/ast.d.ts.map create mode 100644 packages/internal/dist/ast.js create mode 100644 packages/internal/dist/build/api.d.ts create mode 100644 packages/internal/dist/build/api.d.ts.map create mode 100644 packages/internal/dist/build/api.js create mode 100644 packages/internal/dist/cliLogger.d.ts create mode 100644 packages/internal/dist/cliLogger.d.ts.map create mode 100644 packages/internal/dist/cliLogger.js create mode 100644 packages/internal/dist/dev.d.ts create mode 100644 packages/internal/dist/dev.d.ts.map create mode 100644 packages/internal/dist/dev.js create mode 100644 packages/internal/dist/files.d.ts create mode 100644 packages/internal/dist/files.d.ts.map create mode 100644 packages/internal/dist/files.js create mode 100644 packages/internal/dist/generate/clientPreset.d.ts create mode 100644 packages/internal/dist/generate/clientPreset.d.ts.map create mode 100644 packages/internal/dist/generate/clientPreset.js create mode 100644 packages/internal/dist/generate/generate.d.ts create mode 100644 packages/internal/dist/generate/generate.d.ts.map create mode 100755 packages/internal/dist/generate/generate.js create mode 100644 packages/internal/dist/generate/graphqlCodeGen.d.ts create mode 100644 packages/internal/dist/generate/graphqlCodeGen.d.ts.map create mode 100644 packages/internal/dist/generate/graphqlCodeGen.js create mode 100644 packages/internal/dist/generate/graphqlSchema.d.ts create mode 100644 packages/internal/dist/generate/graphqlSchema.d.ts.map create mode 100644 packages/internal/dist/generate/graphqlSchema.js create mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts create mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts.map create mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js create mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts create mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts.map create mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js create mode 100644 packages/internal/dist/generate/possibleTypes.d.ts create mode 100644 packages/internal/dist/generate/possibleTypes.d.ts.map create mode 100644 packages/internal/dist/generate/possibleTypes.js create mode 100644 packages/internal/dist/generate/templates.d.ts create mode 100644 packages/internal/dist/generate/templates.d.ts.map create mode 100644 packages/internal/dist/generate/templates.js create mode 100644 packages/internal/dist/generate/templates/all-currentUser.d.ts.template create mode 100644 packages/internal/dist/generate/templates/api-globImports.d.ts.template create mode 100644 packages/internal/dist/generate/templates/api-globalContext.d.ts.template create mode 100644 packages/internal/dist/generate/templates/api-scenarios.d.ts.template create mode 100644 packages/internal/dist/generate/templates/api-test-globals.d.ts.template create mode 100644 packages/internal/dist/generate/templates/mirror-cell.d.ts.template create mode 100644 packages/internal/dist/generate/templates/mirror-directoryNamedModule.d.ts.template create mode 100644 packages/internal/dist/generate/templates/web-routerRoutes.d.ts.template create mode 100644 packages/internal/dist/generate/templates/web-routesPages.d.ts.template create mode 100644 packages/internal/dist/generate/templates/web-test-globals.d.ts.template create mode 100644 packages/internal/dist/generate/trustedDocuments.d.ts create mode 100644 packages/internal/dist/generate/trustedDocuments.d.ts.map create mode 100644 packages/internal/dist/generate/trustedDocuments.js create mode 100644 packages/internal/dist/generate/typeDefinitions.d.ts create mode 100644 packages/internal/dist/generate/typeDefinitions.d.ts.map create mode 100644 packages/internal/dist/generate/typeDefinitions.js create mode 100644 packages/internal/dist/generate/types.d.ts create mode 100644 packages/internal/dist/generate/types.d.ts.map create mode 100644 packages/internal/dist/generate/types.js create mode 100644 packages/internal/dist/generate/watch.d.ts create mode 100644 packages/internal/dist/generate/watch.d.ts.map create mode 100755 packages/internal/dist/generate/watch.js create mode 100644 packages/internal/dist/gql.d.ts create mode 100644 packages/internal/dist/gql.d.ts.map create mode 100644 packages/internal/dist/gql.js create mode 100644 packages/internal/dist/index.d.ts create mode 100644 packages/internal/dist/index.d.ts.map create mode 100644 packages/internal/dist/index.js create mode 100644 packages/internal/dist/jsx.d.ts create mode 100644 packages/internal/dist/jsx.d.ts.map create mode 100644 packages/internal/dist/jsx.js create mode 100644 packages/internal/dist/jsxAttributeValue.d.ts create mode 100644 packages/internal/dist/jsxAttributeValue.d.ts.map create mode 100644 packages/internal/dist/jsxAttributeValue.js create mode 100644 packages/internal/dist/project.d.ts create mode 100644 packages/internal/dist/project.d.ts.map create mode 100644 packages/internal/dist/project.js create mode 100644 packages/internal/dist/routes.d.ts create mode 100644 packages/internal/dist/routes.d.ts.map create mode 100644 packages/internal/dist/routes.js create mode 100644 packages/internal/dist/ts2js.d.ts create mode 100644 packages/internal/dist/ts2js.d.ts.map create mode 100644 packages/internal/dist/ts2js.js create mode 100644 packages/internal/dist/validateSchema.d.ts create mode 100644 packages/internal/dist/validateSchema.d.ts.map create mode 100644 packages/internal/dist/validateSchema.js diff --git a/.gitignore b/.gitignore index fc106d99ca1f..575bca40e1a9 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,5 @@ packages/create-redwood-app/create-redwood-app.tgz .nx/cache .nx/workspace-data + +!packages/internal/dist diff --git a/packages/internal/dist/__tests__/__snapshots__/graphqlCodeGen.test.ts.snap b/packages/internal/dist/__tests__/__snapshots__/graphqlCodeGen.test.ts.snap new file mode 100644 index 000000000000..71e17b80e5ca --- /dev/null +++ b/packages/internal/dist/__tests__/__snapshots__/graphqlCodeGen.test.ts.snap @@ -0,0 +1,413 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`Generate gql typedefs api 1`] = ` +"import { Prisma } from "@prisma/client" +import { MergePrismaWithSdlTypes, MakeRelationsOptional } from '@redwoodjs/api' +import { PrismaModelOne as PrismaPrismaModelOne, PrismaModelTwo as PrismaPrismaModelTwo, Post as PrismaPost, Todo as PrismaTodo } from '@prisma/client' +import { GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig } from 'graphql'; +import { RedwoodGraphQLContext } from '@redwoodjs/graphql-server/dist/types'; +export type Maybe = T | null; +export type InputMaybe = Maybe; +export type Exact = { [K in keyof T]: T[K] }; +export type MakeOptional = Omit & { [SubKey in K]?: Maybe }; +export type MakeMaybe = Omit & { [SubKey in K]: Maybe }; +export type ResolverFn = ( + args?: TArgs, + obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } + ) => TResult | Promise +export type RequireFields = Omit & { [P in K]-?: NonNullable }; +export type OptArgsResolverFn = ( + args?: TArgs, + obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } + ) => TResult | Promise + + export type RequiredResolverFn = ( + args: TArgs, + obj: { root: TParent; context: TContext; info: GraphQLResolveInfo } + ) => TResult | Promise +/** All built-in and custom scalars, mapped to their actual values */ +export type Scalars = { + ID: string; + String: string; + Boolean: boolean; + Int: number; + Float: number; + BigInt: number; + Byte: Buffer; + Date: Date | string; + DateTime: Date | string; + JSON: Prisma.JsonValue; + JSONObject: Prisma.JsonObject; + Time: Date | string; +}; + +export type Mutation = { + __typename?: 'Mutation'; + createTodo?: Maybe; + renameTodo?: Maybe; + updateTodoStatus?: Maybe; +}; + + +export type MutationcreateTodoArgs = { + body: Scalars['String']; +}; + + +export type MutationrenameTodoArgs = { + body: Scalars['String']; + id: Scalars['Int']; +}; + + +export type MutationupdateTodoStatusArgs = { + id: Scalars['Int']; + status: Scalars['String']; +}; + +/** About the Redwood queries. */ +export type Query = { + __typename?: 'Query'; + currentUser?: Maybe; + /** Fetches the Redwood root schema. */ + redwood?: Maybe; + todos?: Maybe>>; + todosCount: Scalars['Int']; +}; + +/** + * The RedwoodJS Root Schema + * + * Defines details about RedwoodJS such as the current user and version information. + */ +export type Redwood = { + __typename?: 'Redwood'; + /** The current user. */ + currentUser?: Maybe; + /** The version of Prisma. */ + prismaVersion?: Maybe; + /** The version of Redwood. */ + version?: Maybe; +}; + +export type Todo = { + __typename?: 'Todo'; + body: Scalars['String']; + id: Scalars['Int']; + status: Scalars['String']; +}; + +type MaybeOrArrayOfMaybe = T | Maybe | Maybe[]; +type AllMappedModels = MaybeOrArrayOfMaybe + + +export type ResolverTypeWrapper = Promise | T; + +export type Resolver = ResolverFn; + +export type SubscriptionSubscribeFn = ( + parent: TParent, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo +) => AsyncIterable | Promise>; + +export type SubscriptionResolveFn = ( + parent: TParent, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo +) => TResult | Promise; + +export interface SubscriptionSubscriberObject { + subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>; + resolve?: SubscriptionResolveFn; +} + +export interface SubscriptionResolverObject { + subscribe: SubscriptionSubscribeFn; + resolve: SubscriptionResolveFn; +} + +export type SubscriptionObject = + | SubscriptionSubscriberObject + | SubscriptionResolverObject; + +export type SubscriptionResolver = + | ((...args: any[]) => SubscriptionObject) + | SubscriptionObject; + +export type TypeResolveFn = ( + parent: TParent, + context: TContext, + info: GraphQLResolveInfo +) => Maybe | Promise>; + +export type IsTypeOfResolverFn = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise; + +export type NextResolverFn = () => Promise; + +export type DirectiveResolverFn = ( + next: NextResolverFn, + parent: TParent, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo +) => TResult | Promise; + + + +/** Mapping between all available schema types and the resolvers types */ +export type ResolversTypes = { + BigInt: ResolverTypeWrapper; + Boolean: ResolverTypeWrapper; + Byte: ResolverTypeWrapper; + Date: ResolverTypeWrapper; + DateTime: ResolverTypeWrapper; + Int: ResolverTypeWrapper; + JSON: ResolverTypeWrapper; + JSONObject: ResolverTypeWrapper; + Mutation: ResolverTypeWrapper<{}>; + Query: ResolverTypeWrapper<{}>; + Redwood: ResolverTypeWrapper; + String: ResolverTypeWrapper; + Time: ResolverTypeWrapper; + Todo: ResolverTypeWrapper, AllMappedModels>>; +}; + +/** Mapping between all available schema types and the resolvers parents */ +export type ResolversParentTypes = { + BigInt: Scalars['BigInt']; + Boolean: Scalars['Boolean']; + Byte: Scalars['Byte']; + Date: Scalars['Date']; + DateTime: Scalars['DateTime']; + Int: Scalars['Int']; + JSON: Scalars['JSON']; + JSONObject: Scalars['JSONObject']; + Mutation: {}; + Query: {}; + Redwood: Redwood; + String: Scalars['String']; + Time: Scalars['Time']; + Todo: MergePrismaWithSdlTypes, AllMappedModels>; +}; + +export type requireAuthDirectiveArgs = { + roles?: Maybe>>; +}; + +export type requireAuthDirectiveResolver = DirectiveResolverFn; + +export type skipAuthDirectiveArgs = { }; + +export type skipAuthDirectiveResolver = DirectiveResolverFn; + +export interface BigIntScalarConfig extends GraphQLScalarTypeConfig { + name: 'BigInt'; +} + +export interface ByteScalarConfig extends GraphQLScalarTypeConfig { + name: 'Byte'; +} + +export interface DateScalarConfig extends GraphQLScalarTypeConfig { + name: 'Date'; +} + +export interface DateTimeScalarConfig extends GraphQLScalarTypeConfig { + name: 'DateTime'; +} + +export interface JSONScalarConfig extends GraphQLScalarTypeConfig { + name: 'JSON'; +} + +export interface JSONObjectScalarConfig extends GraphQLScalarTypeConfig { + name: 'JSONObject'; +} + +export type MutationResolvers = { + createTodo: Resolver, ParentType, ContextType, RequireFields>; + renameTodo: Resolver, ParentType, ContextType, RequireFields>; + updateTodoStatus: Resolver, ParentType, ContextType, RequireFields>; +}; + +export type MutationRelationResolvers = { + createTodo?: RequiredResolverFn, ParentType, ContextType, RequireFields>; + renameTodo?: RequiredResolverFn, ParentType, ContextType, RequireFields>; + updateTodoStatus?: RequiredResolverFn, ParentType, ContextType, RequireFields>; +}; + +export type QueryResolvers = { + currentUser: OptArgsResolverFn, ParentType, ContextType>; + redwood: OptArgsResolverFn, ParentType, ContextType>; + todos: OptArgsResolverFn>>, ParentType, ContextType>; + todosCount: OptArgsResolverFn; +}; + +export type QueryRelationResolvers = { + currentUser?: RequiredResolverFn, ParentType, ContextType>; + redwood?: RequiredResolverFn, ParentType, ContextType>; + todos?: RequiredResolverFn>>, ParentType, ContextType>; + todosCount?: RequiredResolverFn; +}; + +export type RedwoodResolvers = { + currentUser: OptArgsResolverFn, ParentType, ContextType>; + prismaVersion: OptArgsResolverFn, ParentType, ContextType>; + version: OptArgsResolverFn, ParentType, ContextType>; + __isTypeOf?: IsTypeOfResolverFn; +}; + +export type RedwoodRelationResolvers = { + currentUser?: RequiredResolverFn, ParentType, ContextType>; + prismaVersion?: RequiredResolverFn, ParentType, ContextType>; + version?: RequiredResolverFn, ParentType, ContextType>; + __isTypeOf?: IsTypeOfResolverFn; +}; + +export interface TimeScalarConfig extends GraphQLScalarTypeConfig { + name: 'Time'; +} + +export type TodoResolvers = { + body: OptArgsResolverFn; + id: OptArgsResolverFn; + status: OptArgsResolverFn; + __isTypeOf?: IsTypeOfResolverFn; +}; + +export type TodoRelationResolvers = { + body?: RequiredResolverFn; + id?: RequiredResolverFn; + status?: RequiredResolverFn; + __isTypeOf?: IsTypeOfResolverFn; +}; + +export type Resolvers = { + BigInt: GraphQLScalarType; + Byte: GraphQLScalarType; + Date: GraphQLScalarType; + DateTime: GraphQLScalarType; + JSON: GraphQLScalarType; + JSONObject: GraphQLScalarType; + Mutation: MutationResolvers; + Query: QueryResolvers; + Redwood: RedwoodResolvers; + Time: GraphQLScalarType; + Todo: TodoResolvers; +}; + +export type DirectiveResolvers = { + requireAuth: requireAuthDirectiveResolver; + skipAuth: skipAuthDirectiveResolver; +}; +" +`; + +exports[`Generate gql typedefs web 1`] = ` +"import { Prisma } from "@prisma/client" +export type Maybe = T | null; +export type InputMaybe = Maybe; +export type Exact = { [K in keyof T]: T[K] }; +export type MakeOptional = Omit & { [SubKey in K]?: Maybe }; +export type MakeMaybe = Omit & { [SubKey in K]: Maybe }; +/** All built-in and custom scalars, mapped to their actual values */ +export type Scalars = { + ID: string; + String: string; + Boolean: boolean; + Int: number; + Float: number; + BigInt: number; + Byte: Buffer; + Date: string; + DateTime: string; + JSON: Prisma.JsonValue; + JSONObject: Prisma.JsonObject; + Time: string; +}; + +export type Mutation = { + __typename?: 'Mutation'; + createTodo?: Maybe; + renameTodo?: Maybe; + updateTodoStatus?: Maybe; +}; + + +export type MutationcreateTodoArgs = { + body: Scalars['String']; +}; + + +export type MutationrenameTodoArgs = { + body: Scalars['String']; + id: Scalars['Int']; +}; + + +export type MutationupdateTodoStatusArgs = { + id: Scalars['Int']; + status: Scalars['String']; +}; + +/** About the Redwood queries. */ +export type Query = { + __typename?: 'Query'; + currentUser?: Maybe; + /** Fetches the Redwood root schema. */ + redwood?: Maybe; + todos?: Maybe>>; + todosCount: Scalars['Int']; +}; + +/** + * The RedwoodJS Root Schema + * + * Defines details about RedwoodJS such as the current user and version information. + */ +export type Redwood = { + __typename?: 'Redwood'; + /** The current user. */ + currentUser?: Maybe; + /** The version of Prisma. */ + prismaVersion?: Maybe; + /** The version of Redwood. */ + version?: Maybe; +}; + +export type Todo = { + __typename?: 'Todo'; + body: Scalars['String']; + id: Scalars['Int']; + status: Scalars['String']; +}; + +export type AddTodo_CreateTodoVariables = Exact<{ + body: Scalars['String']; +}>; + + +export type AddTodo_CreateTodo = { __typename?: 'Mutation', createTodo?: { __typename: 'Todo', id: number, body: string, status: string } | null }; + +export type NumTodosCell_GetCountVariables = Exact<{ [key: string]: never; }>; + + +export type NumTodosCell_GetCount = { __typename?: 'Query', todosCount: number }; + +export type TodoListCell_GetTodosVariables = Exact<{ [key: string]: never; }>; + + +export type TodoListCell_GetTodos = { __typename?: 'Query', todos?: Array<{ __typename?: 'Todo', id: number, body: string, status: string } | null> | null }; + +export type TodoListCell_CheckTodoVariables = Exact<{ + id: Scalars['Int']; + status: Scalars['String']; +}>; + + +export type TodoListCell_CheckTodo = { __typename?: 'Mutation', updateTodoStatus?: { __typename: 'Todo', id: number, status: string } | null }; +" +`; diff --git a/packages/internal/dist/__tests__/__snapshots__/graphqlSchema.test.ts.snap b/packages/internal/dist/__tests__/__snapshots__/graphqlSchema.test.ts.snap new file mode 100644 index 000000000000..32dbd0c8536b --- /dev/null +++ b/packages/internal/dist/__tests__/__snapshots__/graphqlSchema.test.ts.snap @@ -0,0 +1,130 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`Generates GraphQL schema 1`] = ` +"directive @requireAuth(roles: [String]) on FIELD_DEFINITION + +directive @skipAuth on FIELD_DEFINITION + +scalar BigInt + +scalar Byte + +scalar Date + +scalar DateTime + +scalar JSON + +scalar JSONObject + +type Mutation { + createTodo(body: String!): Todo + renameTodo(body: String!, id: Int!): Todo + updateTodoStatus(id: Int!, status: String!): Todo +} + +"""About the Redwood queries.""" +type Query { + currentUser: JSON + + """Fetches the Redwood root schema.""" + redwood: Redwood + todos: [Todo] + todosCount: Int! +} + +""" +The RedwoodJS Root Schema + +Defines details about RedwoodJS such as the current user and version information. +""" +type Redwood { + """The current user.""" + currentUser: JSON + + """The version of Prisma.""" + prismaVersion: String + + """The version of Redwood.""" + version: String +} + +scalar Time + +type Todo { + body: String! + id: Int! + status: String! +}" +`; + +exports[`Includes live query directive if serverful and realtime 1`] = ` +"""" +Instruction for establishing a live connection that is updated once the underlying data changes. +""" +directive @live( + """Whether the query should be live or not.""" + if: Boolean = true + + """ + Propose a desired throttle interval ot the server in order to receive updates to at most once per "throttle" milliseconds. The server must not accept this value. + """ + throttle: Int +) on QUERY + +directive @requireAuth(roles: [String]) on FIELD_DEFINITION + +directive @skipAuth on FIELD_DEFINITION + +scalar BigInt + +scalar Byte + +scalar Date + +scalar DateTime + +scalar JSON + +scalar JSONObject + +type Mutation { + createTodo(body: String!): Todo + renameTodo(body: String!, id: Int!): Todo + updateTodoStatus(id: Int!, status: String!): Todo +} + +"""About the Redwood queries.""" +type Query { + currentUser: JSON + + """Fetches the Redwood root schema.""" + redwood: Redwood + todos: [Todo] + todosCount: Int! +} + +""" +The RedwoodJS Root Schema + +Defines details about RedwoodJS such as the current user and version information. +""" +type Redwood { + """The current user.""" + currentUser: JSON + + """The version of Prisma.""" + prismaVersion: String + + """The version of Redwood.""" + version: String +} + +scalar Time + +type Todo { + body: String! + id: Int! + status: String! +}" +`; diff --git a/packages/internal/dist/__tests__/__snapshots__/possibleTypes.test.ts.snap b/packages/internal/dist/__tests__/__snapshots__/possibleTypes.test.ts.snap new file mode 100644 index 000000000000..d4225af91356 --- /dev/null +++ b/packages/internal/dist/__tests__/__snapshots__/possibleTypes.test.ts.snap @@ -0,0 +1,17 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`Generate gql possible types web from the GraphQL Schema > when toml has graphql possible types turned om > when there are union types 1`] = ` +"export interface PossibleTypesResultData { + possibleTypes: { + [key: string]: string[] + } +} +const result: PossibleTypesResultData = { + possibleTypes: { + Groceries: ['Fruit', 'Vegetable'], + Grocery: ['Fruit', 'Vegetable'], + }, +} +export default result +" +`; diff --git a/packages/internal/dist/__tests__/__snapshots__/typeDefinitions.test.ts.snap b/packages/internal/dist/__tests__/__snapshots__/typeDefinitions.test.ts.snap new file mode 100644 index 000000000000..5e448ff75f3c --- /dev/null +++ b/packages/internal/dist/__tests__/__snapshots__/typeDefinitions.test.ts.snap @@ -0,0 +1,36 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`generates global page imports source maps 1`] = ` +{ + "file": "web-routesPages.d.ts", + "mappings": ";;;;;;;;;;;;AAAA;ACQA;ACRA;ACKA;ACLA;ACAA;ACAA;ACAA", + "names": [], + "sources": [ + "../../../web/src/pages/BarPage/BarPage.tsx", + "../../../web/src/pages/FatalErrorPage/FatalErrorPage.js", + "../../../web/src/pages/FooPage/FooPage.tsx", + "../../../web/src/pages/HomePage/HomePage.tsx", + "../../../web/src/pages/NotFoundPage/NotFoundPage.js", + "../../../web/src/pages/PrivatePage/PrivatePage.tsx", + "../../../web/src/pages/TypeScriptPage/TypeScriptPage.tsx", + "../../../web/src/pages/admin/EditUserPage/EditUserPage.jsx", + ], + "version": 3, +} +`; + +exports[`generates source maps for the router routes 1`] = ` +{ + "file": "web-routerRoutes.d.ts", + "mappings": ";;;;;;IAiBM;IACA;IACA;IAEE;IACA;IAGA;IAGA;IAGA", + "names": [], + "sources": [ + "../../../web/src/Routes.js", + ], + "version": 3, +} +`; + +exports[`mirror path for directory named modules 1`] = `".redwood/types/mirror/web/src/graphql"`; + +exports[`mirror path for directory named modules 2`] = `"../../packages/internal/index.d.ts"`; diff --git a/packages/internal/dist/__tests__/__snapshots__/validateSchemaForReservedNames.test.ts.snap b/packages/internal/dist/__tests__/__snapshots__/validateSchemaForReservedNames.test.ts.snap new file mode 100644 index 000000000000..5b84a5cbec47 --- /dev/null +++ b/packages/internal/dist/__tests__/__snapshots__/validateSchemaForReservedNames.test.ts.snap @@ -0,0 +1,19 @@ +// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html + +exports[`SDL with no reserved names used > SDL is invalid > because uses a reserved name as a type 1`] = ` +[TypeError: The type named 'Float' is a reserved GraphQL name. +Please rename it to something more specific, like: ApplicationFloat. +] +`; + +exports[`SDL with no reserved names used > because uses a reserved name as an input 1`] = ` +[TypeError: The input type named 'Float' is a reserved GraphQL name. +Please rename it to something more specific, like: ApplicationFloat. +] +`; + +exports[`SDL with no reserved names used > because uses a reserved name as an interface 1`] = ` +[TypeError: The interface named 'Float' is a reserved GraphQL name. +Please rename it to something more specific, like: ApplicationFloat. +] +`; diff --git a/packages/internal/dist/__tests__/fixtures/.redwood/schema.graphql b/packages/internal/dist/__tests__/fixtures/.redwood/schema.graphql new file mode 100644 index 000000000000..58b0ebd56fe0 --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/.redwood/schema.graphql @@ -0,0 +1,31 @@ +scalar BigInt + +scalar Date + +scalar DateTime + +scalar JSON + +scalar JSONObject + +type Mutation { + createTodo(body: String!): Todo +} + +type Query { + redwood: Redwood +} + +type Redwood { + currentUser: JSON + prismaVersion: String + version: String +} + +scalar Time + +type Todo { + body: String! + id: Int! + status: String! +} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/api/db/schema.prisma b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/api/db/schema.prisma new file mode 100644 index 000000000000..86078a61db0f --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/api/db/schema.prisma @@ -0,0 +1,21 @@ +datasource sqlite { + url = "file:./dev.sqlite" + provider = "sqlite" +} + +generator photonjs { + provider = "prisma-client-js" +} + +model Book { + id Int @id @default(autoincrement()) + title String @unique + Shelf Shelf? @relation(fields: [shelfId], references: [id]) + shelfId Int? +} + +model Shelf { + id Int @id @default(autoincrement()) + name String @unique + books Book[] +} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/redwood.toml b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/redwood.toml new file mode 100644 index 000000000000..f68d0d5de4db --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/redwood.toml @@ -0,0 +1,10 @@ +[web] + port = 8910 + apiProxyPath = "/api/functions" + +[api] + port = 8911 + [api.paths] + functions = './api/src/functions' + graphql = './api/src/graphql' + generated = './api/generated' diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/.redwood/schema.graphql b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/.redwood/schema.graphql new file mode 100644 index 000000000000..911f3095cc3c --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/.redwood/schema.graphql @@ -0,0 +1,21 @@ +scalar BigInt + +scalar Date + +scalar DateTime + +scalar JSON + +scalar JSONObject + +scalar Time + +type Query { + redwood: Redwood +} + +type Redwood { + currentUser: JSON + prismaVersion: String + version: String +} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/redwood.toml b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/redwood.toml new file mode 100644 index 000000000000..efd2d2d4d26e --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/redwood.toml @@ -0,0 +1,2 @@ +[web] + port = 8910 diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/.redwood/schema.graphql b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/.redwood/schema.graphql new file mode 100644 index 000000000000..2fb83f8e2c30 --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/.redwood/schema.graphql @@ -0,0 +1,25 @@ +scalar BigInt + +scalar Date + +scalar DateTime + +scalar JSON + +scalar JSONObject + +scalar Time + +type Mutation { + createTodo(body: String!): Todo +} + +type Query { + redwood: Redwood +} + +type Redwood { + currentUser: JSON + prismaVersion: String + version: String +} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/redwood.toml b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/redwood.toml new file mode 100644 index 000000000000..efd2d2d4d26e --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/redwood.toml @@ -0,0 +1,2 @@ +[web] + port = 8910 diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/.redwood/schema.graphql b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/.redwood/schema.graphql new file mode 100644 index 000000000000..0c301b6ddb26 --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/.redwood/schema.graphql @@ -0,0 +1,31 @@ +scalar BigInt + +scalar Date + +scalar DateTime + +scalar JSON + +scalar JSONObject + +scalar Time + +type Mutation { + createTodo(body: String!): Todo +} + +type Query { + redwood: Redwood +} + +type Redwood { + currentUser: JSON + prismaVersion: String + version: String +} + +type Todo { + id: String! + task: String! + # done: Boolean +} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/redwood.toml b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/redwood.toml new file mode 100644 index 000000000000..efd2d2d4d26e --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/redwood.toml @@ -0,0 +1,2 @@ +[web] + port = 8910 diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/api/db/schema.prisma b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/api/db/schema.prisma new file mode 100644 index 000000000000..86078a61db0f --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/api/db/schema.prisma @@ -0,0 +1,21 @@ +datasource sqlite { + url = "file:./dev.sqlite" + provider = "sqlite" +} + +generator photonjs { + provider = "prisma-client-js" +} + +model Book { + id Int @id @default(autoincrement()) + title String @unique + Shelf Shelf? @relation(fields: [shelfId], references: [id]) + shelfId Int? +} + +model Shelf { + id Int @id @default(autoincrement()) + name String @unique + books Book[] +} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/redwood.toml b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/redwood.toml new file mode 100644 index 000000000000..f68d0d5de4db --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/redwood.toml @@ -0,0 +1,10 @@ +[web] + port = 8910 + apiProxyPath = "/api/functions" + +[api] + port = 8911 + [api.paths] + functions = './api/src/functions' + graphql = './api/src/graphql' + generated = './api/generated' diff --git a/packages/internal/dist/__tests__/fixtures/nestedPages/redwood.toml b/packages/internal/dist/__tests__/fixtures/nestedPages/redwood.toml new file mode 100644 index 000000000000..2b820da9bd63 --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/nestedPages/redwood.toml @@ -0,0 +1,16 @@ +# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run `yarn rw dev`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "RedwoodJS.com" + port = 8910 + apiUrl = "/.netlify/functions" + includeEnvironmentVariables = [] # any ENV vars that should be available to the web side, see https://redwoodjs.com/docs/environment-variables#web +[api] + port = 8911 +[browser] + open = true diff --git a/packages/internal/dist/__tests__/fixtures/nestedPages/web/src/index.html b/packages/internal/dist/__tests__/fixtures/nestedPages/web/src/index.html new file mode 100644 index 000000000000..902339287ed9 --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/nestedPages/web/src/index.html @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + +
+ + <%= prerenderPlaceholder %> +
+ + + diff --git a/packages/internal/dist/__tests__/fixtures/redwood.empty.toml b/packages/internal/dist/__tests__/fixtures/redwood.empty.toml new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/packages/internal/dist/__tests__/fixtures/redwood.toml b/packages/internal/dist/__tests__/fixtures/redwood.toml new file mode 100644 index 000000000000..4d99ef23dee6 --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/redwood.toml @@ -0,0 +1,2 @@ +[web] + port = 8888 \ No newline at end of file diff --git a/packages/internal/dist/__tests__/fixtures/redwood.withEnv.toml b/packages/internal/dist/__tests__/fixtures/redwood.withEnv.toml new file mode 100644 index 000000000000..04c024ecf53c --- /dev/null +++ b/packages/internal/dist/__tests__/fixtures/redwood.withEnv.toml @@ -0,0 +1,9 @@ +[web] + title = "App running on ${APP_ENV}" + port = "${PORT:8910}" + apiUrl = "${API_URL:/.redwood/functions}" # you can customise graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [] # any ENV vars that should be available to the web side, see https://redwoodjs.com/docs/environment-variables#web +[api] + port = 8911 +[browser] + open = true diff --git a/packages/internal/dist/ast.d.ts b/packages/internal/dist/ast.d.ts new file mode 100644 index 000000000000..4e22ecebc793 --- /dev/null +++ b/packages/internal/dist/ast.d.ts @@ -0,0 +1,26 @@ +import { types } from '@babel/core'; +export declare const fileToAst: (filePath: string) => types.Node; +interface NamedExports { + name: string; + type: 're-export' | 'variable' | 'function' | 'class'; + location: { + line: number; + column: number; + }; +} +/** + * get all the named exports in a given piece of code. + */ +export declare const getNamedExports: (ast: types.Node) => NamedExports[]; +/** + * get all the gql queries from the supplied code + */ +export declare const getGqlQueries: (ast: types.Node) => string[]; +export declare const getCellGqlQuery: (ast: types.Node) => undefined; +export declare const hasDefaultExport: (ast: types.Node) => boolean; +export declare const getDefaultExportLocation: (ast: types.Node) => { + line: number; + column: number; +} | null; +export {}; +//# sourceMappingURL=ast.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/ast.d.ts.map b/packages/internal/dist/ast.d.ts.map new file mode 100644 index 000000000000..a5c51415205d --- /dev/null +++ b/packages/internal/dist/ast.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAUnC,eAAO,MAAM,SAAS,aAAc,MAAM,KAAG,KAAK,CAAC,IAyBlD,CAAA;AAED,UAAU,YAAY;IACpB,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,WAAW,GAAG,UAAU,GAAG,UAAU,GAAG,OAAO,CAAA;IACrD,QAAQ,EAAE;QACR,IAAI,EAAE,MAAM,CAAA;QACZ,MAAM,EAAE,MAAM,CAAA;KACf,CAAA;CACF;AACD;;GAEG;AACH,eAAO,MAAM,eAAe,QAAS,KAAK,CAAC,IAAI,KAAG,YAAY,EA4D7D,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,aAAa,QAAS,KAAK,CAAC,IAAI,aAY5C,CAAA;AAED,eAAO,MAAM,eAAe,QAAS,KAAK,CAAC,IAAI,cA4B9C,CAAA;AAED,eAAO,MAAM,gBAAgB,QAAS,KAAK,CAAC,IAAI,KAAG,OASlD,CAAA;AAED,eAAO,MAAM,wBAAwB,QAC9B,KAAK,CAAC,IAAI,KACd;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,IA0CrC,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/ast.js b/packages/internal/dist/ast.js new file mode 100644 index 000000000000..43d80c175c46 --- /dev/null +++ b/packages/internal/dist/ast.js @@ -0,0 +1,186 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.hasDefaultExport = exports.getNamedExports = exports.getGqlQueries = exports.getDefaultExportLocation = exports.getCellGqlQuery = exports.fileToAst = void 0; +require("core-js/modules/es.array.push.js"); +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/find")); +var _fs = _interopRequireDefault(require("fs")); +var _path = _interopRequireDefault(require("path")); +var _core = require("@babel/core"); +var _parser = require("@babel/parser"); +var _traverse = _interopRequireDefault(require("@babel/traverse")); +var _chalk = _interopRequireDefault(require("chalk")); +var _projectConfig = require("@redwoodjs/project-config"); +var _files = require("./files"); +const fileToAst = filePath => { + var _context; + const code = _fs.default.readFileSync(filePath, 'utf-8'); + + // use jsx plugin for web files, because in JS, the .jsx extension is not used + const isJsxFile = _path.default.extname(filePath).match(/[jt]sx$/) || (0, _files.isFileInsideFolder)(filePath, (0, _projectConfig.getPaths)().web.base); + const plugins = (0, _filter.default)(_context = ['typescript', 'nullishCoalescingOperator', 'objectRestSpread', isJsxFile && 'jsx']).call(_context, Boolean); + try { + return (0, _parser.parse)(code, { + sourceType: 'module', + plugins + }); + } catch (e) { + console.error(_chalk.default.red(`Error parsing: ${filePath}`)); + console.error(e); + throw new Error(e?.message); // we throw, so typescript doesn't complain about returning + } +}; +exports.fileToAst = fileToAst; +/** + * get all the named exports in a given piece of code. + */ +const getNamedExports = ast => { + const namedExports = []; + (0, _traverse.default)(ast, { + ExportNamedDeclaration(path) { + // Re-exports from other modules + // Eg: export { a, b } from './module' + const specifiers = path.node?.specifiers; + if (specifiers.length) { + for (const s of specifiers) { + const id = s.exported; + namedExports.push({ + name: id.name, + type: 're-export', + location: { + line: id.loc?.start.line ?? 1, + column: id.loc?.start.column ?? 0 + } + }); + } + return; + } + const declaration = path.node.declaration; + if (!declaration) { + return; + } + if (declaration.type === 'VariableDeclaration') { + const id = declaration.declarations[0].id; + namedExports.push({ + name: id.name, + type: 'variable', + location: { + line: id.loc?.start.line ?? 1, + column: id.loc?.start.column ?? 0 + } + }); + } else if (declaration.type === 'FunctionDeclaration') { + namedExports.push({ + name: declaration?.id?.name, + type: 'function', + location: { + line: declaration?.id?.loc?.start.line ?? 1, + column: declaration?.id?.loc?.start.column ?? 0 + } + }); + } else if (declaration.type === 'ClassDeclaration') { + namedExports.push({ + name: declaration?.id?.name, + type: 'class', + location: { + line: declaration?.id?.loc?.start.line ?? 1, + column: declaration?.id?.loc?.start.column ?? 0 + } + }); + } + } + }); + return namedExports; +}; + +/** + * get all the gql queries from the supplied code + */ +exports.getNamedExports = getNamedExports; +const getGqlQueries = ast => { + const gqlQueries = []; + (0, _traverse.default)(ast, { + TaggedTemplateExpression(path) { + const gqlTag = path.node.tag; + if (gqlTag.type === 'Identifier' && gqlTag.name === 'gql') { + gqlQueries.push(path.node.quasi.quasis[0].value.raw); + } + } + }); + return gqlQueries; +}; +exports.getGqlQueries = getGqlQueries; +const getCellGqlQuery = ast => { + let cellQuery = undefined; + (0, _traverse.default)(ast, { + ExportNamedDeclaration({ + node + }) { + if (node.exportKind === 'value' && _core.types.isVariableDeclaration(node.declaration)) { + var _context2; + const exportedQueryNode = (0, _find.default)(_context2 = node.declaration.declarations).call(_context2, d => { + return _core.types.isIdentifier(d.id) && d.id.name === 'QUERY' && _core.types.isTaggedTemplateExpression(d.init); + }); + if (exportedQueryNode) { + const templateExpression = exportedQueryNode.init; + cellQuery = templateExpression.quasi.quasis[0].value.raw; + } + } + return; + } + }); + return cellQuery; +}; +exports.getCellGqlQuery = getCellGqlQuery; +const hasDefaultExport = ast => { + let exported = false; + (0, _traverse.default)(ast, { + ExportDefaultDeclaration() { + exported = true; + return; + } + }); + return exported; +}; +exports.hasDefaultExport = hasDefaultExport; +const getDefaultExportLocation = ast => { + // Get the default export + let defaultExport; + (0, _traverse.default)(ast, { + ExportDefaultDeclaration(path) { + defaultExport = path.node; + } + }); + if (!defaultExport) { + return null; + } + + // Handle the case were we're exporting a variable declared elsewhere + // as we will want to find the location of that declaration instead + if (_core.types.isIdentifier(defaultExport.declaration) && _core.types.isFile(ast)) { + var _context3; + // Directly search the program body for the declaration of the identifier + // to avoid picking up other identifiers with the same name in the file + const exportedName = defaultExport.declaration.name; + const declaration = (0, _find.default)(_context3 = ast.program.body).call(_context3, node => { + var _context4; + return _core.types.isVariableDeclaration(node) && (0, _find.default)(_context4 = node.declarations).call(_context4, d => { + return _core.types.isVariableDeclarator(d) && _core.types.isIdentifier(d.id) && d.id.name === exportedName; + }); + }); + return { + line: declaration?.loc?.start.line ?? 1, + column: declaration?.loc?.start.column ?? 0 + }; + } + return { + line: defaultExport.loc?.start.line ?? 1, + column: defaultExport.loc?.start.column ?? 0 + }; +}; +exports.getDefaultExportLocation = getDefaultExportLocation; \ No newline at end of file diff --git a/packages/internal/dist/build/api.d.ts b/packages/internal/dist/build/api.d.ts new file mode 100644 index 000000000000..9db86cf79819 --- /dev/null +++ b/packages/internal/dist/build/api.d.ts @@ -0,0 +1,6 @@ +import type { BuildOptions } from 'esbuild'; +export declare const buildApi: () => Promise>; +export declare const rebuildApi: () => Promise>; +export declare const cleanApiBuild: () => Promise; +export declare const transpileApi: (files: string[]) => Promise>; +//# sourceMappingURL=api.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/build/api.d.ts.map b/packages/internal/dist/build/api.d.ts.map new file mode 100644 index 000000000000..0d3024d14fed --- /dev/null +++ b/packages/internal/dist/build/api.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/build/api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,YAAY,EAAe,MAAM,SAAS,CAAA;AAkBtE,eAAO,MAAM,QAAQ,4DAOpB,CAAA;AAED,eAAO,MAAM,UAAU,4DAQtB,CAAA;AAED,eAAO,MAAM,aAAa,qBAGzB,CAAA;AAiCD,eAAO,MAAM,YAAY,UAAiB,MAAM,EAAE,yDAEjD,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/build/api.js b/packages/internal/dist/build/api.js new file mode 100644 index 000000000000..2aed9d2e083a --- /dev/null +++ b/packages/internal/dist/build/api.js @@ -0,0 +1,82 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.transpileApi = exports.rebuildApi = exports.cleanApiBuild = exports.buildApi = void 0; +var _esbuild = require("esbuild"); +var _fsExtra = _interopRequireDefault(require("fs-extra")); +var _babelConfig = require("@redwoodjs/babel-config"); +var _projectConfig = require("@redwoodjs/project-config"); +var _files = require("../files"); +let BUILD_CTX = null; +const buildApi = async () => { + // Reset the build context for rebuilding + // No need to wait for promise to resolve + BUILD_CTX?.dispose(); + BUILD_CTX = null; + return transpileApi((0, _files.findApiFiles)()); +}; +exports.buildApi = buildApi; +const rebuildApi = async () => { + const apiFiles = (0, _files.findApiFiles)(); + if (!BUILD_CTX) { + BUILD_CTX = await (0, _esbuild.context)(getEsbuildOptions(apiFiles)); + } + return BUILD_CTX.rebuild(); +}; +exports.rebuildApi = rebuildApi; +const cleanApiBuild = async () => { + const rwjsPaths = (0, _projectConfig.getPaths)(); + return _fsExtra.default.remove(rwjsPaths.api.dist); +}; +exports.cleanApiBuild = cleanApiBuild; +const runRwBabelTransformsPlugin = { + name: 'rw-esbuild-babel-transform', + setup(build) { + const rwjsConfig = (0, _projectConfig.getConfig)(); + build.onLoad({ + filter: /\.(js|ts|tsx|jsx)$/ + }, async args => { + // @TODO Implement LRU cache? Unsure how much of a performance benefit its going to be + // Generate a CRC of file contents, then save it to LRU cache with a limit + // without LRU cache, the memory usage can become unbound + const transformedCode = await (0, _babelConfig.transformWithBabel)(args.path, (0, _babelConfig.getApiSideBabelPlugins)({ + openTelemetry: rwjsConfig.experimental.opentelemetry.enabled && rwjsConfig.experimental.opentelemetry.wrapApi, + projectIsEsm: (0, _projectConfig.projectSideIsEsm)('api') + })); + if (transformedCode?.code) { + return { + contents: transformedCode.code, + loader: 'js' + }; + } + throw new Error(`Could not transform file: ${args.path}`); + }); + } +}; +const transpileApi = async files => { + return (0, _esbuild.build)(getEsbuildOptions(files)); +}; +exports.transpileApi = transpileApi; +function getEsbuildOptions(files) { + const rwjsPaths = (0, _projectConfig.getPaths)(); + const format = (0, _projectConfig.projectSideIsEsm)('api') ? 'esm' : 'cjs'; + return { + absWorkingDir: rwjsPaths.api.base, + entryPoints: files, + platform: 'node', + target: 'node20', + format, + allowOverwrite: true, + bundle: false, + plugins: [runRwBabelTransformsPlugin], + outdir: rwjsPaths.api.dist, + // setting this to 'true' will generate an external sourcemap x.js.map + // AND set the sourceMappingURL comment + // (setting it to 'external' will ONLY generate the file, but won't add the comment) + sourcemap: true + }; +} \ No newline at end of file diff --git a/packages/internal/dist/cliLogger.d.ts b/packages/internal/dist/cliLogger.d.ts new file mode 100644 index 000000000000..10099b5eccae --- /dev/null +++ b/packages/internal/dist/cliLogger.d.ts @@ -0,0 +1,11 @@ +type CLog = (typeof console)['log']; +/** + * An alternative to createLogger which supports the same logging levels + * but allows for full ANSI when printing to the console. + */ +export declare const cliLogger: CLog & { + trace: CLog; + debug: CLog; +}; +export {}; +//# sourceMappingURL=cliLogger.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/cliLogger.d.ts.map b/packages/internal/dist/cliLogger.d.ts.map new file mode 100644 index 000000000000..3f31bd88c0a6 --- /dev/null +++ b/packages/internal/dist/cliLogger.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cliLogger.d.ts","sourceRoot":"","sources":["../src/cliLogger.ts"],"names":[],"mappings":"AAIA,KAAK,IAAI,GAAG,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,CAAC,CAAA;AAEnC;;;GAGG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,GAAG;IAC7B,KAAK,EAAE,IAAI,CAAA;IACX,KAAK,EAAE,IAAI,CAAA;CAGZ,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/cliLogger.js b/packages/internal/dist/cliLogger.js new file mode 100644 index 000000000000..4e904834e85e --- /dev/null +++ b/packages/internal/dist/cliLogger.js @@ -0,0 +1,20 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.cliLogger = void 0; +var _logger = require("@redwoodjs/api/logger"); +// Can't use color in the createLogger logger - so use a simpler set of log fns +const logLevel = _logger.defaultLoggerOptions.level; +/** + * An alternative to createLogger which supports the same logging levels + * but allows for full ANSI when printing to the console. + */ +const cliLogger = function (...data) { + console.log(...data); +}; +exports.cliLogger = cliLogger; +cliLogger.trace = logLevel === 'trace' ? console.log : () => {}; +cliLogger.debug = logLevel === 'trace' || logLevel === 'debug' ? console.log : () => {}; \ No newline at end of file diff --git a/packages/internal/dist/dev.d.ts b/packages/internal/dist/dev.d.ts new file mode 100644 index 000000000000..3d421ce30ab7 --- /dev/null +++ b/packages/internal/dist/dev.d.ts @@ -0,0 +1,2 @@ +export declare const shutdownPort: (port: number, method?: "tcp" | "udp") => Promise; +//# sourceMappingURL=dev.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/dev.d.ts.map b/packages/internal/dist/dev.d.ts.map new file mode 100644 index 000000000000..edc2c122317e --- /dev/null +++ b/packages/internal/dist/dev.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../src/dev.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,YAAY,SAAU,MAAM,WAAU,KAAK,GAAG,KAAK,kBAE/D,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/dev.js b/packages/internal/dist/dev.js new file mode 100644 index 000000000000..4eae0425bc63 --- /dev/null +++ b/packages/internal/dist/dev.js @@ -0,0 +1,13 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.shutdownPort = void 0; +var _killPort = _interopRequireDefault(require("kill-port")); +const shutdownPort = (port, method = 'tcp') => { + return (0, _killPort.default)(port, method); +}; +exports.shutdownPort = shutdownPort; \ No newline at end of file diff --git a/packages/internal/dist/files.d.ts b/packages/internal/dist/files.d.ts new file mode 100644 index 000000000000..f73a2903b6aa --- /dev/null +++ b/packages/internal/dist/files.d.ts @@ -0,0 +1,51 @@ +export declare const findCells: (cwd?: string) => string[]; +export declare const findPages: (cwd?: string) => string[]; +/** + * This function finds all modules in the 'web' and 'api' directories excluding 'node_modules' and Cell files. + * Cell files are also directory named modules but they have their special type mirror file, so they are ignored. + * + * @param {string} cwd - The directory path to start searching from. By default, it is the base path of the project. + * @returns {Array} modules - An array of absolute paths for the found modules. + * + * @example + * // Assuming the base directory of your project is '/Users/user/myproject' + * findDirectoryNamedModules('/Users/user/myproject'); + * // This will return an array with the absolute paths of all matching files, e.g.: + * // ['/Users/user/myproject/web/src/components/Author/Author.tsx', '/Users/user/myproject/web/src/pages/AboutPage/AboutPage.tsx'] + */ +export declare const findDirectoryNamedModules: (cwd?: string) => string[]; +export declare const findGraphQLSchemas: (cwd?: string) => string[]; +export declare const findApiFiles: (cwd?: string) => string[]; +export declare const findWebFiles: (cwd?: string) => string[]; +export declare const findApiServerFunctions: (cwd?: string) => string[]; +export declare const findApiDistFunctions: (cwd?: string) => string[]; +export declare const findRouteHooksSrc: (cwd?: string) => string[]; +export declare const isCellFile: (p: string) => boolean; +export declare const findScripts: (cwd?: string) => string[]; +export declare const isPageFile: (p: string) => boolean; +/** + * This function checks if the given path belongs to a directory named module. + * A directory named module is where the filename (without extension) is the same as the directory it is in. + * + * @param {string} p - The absolute path of the file. + * @returns {boolean} - Returns true if the path belongs to a directory named module, false otherwise. + * + * @example + * isDirectoryNamedModuleFile('/Users/user/myproject/web/src/components/Author/Author.tsx'); + * // Returns: true + * + * isDirectoryNamedModuleFile('/Users/user/myproject/web/src/components/Author/AuthorInfo.tsx'); + * // Returns: false + */ +export declare const isDirectoryNamedModuleFile: (p: string) => boolean; +export declare const isGraphQLSchemaFile: (p: string) => boolean; +/** + * The following patterns are supported for api functions: + * + * 1. a module at the top level: `/graphql.js` + * 2. a module in a folder with a module of the same name: `/health/health.js` + * 3. a module in a folder named index: `/x/index.js` + */ +export declare const isApiFunction: (p: string, functionsPath: string) => boolean; +export declare const isFileInsideFolder: (filePath: string, folderPath: string) => boolean; +//# sourceMappingURL=files.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/files.d.ts.map b/packages/internal/dist/files.d.ts.map new file mode 100644 index 000000000000..821f958a15b4 --- /dev/null +++ b/packages/internal/dist/files.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../src/files.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,SAAS,SAAS,MAAM,aAOpC,CAAA;AAED,eAAO,MAAM,SAAS,SAAS,MAAM,aAQpC,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,yBAAyB,SAAS,MAAM,aAUpD,CAAA;AAED,eAAO,MAAM,kBAAkB,SAAS,MAAM,aAI7C,CAAA;AASD,eAAO,MAAM,YAAY,SAAS,MAAM,aAOvC,CAAA;AAED,eAAO,MAAM,YAAY,SAAS,MAAM,aAYvC,CAAA;AAED,eAAO,MAAM,sBAAsB,SAC5B,MAAM,aAUZ,CAAA;AAED,eAAO,MAAM,oBAAoB,SAAS,MAAM,aAM/C,CAAA;AAED,eAAO,MAAM,iBAAiB,SAAS,MAAM,aAK5C,CAAA;AAED,eAAO,MAAM,UAAU,MAAO,MAAM,YA6BnC,CAAA;AAED,eAAO,MAAM,WAAW,SAAS,MAAM,aAMtC,CAAA;AAED,eAAO,MAAM,UAAU,MAAO,MAAM,YAoBnC,CAAA;AACD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,0BAA0B,MAAO,MAAM,YAGnD,CAAA;AAED,eAAO,MAAM,mBAAmB,MAAO,MAAM,YAQ5C,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,MAAO,MAAM,iBAAiB,MAAM,YAc7D,CAAA;AAED,eAAO,MAAM,kBAAkB,aAAc,MAAM,cAAc,MAAM,YAYtE,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/files.js b/packages/internal/dist/files.js new file mode 100644 index 000000000000..9530b867510e --- /dev/null +++ b/packages/internal/dist/files.js @@ -0,0 +1,245 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.isPageFile = exports.isGraphQLSchemaFile = exports.isFileInsideFolder = exports.isDirectoryNamedModuleFile = exports.isCellFile = exports.isApiFunction = exports.findWebFiles = exports.findScripts = exports.findRouteHooksSrc = exports.findPages = exports.findGraphQLSchemas = exports.findDirectoryNamedModules = exports.findCells = exports.findApiServerFunctions = exports.findApiFiles = exports.findApiDistFunctions = void 0; +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +var _endsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/ends-with")); +var _findIndex = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/find-index")); +var _startsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/starts-with")); +var _path = _interopRequireDefault(require("path")); +var _fastGlob = _interopRequireDefault(require("fast-glob")); +var _projectConfig = require("@redwoodjs/project-config"); +var _ast = require("./ast"); +const findCells = (cwd = (0, _projectConfig.getPaths)().web.src) => { + const modules = _fastGlob.default.sync('**/*Cell.{js,jsx,ts,tsx}', { + cwd, + absolute: true, + ignore: ['node_modules'] + }); + return (0, _filter.default)(modules).call(modules, isCellFile); +}; +exports.findCells = findCells; +const findPages = (cwd = (0, _projectConfig.getPaths)().web.pages) => { + const modules = _fastGlob.default.sync('**/*Page.{tsx,js,jsx}', { + cwd, + absolute: true, + ignore: ['node_modules'] + }); + return (0, _filter.default)(modules).call(modules, isPageFile); +}; + +/** + * This function finds all modules in the 'web' and 'api' directories excluding 'node_modules' and Cell files. + * Cell files are also directory named modules but they have their special type mirror file, so they are ignored. + * + * @param {string} cwd - The directory path to start searching from. By default, it is the base path of the project. + * @returns {Array} modules - An array of absolute paths for the found modules. + * + * @example + * // Assuming the base directory of your project is '/Users/user/myproject' + * findDirectoryNamedModules('/Users/user/myproject'); + * // This will return an array with the absolute paths of all matching files, e.g.: + * // ['/Users/user/myproject/web/src/components/Author/Author.tsx', '/Users/user/myproject/web/src/pages/AboutPage/AboutPage.tsx'] + */ +exports.findPages = findPages; +const findDirectoryNamedModules = (cwd = (0, _projectConfig.getPaths)().base) => { + var _context; + const modules = _fastGlob.default.sync('(api|web)/src/**/*.{ts,js,jsx,tsx}', { + cwd, + absolute: true, + ignore: ['node_modules'] + }); + return (0, _filter.default)(_context = (0, _filter.default)(modules).call(modules, isDirectoryNamedModuleFile)).call(_context, p => !isCellFile(p)); +}; +exports.findDirectoryNamedModules = findDirectoryNamedModules; +const findGraphQLSchemas = (cwd = (0, _projectConfig.getPaths)().api.graphql) => { + var _context2; + return (0, _filter.default)(_context2 = _fastGlob.default.sync('**/*.sdl.{ts,js}', { + cwd, + absolute: true + })).call(_context2, isGraphQLSchemaFile); +}; +exports.findGraphQLSchemas = findGraphQLSchemas; +const ignoreApiFiles = ['**/*.test.{js,ts}', '**/*.scenarios.{js,ts}', '**/*.fixtures.{js,ts}', '**/*.d.ts']; +const findApiFiles = (cwd = (0, _projectConfig.getPaths)().api.src) => { + const files = _fastGlob.default.sync('**/*.{js,ts,jsx,tsx}', { + cwd, + absolute: true, + ignore: ignoreApiFiles + }); + return files; +}; +exports.findApiFiles = findApiFiles; +const findWebFiles = (cwd = (0, _projectConfig.getPaths)().web.src) => { + const files = _fastGlob.default.sync('**/*.{js,ts,jsx,tsx}', { + cwd, + absolute: true, + ignore: ['**/*.test.{js,ts,tsx,jsx}', '**/*.fixtures.{js,ts,tsx,jsx}', '**/*.mock.{js,ts,tsx,jsx}', '**/*.d.ts'] + }); + return files; +}; +exports.findWebFiles = findWebFiles; +const findApiServerFunctions = (cwd = (0, _projectConfig.getPaths)().api.functions) => { + const files = _fastGlob.default.sync('**/*.{js,ts}', { + cwd, + absolute: true, + deep: 2, + // We don't support deeply nested api functions. + ignore: ignoreApiFiles + }); + return (0, _filter.default)(files).call(files, f => isApiFunction(f, cwd)); +}; +exports.findApiServerFunctions = findApiServerFunctions; +const findApiDistFunctions = (cwd = (0, _projectConfig.getPaths)().api.base) => { + return _fastGlob.default.sync('dist/functions/**/*.{ts,js}', { + cwd, + deep: 2, + // We don't support deeply nested api functions, to maximise compatibility with deployment providers + absolute: true + }); +}; +exports.findApiDistFunctions = findApiDistFunctions; +const findRouteHooksSrc = (cwd = (0, _projectConfig.getPaths)().web.src) => { + return _fastGlob.default.sync('**/*.routeHooks.{js,ts,tsx,jsx}', { + absolute: true, + cwd + }); +}; +exports.findRouteHooksSrc = findRouteHooksSrc; +const isCellFile = p => { + const { + dir, + name + } = _path.default.parse(p); + + // If the path isn't on the web side it cannot be a cell + if (!isFileInsideFolder(p, (0, _projectConfig.getPaths)().web.src)) { + return false; + } + + // A Cell must be a directory named module. + if (!(0, _endsWith.default)(dir).call(dir, name)) { + return false; + } + const ast = (0, _ast.fileToAst)(p); + + // A Cell should not have a default export. + if ((0, _ast.hasDefaultExport)(ast)) { + return false; + } + + // A Cell must export QUERY and Success. + const exports = (0, _ast.getNamedExports)(ast); + const exportedQUERY = (0, _findIndex.default)(exports).call(exports, v => v.name === 'QUERY') !== -1; + const exportedSuccess = (0, _findIndex.default)(exports).call(exports, v => v.name === 'Success') !== -1; + if (!exportedQUERY && !exportedSuccess) { + return false; + } + return true; +}; +exports.isCellFile = isCellFile; +const findScripts = (cwd = (0, _projectConfig.getPaths)().scripts) => { + return _fastGlob.default.sync('./**/*.{js,jsx,ts,tsx}', { + cwd, + absolute: true, + ignore: ['node_modules'] + }); +}; +exports.findScripts = findScripts; +const isPageFile = p => { + const { + name + } = _path.default.parse(p); + + // A page must end with "Page.{jsx,js,tsx}". + if (!(0, _endsWith.default)(name).call(name, 'Page')) { + return false; + } + + // A page should be in the `web/src/pages` directory. + if (!isFileInsideFolder(p, (0, _projectConfig.getPaths)().web.pages)) { + return false; + } + + // A Page should have a default export. + const ast = (0, _ast.fileToAst)(p); + if (!(0, _ast.hasDefaultExport)(ast)) { + return false; + } + return true; +}; +/** + * This function checks if the given path belongs to a directory named module. + * A directory named module is where the filename (without extension) is the same as the directory it is in. + * + * @param {string} p - The absolute path of the file. + * @returns {boolean} - Returns true if the path belongs to a directory named module, false otherwise. + * + * @example + * isDirectoryNamedModuleFile('/Users/user/myproject/web/src/components/Author/Author.tsx'); + * // Returns: true + * + * isDirectoryNamedModuleFile('/Users/user/myproject/web/src/components/Author/AuthorInfo.tsx'); + * // Returns: false + */ +exports.isPageFile = isPageFile; +const isDirectoryNamedModuleFile = p => { + const { + dir, + name + } = _path.default.parse(p); + return (0, _endsWith.default)(dir).call(dir, name); +}; +exports.isDirectoryNamedModuleFile = isDirectoryNamedModuleFile; +const isGraphQLSchemaFile = p => { + if (!p.match(/\.sdl\.(ts|js)$/)?.[0]) { + return false; + } + const ast = (0, _ast.fileToAst)(p); + const exports = (0, _ast.getNamedExports)(ast); + return (0, _findIndex.default)(exports).call(exports, v => v.name === 'schema') !== -1; +}; + +/** + * The following patterns are supported for api functions: + * + * 1. a module at the top level: `/graphql.js` + * 2. a module in a folder with a module of the same name: `/health/health.js` + * 3. a module in a folder named index: `/x/index.js` + */ +exports.isGraphQLSchemaFile = isGraphQLSchemaFile; +const isApiFunction = (p, functionsPath) => { + p = _path.default.relative(functionsPath, p); + const { + dir, + name + } = _path.default.parse(p); + if (dir === name) { + // Directory named module + return true; + } else if (dir === '') { + // Module in the functions root + return true; + } else if (dir.length && name === 'index') { + // Directory with an `index.js` file + return true; + } + return false; +}; +exports.isApiFunction = isApiFunction; +const isFileInsideFolder = (filePath, folderPath) => { + const { + dir + } = _path.default.parse(filePath); + const relativePathFromFolder = _path.default.relative(folderPath, dir); + if (!relativePathFromFolder || (0, _startsWith.default)(relativePathFromFolder).call(relativePathFromFolder, '..') || _path.default.isAbsolute(relativePathFromFolder)) { + return false; + } else { + return true; + } +}; +exports.isFileInsideFolder = isFileInsideFolder; \ No newline at end of file diff --git a/packages/internal/dist/generate/clientPreset.d.ts b/packages/internal/dist/generate/clientPreset.d.ts new file mode 100644 index 000000000000..99f808bc32ed --- /dev/null +++ b/packages/internal/dist/generate/clientPreset.d.ts @@ -0,0 +1,17 @@ +export declare const shouldGenerateTrustedDocuments: () => boolean; +export declare const generateClientPreset: () => Promise<{ + clientPresetFiles: string[]; + trustedDocumentsStoreFile: never[]; + errors: { + message: string; + error: unknown; + }[]; +} | { + clientPresetFiles: string[]; + trustedDocumentsStoreFile: string; + errors: { + message: string; + error: unknown; + }[]; +}>; +//# sourceMappingURL=clientPreset.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/clientPreset.d.ts.map b/packages/internal/dist/generate/clientPreset.d.ts.map new file mode 100644 index 000000000000..37a9ef416c4a --- /dev/null +++ b/packages/internal/dist/generate/clientPreset.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clientPreset.d.ts","sourceRoot":"","sources":["../../src/generate/clientPreset.ts"],"names":[],"mappings":"AAYA,eAAO,MAAM,8BAA8B,QAAO,OAIjD,CAAA;AAED,eAAO,MAAM,oBAAoB;;;;iBAIN,MAAM;eAAS,OAAO;;;;;;iBAAtB,MAAM;eAAS,OAAO;;EAoDhD,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/clientPreset.js b/packages/internal/dist/generate/clientPreset.js new file mode 100644 index 000000000000..4dc1aa061654 --- /dev/null +++ b/packages/internal/dist/generate/clientPreset.js @@ -0,0 +1,72 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.shouldGenerateTrustedDocuments = exports.generateClientPreset = void 0; +require("core-js/modules/es.array.push.js"); +var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); +var _cli = require("@graphql-codegen/cli"); +var _clientPreset = require("@graphql-codegen/client-preset"); +var _projectConfig = require("@redwoodjs/project-config"); +var _trustedDocuments = require("./trustedDocuments"); +const shouldGenerateTrustedDocuments = () => { + const config = (0, _projectConfig.getConfig)(); + return config.graphql.trustedDocuments; +}; +exports.shouldGenerateTrustedDocuments = shouldGenerateTrustedDocuments; +const generateClientPreset = async () => { + let generatedFiles = []; + let clientPresetFiles = []; + const errors = []; + if (!shouldGenerateTrustedDocuments()) { + return { + clientPresetFiles, + trustedDocumentsStoreFile: [], + errors + }; + } + const documentsGlob = `${(0, _projectConfig.getPaths)().web.src}/**/!(*.d).{ts,tsx,js,jsx}`; + const config = { + schema: (0, _projectConfig.getPaths)().generated.schema, + documents: documentsGlob, + silent: true, + // Plays nicely with cli task output + generates: { + [`${(0, _projectConfig.getPaths)().web.src}/graphql/`]: { + preset: 'client', + presetConfig: { + persistedDocuments: true + }, + documentTransforms: [_clientPreset.addTypenameSelectionDocumentTransform], + config: { + // DO NOT USE documentMode: 'string', + } + } + } + }; + try { + generatedFiles = await (0, _cli.generate)(config, true); + clientPresetFiles = (0, _map.default)(generatedFiles).call(generatedFiles, f => f.filename); + const trustedDocumentsStoreFile = await (0, _trustedDocuments.trustedDocumentsStore)(generatedFiles); + (0, _trustedDocuments.replaceGqlTagWithTrustedDocumentGraphql)(generatedFiles); + return { + clientPresetFiles, + trustedDocumentsStoreFile, + errors + }; + } catch (e) { + errors.push({ + message: 'Error: Could not generate GraphQL client preset', + error: e + }); + return { + clientPresetFiles, + trustedDocumentsStoreFile: [], + errors + }; + } +}; +exports.generateClientPreset = generateClientPreset; \ No newline at end of file diff --git a/packages/internal/dist/generate/generate.d.ts b/packages/internal/dist/generate/generate.d.ts new file mode 100644 index 000000000000..365271fa7684 --- /dev/null +++ b/packages/internal/dist/generate/generate.d.ts @@ -0,0 +1,10 @@ +#!/usr/bin/env node +export declare const generate: () => Promise<{ + files: string[]; + errors: { + message: string; + error: unknown; + }[]; +}>; +export declare const run: () => Promise; +//# sourceMappingURL=generate.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/generate.d.ts.map b/packages/internal/dist/generate/generate.d.ts.map new file mode 100644 index 000000000000..5a885232157f --- /dev/null +++ b/packages/internal/dist/generate/generate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../src/generate/generate.ts"],"names":[],"mappings":";AASA,eAAO,MAAM,QAAQ;;;;;;EAsCpB,CAAA;AAED,eAAO,MAAM,GAAG,qBA4Bf,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/generate.js b/packages/internal/dist/generate/generate.js new file mode 100755 index 000000000000..ad7ce76f710b --- /dev/null +++ b/packages/internal/dist/generate/generate.js @@ -0,0 +1,81 @@ +#!/usr/bin/env node +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.run = exports.generate = void 0; +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +require("core-js/modules/es.array.push.js"); +var _projectConfig = require("@redwoodjs/project-config"); +var _clientPreset = require("./clientPreset"); +var _graphqlSchema = require("./graphqlSchema"); +var _possibleTypes = require("./possibleTypes"); +var _typeDefinitions = require("./typeDefinitions"); +const generate = async () => { + var _context; + const config = (0, _projectConfig.getConfig)(); + const { + schemaPath, + errors: generateGraphQLSchemaErrors + } = await (0, _graphqlSchema.generateGraphQLSchema)(); + const { + typeDefFiles, + errors: generateTypeDefsErrors + } = await (0, _typeDefinitions.generateTypeDefs)(); + const clientPresetFiles = []; + const { + possibleTypesFiles, + errors: generatePossibleTypesErrors + } = await (0, _possibleTypes.generatePossibleTypes)(); + if (config.graphql.trustedDocuments) { + const preset = await (0, _clientPreset.generateClientPreset)(); + clientPresetFiles.push(...preset.clientPresetFiles); + } + let files = []; + if (schemaPath !== '') { + files.push(schemaPath); + } + files = (0, _filter.default)(_context = [...files, ...typeDefFiles, ...clientPresetFiles, ...possibleTypesFiles]).call(_context, x => typeof x === 'string'); + return { + files, + errors: [...generateGraphQLSchemaErrors, ...generateTypeDefsErrors, ...generatePossibleTypesErrors] + }; +}; +exports.generate = generate; +const run = async () => { + console.log('Generating...'); + console.log(); + const { + files, + errors + } = await generate(); + const rwjsPaths = (0, _projectConfig.getPaths)(); + for (const f of files) { + console.log('-', f.replace(rwjsPaths.base + '/', '')); + } + console.log(); + if (errors.length === 0) { + console.log('... done.'); + console.log(); + return; + } + process.exitCode ||= 1; + console.log('... done with errors.'); + console.log(); + for (const { + message, + error + } of errors) { + console.error(message); + console.log(); + console.error(error); + console.log(); + } +}; +exports.run = run; +if (require.main === module) { + run(); +} \ No newline at end of file diff --git a/packages/internal/dist/generate/graphqlCodeGen.d.ts b/packages/internal/dist/generate/graphqlCodeGen.d.ts new file mode 100644 index 000000000000..0d26cab92744 --- /dev/null +++ b/packages/internal/dist/generate/graphqlCodeGen.d.ts @@ -0,0 +1,16 @@ +import type { LoadTypedefsOptions } from '@graphql-tools/load'; +type TypeDefResult = { + typeDefFiles: string[]; + errors: { + message: string; + error: unknown; + }[]; +}; +export declare const generateTypeDefGraphQLApi: () => Promise; +export declare const generateTypeDefGraphQLWeb: () => Promise; +export declare function getLoadDocumentsOptions(filename: string): LoadTypedefsOptions<{ + cwd: string; +}>; +export declare const getResolverFnType: () => "(\n args: TArgs,\n obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo }\n ) => TResult | Promise" | "(\n args?: TArgs,\n obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo }\n ) => TResult | Promise"; +export {}; +//# sourceMappingURL=graphqlCodeGen.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/graphqlCodeGen.d.ts.map b/packages/internal/dist/generate/graphqlCodeGen.d.ts.map new file mode 100644 index 000000000000..ee814b8c51db --- /dev/null +++ b/packages/internal/dist/generate/graphqlCodeGen.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"graphqlCodeGen.d.ts","sourceRoot":"","sources":["../../src/generate/graphqlCodeGen.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAA;AAc9D,KAAK,aAAa,GAAG;IACnB,YAAY,EAAE,MAAM,EAAE,CAAA;IACtB,MAAM,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,EAAE,CAAA;CAC9C,CAAA;AAED,eAAO,MAAM,yBAAyB,QAAa,OAAO,CAAC,aAAa,CAgFvE,CAAA;AAED,eAAO,MAAM,yBAAyB,QAAa,OAAO,CAAC,aAAa,CAwDvE,CAAA;AAiCD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM;SACD,MAAM;GAQ5D;AA+FD,eAAO,MAAM,iBAAiB,4RAe7B,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/graphqlCodeGen.js b/packages/internal/dist/generate/graphqlCodeGen.js new file mode 100644 index 000000000000..788cfed5584b --- /dev/null +++ b/packages/internal/dist/generate/graphqlCodeGen.js @@ -0,0 +1,350 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard").default; +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.generateTypeDefGraphQLWeb = exports.generateTypeDefGraphQLApi = void 0; +exports.getLoadDocumentsOptions = getLoadDocumentsOptions; +exports.getResolverFnType = void 0; +require("core-js/modules/es.array.push.js"); +var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/concat")); +var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); +var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/keys")); +var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/for-each")); +var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +var _values = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/values")); +var _reduce = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/reduce")); +var _fs = _interopRequireDefault(require("fs")); +var _path = _interopRequireDefault(require("path")); +var addPlugin = _interopRequireWildcard(require("@graphql-codegen/add")); +var _cli = require("@graphql-codegen/cli"); +var _core = require("@graphql-codegen/core"); +var typescriptPlugin = _interopRequireWildcard(require("@graphql-codegen/typescript")); +var typescriptOperations = _interopRequireWildcard(require("@graphql-codegen/typescript-operations")); +var _codeFileLoader = require("@graphql-tools/code-file-loader"); +var _graphqlFileLoader = require("@graphql-tools/graphql-file-loader"); +var _load = require("@graphql-tools/load"); +var _execa = _interopRequireDefault(require("execa")); +var _graphql = require("graphql"); +var _projectConfig = require("@redwoodjs/project-config"); +var _project = require("../project"); +var rwTypescriptResolvers = _interopRequireWildcard(require("./plugins/rw-typescript-resolvers")); +var CodegenSide = /*#__PURE__*/function (CodegenSide) { + CodegenSide[CodegenSide["API"] = 0] = "API"; + CodegenSide[CodegenSide["WEB"] = 1] = "WEB"; + return CodegenSide; +}(CodegenSide || {}); +const generateTypeDefGraphQLApi = async () => { + var _context; + const config = (0, _projectConfig.getConfig)(); + const errors = []; + if (config.experimental.useSDLCodeGenForGraphQLTypes) { + const paths = (0, _projectConfig.getPaths)(); + const sdlCodegen = await import('@sdl-codegen/node'); + const dtsFiles = []; + try { + const output = sdlCodegen.runFullCodegen('redwood', { + paths + }); + (0, _concat.default)(dtsFiles).call(dtsFiles, output.paths); + } catch (e) { + if (e instanceof Error) { + errors.push({ + message: e.message, + error: e + }); + } + } + return { + typeDefFiles: dtsFiles, + errors + }; + } + const filename = _path.default.join((0, _projectConfig.getPaths)().api.types, 'graphql.d.ts'); + const prismaModels = await getPrismaModels(); + const prismaImports = (0, _map.default)(_context = (0, _keys.default)(prismaModels)).call(_context, key => { + return `${key} as Prisma${key}`; + }); + const extraPlugins = [{ + name: 'add', + options: { + content: ['import { Prisma } from "@prisma/client"', "import { MergePrismaWithSdlTypes, MakeRelationsOptional } from '@redwoodjs/api'", `import { ${prismaImports.join(', ')} } from '@prisma/client'`], + placement: 'prepend' + }, + codegenPlugin: addPlugin + }, { + name: 'print-mapped-models', + options: {}, + codegenPlugin: printMappedModelsPlugin + }, { + name: 'typescript-resolvers', + options: {}, + codegenPlugin: rwTypescriptResolvers + }]; + try { + return { + typeDefFiles: await runCodegenGraphQL([], extraPlugins, filename, CodegenSide.API), + errors + }; + } catch (e) { + errors.push({ + message: 'Error: Could not generate GraphQL type definitions (api)', + error: e + }); + return { + typeDefFiles: [], + errors + }; + } +}; +exports.generateTypeDefGraphQLApi = generateTypeDefGraphQLApi; +const generateTypeDefGraphQLWeb = async () => { + const filename = _path.default.join((0, _projectConfig.getPaths)().web.types, 'graphql.d.ts'); + const options = getLoadDocumentsOptions(filename); + const documentsGlob = './web/src/**/!(*.d).{ts,tsx,js,jsx}'; + let documents; + try { + documents = await (0, _load.loadDocuments)([documentsGlob], options); + } catch { + // No GraphQL documents present, no need to try to run codegen + return { + typeDefFiles: [], + errors: [] + }; + } + const extraPlugins = [{ + name: 'add', + options: { + content: 'import { Prisma } from "@prisma/client"', + placement: 'prepend' + }, + codegenPlugin: addPlugin + }, { + name: 'typescript-operations', + options: {}, + codegenPlugin: typescriptOperations + }]; + const errors = []; + try { + return { + typeDefFiles: await runCodegenGraphQL(documents, extraPlugins, filename, CodegenSide.WEB), + errors + }; + } catch (e) { + errors.push({ + message: 'Error: Could not generate GraphQL type definitions (web)', + error: e + }); + return { + typeDefFiles: [], + errors + }; + } +}; + +/** + * This is the function used internally by generateTypeDefGraphQLApi and generateTypeDefGraphQLWeb + * And contains the base configuration for generating gql types with codegen + * + * Named a little differently to make it easier to spot + */ +exports.generateTypeDefGraphQLWeb = generateTypeDefGraphQLWeb; +async function runCodegenGraphQL(documents, extraPlugins, filename, side) { + const userCodegenConfig = await (0, _cli.loadCodegenConfig)({ + configFilePath: (0, _projectConfig.getPaths)().base + }); + + // Merge in user codegen config with the rw built-in one + const mergedConfig = { + ...(await getPluginConfig(side)), + ...userCodegenConfig?.config?.config + }; + const options = getCodegenOptions(documents, mergedConfig, extraPlugins); + const output = await (0, _core.codegen)(options); + _fs.default.mkdirSync(_path.default.dirname(filename), { + recursive: true + }); + _fs.default.writeFileSync(filename, output); + return [filename]; +} +function getLoadDocumentsOptions(filename) { + const loadTypedefsConfig = { + cwd: (0, _projectConfig.getPaths)().base, + ignore: [_path.default.join(process.cwd(), filename)], + loaders: [new _codeFileLoader.CodeFileLoader()], + sort: true + }; + return loadTypedefsConfig; +} +async function getPrismaClient(hasGenerated = false) { + const { + default: localPrisma + } = await import('@prisma/client'); + + // @ts-expect-error I believe this type will only exist if the prisma client has been generated + if (!localPrisma.ModelName) { + if (hasGenerated) { + return { + ModelName: {} + }; + } else { + var _context2; + _execa.default.sync('yarn rw prisma generate', { + shell: true + }); + + // Purge Prisma Client from node's require cache, so that the newly + // generated client gets picked up by any script that uses it + (0, _forEach.default)(_context2 = (0, _keys.default)(require.cache)).call(_context2, key => { + if ((0, _includes.default)(key).call(key, '/node_modules/@prisma/client/') || (0, _includes.default)(key).call(key, '/node_modules/.prisma/client/')) { + delete require.cache[key]; + } + }); + return getPrismaClient(true); + } + } + + // @ts-expect-error See above, the generated client should contain a ModelName property that + // satisfies Record + return localPrisma; +} +async function getPrismaModels() { + // Extract the models from the prisma client and use those to + // set up internal redirects for the return values in resolvers. + const localPrisma = await getPrismaClient(); + const prismaModels = localPrisma.ModelName; + + // This isn't really something you'd put in the GraphQL API, so + // we can skip the model. + if (prismaModels.RW_DataMigration) { + delete prismaModels.RW_DataMigration; + } + return prismaModels; +} +async function getPluginConfig(side) { + var _context3; + const prismaModels = await getPrismaModels(); + (0, _forEach.default)(_context3 = (0, _keys.default)(prismaModels)).call(_context3, key => { + /** creates an object like this + * { + * Post: MergePrismaWithSdlTypes, AllMappedModels>> + * ... + * } + */ + prismaModels[key] = `MergePrismaWithSdlTypes, AllMappedModels>`; + }); + const pluginConfig = { + makeResolverTypeCallable: true, + namingConvention: 'keep', + // to allow camelCased query names + scalars: { + // We need these, otherwise these scalars are mapped to any + BigInt: 'number', + // @Note: DateTime fields can be valid Date-strings, or the Date object in the api side. They're always strings on the web side. + DateTime: side === CodegenSide.WEB ? 'string' : 'Date | string', + Date: side === CodegenSide.WEB ? 'string' : 'Date | string', + JSON: 'Prisma.JsonValue', + JSONObject: 'Prisma.JsonObject', + Time: side === CodegenSide.WEB ? 'string' : 'Date | string', + Byte: 'Buffer' + }, + // prevent type names being PetQueryQuery, RW generators already append + // Query/Mutation/etc + omitOperationSuffix: true, + showUnusedMappers: false, + customResolverFn: getResolverFnType(), + mappers: prismaModels, + avoidOptionals: { + // We do this, so that service tests can call resolvers without doing a null check + // see https://github.com/redwoodjs/redwood/pull/6222#issuecomment-1230156868 + // Look at type or source https://shrtm.nu/2BA0 for possible config, not well documented + resolvers: true + }, + contextType: `@redwoodjs/graphql-server/dist/types#RedwoodGraphQLContext` + }; + return pluginConfig; +} +const getResolverFnType = () => { + const tsConfig = (0, _project.getTsConfigs)(); + if (tsConfig.api?.compilerOptions?.strict) { + // In strict mode, bring a world of pain to the tests + return `( + args: TArgs, + obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } + ) => TResult | Promise`; + } else { + return `( + args?: TArgs, + obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } + ) => TResult | Promise`; + } +}; +exports.getResolverFnType = getResolverFnType; +/** + * Codgen plugin that just lists all the SDL models that are also mapped Prisma models + * We use a plugin, because its possible to have Prisma models that do not have an SDL model + * so we can't just list all the Prisma models, even if they're included in the mappers object. + * + * Example: + * type AllMappedModels = MaybeOrArrayOfMaybe + * + * Note that the types are SDL types, not Prisma types. + * We do not include SDL-only types in this list. + */ +const printMappedModelsPlugin = { + plugin: (schema, _documents, config) => { + var _context4, _context5, _context6; + // this way we can make sure relation types are not required + const sdlTypesWhichAreMapped = (0, _map.default)(_context4 = (0, _filter.default)(_context5 = (0, _filter.default)(_context6 = (0, _values.default)(schema.getTypeMap())).call(_context6, type => { + return type.astNode?.kind === _graphql.Kind.OBJECT_TYPE_DEFINITION; + })).call(_context5, objectDefType => { + const modelName = objectDefType.astNode?.name.value; + return modelName && modelName in config.mappers // Only keep the mapped Prisma models + ; + })).call(_context4, objectDefType => objectDefType.astNode?.name.value); + return `type MaybeOrArrayOfMaybe = T | Maybe | Maybe[];\ntype AllMappedModels = MaybeOrArrayOfMaybe<${sdlTypesWhichAreMapped.join(' | ')}>`; + } +}; +function getCodegenOptions(documents, config, extraPlugins) { + const plugins = [{ + typescript: { + enumsAsTypes: true + } + }, ...(0, _map.default)(extraPlugins).call(extraPlugins, plugin => ({ + [plugin.name]: plugin.options + }))]; + const pluginMap = { + typescript: typescriptPlugin, + ...(0, _reduce.default)(extraPlugins).call(extraPlugins, (acc, cur) => ({ + ...acc, + [cur.name]: cur.codegenPlugin + }), {}) + }; + const options = { + // The typescript plugin returns a string instead of writing to a file, so + // `filename` is not used + filename: '', + // `schemaAst` is used instead of `schema` if `schemaAst` is defined, and + // `schema` isn't. In the source for GenerateOptions they have this + // comment: + // Remove schemaAst and change schema to GraphQLSchema in the next major + // version + // When that happens we'll have have to remove our `schema` line, and + // rename `schemaAst` to `schema` + schema: undefined, + schemaAst: (0, _load.loadSchemaSync)((0, _projectConfig.getPaths)().generated.schema, { + loaders: [new _graphqlFileLoader.GraphQLFileLoader()], + sort: true + }), + documents, + config, + plugins, + pluginMap, + pluginContext: {} + }; + return options; +} \ No newline at end of file diff --git a/packages/internal/dist/generate/graphqlSchema.d.ts b/packages/internal/dist/generate/graphqlSchema.d.ts new file mode 100644 index 000000000000..837890635876 --- /dev/null +++ b/packages/internal/dist/generate/graphqlSchema.d.ts @@ -0,0 +1,8 @@ +export declare const generateGraphQLSchema: () => Promise<{ + schemaPath: string; + errors: { + message: string; + error: unknown; + }[]; +}>; +//# sourceMappingURL=graphqlSchema.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/graphqlSchema.d.ts.map b/packages/internal/dist/generate/graphqlSchema.d.ts.map new file mode 100644 index 000000000000..9187eff6ad01 --- /dev/null +++ b/packages/internal/dist/generate/graphqlSchema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"graphqlSchema.d.ts","sourceRoot":"","sources":["../../src/generate/graphqlSchema.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,qBAAqB;;;iBA4CP,MAAM;eAAS,OAAO;;EAyEhD,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/graphqlSchema.js b/packages/internal/dist/generate/graphqlSchema.js new file mode 100644 index 000000000000..172611dffd23 --- /dev/null +++ b/packages/internal/dist/generate/graphqlSchema.js @@ -0,0 +1,122 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard").default; +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.generateGraphQLSchema = void 0; +require("core-js/modules/es.array.push.js"); +var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/keys")); +var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); +var _fs = _interopRequireDefault(require("fs")); +var _core = require("@graphql-codegen/core"); +var schemaAstPlugin = _interopRequireWildcard(require("@graphql-codegen/schema-ast")); +var _codeFileLoader = require("@graphql-tools/code-file-loader"); +var _load = require("@graphql-tools/load"); +var _internals = require("@prisma/internals"); +var _chalk = _interopRequireDefault(require("chalk")); +var _graphql = require("graphql"); +var _terminalLink = _interopRequireDefault(require("terminal-link")); +var _graphqlServer = require("@redwoodjs/graphql-server"); +var _projectConfig = require("@redwoodjs/project-config"); +const generateGraphQLSchema = async () => { + const redwoodProjectPaths = (0, _projectConfig.getPaths)(); + const schemaPointerMap = { + [(0, _graphql.print)(_graphqlServer.rootSchema.schema)]: {}, + 'graphql/**/*.sdl.{js,ts}': {}, + 'directives/**/*.{js,ts}': {}, + 'subscriptions/**/*.{js,ts}': {} + }; + + // If we're serverful and the user is using realtime, we need to include the live directive for realtime support. + // Note the `ERR_ prefix in`ERR_MODULE_NOT_FOUND`. Since we're using `await import`, + // if the package (here, `@redwoodjs/realtime`) can't be found, it throws this error, with the prefix. + // Whereas `require('@redwoodjs/realtime')` would throw `MODULE_NOT_FOUND`. + if ((0, _projectConfig.resolveFile)(`${(0, _projectConfig.getPaths)().api.src}/server`)) { + try { + const { + liveDirectiveTypeDefs + } = await import('@redwoodjs/realtime'); + schemaPointerMap[liveDirectiveTypeDefs] = {}; + } catch (error) { + if (error.code !== 'ERR_MODULE_NOT_FOUND') { + throw error; + } + } + } + const loadSchemaConfig = { + assumeValidSDL: true, + sort: true, + convertExtensions: true, + includeSources: true, + cwd: redwoodProjectPaths.api.src, + schema: (0, _keys.default)(schemaPointerMap), + generates: { + [redwoodProjectPaths.generated.schema]: { + plugins: ['schema-ast'] + } + }, + silent: false, + errorsOnly: false, + pluginContext: {}, + loaders: [new _codeFileLoader.CodeFileLoader()] + }; + let loadedSchema; + const errors = []; + try { + loadedSchema = await (0, _load.loadSchema)(schemaPointerMap, loadSchemaConfig); + } catch (e) { + if (e instanceof Error) { + const match = e.message.match(/Unknown type: "(\w+)"/); + const name = match?.[1]; + const schemaPrisma = (await (0, _internals.getSchema)(redwoodProjectPaths.api.dbSchema)).toString(); + const errorObject = { + message: `Schema loading failed. ${e.message}`, + error: e + }; + errors.push(errorObject); + if (name && (0, _includes.default)(schemaPrisma).call(schemaPrisma, `model ${name}`)) { + // Not all SDLs need to be backed by a DB model, but if they are we can + // provide a more helpful error message + + errorObject.message = [errorObject.message, '', ` ${_chalk.default.bgYellow(` ${_chalk.default.black.bold('Heads up')} `)}`, '', _chalk.default.yellow(` It looks like you have a ${name} model in your Prisma schema.`), _chalk.default.yellow(` If it's part of a relation, you may have to generate SDL or scaffolding for ${name} too.`), _chalk.default.yellow(` So, if you haven't done that yet, ignore this error message and run the SDL or scaffold generator for ${name} now.`), '', _chalk.default.yellow(` See the ${(0, _terminalLink.default)('Troubleshooting Generators', 'https://redwoodjs.com/docs/schema-relations#troubleshooting-generators')} section in our docs for more help.`)].join('\n'); + } + } + } + const options = { + config: {}, + // no extra config needed for merged schema file generation + plugins: [{ + 'schema-ast': {} + }], + pluginMap: { + 'schema-ast': schemaAstPlugin + }, + schema: {}, + schemaAst: loadedSchema, + filename: redwoodProjectPaths.generated.schema, + documents: [] + }; + if (loadedSchema) { + try { + const schema = await (0, _core.codegen)(options); + _fs.default.writeFileSync(redwoodProjectPaths.generated.schema, schema); + return { + schemaPath: redwoodProjectPaths.generated.schema, + errors + }; + } catch (e) { + errors.push({ + message: `GraphQL Schema codegen failed`, + error: e + }); + } + } + return { + schemaPath: '', + errors + }; +}; +exports.generateGraphQLSchema = generateGraphQLSchema; \ No newline at end of file diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts new file mode 100644 index 000000000000..c307534e9ddc --- /dev/null +++ b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts @@ -0,0 +1,6 @@ +import type { Types, PluginFunction } from '@graphql-codegen/plugin-helpers'; +import { TypeScriptResolversPluginConfig } from '@graphql-codegen/typescript-resolvers'; +import { RwTypeScriptResolversVisitor } from './visitor'; +export declare const plugin: PluginFunction; +export { RwTypeScriptResolversVisitor, TypeScriptResolversPluginConfig }; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts.map b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts.map new file mode 100644 index 000000000000..574554a69213 --- /dev/null +++ b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/generate/plugins/rw-typescript-resolvers/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAA;AAK5E,OAAO,EACL,+BAA+B,EAEhC,MAAM,uCAAuC,CAAA;AAG9C,OAAO,EAAE,4BAA4B,EAAE,MAAM,WAAW,CAAA;AAExD,eAAO,MAAM,MAAM,EAAE,cAAc,CACjC,+BAA+B,EAC/B,KAAK,CAAC,mBAAmB,CAgF1B,CAAA;AAED,OAAO,EAAE,4BAA4B,EAAE,+BAA+B,EAAE,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js new file mode 100644 index 000000000000..2c69d137c8f9 --- /dev/null +++ b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js @@ -0,0 +1,92 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +_Object$defineProperty(exports, "RwTypeScriptResolversVisitor", { + enumerable: true, + get: function () { + return _visitor.RwTypeScriptResolversVisitor; + } +}); +_Object$defineProperty(exports, "TypeScriptResolversPluginConfig", { + enumerable: true, + get: function () { + return _typescriptResolvers.TypeScriptResolversPluginConfig; + } +}); +exports.plugin = void 0; +var _indexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/index-of")); +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +var _findIndex = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/find-index")); +var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/slice")); +require("core-js/modules/es.array.push.js"); +var _pluginHelpers = require("@graphql-codegen/plugin-helpers"); +var _typescriptResolvers = require("@graphql-codegen/typescript-resolvers"); +var _visitor = require("./visitor"); +const plugin = (schema, _documents, config) => { + var _context, _context2; + // This is the key change compared to the standard typescript-resolver + // plugin implementation - we use our own Visitor here. + const visitor = new _visitor.RwTypeScriptResolversVisitor(config, schema); + + // runs visitor + const visitorResult = (0, _pluginHelpers.oldVisit)((0, _pluginHelpers.getCachedDocumentNodeFromSchema)(schema), { + leave: visitor + }); + + // `content` here is the output of the original plugin, including the + // original visitor + const { + prepend, + content + } = (0, _typescriptResolvers.plugin)(schema, [], config); + + // A few types needed for our own RW-specific solution + prepend.push(`export type OptArgsResolverFn = ( + args?: TArgs, + obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } + ) => TResult | Promise + + export type RequiredResolverFn = ( + args: TArgs, + obj: { root: TParent; context: TContext; info: GraphQLResolveInfo } + ) => TResult | Promise`); + + // `content` is constructed like this: + // content: [ + // header, + // resolversTypeMapping, + // resolversParentTypeMapping, + // <--- `visitorResultStart` below + // ...visitorResult.definitions.filter( + // (d: unknown) => typeof d === 'string' + // ), + // <--- `visitorResultEnd` below + // getRootResolver(), + // getAllDirectiveResolvers(), + // ].join('\n'), + // We want to replace `visitorResult` with our own result. + // We assume that the original visitorResult begins with the same text as our + // `visitorResult`. We use this to find where we should start replacing content + // We then execute `getRootResolver()` to know what that looks like, and find + // the first line of that output. This is where we'll end our replacement. + // Then we just replace whatever is between those two things with our own + // result + + const splitContent = content.split('\n'); + const visitorResultStart = (0, _indexOf.default)(splitContent).call(splitContent, (0, _filter.default)(_context = visitorResult.definitions).call(_context, d => typeof d === 'string')[0].split('\n')[0]); + const splitRootResolver = visitor.getRootResolver().split('\n'); + const visitorResultEnd = (0, _findIndex.default)(splitContent).call(splitContent, (line, index) => line === splitRootResolver[0] && splitContent[index + 1] === splitRootResolver[1]); + + // Building up `content` with the original visitor content replaced by our + // visitor content + const newContent = [...(0, _slice.default)(splitContent).call(splitContent, 0, visitorResultStart), ...(0, _filter.default)(_context2 = visitorResult.definitions).call(_context2, d => typeof d === 'string'), ...(0, _slice.default)(splitContent).call(splitContent, visitorResultEnd)]; + return { + prepend, + content: newContent.join('\n') + }; +}; +exports.plugin = plugin; \ No newline at end of file diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts new file mode 100644 index 000000000000..6a730fdd98e9 --- /dev/null +++ b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts @@ -0,0 +1,9 @@ +import type { TypeScriptResolversPluginConfig } from '@graphql-codegen/typescript-resolvers'; +import { TypeScriptResolversVisitor } from '@graphql-codegen/typescript-resolvers'; +import type { FieldDefinitionNode, GraphQLSchema, ObjectTypeDefinitionNode } from 'graphql'; +export declare class RwTypeScriptResolversVisitor extends TypeScriptResolversVisitor { + constructor(pluginConfig: TypeScriptResolversPluginConfig, schema: GraphQLSchema); + FieldDefinition(node: FieldDefinitionNode, key: string | number, parent: any): (parentName: string) => string | null; + ObjectTypeDefinition(node: ObjectTypeDefinitionNode): string; +} +//# sourceMappingURL=visitor.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts.map b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts.map new file mode 100644 index 000000000000..7d95193d7cb0 --- /dev/null +++ b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"visitor.d.ts","sourceRoot":"","sources":["../../../../src/generate/plugins/rw-typescript-resolvers/visitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAA;AAC5F,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAA;AAKlF,OAAO,KAAK,EACV,mBAAmB,EACnB,aAAa,EACb,wBAAwB,EACzB,MAAM,SAAS,CAAA;AAEhB,qBAAa,4BAA6B,SAAQ,0BAA0B;gBAExE,YAAY,EAAE,+BAA+B,EAC7C,MAAM,EAAE,aAAa;IAKvB,eAAe,CACb,IAAI,EAAE,mBAAmB,EACzB,GAAG,EAAE,MAAM,GAAG,MAAM,EACpB,MAAM,EAAE,GAAG,GACV,CAAC,UAAU,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI;IAuBxC,oBAAoB,CAAC,IAAI,EAAE,wBAAwB,GAAG,MAAM;CAgG7D"} \ No newline at end of file diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js new file mode 100644 index 000000000000..7819d09af151 --- /dev/null +++ b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js @@ -0,0 +1,101 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.RwTypeScriptResolversVisitor = void 0; +require("core-js/modules/es.array.push.js"); +var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); +var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); +var _typescriptResolvers = require("@graphql-codegen/typescript-resolvers"); +var _visitorPluginCommon = require("@graphql-codegen/visitor-plugin-common"); +class RwTypeScriptResolversVisitor extends _typescriptResolvers.TypeScriptResolversVisitor { + constructor(pluginConfig, schema) { + super(pluginConfig, schema); + } + FieldDefinition(node, key, parent) { + const hasArguments = node.arguments && node.arguments.length > 0; + const superFieldDefinition = super.FieldDefinition(node, key, parent); + return parentName => { + // We're reusing pretty much all of the logic in the original plugin + // Visitor implementation by calling the `super` method here + const fieldDef = superFieldDefinition(parentName); + + // If this field doesn't take any arguments, and it is a resolver, then + // we switch to using the OptArgsResolver type instead, so that the user + // isn't forced to pass in arguments that aren't going to be used anyway + if (!hasArguments && fieldDef?.includes(': Resolver<')) { + return fieldDef.replace(': Resolver<', ': OptArgsResolverFn<'); + } + return fieldDef; + }; + } + + // Original implementation is here: + // https://github.com/dotansimha/graphql-code-generator/blob/c6c60a3078f3797af435c3852220d8898964031d/packages/plugins/other/visitor-plugin-common/src/base-resolvers-visitor.ts#L1091 + ObjectTypeDefinition(node) { + var _context, _context2; + // Call the original implementation to get a block of resolvers + const originalBlock = super.ObjectTypeDefinition(node); + + // The rest of this function is pretty much a copy/paste of the original + // function. We're duplicating every block to get RequiredResolver types + // for use with what we call "relation resolvers" (The stuff at the bottom + // of service files for models that have relations) + const name = this.convertName(node, { + suffix: this.config.resolverTypeSuffix + }); + const typeName = node.name; + const parentType = this.getParentTypeToUse(typeName); + const fieldsContent = (0, _map.default)(_context = node.fields || []).call(_context, f => f(node.name)); + const isRootType = (0, _includes.default)(_context2 = [this.schema.getQueryType()?.name, this.schema.getMutationType()?.name, this.schema.getSubscriptionType()?.name]).call(_context2, typeName); + if (!isRootType) { + fieldsContent.push((0, _visitorPluginCommon.indent)(`${this.config.internalResolversPrefix}isTypeOf?: IsTypeOfResolverFn${this.getPunctuation('type')}`)); + } + + // This is what's different compared to the implementation I copy/pasted + // We create a new block with a different type called + // "ModelRelationResolver" where "Model" is the name of a prisma model. + // We also replace all Resolver types with RequiredResolverFn types where + // all arguments are required + // + // 1. We start by creating a DeclarationBlock. So something on the form + // X = {} + // 2. Begin by defining X. It should be an exported type. + // 3. `name` is our resolvers, so like 'PostResolvers', 'RedwoodResolvers', + // 'QueryResolvers' etc. + // Replace 'Resolvers' with 'RelationResolvers' to construct our type name. + // Also set the generics for the type + // 4. Time to generate our Block, i.e. what goes inside {} in the X = {} that + // we started with. + // 5. `fieldsContent` is something like + // [ + // " contact: Resolver, ParentType, ContextType, RequireFields>;", + // " contacts: OptArgsResolverFn, ParentType, ContextType>;", + // " post: Resolver, ParentType, ContextType, RequireFields>;", + // " posts: OptArgsResolverFn, ParentType, ContextType>;", + // " redwood: OptArgsResolverFn, ParentType, ContextType>;", + // " user: Resolver, ParentType, ContextType, RequireFields>;" + // ] + // Here the type name needs to be replaced by 'RequiredResolverFn'. We + // do that by running a regex `replace()` on the string + // 6. Finally we join the array with '\n' and we'll have something that + // looks like the type below that we can return together whatever the + // original implementation of this function returned (this is a + // different example than the one above) + // export type PostRelationResolvers = { + // author?: RequiredResolverFn; + // authorId?: RequiredResolverFn; + // body?: RequiredResolverFn; + // createdAt?: RequiredResolverFn; + // id?: RequiredResolverFn; + // title?: RequiredResolverFn; + // __isTypeOf?: IsTypeOfResolverFn; + // }; + const blockRelationsResolver = new _visitorPluginCommon.DeclarationBlock(this._declarationBlockConfig).export().asKind('type').withName(name.replace('Resolvers', 'RelationResolvers'), ``).withBlock((0, _map.default)(fieldsContent).call(fieldsContent, content => content.replace(/: (?:OptArgs)?Resolver(?:Fn)?/, '?: RequiredResolverFn')).join('\n')); + return originalBlock + '\n' + blockRelationsResolver.string; + } +} +exports.RwTypeScriptResolversVisitor = RwTypeScriptResolversVisitor; \ No newline at end of file diff --git a/packages/internal/dist/generate/possibleTypes.d.ts b/packages/internal/dist/generate/possibleTypes.d.ts new file mode 100644 index 000000000000..346b4038efd5 --- /dev/null +++ b/packages/internal/dist/generate/possibleTypes.d.ts @@ -0,0 +1,36 @@ +type PossibleTypesResult = { + possibleTypesFiles: string[]; + errors: { + message: string; + error: unknown; + }[]; +}; +/** + * Generate possible types from fragments and union types + * + * In order to use fragments with unions and interfaces in Apollo Client, + * you need to tell the client how to discriminate between the different + * types that implement or belong to a supertype. + * + * You pass a possibleTypes option to the InMemoryCache constructor + * to specify these relationships in your schema. + * + * This object maps the name of an interface or union type (the supertype) + * to the types that implement or belong to it (the subtypes). + * + * For example: + * + * ```ts + * possibleTypes: { + * Character: ["Jedi", "Droid"], + * Test: ["PassingTest", "FailingTest", "SkippedTest"], + * Snake: ["Viper", "Python"], + * Groceries: ['Fruit', 'Vegetable'], + * }, + * ``` + * + * @see https://www.apollographql.com/docs/react/data/fragments/#using-fragments-with-unions-and-interfaces + **/ +export declare const generatePossibleTypes: () => Promise; +export {}; +//# sourceMappingURL=possibleTypes.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/possibleTypes.d.ts.map b/packages/internal/dist/generate/possibleTypes.d.ts.map new file mode 100644 index 000000000000..b08b915d8042 --- /dev/null +++ b/packages/internal/dist/generate/possibleTypes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"possibleTypes.d.ts","sourceRoot":"","sources":["../../src/generate/possibleTypes.ts"],"names":[],"mappings":"AAYA,KAAK,mBAAmB,GAAG;IACzB,kBAAkB,EAAE,MAAM,EAAE,CAAA;IAC5B,MAAM,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,EAAE,CAAA;CAC9C,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;IAyBI;AACJ,eAAO,MAAM,qBAAqB,QAAa,OAAO,CAAC,mBAAmB,CAyEzE,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/possibleTypes.js b/packages/internal/dist/generate/possibleTypes.js new file mode 100644 index 000000000000..49c4e3218392 --- /dev/null +++ b/packages/internal/dist/generate/possibleTypes.js @@ -0,0 +1,107 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard").default; +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.generatePossibleTypes = void 0; +require("core-js/modules/es.array.push.js"); +var _fs = _interopRequireDefault(require("fs")); +var _path = _interopRequireDefault(require("path")); +var fragmentMatcher = _interopRequireWildcard(require("@graphql-codegen/fragment-matcher")); +var _graphqlFileLoader = require("@graphql-tools/graphql-file-loader"); +var _load = require("@graphql-tools/load"); +var _prettier = require("prettier"); +var _projectConfig = require("@redwoodjs/project-config"); +var _graphqlCodeGen = require("./graphqlCodeGen"); +/** + * Generate possible types from fragments and union types + * + * In order to use fragments with unions and interfaces in Apollo Client, + * you need to tell the client how to discriminate between the different + * types that implement or belong to a supertype. + * + * You pass a possibleTypes option to the InMemoryCache constructor + * to specify these relationships in your schema. + * + * This object maps the name of an interface or union type (the supertype) + * to the types that implement or belong to it (the subtypes). + * + * For example: + * + * ```ts + * possibleTypes: { + * Character: ["Jedi", "Droid"], + * Test: ["PassingTest", "FailingTest", "SkippedTest"], + * Snake: ["Viper", "Python"], + * Groceries: ['Fruit', 'Vegetable'], + * }, + * ``` + * + * @see https://www.apollographql.com/docs/react/data/fragments/#using-fragments-with-unions-and-interfaces + **/ +const generatePossibleTypes = async () => { + const config = (0, _projectConfig.getConfig)(); + if (!config.graphql.fragments) { + return { + possibleTypesFiles: [], + errors: [] + }; + } + const filename = _path.default.join((0, _projectConfig.getPaths)().web.graphql, 'possibleTypes.ts'); + const options = (0, _graphqlCodeGen.getLoadDocumentsOptions)(filename); + const documentsGlob = './web/src/**/!(*.d).{ts,tsx,js,jsx}'; + let documents; + try { + documents = await (0, _load.loadDocuments)([documentsGlob], options); + } catch { + // No GraphQL documents present, no need to try to generate possibleTypes + return { + possibleTypesFiles: [], + errors: [] + }; + } + const errors = []; + try { + const files = []; + const pluginConfig = {}; + const info = { + outputFile: filename + }; + const schema = (0, _load.loadSchemaSync)((0, _projectConfig.getPaths)().generated.schema, { + loaders: [new _graphqlFileLoader.GraphQLFileLoader()], + sort: true + }); + const possibleTypes = await fragmentMatcher.plugin(schema, documents, pluginConfig, info); + files.push(filename); + const output = await (0, _prettier.format)(possibleTypes.toString(), { + trailingComma: 'es5', + bracketSpacing: true, + tabWidth: 2, + semi: false, + singleQuote: true, + arrowParens: 'always', + parser: 'typescript' + }); + _fs.default.mkdirSync(_path.default.dirname(filename), { + recursive: true + }); + _fs.default.writeFileSync(filename, output); + return { + possibleTypesFiles: [filename], + errors + }; + } catch (e) { + errors.push({ + message: 'Error: Could not generate GraphQL possible types (web)', + error: e + }); + return { + possibleTypesFiles: [], + errors + }; + } +}; +exports.generatePossibleTypes = generatePossibleTypes; \ No newline at end of file diff --git a/packages/internal/dist/generate/templates.d.ts b/packages/internal/dist/generate/templates.d.ts new file mode 100644 index 000000000000..b8c393d463ca --- /dev/null +++ b/packages/internal/dist/generate/templates.d.ts @@ -0,0 +1,6 @@ +/** + * Write the contents of the template to the destination and interpolate the variables. + * The template is a string that uses standard es6 template literals which allow embded expression. + */ +export declare const writeTemplate: (templatePath: string, destination: string, templateValues?: Record) => void; +//# sourceMappingURL=templates.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/templates.d.ts.map b/packages/internal/dist/generate/templates.d.ts.map new file mode 100644 index 000000000000..f320a52ae0c3 --- /dev/null +++ b/packages/internal/dist/generate/templates.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/generate/templates.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,eAAO,MAAM,aAAa,iBACV,MAAM,eACP,MAAM,mBACH,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,SAYxC,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/templates.js b/packages/internal/dist/generate/templates.js new file mode 100644 index 000000000000..f5a0b211c0ac --- /dev/null +++ b/packages/internal/dist/generate/templates.js @@ -0,0 +1,26 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.writeTemplate = void 0; +var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/keys")); +var _fs = _interopRequireDefault(require("fs")); +var _path = _interopRequireDefault(require("path")); +/** + * Write the contents of the template to the destination and interpolate the variables. + * The template is a string that uses standard es6 template literals which allow embded expression. + */ +const writeTemplate = (templatePath, destination, templateValues = {}) => { + const templateString = _fs.default.readFileSync(_path.default.join(__dirname, templatePath), 'utf-8'); + const template = templatized(templateString, templateValues); + _fs.default.writeFileSync(destination, '// This file was generated by RedwoodJS\n' + template); +}; +exports.writeTemplate = writeTemplate; +const templatized = (template, vars = {}) => { + // eslint-disable-next-line @typescript-eslint/no-implied-eval + const handler = new Function('vars', ['const tagged = ( ' + (0, _keys.default)(vars).join(', ') + ' ) =>', '`' + template + '`', 'return tagged(...Object.values(vars))'].join('\n')); + return handler(vars); +}; \ No newline at end of file diff --git a/packages/internal/dist/generate/templates/all-currentUser.d.ts.template b/packages/internal/dist/generate/templates/all-currentUser.d.ts.template new file mode 100644 index 000000000000..c9138e88b2a6 --- /dev/null +++ b/packages/internal/dist/generate/templates/all-currentUser.d.ts.template @@ -0,0 +1,28 @@ +import '@redwoodjs/api' +import '@redwoodjs/auth' + +import { getCurrentUser } from '../../../api/src/lib/auth' + +export type InferredCurrentUser = Awaited> + +type UndefinedRoles = { + /** + * ⚠️ Heads-Up: This is undefined unless roles key is returned from {@link getCurrentUser()} + * + * You may take a look at https://redwoodjs.com/docs/tutorial/chapter7/rbac for a tutorial on + * how to add fully-fledged RBAC (Role-based Access Control) to your database model. + */ + roles?: unknown | unknown[] +} + +type Overwrite = Omit & U + +declare module '@redwoodjs/context' { + interface GlobalContext { + currentUser?: Overwrite + } +} + +declare module '@redwoodjs/auth' { + interface CurrentUser extends InferredCurrentUser {} +} diff --git a/packages/internal/dist/generate/templates/api-globImports.d.ts.template b/packages/internal/dist/generate/templates/api-globImports.d.ts.template new file mode 100644 index 000000000000..ada756867205 --- /dev/null +++ b/packages/internal/dist/generate/templates/api-globImports.d.ts.template @@ -0,0 +1,9 @@ +declare module 'src/services/**/*.{js,ts}' +declare module 'src/directives/**/*.{js,ts}' +declare module 'src/graphql/**/*.sdl.{js,ts}' +declare module 'src/subscriptions/**/*.{js,ts}' + + +declare module 'api/src/services/**/*.{js,ts}' +declare module 'api/src/directives/**/*.{js,ts}' +declare module 'api/src/graphql/**/*.sdl.{js,ts}' diff --git a/packages/internal/dist/generate/templates/api-globalContext.d.ts.template b/packages/internal/dist/generate/templates/api-globalContext.d.ts.template new file mode 100644 index 000000000000..c13d883e4e16 --- /dev/null +++ b/packages/internal/dist/generate/templates/api-globalContext.d.ts.template @@ -0,0 +1,7 @@ +import type { GlobalContext } from "@redwoodjs/context" + +export {} + +declare global { + const context: GlobalContext +} diff --git a/packages/internal/dist/generate/templates/api-scenarios.d.ts.template b/packages/internal/dist/generate/templates/api-scenarios.d.ts.template new file mode 100644 index 000000000000..8be4f6182462 --- /dev/null +++ b/packages/internal/dist/generate/templates/api-scenarios.d.ts.template @@ -0,0 +1,10 @@ +import type { Scenario, DefineScenario, DescribeScenario } from '@redwoodjs/testing/api' + +declare global { + /** + * Note that the scenario name must match the exports in your {model}.scenarios.ts file + */ + const scenario: Scenario + const describeScenario: DescribeScenario + const defineScenario: DefineScenario +} diff --git a/packages/internal/dist/generate/templates/api-test-globals.d.ts.template b/packages/internal/dist/generate/templates/api-test-globals.d.ts.template new file mode 100644 index 000000000000..575e28d6c111 --- /dev/null +++ b/packages/internal/dist/generate/templates/api-test-globals.d.ts.template @@ -0,0 +1,5 @@ +import type { CurrentUser } from '@redwoodjs/auth' + +declare global { + const mockCurrentUser: (currentUser: CurrentUser) => void +} diff --git a/packages/internal/dist/generate/templates/mirror-cell.d.ts.template b/packages/internal/dist/generate/templates/mirror-cell.d.ts.template new file mode 100644 index 000000000000..fba45262cc26 --- /dev/null +++ b/packages/internal/dist/generate/templates/mirror-cell.d.ts.template @@ -0,0 +1,13 @@ +import * as Cell from './${name}' +import type { CellProps } from '@redwoodjs/web' +import type { ${queryResultType}, ${queryVariablesType} } from 'types/graphql' + +type SuccessType = typeof Cell.Success + +export * from './${name}' + +type CellInputs = CellProps + +export default function (props: CellInputs): ReturnType + +//# sourceMappingURL=index.d.ts.map diff --git a/packages/internal/dist/generate/templates/mirror-directoryNamedModule.d.ts.template b/packages/internal/dist/generate/templates/mirror-directoryNamedModule.d.ts.template new file mode 100644 index 000000000000..1fe40a46da59 --- /dev/null +++ b/packages/internal/dist/generate/templates/mirror-directoryNamedModule.d.ts.template @@ -0,0 +1,5 @@ +import { default as DEFAULT } from './${name}' +export default DEFAULT +export * from './${name}' + +//# sourceMappingURL=index.d.ts.map diff --git a/packages/internal/dist/generate/templates/web-routerRoutes.d.ts.template b/packages/internal/dist/generate/templates/web-routerRoutes.d.ts.template new file mode 100644 index 000000000000..2c6bca1f1548 --- /dev/null +++ b/packages/internal/dist/generate/templates/web-routerRoutes.d.ts.template @@ -0,0 +1,20 @@ +import { RouteParams, QueryParams } from '@redwoodjs/router' + +declare module '@redwoodjs/router' { + interface AvailableRoutes { + // Only "" components with a "name" and "path" prop will be populated here. +${routes.map( + ({ props: { name, path }}) => { + return ` ${name}: (params?: RouteParams<"${path}"> & QueryParams) => "${path}"` + } +).join('\n')} + } + + export function useRoutePaths(): Record + export function useRoutePath(routeName: keyof AvailableRoutes): string + + /** Gets the name of the current route (as defined in your Routes file) */ + export function useRouteName(): keyof AvailableRoutes | undefined +} + +//# sourceMappingURL=web-routerRoutes.d.ts.map diff --git a/packages/internal/dist/generate/templates/web-routesPages.d.ts.template b/packages/internal/dist/generate/templates/web-routesPages.d.ts.template new file mode 100644 index 000000000000..2b99077d7b16 --- /dev/null +++ b/packages/internal/dist/generate/templates/web-routesPages.d.ts.template @@ -0,0 +1,13 @@ +${pages + .map(({ importName, importPath }) => { + return `import ${importName}Type from '${importPath}'` + }) + .join('\n')} + +declare global { +${pages.map(({ importName }) => { + return ` const ${importName}: typeof ${importName}Type` +}).join('\n')} +} + +//# sourceMappingURL=web-routesPages.d.ts.map diff --git a/packages/internal/dist/generate/templates/web-test-globals.d.ts.template b/packages/internal/dist/generate/templates/web-test-globals.d.ts.template new file mode 100644 index 000000000000..74023a6f73a1 --- /dev/null +++ b/packages/internal/dist/generate/templates/web-test-globals.d.ts.template @@ -0,0 +1,7 @@ +// Import other mocking function globals +import '@redwoodjs/testing' +import { InferredCurrentUser } from './all-currentUser' + +declare global { + const mockCurrentUser: (currentUser: InferredCurrentUser) => void +} diff --git a/packages/internal/dist/generate/trustedDocuments.d.ts b/packages/internal/dist/generate/trustedDocuments.d.ts new file mode 100644 index 000000000000..7063723d63ea --- /dev/null +++ b/packages/internal/dist/generate/trustedDocuments.d.ts @@ -0,0 +1,3 @@ +export declare const trustedDocumentsStore: (generatedFiles: any) => Promise; +export declare const replaceGqlTagWithTrustedDocumentGraphql: (generatedFiles: any) => Promise; +//# sourceMappingURL=trustedDocuments.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/trustedDocuments.d.ts.map b/packages/internal/dist/generate/trustedDocuments.d.ts.map new file mode 100644 index 000000000000..44800ce29411 --- /dev/null +++ b/packages/internal/dist/generate/trustedDocuments.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"trustedDocuments.d.ts","sourceRoot":"","sources":["../../src/generate/trustedDocuments.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,qBAAqB,mBAA0B,GAAG,oBA8B9D,CAAA;AAID,eAAO,MAAM,uCAAuC,mBAClC,GAAG,kBA8BpB,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/trustedDocuments.js b/packages/internal/dist/generate/trustedDocuments.js new file mode 100644 index 000000000000..0865e2227637 --- /dev/null +++ b/packages/internal/dist/generate/trustedDocuments.js @@ -0,0 +1,72 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.trustedDocumentsStore = exports.replaceGqlTagWithTrustedDocumentGraphql = void 0; +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +var _endsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/ends-with")); +var _fs = _interopRequireDefault(require("fs")); +var _path = _interopRequireDefault(require("path")); +var _prettier = require("prettier"); +var _projectConfig = require("@redwoodjs/project-config"); +// Copy the persisted-documents.json to api side as a trustedDocumentsStore +const trustedDocumentsStore = async generatedFiles => { + let trustedDocumentsStoreFile = ''; + const output = (0, _filter.default)(generatedFiles).call(generatedFiles, f => { + var _context; + return (0, _endsWith.default)(_context = f.filename).call(_context, 'persisted-documents.json'); + }); + const storeFile = output[0]; + if (storeFile?.content) { + const content = await (0, _prettier.format)(`export const store = ${storeFile.content}`, { + trailingComma: 'es5', + bracketSpacing: true, + tabWidth: 2, + semi: false, + singleQuote: true, + arrowParens: 'always', + parser: 'typescript' + }); + trustedDocumentsStoreFile = _path.default.join((0, _projectConfig.getPaths)().api.lib, 'trustedDocumentsStore.ts'); + _fs.default.mkdirSync(_path.default.dirname(trustedDocumentsStoreFile), { + recursive: true + }); + _fs.default.writeFileSync(trustedDocumentsStoreFile, content); + } + return trustedDocumentsStoreFile; +}; + +// Add the gql function to the generated graphql.ts file +// that is used by trusted documents +exports.trustedDocumentsStore = trustedDocumentsStore; +const replaceGqlTagWithTrustedDocumentGraphql = async generatedFiles => { + const gqlFileOutput = (0, _filter.default)(generatedFiles).call(generatedFiles, f => { + var _context2; + return (0, _endsWith.default)(_context2 = f.filename).call(_context2, 'gql.ts'); + }); + const gqlFile = gqlFileOutput[0]; + if (gqlFile?.content) { + gqlFile.content += `\n + export function gql(source: string | TemplateStringsArray) { + if (typeof source === 'string') { + return graphql(source) + } + + return graphql(source.join('\\n')) + }`; + const content = await (0, _prettier.format)(gqlFile.content, { + trailingComma: 'es5', + bracketSpacing: true, + tabWidth: 2, + semi: true, + singleQuote: false, + arrowParens: 'always', + parser: 'typescript' + }); + _fs.default.writeFileSync(gqlFile.filename, content); + } +}; +exports.replaceGqlTagWithTrustedDocumentGraphql = replaceGqlTagWithTrustedDocumentGraphql; \ No newline at end of file diff --git a/packages/internal/dist/generate/typeDefinitions.d.ts b/packages/internal/dist/generate/typeDefinitions.d.ts new file mode 100644 index 000000000000..59ce425b20da --- /dev/null +++ b/packages/internal/dist/generate/typeDefinitions.d.ts @@ -0,0 +1,30 @@ +/** + * Generate all the types for a RedwoodJS project + * and return the generated path to files, so they're logged + */ +export declare const generateTypeDefs: () => Promise<{ + typeDefFiles: string[]; + errors: { + message: string; + error: unknown; + }[]; +}>; +export declare const generateMirrorDirectoryNamedModules: () => string[]; +export declare const mirrorPathForDirectoryNamedModules: (p: string, rwjsPaths?: import("@redwoodjs/project-config").Paths) => string[]; +export declare const generateMirrorDirectoryNamedModule: (p: string, rwjsPaths?: import("@redwoodjs/project-config").Paths) => string; +export declare const generateMirrorCells: () => string[]; +export declare const mirrorPathForCell: (p: string, rwjsPaths?: import("@redwoodjs/project-config").Paths) => string[]; +export declare const generateMirrorCell: (p: string, rwjsPaths?: import("@redwoodjs/project-config").Paths) => string; +export declare const generateTypeDefRouterRoutes: () => string[]; +export declare const generateTypeDefRouterPages: () => string[]; +export declare const generateTypeDefCurrentUser: () => string[]; +export declare const generateTypeDefScenarios: () => string[]; +export declare const generateTypeDefTestMocks: () => string[]; +export declare const generateTypeDefGlobImports: () => string[]; +export declare const generateTypeDefGlobalContext: () => string[]; +/** + * Typescript does not preserve triple slash directives when outputting js or d.ts files. + * This is a work around so that *.svg, *.png, etc. imports have types. + */ +export declare const generateViteClientTypesDirective: () => string[]; +//# sourceMappingURL=typeDefinitions.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/typeDefinitions.d.ts.map b/packages/internal/dist/generate/typeDefinitions.d.ts.map new file mode 100644 index 000000000000..38e05b5f67d0 --- /dev/null +++ b/packages/internal/dist/generate/typeDefinitions.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"typeDefinitions.d.ts","sourceRoot":"","sources":["../../src/generate/typeDefinitions.ts"],"names":[],"mappings":"AAyCA;;;GAGG;AACH,eAAO,MAAM,gBAAgB;;;;;;EAyB5B,CAAA;AAED,eAAO,MAAM,mCAAmC,gBAK/C,CAAA;AAED,eAAO,MAAM,kCAAkC,MAC1C,MAAM,oEAUV,CAAA;AAED,eAAO,MAAM,kCAAkC,MAC1C,MAAM,kEAqDV,CAAA;AAED,eAAO,MAAM,mBAAmB,gBAG/B,CAAA;AAED,eAAO,MAAM,iBAAiB,MAAO,MAAM,oEAQ1C,CAAA;AAED,eAAO,MAAM,kBAAkB,MAAO,MAAM,kEA8D3C,CAAA;AAiBD,eAAO,MAAM,2BAA2B,gBAmEvC,CAAA;AAED,eAAO,MAAM,0BAA0B,gBA8CtC,CAAA;AAED,eAAO,MAAM,0BAA0B,gBAEtC,CAAA;AAED,eAAO,MAAM,wBAAwB,gBAEpC,CAAA;AAED,eAAO,MAAM,wBAAwB,gBAKpC,CAAA;AAED,eAAO,MAAM,0BAA0B,gBAEtC,CAAA;AAED,eAAO,MAAM,4BAA4B,gBAExC,CAAA;AACD;;;GAGG;AACH,eAAO,MAAM,gCAAgC,gBAW5C,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/typeDefinitions.js b/packages/internal/dist/generate/typeDefinitions.js new file mode 100644 index 000000000000..9a524b29273b --- /dev/null +++ b/packages/internal/dist/generate/typeDefinitions.js @@ -0,0 +1,349 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.mirrorPathForDirectoryNamedModules = exports.mirrorPathForCell = exports.generateViteClientTypesDirective = exports.generateTypeDefs = exports.generateTypeDefTestMocks = exports.generateTypeDefScenarios = exports.generateTypeDefRouterRoutes = exports.generateTypeDefRouterPages = exports.generateTypeDefGlobalContext = exports.generateTypeDefGlobImports = exports.generateTypeDefCurrentUser = exports.generateMirrorDirectoryNamedModules = exports.generateMirrorDirectoryNamedModule = exports.generateMirrorCells = exports.generateMirrorCell = void 0; +require("core-js/modules/es.array.push.js"); +require("core-js/modules/esnext.json.parse.js"); +var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); +var _startsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/starts-with")); +var _stringify = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/json/stringify")); +var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/find")); +var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +var _flat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/flat")); +var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/keys")); +var _fs = _interopRequireDefault(require("fs")); +var _path = _interopRequireDefault(require("path")); +var _sourceMap = require("source-map"); +var _projectConfig = require("@redwoodjs/project-config"); +var _ast = require("../ast"); +var _files = require("../files"); +var _gql = require("../gql"); +var _jsx = require("../jsx"); +var _graphqlCodeGen = require("./graphqlCodeGen"); +var _templates = require("./templates"); +// TODO: +// Common return format for CLI output: +// ['type', 'relative path to base'] + +// Note for contributors: +// +// The functions in this file generate type definitions of which there are two types: +// +// 1. Mirror types: Create a virtual directory that allows us to type +// cells and directory named modules. +// 2. Types based on contents of other files +// +// When generating a new type definition that targets a particular side, +// you must prefix the generated filename +// with "web-" or "api-" to target inclusion for that side, +// or use "all-" for both. This is controlled by the user's "tsconfig.json" +// file. + +/** + * Generate all the types for a RedwoodJS project + * and return the generated path to files, so they're logged + */ +const generateTypeDefs = async () => { + // Return all the paths so they can be printed + const { + typeDefFiles: gqlApiTypeDefFiles, + errors: apiErrors + } = await (0, _graphqlCodeGen.generateTypeDefGraphQLApi)(); + const { + typeDefFiles: gqlWebTypeDefFiles, + errors: webErrors + } = await (0, _graphqlCodeGen.generateTypeDefGraphQLWeb)(); + return { + typeDefFiles: [...generateMirrorDirectoryNamedModules(), ...generateMirrorCells(), ...generateTypeDefRouterPages(), ...generateTypeDefCurrentUser(), ...generateTypeDefRouterRoutes(), ...generateTypeDefGlobImports(), ...generateTypeDefGlobalContext(), ...generateTypeDefScenarios(), ...generateTypeDefTestMocks(), ...generateStubStorybookTypes(), ...generateViteClientTypesDirective(), ...gqlApiTypeDefFiles, ...gqlWebTypeDefFiles], + errors: [...apiErrors, ...webErrors] + }; +}; +exports.generateTypeDefs = generateTypeDefs; +const generateMirrorDirectoryNamedModules = () => { + var _context; + const rwjsPaths = (0, _projectConfig.getPaths)(); + return (0, _map.default)(_context = (0, _files.findDirectoryNamedModules)()).call(_context, p => generateMirrorDirectoryNamedModule(p, rwjsPaths)); +}; +exports.generateMirrorDirectoryNamedModules = generateMirrorDirectoryNamedModules; +const mirrorPathForDirectoryNamedModules = (p, rwjsPaths = (0, _projectConfig.getPaths)()) => { + return [_path.default.join(rwjsPaths.generated.types.mirror, _path.default.relative(rwjsPaths.base, _path.default.dirname(p))), 'index.d.ts']; +}; +exports.mirrorPathForDirectoryNamedModules = mirrorPathForDirectoryNamedModules; +const generateMirrorDirectoryNamedModule = (p, rwjsPaths = (0, _projectConfig.getPaths)()) => { + const [mirrorDir, typeDef] = mirrorPathForDirectoryNamedModules(p, rwjsPaths); + _fs.default.mkdirSync(mirrorDir, { + recursive: true + }); + const typeDefPath = _path.default.join(mirrorDir, typeDef); + const { + name + } = _path.default.parse(p); + (0, _templates.writeTemplate)('templates/mirror-directoryNamedModule.d.ts.template', typeDefPath, { + name + }); + + // We add a source map to allow "go to definition" to avoid ending in the .d.ts file + // We do this for the web side only + if ((0, _startsWith.default)(p).call(p, rwjsPaths.web.src)) { + try { + // Get the line and column where the default export is defined + const fileContents = (0, _ast.fileToAst)(p); + const defaultExportLocation = (0, _ast.getDefaultExportLocation)(fileContents) ?? { + line: 1, + column: 0 + }; + + // Generate a source map that points to the definition of the default export + const map = new _sourceMap.SourceMapGenerator({ + file: 'index.d.ts' + }); + map.addMapping({ + generated: { + line: 4, + column: 0 + }, + source: _path.default.relative(_path.default.dirname(typeDefPath), p), + original: defaultExportLocation + }); + _fs.default.writeFileSync(`${typeDefPath}.map`, (0, _stringify.default)(map.toJSON(), undefined, 2)); + } catch (error) { + console.error("Couldn't generate a definition map for directory named module at path:", p); + console.error(error); + } + } + return typeDefPath; +}; +exports.generateMirrorDirectoryNamedModule = generateMirrorDirectoryNamedModule; +const generateMirrorCells = () => { + var _context2; + const rwjsPaths = (0, _projectConfig.getPaths)(); + return (0, _map.default)(_context2 = (0, _files.findCells)()).call(_context2, p => generateMirrorCell(p, rwjsPaths)); +}; +exports.generateMirrorCells = generateMirrorCells; +const mirrorPathForCell = (p, rwjsPaths = (0, _projectConfig.getPaths)()) => { + const mirrorDir = _path.default.join(rwjsPaths.generated.types.mirror, _path.default.relative(rwjsPaths.base, _path.default.dirname(p))); + _fs.default.mkdirSync(mirrorDir, { + recursive: true + }); + return [mirrorDir, 'index.d.ts']; +}; +exports.mirrorPathForCell = mirrorPathForCell; +const generateMirrorCell = (p, rwjsPaths = (0, _projectConfig.getPaths)()) => { + const [mirrorDir, typeDef] = mirrorPathForCell(p, rwjsPaths); + _fs.default.mkdirSync(mirrorDir, { + recursive: true + }); + const typeDefPath = _path.default.join(mirrorDir, typeDef); + const { + name + } = _path.default.parse(p); + const fileContents = (0, _ast.fileToAst)(p); + const cellQuery = (0, _ast.getCellGqlQuery)(fileContents); + if (cellQuery) { + const gqlDoc = (0, _gql.parseGqlQueryToAst)(cellQuery)[0]; + (0, _templates.writeTemplate)('templates/mirror-cell.d.ts.template', typeDefPath, { + name, + queryResultType: `${gqlDoc?.name}`, + queryVariablesType: `${gqlDoc?.name}Variables` + }); + } else { + // If for some reason we can't parse the query, generated the mirror cell anyway + (0, _templates.writeTemplate)('templates/mirror-cell.d.ts.template', typeDefPath, { + name, + queryResultType: 'any', + queryVariablesType: 'any' + }); + } + + // We add a source map to allow "go to definition" to avoid ending in the .d.ts file + // Unlike pages, layouts, components etc. there is no clear definition location so we link + // to the Success component + try { + // Get the location of the Success component + const exportedComponents = (0, _ast.getNamedExports)(fileContents); + const successComponent = (0, _find.default)(exportedComponents).call(exportedComponents, x => x.name === 'Success'); + if (successComponent === undefined) { + throw new Error('No Success component found'); + } + + // Generate the map + const map = new _sourceMap.SourceMapGenerator({ + file: 'index.d.ts' + }); + map.addMapping({ + generated: { + line: 12, + column: 0 + }, + source: _path.default.relative(_path.default.dirname(typeDefPath), p), + original: successComponent.location + }); + _fs.default.writeFileSync(`${typeDefPath}.map`, (0, _stringify.default)(map.toJSON(), undefined, 2)); + } catch (error) { + console.error("Couldn't generate a definition map for cell at path:", p); + console.error(error); + } + return typeDefPath; +}; +exports.generateMirrorCell = generateMirrorCell; +const writeTypeDefIncludeFile = (template, values = {}) => { + const rwjsPaths = (0, _projectConfig.getPaths)(); + const typeDefPath = _path.default.join((0, _includes.default)(rwjsPaths.generated.types), template.replace('.template', '')); + const templateFilename = _path.default.join('templates', template); + (0, _templates.writeTemplate)(templateFilename, typeDefPath, values); + return [typeDefPath]; +}; +const generateTypeDefRouterRoutes = () => { + var _context3; + const ast = (0, _ast.fileToAst)((0, _projectConfig.getPaths)().web.routes); + let hasRootRoute = false; + const routes = (0, _filter.default)(_context3 = (0, _jsx.getJsxElements)(ast, 'Route')).call(_context3, x => { + // All generated "routes" should have a "name" and "path" prop-value + const isValidRoute = typeof x.props?.path !== 'undefined' && typeof x.props?.name !== 'undefined'; + if (isValidRoute && x.props.path === '/') { + hasRootRoute = true; + } + return isValidRoute; + }); + + // Generate declaration mapping for improved go-to-definition behaviour + try { + const typeDefPath = _path.default.join((0, _includes.default)((0, _projectConfig.getPaths)().generated.types), 'web-routerRoutes.d.ts'); + const map = new _sourceMap.SourceMapGenerator({ + file: 'web-routerRoutes.d.ts' + }); + + // Start line is based on where in the template the + // ` ${name}: (params?: RouteParams<"${path}"> & QueryParams) => "${path}"` + // line is defined + const startLine = 7; + + // Map the location of the default export for each page + for (let i = 0; i < routes.length; i++) { + map.addMapping({ + generated: { + line: startLine + i, + column: 4 + }, + source: _path.default.relative(_path.default.dirname(typeDefPath), (0, _projectConfig.getPaths)().web.routes), + original: routes[i].location + }); + } + _fs.default.writeFileSync(`${typeDefPath}.map`, (0, _stringify.default)(map.toJSON(), undefined, 2)); + } catch (error) { + console.error("Couldn't generate a definition map for web-routerRoutes.d.ts:"); + console.error(error); + } + if (!hasRootRoute) { + routes.push({ + name: 'splashPage route', + location: { + line: -1, + column: -1 + }, + props: { + path: '/', + name: 'home' + } + }); + } + return writeTypeDefIncludeFile('web-routerRoutes.d.ts.template', { + routes + }); +}; +exports.generateTypeDefRouterRoutes = generateTypeDefRouterRoutes; +const generateTypeDefRouterPages = () => { + const pages = (0, _projectConfig.processPagesDir)(); + + // Generate declaration map for better go-to-definition behaviour + try { + const typeDefPath = _path.default.join((0, _includes.default)((0, _projectConfig.getPaths)().generated.types), 'web-routesPages.d.ts'); + const map = new _sourceMap.SourceMapGenerator({ + file: 'web-routesPages.d.ts' + }); + + // Start line is based on where in the template the ` const ${importName}: typeof ${importName}Type` are defined + const startLine = pages.length + 5; + + // Map the location of the default export for each page + for (let i = 0; i < pages.length; i++) { + const fileContents = (0, _ast.fileToAst)(pages[i].path); + const defaultExportLocation = (0, _ast.getDefaultExportLocation)(fileContents) ?? { + line: 1, + column: 0 + }; + map.addMapping({ + generated: { + line: startLine + i, + column: 0 + }, + source: _path.default.relative(_path.default.dirname(typeDefPath), pages[i].path), + original: defaultExportLocation + }); + } + _fs.default.writeFileSync(`${typeDefPath}.map`, (0, _stringify.default)(map.toJSON(), undefined, 2)); + } catch (error) { + console.error("Couldn't generate a definition map for web-routesPages.d.ts:"); + console.error(error); + } + return writeTypeDefIncludeFile('web-routesPages.d.ts.template', { + pages + }); +}; +exports.generateTypeDefRouterPages = generateTypeDefRouterPages; +const generateTypeDefCurrentUser = () => { + return writeTypeDefIncludeFile('all-currentUser.d.ts.template'); +}; +exports.generateTypeDefCurrentUser = generateTypeDefCurrentUser; +const generateTypeDefScenarios = () => { + return writeTypeDefIncludeFile('api-scenarios.d.ts.template'); +}; +exports.generateTypeDefScenarios = generateTypeDefScenarios; +const generateTypeDefTestMocks = () => { + var _context4; + return (0, _flat.default)(_context4 = [writeTypeDefIncludeFile('api-test-globals.d.ts.template'), writeTypeDefIncludeFile('web-test-globals.d.ts.template')]).call(_context4); +}; +exports.generateTypeDefTestMocks = generateTypeDefTestMocks; +const generateTypeDefGlobImports = () => { + return writeTypeDefIncludeFile('api-globImports.d.ts.template'); +}; +exports.generateTypeDefGlobImports = generateTypeDefGlobImports; +const generateTypeDefGlobalContext = () => { + return writeTypeDefIncludeFile('api-globalContext.d.ts.template'); +}; +/** + * Typescript does not preserve triple slash directives when outputting js or d.ts files. + * This is a work around so that *.svg, *.png, etc. imports have types. + */ +exports.generateTypeDefGlobalContext = generateTypeDefGlobalContext; +const generateViteClientTypesDirective = () => { + const viteClientDirective = `/// `; + const redwoodProjectPaths = (0, _projectConfig.getPaths)(); + const viteClientDirectivePath = _path.default.join((0, _includes.default)(redwoodProjectPaths.generated.types), 'web-vite-client.d.ts'); + _fs.default.writeFileSync(viteClientDirectivePath, viteClientDirective); + return [viteClientDirectivePath]; +}; +exports.generateViteClientTypesDirective = generateViteClientTypesDirective; +function generateStubStorybookTypes() { + var _context5; + const stubStorybookTypesFileContent = `\ +declare module '@storybook/react' { + export type Meta = any + export type StoryObj = any +} +`; + const redwoodProjectPaths = (0, _projectConfig.getPaths)(); + const packageJson = JSON.parse(_fs.default.readFileSync(_path.default.join(redwoodProjectPaths.base, 'package.json'), 'utf-8')); + const hasCliStorybookVite = (0, _includes.default)(_context5 = (0, _keys.default)(packageJson['devDependencies'])).call(_context5, '@redwoodjs/cli-storybook-vite'); + if (hasCliStorybookVite) { + return []; + } + const stubStorybookTypesFilePath = _path.default.join((0, _includes.default)(redwoodProjectPaths.generated.types), 'web-storybook.d.ts'); + _fs.default.writeFileSync(stubStorybookTypesFilePath, stubStorybookTypesFileContent); + return [stubStorybookTypesFilePath]; +} \ No newline at end of file diff --git a/packages/internal/dist/generate/types.d.ts b/packages/internal/dist/generate/types.d.ts new file mode 100644 index 000000000000..1399078f83bc --- /dev/null +++ b/packages/internal/dist/generate/types.d.ts @@ -0,0 +1,6 @@ +export interface GeneratedFile { + filename: string; + content: string; + hooks: string; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/types.d.ts.map b/packages/internal/dist/generate/types.d.ts.map new file mode 100644 index 000000000000..05de179f3f58 --- /dev/null +++ b/packages/internal/dist/generate/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/generate/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,MAAM,CAAA;CACd"} \ No newline at end of file diff --git a/packages/internal/dist/generate/types.js b/packages/internal/dist/generate/types.js new file mode 100644 index 000000000000..16ae9a868a6a --- /dev/null +++ b/packages/internal/dist/generate/types.js @@ -0,0 +1,6 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +_Object$defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/packages/internal/dist/generate/watch.d.ts b/packages/internal/dist/generate/watch.d.ts new file mode 100644 index 000000000000..7137bb385e77 --- /dev/null +++ b/packages/internal/dist/generate/watch.d.ts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=watch.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/watch.d.ts.map b/packages/internal/dist/generate/watch.d.ts.map new file mode 100644 index 000000000000..c47f7e57e158 --- /dev/null +++ b/packages/internal/dist/generate/watch.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"watch.d.ts","sourceRoot":"","sources":["../../src/generate/watch.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/internal/dist/generate/watch.js b/packages/internal/dist/generate/watch.js new file mode 100755 index 000000000000..57fe1009a09e --- /dev/null +++ b/packages/internal/dist/generate/watch.js @@ -0,0 +1,109 @@ +#!/usr/bin/env node +"use strict"; + +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +var _trim = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/trim")); +var _now = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/date/now")); +var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); +var _fs = _interopRequireDefault(require("fs")); +var _path = _interopRequireDefault(require("path")); +var _chalk = _interopRequireDefault(require("chalk")); +var _chokidar = _interopRequireDefault(require("chokidar")); +var _projectConfig = require("@redwoodjs/project-config"); +var _cliLogger = require("../cliLogger"); +var _files = require("../files"); +var _routes = require("../routes"); +var _clientPreset = require("./clientPreset"); +var _generate = require("./generate"); +var _graphqlCodeGen = require("./graphqlCodeGen"); +var _graphqlSchema = require("./graphqlSchema"); +var _typeDefinitions = require("./typeDefinitions"); +const rwjsPaths = (0, _projectConfig.getPaths)(); +const watcher = _chokidar.default.watch('(web|api)/src/**/*.{ts,js,jsx,tsx}', { + persistent: true, + ignored: ['node_modules', '.redwood'], + ignoreInitial: true, + cwd: rwjsPaths.base, + awaitWriteFinish: true +}); +const action = { + add: 'Created', + unlink: 'Deleted', + change: 'Modified' +}; +let routesWarningMessage = ''; +process.stdin.on('data', async data => { + var _context; + const str = (0, _trim.default)(_context = data.toString()).call(_context).toLowerCase(); + if (str === 'g' || str === 'rs') { + (0, _cliLogger.cliLogger)('Re-creating TypeScript definitions and GraphQL schemas'); + await (0, _generate.generate)(); + } +}); +watcher.on('ready', async () => { + const start = (0, _now.default)(); + (0, _cliLogger.cliLogger)('Generating full TypeScript definitions and GraphQL schemas'); + const { + files, + errors + } = await (0, _generate.generate)(); + (0, _cliLogger.cliLogger)(`Done.`); + _cliLogger.cliLogger.debug(`\nCreated ${files.length} in ${(0, _now.default)() - start} ms`); + if (errors.length > 0) { + for (const { + message, + error + } of errors) { + console.error(message); + console.error(error); + console.log(); + } + } + routesWarningMessage = (0, _routes.warningForDuplicateRoutes)(); + if (routesWarningMessage) { + console.warn(routesWarningMessage); + } +}).on('all', async (eventName, p) => { + var _context2; + _cliLogger.cliLogger.trace(`File system change: ${_chalk.default.magenta(eventName)} ${_chalk.default.dim(p)}`); + if (!(0, _includes.default)(_context2 = ['add', 'change', 'unlink']).call(_context2, eventName)) { + return; + } + const eventTigger = eventName; + const absPath = _path.default.join(rwjsPaths.base, p); + + // Track the time in debug + const start = (0, _now.default)(); + const finished = type => _cliLogger.cliLogger.debug(action[eventTigger], type + ':', _chalk.default.dim(p), _chalk.default.dim.italic((0, _now.default)() - start + ' ms')); + if ((0, _includes.default)(absPath).call(absPath, 'Cell') && (0, _files.isCellFile)(absPath)) { + await (0, _graphqlCodeGen.generateTypeDefGraphQLWeb)(); + await (0, _clientPreset.generateClientPreset)(); + if (eventName === 'unlink') { + _fs.default.unlinkSync((0, _typeDefinitions.mirrorPathForCell)(absPath, rwjsPaths)[0]); + } else { + (0, _typeDefinitions.generateMirrorCell)(absPath, rwjsPaths); + } + finished('Cell'); + } else if (absPath === rwjsPaths.web.routes) { + (0, _typeDefinitions.generateTypeDefRouterRoutes)(); + routesWarningMessage = (0, _routes.warningForDuplicateRoutes)(); + finished('Routes'); + } else if ((0, _includes.default)(absPath).call(absPath, 'Page') && (0, _files.isPageFile)(absPath)) { + (0, _typeDefinitions.generateTypeDefRouterPages)(); + finished('Page'); + } else if ((0, _files.isDirectoryNamedModuleFile)(absPath)) { + if (eventName === 'unlink') { + _fs.default.unlinkSync((0, _typeDefinitions.mirrorPathForDirectoryNamedModules)(absPath, rwjsPaths)[0]); + } else { + (0, _typeDefinitions.generateMirrorDirectoryNamedModule)(absPath, rwjsPaths); + } + finished('Directory named module'); + } else if ((0, _files.isGraphQLSchemaFile)(absPath)) { + await (0, _graphqlSchema.generateGraphQLSchema)(); + await (0, _graphqlCodeGen.generateTypeDefGraphQLApi)(); + finished('GraphQL Schema'); + } + if (routesWarningMessage) { + console.warn(routesWarningMessage); + } +}); \ No newline at end of file diff --git a/packages/internal/dist/gql.d.ts b/packages/internal/dist/gql.d.ts new file mode 100644 index 000000000000..a65a4c669b68 --- /dev/null +++ b/packages/internal/dist/gql.d.ts @@ -0,0 +1,14 @@ +import type { DocumentNode, OperationTypeNode } from 'graphql'; +interface Operation { + operation: OperationTypeNode; + name: string | undefined; + fields: (string | Field)[]; +} +interface Field { + string: (string | Field)[]; +} +export declare const parseGqlQueryToAst: (gqlQuery: string) => Operation[]; +export declare const parseDocumentAST: (document: DocumentNode) => Operation[]; +export declare const listQueryTypeFieldsInProject: () => Promise; +export {}; +//# sourceMappingURL=gql.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/gql.d.ts.map b/packages/internal/dist/gql.d.ts.map new file mode 100644 index 000000000000..0d953fde9c40 --- /dev/null +++ b/packages/internal/dist/gql.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"gql.d.ts","sourceRoot":"","sources":["../src/gql.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,YAAY,EAIZ,iBAAiB,EAClB,MAAM,SAAS,CAAA;AAMhB,UAAU,SAAS;IACjB,SAAS,EAAE,iBAAiB,CAAA;IAC5B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAA;IACxB,MAAM,EAAE,CAAC,MAAM,GAAG,KAAK,CAAC,EAAE,CAAA;CAC3B;AAED,UAAU,KAAK;IACb,MAAM,EAAE,CAAC,MAAM,GAAG,KAAK,CAAC,EAAE,CAAA;CAC3B;AAED,eAAO,MAAM,kBAAkB,aAAc,MAAM,gBAGlD,CAAA;AAED,eAAO,MAAM,gBAAgB,aAAc,YAAY,gBAoBtD,CAAA;AAgCD,eAAO,MAAM,4BAA4B,yBA8BxC,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/gql.js b/packages/internal/dist/gql.js new file mode 100644 index 000000000000..ed34447bbdc9 --- /dev/null +++ b/packages/internal/dist/gql.js @@ -0,0 +1,94 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.parseGqlQueryToAst = exports.parseDocumentAST = exports.listQueryTypeFieldsInProject = void 0; +require("core-js/modules/es.array.push.js"); +var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/for-each")); +var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/keys")); +var _codeFileLoader = require("@graphql-tools/code-file-loader"); +var _load = require("@graphql-tools/load"); +var _graphql = require("graphql"); +var _graphqlServer = require("@redwoodjs/graphql-server"); +var _projectConfig = require("@redwoodjs/project-config"); +const parseGqlQueryToAst = gqlQuery => { + const ast = (0, _graphql.parse)(gqlQuery); + return parseDocumentAST(ast); +}; +exports.parseGqlQueryToAst = parseGqlQueryToAst; +const parseDocumentAST = document => { + const operations = []; + (0, _graphql.visit)(document, { + OperationDefinition(node) { + var _context; + const fields = []; + (0, _forEach.default)(_context = node.selectionSet.selections).call(_context, field => { + fields.push(getFields(field)); + }); + operations.push({ + operation: node.operation, + name: node.name?.value, + fields + }); + } + }); + return operations; +}; +exports.parseDocumentAST = parseDocumentAST; +const getFields = field => { + // base + if (!field.selectionSet) { + return field.name.value; + } else { + const obj = { + [field.name.value]: [] + }; + const lookAtFieldNode = node => { + node.selectionSet?.selections.forEach(subField => { + switch (subField.kind) { + case _graphql.Kind.FIELD: + obj[field.name.value].push(getFields(subField)); + break; + case _graphql.Kind.FRAGMENT_SPREAD: + // TODO: Maybe this will also be needed, right now it's accounted for to not crash in the tests + break; + case _graphql.Kind.INLINE_FRAGMENT: + lookAtFieldNode(subField); + } + }); + }; + lookAtFieldNode(field); + return obj; + } +}; +const listQueryTypeFieldsInProject = async () => { + try { + const schemaPointerMap = { + [(0, _graphql.print)(_graphqlServer.rootSchema.schema)]: {}, + 'graphql/**/*.sdl.{js,ts}': {}, + 'directives/**/*.{js,ts}': {}, + 'subscriptions/**/*.{js,ts}': {} + }; + const mergedSchema = await (0, _load.loadSchema)(schemaPointerMap, { + loaders: [new _codeFileLoader.CodeFileLoader({ + noRequire: true, + pluckConfig: { + globalGqlIdentifierName: 'gql' + } + })], + cwd: (0, _projectConfig.getPaths)().api.src, + assumeValidSDL: true + }); + const queryTypeFields = mergedSchema.getQueryType()?.getFields(); + + // Return empty array if no schema found + return (0, _keys.default)(queryTypeFields ?? {}); + } catch (e) { + console.error(e); + return []; + } +}; +exports.listQueryTypeFieldsInProject = listQueryTypeFieldsInProject; \ No newline at end of file diff --git a/packages/internal/dist/index.d.ts b/packages/internal/dist/index.d.ts new file mode 100644 index 000000000000..dd0c86c08f03 --- /dev/null +++ b/packages/internal/dist/index.d.ts @@ -0,0 +1,11 @@ +export * from '@redwoodjs/project-config'; +export * from './ts2js'; +export * from './dev'; +export * from './routes'; +export * from './files'; +export { generate } from './generate/generate'; +export { buildApi } from './build/api'; +export * from './validateSchema'; +export * from '@redwoodjs/babel-config'; +export { listQueryTypeFieldsInProject } from './gql'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/index.d.ts.map b/packages/internal/dist/index.d.ts.map new file mode 100644 index 000000000000..3b25161fd1e9 --- /dev/null +++ b/packages/internal/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,2BAA2B,CAAA;AAEzC,cAAc,SAAS,CAAA;AACvB,cAAc,OAAO,CAAA;AACrB,cAAc,UAAU,CAAA;AAExB,cAAc,SAAS,CAAA;AACvB,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAEtC,cAAc,kBAAkB,CAAA;AAGhC,cAAc,yBAAyB,CAAA;AAEvC,OAAO,EAAE,4BAA4B,EAAE,MAAM,OAAO,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/index.js b/packages/internal/dist/index.js new file mode 100644 index 000000000000..2c88d795f598 --- /dev/null +++ b/packages/internal/dist/index.js @@ -0,0 +1,119 @@ +"use strict"; + +var _context, _context2, _context3, _context4, _context5, _context6, _context7; +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _forEachInstanceProperty = require("@babel/runtime-corejs3/core-js/instance/for-each"); +var _Object$keys = require("@babel/runtime-corejs3/core-js/object/keys"); +_Object$defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + generate: true, + buildApi: true, + listQueryTypeFieldsInProject: true +}; +_Object$defineProperty(exports, "buildApi", { + enumerable: true, + get: function () { + return _api.buildApi; + } +}); +_Object$defineProperty(exports, "generate", { + enumerable: true, + get: function () { + return _generate.generate; + } +}); +_Object$defineProperty(exports, "listQueryTypeFieldsInProject", { + enumerable: true, + get: function () { + return _gql.listQueryTypeFieldsInProject; + } +}); +var _projectConfig = require("@redwoodjs/project-config"); +_forEachInstanceProperty(_context = _Object$keys(_projectConfig)).call(_context, function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _projectConfig[key]) return; + _Object$defineProperty(exports, key, { + enumerable: true, + get: function () { + return _projectConfig[key]; + } + }); +}); +var _ts2js = require("./ts2js"); +_forEachInstanceProperty(_context2 = _Object$keys(_ts2js)).call(_context2, function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _ts2js[key]) return; + _Object$defineProperty(exports, key, { + enumerable: true, + get: function () { + return _ts2js[key]; + } + }); +}); +var _dev = require("./dev"); +_forEachInstanceProperty(_context3 = _Object$keys(_dev)).call(_context3, function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _dev[key]) return; + _Object$defineProperty(exports, key, { + enumerable: true, + get: function () { + return _dev[key]; + } + }); +}); +var _routes = require("./routes"); +_forEachInstanceProperty(_context4 = _Object$keys(_routes)).call(_context4, function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _routes[key]) return; + _Object$defineProperty(exports, key, { + enumerable: true, + get: function () { + return _routes[key]; + } + }); +}); +var _files = require("./files"); +_forEachInstanceProperty(_context5 = _Object$keys(_files)).call(_context5, function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _files[key]) return; + _Object$defineProperty(exports, key, { + enumerable: true, + get: function () { + return _files[key]; + } + }); +}); +var _generate = require("./generate/generate"); +var _api = require("./build/api"); +var _validateSchema = require("./validateSchema"); +_forEachInstanceProperty(_context6 = _Object$keys(_validateSchema)).call(_context6, function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _validateSchema[key]) return; + _Object$defineProperty(exports, key, { + enumerable: true, + get: function () { + return _validateSchema[key]; + } + }); +}); +var _babelConfig = require("@redwoodjs/babel-config"); +_forEachInstanceProperty(_context7 = _Object$keys(_babelConfig)).call(_context7, function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _babelConfig[key]) return; + _Object$defineProperty(exports, key, { + enumerable: true, + get: function () { + return _babelConfig[key]; + } + }); +}); +var _gql = require("./gql"); \ No newline at end of file diff --git a/packages/internal/dist/jsx.d.ts b/packages/internal/dist/jsx.d.ts new file mode 100644 index 000000000000..2381f2ff146e --- /dev/null +++ b/packages/internal/dist/jsx.d.ts @@ -0,0 +1,16 @@ +import type { types } from '@babel/core'; +interface JsxElement { + name: string; + props: Record; + children?: JsxElement[]; + location: { + line: number; + column: number; + }; +} +/** + * Extract JSX elements, children and props from static code. + */ +export declare const getJsxElements: (ast: types.Node, name: string) => JsxElement[]; +export {}; +//# sourceMappingURL=jsx.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/jsx.d.ts.map b/packages/internal/dist/jsx.d.ts.map new file mode 100644 index 000000000000..097c46e23aba --- /dev/null +++ b/packages/internal/dist/jsx.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jsx.d.ts","sourceRoot":"","sources":["../src/jsx.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAKxC,UAAU,UAAU;IAClB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC1B,QAAQ,CAAC,EAAE,UAAU,EAAE,CAAA;IACvB,QAAQ,EAAE;QACR,IAAI,EAAE,MAAM,CAAA;QACZ,MAAM,EAAE,MAAM,CAAA;KACf,CAAA;CACF;AACD;;GAEG;AACH,eAAO,MAAM,cAAc,QAAS,KAAK,CAAC,IAAI,QAAQ,MAAM,iBAgB3D,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/jsx.js b/packages/internal/dist/jsx.js new file mode 100644 index 000000000000..d13bf9570c19 --- /dev/null +++ b/packages/internal/dist/jsx.js @@ -0,0 +1,91 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.getJsxElements = void 0; +require("core-js/modules/es.array.push.js"); +var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/concat")); +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/for-each")); +var _traverse = _interopRequireDefault(require("@babel/traverse")); +var _jsxAttributeValue = require("./jsxAttributeValue"); +/** + * Extract JSX elements, children and props from static code. + */ +const getJsxElements = (ast, name) => { + let elements = []; + (0, _traverse.default)(ast, { + JSXIdentifier(path) { + if (path.node.name === name && path.parentPath.type === 'JSXOpeningElement') { + if (path?.parentPath?.parentPath?.type === 'JSXElement') { + const element = reduceJsxElement([], path.parentPath.parentPath.node); + elements = (0, _concat.default)(elements).call(elements, element); + } + } + } + }); + return elements; +}; + +/** + * Extract attributes (props) from a JSX element. + */ +exports.getJsxElements = getJsxElements; +const getJsxAttributes = jsxElement => { + var _context; + return (0, _filter.default)(_context = jsxElement.openingElement.attributes).call(_context, ({ + type + }) => type === 'JSXAttribute'); +}; + +/** + * Extract and format props (attributes) from a JSX element. + */ +const getJsxProps = jsxElement => { + const attributes = getJsxAttributes(jsxElement); + const props = {}; + for (const a of attributes) { + if (typeof a.name.name === 'string') { + props[a.name.name] = (0, _jsxAttributeValue.getJsxAttributeValue)(a.value); + } + } + return props; +}; + +/** + * Traverse a JSX element tree and place it into a simple JSON format. + */ +const reduceJsxElement = (oldNode, currentNode) => { + let element = { + name: '', + props: {}, + children: [], + location: { + line: 1, + column: 0 + } + }; + if (currentNode.type === 'JSXElement') { + const props = getJsxProps(currentNode); + if (currentNode.openingElement.name.type === 'JSXIdentifier') { + element = { + name: currentNode.openingElement.name.name, + props, + children: [], + location: { + line: currentNode.openingElement.loc?.start.line ?? 1, + column: currentNode.openingElement.loc?.start.column ?? 0 + } + }; + oldNode.push(element); + } + } + if ('children' in currentNode) { + var _context2; + (0, _forEach.default)(_context2 = currentNode.children).call(_context2, node => oldNode.length > 0 ? reduceJsxElement(element.children, node) : reduceJsxElement(oldNode, node)); + } + return oldNode; +}; \ No newline at end of file diff --git a/packages/internal/dist/jsxAttributeValue.d.ts b/packages/internal/dist/jsxAttributeValue.d.ts new file mode 100644 index 000000000000..915ee794738c --- /dev/null +++ b/packages/internal/dist/jsxAttributeValue.d.ts @@ -0,0 +1,2 @@ +export declare const getJsxAttributeValue: (expression: any) => any; +//# sourceMappingURL=jsxAttributeValue.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/jsxAttributeValue.d.ts.map b/packages/internal/dist/jsxAttributeValue.d.ts.map new file mode 100644 index 000000000000..7df800d13bbe --- /dev/null +++ b/packages/internal/dist/jsxAttributeValue.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jsxAttributeValue.d.ts","sourceRoot":"","sources":["../src/jsxAttributeValue.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,oBAAoB,eAAgB,GAAG,KAAG,GAsLtD,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/jsxAttributeValue.js b/packages/internal/dist/jsxAttributeValue.js new file mode 100644 index 000000000000..5a92f9d56af0 --- /dev/null +++ b/packages/internal/dist/jsxAttributeValue.js @@ -0,0 +1,127 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.getJsxAttributeValue = void 0; +var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); +var _reduce = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/reduce")); +var _sort = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/sort")); +var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/concat")); +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +/* eslint-disable @typescript-eslint/ban-ts-comment */ +// @ts-nocheck This function was adapted from: https://github.com/gglnx/simplified-jsx-to-json/blob/master/index.js#L13 +const getJsxAttributeValue = expression => { + // If the expression is null, this is an implicitly "true" prop, such as readOnly + if (expression === null) { + return true; + } + if (expression.type === 'StringLiteral') { + return expression.value; + } + if (expression.type === 'JSXExpressionContainer') { + return getJsxAttributeValue(expression.expression); + } + if (expression.type === 'ArrayExpression') { + var _context; + return (0, _map.default)(_context = expression.elements).call(_context, element => getJsxAttributeValue(element)); + } + if (expression.type === 'TemplateLiteral') { + var _context2, _context3, _context4; + const expressions = (0, _map.default)(_context2 = expression.expressions).call(_context2, element => ({ + ...element, + value: { + raw: element.value, + cooked: getJsxAttributeValue(element) + } + })); + return (0, _reduce.default)(_context3 = (0, _sort.default)(_context4 = (0, _concat.default)(expressions).call(expressions, expression.quasis)).call(_context4, (elementA, elementB) => elementA.start - elementB.start)).call(_context3, (string, element) => `${string}${element.value.cooked.toString()}`, ''); + } + if (expression.type === 'ObjectExpression') { + var _context5, _context6, _context7; + const entries = (0, _reduce.default)(_context5 = (0, _filter.default)(_context6 = (0, _map.default)(_context7 = expression.properties).call(_context7, property => { + const key = getJsxAttributeValue(property.key); + const value = getJsxAttributeValue(property.value); + if (key === undefined || value === undefined) { + return null; + } + return { + key, + value + }; + })).call(_context6, property => property)).call(_context5, (properties, property) => { + return { + ...properties, + [property.key]: property.value + }; + }, {}); + return entries; + } + if (expression.type === 'Identifier') { + return expression.name; + } + if (expression.type === 'BinaryExpression') { + switch (expression.operator) { + case '+': + return getJsxAttributeValue(expression.left) + getJsxAttributeValue(expression.right); + case '-': + return getJsxAttributeValue(expression.left) - getJsxAttributeValue(expression.right); + case '*': + return getJsxAttributeValue(expression.left) * getJsxAttributeValue(expression.right); + case '**': + return getJsxAttributeValue(expression.left) ** getJsxAttributeValue(expression.right); + case '/': + return getJsxAttributeValue(expression.left) / getJsxAttributeValue(expression.right); + case '%': + return getJsxAttributeValue(expression.left) % getJsxAttributeValue(expression.right); + case '==': + return getJsxAttributeValue(expression.left) == getJsxAttributeValue(expression.right); + case '===': + return getJsxAttributeValue(expression.left) === getJsxAttributeValue(expression.right); + case '!=': + return getJsxAttributeValue(expression.left) != getJsxAttributeValue(expression.right); + case '!==': + return getJsxAttributeValue(expression.left) !== getJsxAttributeValue(expression.right); + case '<': + return getJsxAttributeValue(expression.left) < getJsxAttributeValue(expression.right); + case '<=': + return getJsxAttributeValue(expression.left) <= getJsxAttributeValue(expression.right); + case '>': + return getJsxAttributeValue(expression.left) > getJsxAttributeValue(expression.right); + case '>=': + return getJsxAttributeValue(expression.left) >= getJsxAttributeValue(expression.right); + case '<<': + return getJsxAttributeValue(expression.left) << getJsxAttributeValue(expression.right); + case '>>': + return getJsxAttributeValue(expression.left) >> getJsxAttributeValue(expression.right); + case '>>>': + return getJsxAttributeValue(expression.left) >>> getJsxAttributeValue(expression.right); + case '|': + return getJsxAttributeValue(expression.left) | getJsxAttributeValue(expression.right); + case '&': + return getJsxAttributeValue(expression.left) & getJsxAttributeValue(expression.right); + case '^': + return getJsxAttributeValue(expression.left) ^ getJsxAttributeValue(expression.right); + default: + return `BinaryExpression with "${expression.operator}" is not supported`; + } + } + if (expression.type === 'UnaryExpression') { + switch (expression.operator) { + case '+': + return +getJsxAttributeValue(expression.argument); + case '-': + return -getJsxAttributeValue(expression.argument); + case '~': + return ~getJsxAttributeValue(expression.argument); + default: + return `UnaryExpression with "${expression.operator}" is not supported`; + } + } + + // Unsupported type + return `${expression.type} is not supported`; +}; +exports.getJsxAttributeValue = getJsxAttributeValue; \ No newline at end of file diff --git a/packages/internal/dist/project.d.ts b/packages/internal/dist/project.d.ts new file mode 100644 index 000000000000..9e44608a8cb9 --- /dev/null +++ b/packages/internal/dist/project.d.ts @@ -0,0 +1,8 @@ +export declare const getTsConfigs: () => { + api: any; + web: any; +}; +export declare const isTypeScriptProject: () => boolean; +export declare const isServerFileSetup: () => boolean; +export declare const isRealtimeSetup: () => boolean; +//# sourceMappingURL=project.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/project.d.ts.map b/packages/internal/dist/project.d.ts.map new file mode 100644 index 000000000000..2e71db234292 --- /dev/null +++ b/packages/internal/dist/project.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"project.d.ts","sourceRoot":"","sources":["../src/project.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,YAAY;;;CAuBxB,CAAA;AAED,eAAO,MAAM,mBAAmB,eAM/B,CAAA;AAED,eAAO,MAAM,iBAAiB,eAO7B,CAAA;AAED,eAAO,MAAM,eAAe,eAO3B,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/project.js b/packages/internal/dist/project.js new file mode 100644 index 000000000000..06cbaea165ac --- /dev/null +++ b/packages/internal/dist/project.js @@ -0,0 +1,39 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.isTypeScriptProject = exports.isServerFileSetup = exports.isRealtimeSetup = exports.getTsConfigs = void 0; +var _fs = _interopRequireDefault(require("fs")); +var _path = _interopRequireDefault(require("path")); +var _typescript = require("typescript"); +var _projectConfig = require("@redwoodjs/project-config"); +const getTsConfigs = () => { + const rwPaths = (0, _projectConfig.getPaths)(); + const apiTsConfigPath = _path.default.join(rwPaths.api.base, 'tsconfig.json'); + const webTsConfigPath = _path.default.join(rwPaths.web.base, 'tsconfig.json'); + const apiTsConfig = _fs.default.existsSync(apiTsConfigPath) ? (0, _typescript.parseConfigFileTextToJson)(apiTsConfigPath, _fs.default.readFileSync(apiTsConfigPath, 'utf-8')) : null; + const webTsConfig = _fs.default.existsSync(webTsConfigPath) ? (0, _typescript.parseConfigFileTextToJson)(webTsConfigPath, _fs.default.readFileSync(webTsConfigPath, 'utf-8')) : null; + return { + api: apiTsConfig?.config ?? null, + web: webTsConfig?.config ?? null + }; +}; +exports.getTsConfigs = getTsConfigs; +const isTypeScriptProject = () => { + const paths = (0, _projectConfig.getPaths)(); + return _fs.default.existsSync(_path.default.join(paths.web.base, 'tsconfig.json')) || _fs.default.existsSync(_path.default.join(paths.api.base, 'tsconfig.json')); +}; +exports.isTypeScriptProject = isTypeScriptProject; +const isServerFileSetup = () => { + const serverFilePath = _path.default.join((0, _projectConfig.getPaths)().api.src, `server.${isTypeScriptProject() ? 'ts' : 'js'}`); + return _fs.default.existsSync(serverFilePath); +}; +exports.isServerFileSetup = isServerFileSetup; +const isRealtimeSetup = () => { + const realtimePath = _path.default.join((0, _projectConfig.getPaths)().api.lib, `realtime.${isTypeScriptProject() ? 'ts' : 'js'}`); + return _fs.default.existsSync(realtimePath); +}; +exports.isRealtimeSetup = isRealtimeSetup; \ No newline at end of file diff --git a/packages/internal/dist/routes.d.ts b/packages/internal/dist/routes.d.ts new file mode 100644 index 000000000000..f02b1a85beac --- /dev/null +++ b/packages/internal/dist/routes.d.ts @@ -0,0 +1,42 @@ +export interface RouteInformation { + name?: string; + path?: string; + page?: string; +} +/** + * Returns an array of routes which conflict on their defined names + */ +export declare function getDuplicateRoutes(): RouteInformation[]; +/** + * Detects any potential duplicate routes and returns a formatted warning message + * @see {@link getDuplicateRoutes} for how duplicate routes are detected + * @return {string} Warning message when duplicate routes found, empty string if not + */ +export declare function warningForDuplicateRoutes(): string; +export interface RWRouteManifestItem { + name: string; + pathDefinition: string; + matchRegexString: string | null; + routeHooks: string | null; + bundle: string | null; + hasParams: boolean; + relativeFilePath: string; + redirect: { + to: string; + permanent: boolean; + } | null; + isPrivate: boolean; + unauthenticated: string | null; + roles: string | string[] | null; + pageIdentifier: string | null; +} +export interface RouteSpec extends RWRouteManifestItem { + id: string; + isNotFound: boolean; + filePath: string | undefined; + isPrivate: boolean; + unauthenticated: string | null; + relativeFilePath: string; +} +export declare const getProjectRoutes: () => RouteSpec[]; +//# sourceMappingURL=routes.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/routes.d.ts.map b/packages/internal/dist/routes.d.ts.map new file mode 100644 index 000000000000..9b1f96b51473 --- /dev/null +++ b/packages/internal/dist/routes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AASA,MAAM,WAAW,gBAAgB;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED;;GAEG;AACH,wBAAgB,kBAAkB,uBAyBjC;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,WAcxC;AAED,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,CAAA;IACZ,cAAc,EAAE,MAAM,CAAA;IACtB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAA;IAC/B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IACrB,SAAS,EAAE,OAAO,CAAA;IAClB,gBAAgB,EAAE,MAAM,CAAA;IACxB,QAAQ,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAA;IACnD,SAAS,EAAE,OAAO,CAAA;IAClB,eAAe,EAAE,MAAM,GAAG,IAAI,CAAA;IAC9B,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,IAAI,CAAA;IAC/B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAA;CAE9B;AAED,MAAM,WAAW,SAAU,SAAQ,mBAAmB;IACpD,EAAE,EAAE,MAAM,CAAA;IACV,UAAU,EAAE,OAAO,CAAA;IACnB,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAA;IAC5B,SAAS,EAAE,OAAO,CAAA;IAClB,eAAe,EAAE,MAAM,GAAG,IAAI,CAAA;IAC9B,gBAAgB,EAAE,MAAM,CAAA;CACzB;AAED,eAAO,MAAM,gBAAgB,QAAO,SAAS,EAkC5C,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/routes.js b/packages/internal/dist/routes.js new file mode 100644 index 000000000000..9d298bd82217 --- /dev/null +++ b/packages/internal/dist/routes.js @@ -0,0 +1,100 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.getDuplicateRoutes = getDuplicateRoutes; +exports.getProjectRoutes = void 0; +exports.warningForDuplicateRoutes = warningForDuplicateRoutes; +require("core-js/modules/es.array.push.js"); +var _set = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/set")); +var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/for-each")); +var _trimEnd = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/trim-end")); +var _path = _interopRequireDefault(require("path")); +var _chalk = _interopRequireDefault(require("chalk")); +var _projectConfig = require("@redwoodjs/project-config"); +var _router = require("@redwoodjs/router"); +var _index = require("@redwoodjs/structure/dist/index.js"); +/** + * Returns an array of routes which conflict on their defined names + */ +function getDuplicateRoutes() { + var _context; + const duplicateRoutes = []; + const allRoutes = (0, _index.getProject)((0, _projectConfig.getPaths)().base).router.routes; + const uniqueNames = new _set.default((0, _map.default)(_context = (0, _filter.default)(allRoutes).call(allRoutes, route => route.name !== undefined)).call(_context, route => route.name)); + (0, _forEach.default)(uniqueNames).call(uniqueNames, name => { + const routesWithName = (0, _filter.default)(allRoutes).call(allRoutes, route => { + return route.name === name; + }); + if (routesWithName.length > 1) { + duplicateRoutes.push(...(0, _map.default)(routesWithName).call(routesWithName, route => { + return { + name: route.name, + page: route.page_identifier_str, + path: route.path + }; + })); + } + }); + return duplicateRoutes; +} + +/** + * Detects any potential duplicate routes and returns a formatted warning message + * @see {@link getDuplicateRoutes} for how duplicate routes are detected + * @return {string} Warning message when duplicate routes found, empty string if not + */ +function warningForDuplicateRoutes() { + const duplicatedRoutes = getDuplicateRoutes(); + let message = ''; + if (duplicatedRoutes.length > 0) { + message += _chalk.default.keyword('orange')(`Warning: ${duplicatedRoutes.length} duplicate routes have been detected, only the route(s) closest to the top of the file will be used.\n`); + (0, _forEach.default)(duplicatedRoutes).call(duplicatedRoutes, route => { + message += ` ${_chalk.default.keyword('orange')('->')} Name: "${route.name}", Path: "${route.path}", Page: "${route.page}"\n`; + }); + } + return (0, _trimEnd.default)(message).call(message); +} +const getProjectRoutes = () => { + const rwProject = (0, _index.getProject)((0, _projectConfig.getPaths)().base); + const routes = rwProject.getRouter().routes; + + // @ts-expect-error "Bundle" is not found but is in the Spec type? + return (0, _map.default)(routes).call(routes, route => { + const { + matchRegexString, + routeParams + } = route.isNotFound ? { + matchRegexString: null, + routeParams: null + } : (0, _router.getRouteRegexAndParams)(route.path); + return { + name: route.isNotFound ? 'NotFoundPage' : route.name, + pathDefinition: route.isNotFound ? 'notfound' : route.path, + hasParams: route.hasParameters, + id: route.id, + isNotFound: route.isNotFound, + filePath: route.page?.filePath, + relativeFilePath: route.page?.filePath ? _path.default.relative((0, _projectConfig.getPaths)().web.src, route.page?.filePath) : undefined, + routeHooks: (0, _projectConfig.getRouteHookForPage)(route.page?.filePath), + renderMode: route.renderMode, + matchRegexString: matchRegexString, + paramNames: routeParams, + // TODO (STREAMING) deal with permanent/temp later + redirect: route.redirect ? { + to: route.redirect, + permanent: false + } : null, + isPrivate: route.isPrivate, + unauthenticated: route.unauthenticated, + roles: route.roles, + pageIdentifier: route.page_identifier_str + }; + }); +}; +exports.getProjectRoutes = getProjectRoutes; \ No newline at end of file diff --git a/packages/internal/dist/ts2js.d.ts b/packages/internal/dist/ts2js.d.ts new file mode 100644 index 000000000000..f4507a369e24 --- /dev/null +++ b/packages/internal/dist/ts2js.d.ts @@ -0,0 +1,40 @@ +/** + * Converts all the TypeScript files in the `api` and `web` sides to JavaScript. + * + * @param {string} cwd - The base path to the project. + */ +export declare const convertTsProjectToJs: (cwd?: string) => void; +/** + * Converts all the TypeScript files in the `api` and `web` sides to JavaScript. + * + * @param {string} cwd - The base path to the project. + */ +export declare const convertTsScriptsToJs: (cwd?: string) => void; +/** + * Converts TypeScript files to JavaScript. + * + * @param {string} cwd - Current directory + * @param {string[]} files - Collection of files to convert + */ +export declare const convertTsFilesToJs: (cwd: string, files: string[]) => Promise; +/** + * Get all the source code from a Redwood project + */ +export declare const typeScriptSourceFiles: (cwd: string, globPattern?: string) => string[]; +/** + * Read the contents of a TypeScript file, transpile it to JavaScript, + * but leave the JSX intact and format via Prettier. + * + * @param {string} file - The path to the TypeScript file. + */ +export declare const transformTSToJS: (file: string) => Promise | undefined; +export declare const getPrettierConfig: () => Promise; +/** + * Prettify `code` according to the extension in `filename`. + * This will also read a user's `prettier.config.js` file if it exists. + * + * @param {string} code + * @param {string} filename + */ +export declare const prettify: (code: string, filename: string) => Promise; +//# sourceMappingURL=ts2js.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/ts2js.d.ts.map b/packages/internal/dist/ts2js.d.ts.map new file mode 100644 index 000000000000..ecd2e79ca64c --- /dev/null +++ b/packages/internal/dist/ts2js.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ts2js.d.ts","sourceRoot":"","sources":["../src/ts2js.ts"],"names":[],"mappings":"AASA;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,wBAGhC,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,wBAGhC,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,QAAe,MAAM,SAAS,MAAM,EAAE,kBAkCpE,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,qBAAqB,QAC3B,MAAM,mCAUZ,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,eAAe,SAAU,MAAM,gCAwB3C,CAAA;AAED,eAAO,MAAM,iBAAiB,oBAS7B,CAAA;AAsBD;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ,SAAgB,MAAM,YAAY,MAAM,oBAa5D,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/ts2js.js b/packages/internal/dist/ts2js.js new file mode 100644 index 000000000000..a2721a32528a --- /dev/null +++ b/packages/internal/dist/ts2js.js @@ -0,0 +1,156 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.typeScriptSourceFiles = exports.transformTSToJS = exports.prettify = exports.getPrettierConfig = exports.convertTsScriptsToJs = exports.convertTsProjectToJs = exports.convertTsFilesToJs = void 0; +var _fs = _interopRequireDefault(require("fs")); +var _path = _interopRequireDefault(require("path")); +var _core = require("@babel/core"); +var _fastGlob = _interopRequireDefault(require("fast-glob")); +var _prettier = require("prettier"); +var _projectConfig = require("@redwoodjs/project-config"); +/** + * Converts all the TypeScript files in the `api` and `web` sides to JavaScript. + * + * @param {string} cwd - The base path to the project. + */ +const convertTsProjectToJs = (cwd = (0, _projectConfig.getPaths)().base) => { + const files = typeScriptSourceFiles(cwd); + convertTsFilesToJs(cwd, files); +}; + +/** + * Converts all the TypeScript files in the `api` and `web` sides to JavaScript. + * + * @param {string} cwd - The base path to the project. + */ +exports.convertTsProjectToJs = convertTsProjectToJs; +const convertTsScriptsToJs = (cwd = (0, _projectConfig.getPaths)().base) => { + const files = typeScriptSourceFiles(cwd, 'scripts/*.{ts,tsx}'); + convertTsFilesToJs(cwd, files); +}; + +/** + * Converts TypeScript files to JavaScript. + * + * @param {string} cwd - Current directory + * @param {string[]} files - Collection of files to convert + */ +exports.convertTsScriptsToJs = convertTsScriptsToJs; +const convertTsFilesToJs = async (cwd, files) => { + if (files.length === 0) { + console.log('No TypeScript files found to convert to JS in this project.'); + } + for (const f of files) { + const code = await transformTSToJS(f); + if (code) { + _fs.default.writeFileSync(_path.default.join(cwd, f.replace('.tsx', '.jsx').replace('.ts', '.js')), code, 'utf8'); + _fs.default.unlinkSync(_path.default.join(cwd, f)); + } + } + if (_fs.default.existsSync(_path.default.join(cwd, 'api/tsconfig.json'))) { + _fs.default.renameSync(_path.default.join(cwd, 'api/tsconfig.json'), _path.default.join(cwd, 'api/jsconfig.json')); + } + if (_fs.default.existsSync(_path.default.join(cwd, 'web/tsconfig.json'))) { + _fs.default.renameSync(_path.default.join(cwd, 'web/tsconfig.json'), _path.default.join(cwd, 'web/jsconfig.json')); + } + if (_fs.default.existsSync(_path.default.join(cwd, 'scripts/tsconfig.json'))) { + _fs.default.renameSync(_path.default.join(cwd, 'scripts/tsconfig.json'), _path.default.join(cwd, 'scripts/jsconfig.json')); + } +}; + +/** + * Get all the source code from a Redwood project + */ +exports.convertTsFilesToJs = convertTsFilesToJs; +const typeScriptSourceFiles = (cwd, globPattern = '{api,web}/src/**/*.{ts,tsx}') => { + console.log(globPattern); + // TODO: When sides are expanded read the `api` and `web` string instead + // of hard-coding them. + return _fastGlob.default.sync(globPattern, { + cwd, + ignore: ['node_modules'] + }); +}; + +/** + * Read the contents of a TypeScript file, transpile it to JavaScript, + * but leave the JSX intact and format via Prettier. + * + * @param {string} file - The path to the TypeScript file. + */ +exports.typeScriptSourceFiles = typeScriptSourceFiles; +const transformTSToJS = file => { + const tsCode = _fs.default.readFileSync(file, 'utf8'); + const filename = _path.default.basename(file); + const result = (0, _core.transform)(tsCode, { + filename, + cwd: (0, _projectConfig.getPaths)().base, + configFile: false, + plugins: [['@babel/plugin-transform-typescript', { + isTSX: true, + allExtensions: true + }]], + retainLines: true + }); + if (!result?.code) { + return undefined; + } + return prettify(result.code, filename.replace(/\.ts$/, '.js')); +}; +exports.transformTSToJS = transformTSToJS; +const getPrettierConfig = async () => { + try { + const { + default: prettierConfig + } = await import(`file://${_path.default.join((0, _projectConfig.getPaths)().base, 'prettier.config.js')}`); + return prettierConfig; + } catch { + return undefined; + } +}; + +/** + * Determine the prettier parser based off of the extension. + * + * See: https://prettier.io/docs/en/options.html#parser + * @param {string} filename + */ +exports.getPrettierConfig = getPrettierConfig; +const prettierParser = filename => { + switch (_path.default.extname(filename.replace('.template', ''))) { + case '.css': + return 'css'; + case '.js': + return 'babel'; + case '.ts': + case '.tsx': + return 'babel-ts'; + default: + return undefined; + } +}; + +/** + * Prettify `code` according to the extension in `filename`. + * This will also read a user's `prettier.config.js` file if it exists. + * + * @param {string} code + * @param {string} filename + */ +const prettify = async (code, filename) => { + const parser = prettierParser(filename); + // Return unformatted code if we could not determine the parser. + if (typeof parser === 'undefined') { + return code; + } + const prettierConfig = await getPrettierConfig(); + return (0, _prettier.format)(code, { + ...prettierConfig, + parser + }); +}; +exports.prettify = prettify; \ No newline at end of file diff --git a/packages/internal/dist/validateSchema.d.ts b/packages/internal/dist/validateSchema.d.ts new file mode 100644 index 000000000000..4245885c343c --- /dev/null +++ b/packages/internal/dist/validateSchema.d.ts @@ -0,0 +1,14 @@ +import type { DocumentNode } from 'graphql'; +export declare const DIRECTIVE_REQUIRED_ERROR_MESSAGE = "You must specify one of @requireAuth, @skipAuth or a custom directive"; +export declare const DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE = "Please check that the requireAuth roles is a string or an array of strings."; +/** + * These are names that are commonly used in GraphQL schemas as scalars + * and would cause a conflict if used as a type name. + * + * Note: Query, Mutation, and Subscription are not included here because + * they are checked for separately. + */ +export declare const RESERVED_TYPES: string[]; +export declare function validateSchema(schemaDocumentNode: DocumentNode, typesToCheck?: string[]): void; +export declare const loadAndValidateSdls: () => Promise; +//# sourceMappingURL=validateSchema.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/validateSchema.d.ts.map b/packages/internal/dist/validateSchema.d.ts.map new file mode 100644 index 000000000000..4058f525fbba --- /dev/null +++ b/packages/internal/dist/validateSchema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"validateSchema.d.ts","sourceRoot":"","sources":["../src/validateSchema.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAA4B,MAAM,SAAS,CAAA;AAQrE,eAAO,MAAM,gCAAgC,0EAC4B,CAAA;AAEzE,eAAO,MAAM,0CAA0C,gFACwB,CAAA;AAE/E;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,UAS1B,CAAA;AAED,wBAAgB,cAAc,CAC5B,kBAAkB,EAAE,YAAY,EAChC,YAAY,GAAE,MAAM,EAA0B,QAmI/C;AAED,eAAO,MAAM,mBAAmB,qBAkC/B,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/validateSchema.js b/packages/internal/dist/validateSchema.js new file mode 100644 index 000000000000..8d4f71b3ce0f --- /dev/null +++ b/packages/internal/dist/validateSchema.js @@ -0,0 +1,158 @@ +"use strict"; + +var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); +var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; +_Object$defineProperty(exports, "__esModule", { + value: true +}); +exports.loadAndValidateSdls = exports.RESERVED_TYPES = exports.DIRECTIVE_REQUIRED_ERROR_MESSAGE = exports.DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE = void 0; +exports.validateSchema = validateSchema; +var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); +var _values = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/values")); +var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/for-each")); +var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); +var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); +var _values2 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/values")); +require("core-js/modules/es.array.push.js"); +var _codeFileLoader = require("@graphql-tools/code-file-loader"); +var _load = require("@graphql-tools/load"); +var _merge = require("@graphql-tools/merge"); +var _graphql = require("graphql"); +var _graphqlServer = require("@redwoodjs/graphql-server"); +var _projectConfig = require("@redwoodjs/project-config"); +var _project = require("./project"); +const DIRECTIVE_REQUIRED_ERROR_MESSAGE = exports.DIRECTIVE_REQUIRED_ERROR_MESSAGE = 'You must specify one of @requireAuth, @skipAuth or a custom directive'; +const DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE = exports.DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE = 'Please check that the requireAuth roles is a string or an array of strings.'; + +/** + * These are names that are commonly used in GraphQL schemas as scalars + * and would cause a conflict if used as a type name. + * + * Note: Query, Mutation, and Subscription are not included here because + * they are checked for separately. + */ +const RESERVED_TYPES = exports.RESERVED_TYPES = ['Int', 'Float', 'Boolean', 'String', 'DateTime', 'ID', 'uid', 'as']; +function validateSchema(schemaDocumentNode, typesToCheck = ['Query', 'Mutation']) { + const validationOutput = []; + const reservedNameValidationOutput = []; + const directiveRoleValidationOutput = []; + + // Is Subscriptions are enabled with Redwood Realtime, then enforce a rule + // that a Subscription type needs to have a authentication directive applied, + // just as Query and Mutation requires + if ((0, _project.isServerFileSetup)() && (0, _project.isRealtimeSetup)()) { + typesToCheck.push('Subscription'); + } + (0, _graphql.visit)(schemaDocumentNode, { + InterfaceTypeDefinition(typeNode) { + // Warn that an interface definition in the SDL is using a reserved GraphQL type + if ((0, _includes.default)(RESERVED_TYPES).call(RESERVED_TYPES, typeNode.name.value)) { + reservedNameValidationOutput.push({ + objectType: 'interface', + name: typeNode.name.value + }); + } + }, + InputObjectTypeDefinition(typeNode) { + // Warn that an input definition in the SDL is using a reserved GraphQL type + if ((0, _includes.default)(RESERVED_TYPES).call(RESERVED_TYPES, typeNode.name.value)) { + reservedNameValidationOutput.push({ + objectType: 'input type', + name: typeNode.name.value + }); + } + }, + ObjectTypeDefinition(typeNode) { + // Warn that a type definition in the SDL is using a reserved GraphQL type + if ((0, _includes.default)(RESERVED_TYPES).call(RESERVED_TYPES, typeNode.name.value)) { + reservedNameValidationOutput.push({ + objectType: 'type', + name: typeNode.name.value + }); + } + if ((0, _includes.default)(typesToCheck).call(typesToCheck, typeNode.name.value)) { + for (const field of typeNode.fields || []) { + const fieldName = field.name.value; + const fieldTypeName = typeNode.name.value; + const isRedwoodQuery = fieldName === 'redwood' && fieldTypeName === 'Query'; + const isCurrentUserQuery = fieldName === 'currentUser' && fieldTypeName === 'Query'; + // skip validation for redwood query and currentUser + if (!(isRedwoodQuery || isCurrentUserQuery)) { + const hasDirective = field.directives?.length; + if (!hasDirective) { + validationOutput.push(`${fieldName} ${fieldTypeName}`); + } + + // we want to check that the requireAuth directive roles argument value + // is a string or an array of strings + field.directives?.forEach(directive => { + if (directive.name.value === 'requireAuth') { + directive.arguments?.forEach(arg => { + if (arg.name.value === 'roles') { + if (arg.value.kind !== _graphql.Kind.STRING && arg.value.kind !== _graphql.Kind.LIST) { + directiveRoleValidationOutput.push({ + fieldName: fieldName, + invalid: arg.value.kind + }); + } + + // check list (array) + if (arg.value.kind === _graphql.Kind.LIST) { + const invalidValues = (0, _values.default)(arg.value)?.filter(val => val.kind !== _graphql.Kind.STRING); + if (invalidValues.length > 0) { + (0, _forEach.default)(invalidValues).call(invalidValues, invalid => { + directiveRoleValidationOutput.push({ + fieldName: fieldName, + invalid: invalid.kind + }); + }); + } + } + } + }); + } + }); + } + } + } + } + }); + if (validationOutput.length > 0) { + const fieldsWithoutDirectives = (0, _map.default)(validationOutput).call(validationOutput, field => `- ${field}`); + throw new Error(`${DIRECTIVE_REQUIRED_ERROR_MESSAGE} for\n${fieldsWithoutDirectives.join('\n')} \n`); + } + if (directiveRoleValidationOutput.length > 0) { + const fieldWithInvalidRoleValues = (0, _map.default)(directiveRoleValidationOutput).call(directiveRoleValidationOutput, field => `- ${field.fieldName} has an invalid ${field.invalid}`); + throw new RangeError(`${DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE}\n\n${fieldWithInvalidRoleValues.join('\n')} \n\nFor example: @requireAuth(roles: "admin") or @requireAuth(roles: ["admin", "editor"])`); + } + if (reservedNameValidationOutput.length > 0) { + const reservedNameMsg = (0, _map.default)(reservedNameValidationOutput).call(reservedNameValidationOutput, output => { + return `The ${output.objectType} named '${output.name}' is a reserved GraphQL name.\nPlease rename it to something more specific, like: Application${output.name}.\n`; + }); + throw new TypeError(reservedNameMsg.join('\n')); + } +} +const loadAndValidateSdls = async () => { + var _context, _context2; + const projectTypeSrc = await (0, _load.loadTypedefs)(['graphql/**/*.sdl.{js,ts}', 'directives/**/*.{js,ts}', 'subscriptions/**/*.{js,ts}'], { + loaders: [new _codeFileLoader.CodeFileLoader({ + noRequire: true, + pluckConfig: { + globalGqlIdentifierName: 'gql' + } + })], + cwd: (0, _projectConfig.getPaths)().api.src + }); + + // The output of the above function doesn't give us the documents directly + const projectDocumentNodes = (0, _filter.default)(_context = (0, _map.default)(_context2 = (0, _values2.default)(projectTypeSrc)).call(_context2, ({ + document + }) => document)).call(_context, documentNode => { + return !!documentNode; + }); + + // Merge in the rootSchema with JSON scalars, etc. + const mergedDocumentNode = (0, _merge.mergeTypeDefs)([_graphqlServer.rootSchema.schema, projectDocumentNodes]); + validateSchema(mergedDocumentNode); +}; +exports.loadAndValidateSdls = loadAndValidateSdls; \ No newline at end of file From 279c91f2ccaf66ecf86c6fd0ce7dd31d6c07dad7 Mon Sep 17 00:00:00 2001 From: Josh GM Walker <56300765+Josh-Walker-GM@users.noreply.github.com> Date: Sun, 18 Aug 2024 00:15:02 +0100 Subject: [PATCH 2/8] initial --- packages/internal/.babelrc.js | 1 - packages/internal/build.mts | 3 +++ packages/internal/package.json | 13 +++++++++---- packages/internal/tsconfig.json | 5 ++++- yarn.lock | 5 ++++- 5 files changed, 20 insertions(+), 7 deletions(-) delete mode 100644 packages/internal/.babelrc.js create mode 100644 packages/internal/build.mts diff --git a/packages/internal/.babelrc.js b/packages/internal/.babelrc.js deleted file mode 100644 index 3b2c815712d9..000000000000 --- a/packages/internal/.babelrc.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = { extends: '../../babel.config.js' } diff --git a/packages/internal/build.mts b/packages/internal/build.mts new file mode 100644 index 000000000000..16175a6725c0 --- /dev/null +++ b/packages/internal/build.mts @@ -0,0 +1,3 @@ +import { build } from '@redwoodjs/framework-tools' + +await build() diff --git a/packages/internal/package.json b/packages/internal/package.json index 21f7015e27f1..7c0b5de33279 100644 --- a/packages/internal/package.json +++ b/packages/internal/package.json @@ -7,6 +7,7 @@ "directory": "packages/internal" }, "license": "MIT", + "type": "commonjs", "main": "dist/index.js", "types": "dist/index.d.ts", "bin": { @@ -17,12 +18,13 @@ "dist" ], "scripts": { - "build": "yarn build:js && yarn build:types", + "build": "tsx ./build.mts && yarn build:types", "build:clean-dist": "rimraf 'dist/**/*/__tests__' --glob", - "build:js": "babel src -d dist --extensions \".js,.jsx,.ts,.tsx\" --copy-files --no-copy-ignored && yarn build:clean-dist", "build:pack": "yarn pack -o redwoodjs-internal.tgz", - "build:types": "tsc --build --verbose", + "build:types": "tsc --build --verbose ./tsconfig.json", "build:watch": "nodemon --watch src --ext \"js,jsx,ts,tsx\" --ignore dist --exec \"yarn build\"", + "check:attw": "yarn attw -P", + "check:package": "concurrently npm:check:attw yarn:publint", "fix:permissions": "chmod +x dist/generate/generate.js dist/generate/watch.js", "prepublishOnly": "NODE_ENV=production yarn build", "test": "vitest run", @@ -70,9 +72,12 @@ "typescript": "5.5.4" }, "devDependencies": { - "@babel/cli": "7.24.8", + "@arethetypeswrong/cli": "0.15.4", + "@redwoodjs/framework-tools": "workspace:*", "@types/fs-extra": "11.0.4", + "concurrently": "8.2.2", "graphql-tag": "2.12.6", + "publint": "0.2.10", "tsx": "4.17.0", "vitest": "2.0.5" }, diff --git a/packages/internal/tsconfig.json b/packages/internal/tsconfig.json index cbc1a3ef398c..e0ba04a6a84f 100644 --- a/packages/internal/tsconfig.json +++ b/packages/internal/tsconfig.json @@ -2,7 +2,10 @@ "extends": "../../tsconfig.compilerOption.json", "compilerOptions": { "rootDir": "src", - "outDir": "dist" + "outDir": "dist", + "module": "Node16", + "moduleResolution": "Node16", + "tsBuildInfoFile": "./tsconfig.tsbuildinfo" }, "include": ["src/**/*", "./ambient.d.ts"], "references": [ diff --git a/yarn.lock b/yarn.lock index 2c7089a52f68..a085359a165d 100644 --- a/yarn.lock +++ b/yarn.lock @@ -8213,7 +8213,7 @@ __metadata: version: 0.0.0-use.local resolution: "@redwoodjs/internal@workspace:packages/internal" dependencies: - "@babel/cli": "npm:7.24.8" + "@arethetypeswrong/cli": "npm:0.15.4" "@babel/core": "npm:^7.22.20" "@babel/parser": "npm:^7.22.16" "@babel/plugin-transform-react-jsx": "npm:^7.22.15" @@ -8233,12 +8233,14 @@ __metadata: "@graphql-codegen/typescript-resolvers": "npm:3.2.1" "@graphql-tools/documents": "npm:1.0.1" "@redwoodjs/babel-config": "workspace:*" + "@redwoodjs/framework-tools": "workspace:*" "@redwoodjs/graphql-server": "workspace:*" "@redwoodjs/project-config": "workspace:*" "@redwoodjs/router": "workspace:*" "@sdl-codegen/node": "npm:1.0.2" "@types/fs-extra": "npm:11.0.4" chalk: "npm:4.1.2" + concurrently: "npm:8.2.2" core-js: "npm:3.38.0" deepmerge: "npm:4.3.1" esbuild: "npm:0.23.0" @@ -8248,6 +8250,7 @@ __metadata: graphql-tag: "npm:2.12.6" kill-port: "npm:1.6.1" prettier: "npm:3.3.3" + publint: "npm:0.2.10" rimraf: "npm:6.0.1" source-map: "npm:0.7.4" string-env-interpolation: "npm:1.0.1" From d68cb5af6180b56caa420bea7296e2450caacdc2 Mon Sep 17 00:00:00 2001 From: Josh GM Walker <56300765+Josh-Walker-GM@users.noreply.github.com> Date: Sun, 18 Aug 2024 00:16:45 +0100 Subject: [PATCH 3/8] accept not including test content --- .../__snapshots__/graphqlCodeGen.test.ts.snap | 413 ------------------ .../__snapshots__/graphqlSchema.test.ts.snap | 130 ------ .../__snapshots__/possibleTypes.test.ts.snap | 17 - .../typeDefinitions.test.ts.snap | 36 -- ...alidateSchemaForReservedNames.test.ts.snap | 19 - .../fixtures/.redwood/schema.graphql | 31 -- .../bookshelf/api/db/schema.prisma | 21 - .../graphqlCodeGen/bookshelf/redwood.toml | 10 - .../invalidQueryType/.redwood/schema.graphql | 21 - .../invalidQueryType/redwood.toml | 2 - .../missingType/.redwood/schema.graphql | 25 -- .../graphqlCodeGen/missingType/redwood.toml | 2 - .../nonExistingField/.redwood/schema.graphql | 31 -- .../nonExistingField/redwood.toml | 2 - .../realtime/api/db/schema.prisma | 21 - .../graphqlCodeGen/realtime/redwood.toml | 10 - .../fixtures/nestedPages/redwood.toml | 16 - .../fixtures/nestedPages/web/src/index.html | 21 - .../__tests__/fixtures/redwood.empty.toml | 0 .../dist/__tests__/fixtures/redwood.toml | 2 - .../__tests__/fixtures/redwood.withEnv.toml | 9 - 21 files changed, 839 deletions(-) delete mode 100644 packages/internal/dist/__tests__/__snapshots__/graphqlCodeGen.test.ts.snap delete mode 100644 packages/internal/dist/__tests__/__snapshots__/graphqlSchema.test.ts.snap delete mode 100644 packages/internal/dist/__tests__/__snapshots__/possibleTypes.test.ts.snap delete mode 100644 packages/internal/dist/__tests__/__snapshots__/typeDefinitions.test.ts.snap delete mode 100644 packages/internal/dist/__tests__/__snapshots__/validateSchemaForReservedNames.test.ts.snap delete mode 100644 packages/internal/dist/__tests__/fixtures/.redwood/schema.graphql delete mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/api/db/schema.prisma delete mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/redwood.toml delete mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/.redwood/schema.graphql delete mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/redwood.toml delete mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/.redwood/schema.graphql delete mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/redwood.toml delete mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/.redwood/schema.graphql delete mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/redwood.toml delete mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/api/db/schema.prisma delete mode 100644 packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/redwood.toml delete mode 100644 packages/internal/dist/__tests__/fixtures/nestedPages/redwood.toml delete mode 100644 packages/internal/dist/__tests__/fixtures/nestedPages/web/src/index.html delete mode 100644 packages/internal/dist/__tests__/fixtures/redwood.empty.toml delete mode 100644 packages/internal/dist/__tests__/fixtures/redwood.toml delete mode 100644 packages/internal/dist/__tests__/fixtures/redwood.withEnv.toml diff --git a/packages/internal/dist/__tests__/__snapshots__/graphqlCodeGen.test.ts.snap b/packages/internal/dist/__tests__/__snapshots__/graphqlCodeGen.test.ts.snap deleted file mode 100644 index 71e17b80e5ca..000000000000 --- a/packages/internal/dist/__tests__/__snapshots__/graphqlCodeGen.test.ts.snap +++ /dev/null @@ -1,413 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`Generate gql typedefs api 1`] = ` -"import { Prisma } from "@prisma/client" -import { MergePrismaWithSdlTypes, MakeRelationsOptional } from '@redwoodjs/api' -import { PrismaModelOne as PrismaPrismaModelOne, PrismaModelTwo as PrismaPrismaModelTwo, Post as PrismaPost, Todo as PrismaTodo } from '@prisma/client' -import { GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig } from 'graphql'; -import { RedwoodGraphQLContext } from '@redwoodjs/graphql-server/dist/types'; -export type Maybe = T | null; -export type InputMaybe = Maybe; -export type Exact = { [K in keyof T]: T[K] }; -export type MakeOptional = Omit & { [SubKey in K]?: Maybe }; -export type MakeMaybe = Omit & { [SubKey in K]: Maybe }; -export type ResolverFn = ( - args?: TArgs, - obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } - ) => TResult | Promise -export type RequireFields = Omit & { [P in K]-?: NonNullable }; -export type OptArgsResolverFn = ( - args?: TArgs, - obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } - ) => TResult | Promise - - export type RequiredResolverFn = ( - args: TArgs, - obj: { root: TParent; context: TContext; info: GraphQLResolveInfo } - ) => TResult | Promise -/** All built-in and custom scalars, mapped to their actual values */ -export type Scalars = { - ID: string; - String: string; - Boolean: boolean; - Int: number; - Float: number; - BigInt: number; - Byte: Buffer; - Date: Date | string; - DateTime: Date | string; - JSON: Prisma.JsonValue; - JSONObject: Prisma.JsonObject; - Time: Date | string; -}; - -export type Mutation = { - __typename?: 'Mutation'; - createTodo?: Maybe; - renameTodo?: Maybe; - updateTodoStatus?: Maybe; -}; - - -export type MutationcreateTodoArgs = { - body: Scalars['String']; -}; - - -export type MutationrenameTodoArgs = { - body: Scalars['String']; - id: Scalars['Int']; -}; - - -export type MutationupdateTodoStatusArgs = { - id: Scalars['Int']; - status: Scalars['String']; -}; - -/** About the Redwood queries. */ -export type Query = { - __typename?: 'Query'; - currentUser?: Maybe; - /** Fetches the Redwood root schema. */ - redwood?: Maybe; - todos?: Maybe>>; - todosCount: Scalars['Int']; -}; - -/** - * The RedwoodJS Root Schema - * - * Defines details about RedwoodJS such as the current user and version information. - */ -export type Redwood = { - __typename?: 'Redwood'; - /** The current user. */ - currentUser?: Maybe; - /** The version of Prisma. */ - prismaVersion?: Maybe; - /** The version of Redwood. */ - version?: Maybe; -}; - -export type Todo = { - __typename?: 'Todo'; - body: Scalars['String']; - id: Scalars['Int']; - status: Scalars['String']; -}; - -type MaybeOrArrayOfMaybe = T | Maybe | Maybe[]; -type AllMappedModels = MaybeOrArrayOfMaybe - - -export type ResolverTypeWrapper = Promise | T; - -export type Resolver = ResolverFn; - -export type SubscriptionSubscribeFn = ( - parent: TParent, - args: TArgs, - context: TContext, - info: GraphQLResolveInfo -) => AsyncIterable | Promise>; - -export type SubscriptionResolveFn = ( - parent: TParent, - args: TArgs, - context: TContext, - info: GraphQLResolveInfo -) => TResult | Promise; - -export interface SubscriptionSubscriberObject { - subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>; - resolve?: SubscriptionResolveFn; -} - -export interface SubscriptionResolverObject { - subscribe: SubscriptionSubscribeFn; - resolve: SubscriptionResolveFn; -} - -export type SubscriptionObject = - | SubscriptionSubscriberObject - | SubscriptionResolverObject; - -export type SubscriptionResolver = - | ((...args: any[]) => SubscriptionObject) - | SubscriptionObject; - -export type TypeResolveFn = ( - parent: TParent, - context: TContext, - info: GraphQLResolveInfo -) => Maybe | Promise>; - -export type IsTypeOfResolverFn = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise; - -export type NextResolverFn = () => Promise; - -export type DirectiveResolverFn = ( - next: NextResolverFn, - parent: TParent, - args: TArgs, - context: TContext, - info: GraphQLResolveInfo -) => TResult | Promise; - - - -/** Mapping between all available schema types and the resolvers types */ -export type ResolversTypes = { - BigInt: ResolverTypeWrapper; - Boolean: ResolverTypeWrapper; - Byte: ResolverTypeWrapper; - Date: ResolverTypeWrapper; - DateTime: ResolverTypeWrapper; - Int: ResolverTypeWrapper; - JSON: ResolverTypeWrapper; - JSONObject: ResolverTypeWrapper; - Mutation: ResolverTypeWrapper<{}>; - Query: ResolverTypeWrapper<{}>; - Redwood: ResolverTypeWrapper; - String: ResolverTypeWrapper; - Time: ResolverTypeWrapper; - Todo: ResolverTypeWrapper, AllMappedModels>>; -}; - -/** Mapping between all available schema types and the resolvers parents */ -export type ResolversParentTypes = { - BigInt: Scalars['BigInt']; - Boolean: Scalars['Boolean']; - Byte: Scalars['Byte']; - Date: Scalars['Date']; - DateTime: Scalars['DateTime']; - Int: Scalars['Int']; - JSON: Scalars['JSON']; - JSONObject: Scalars['JSONObject']; - Mutation: {}; - Query: {}; - Redwood: Redwood; - String: Scalars['String']; - Time: Scalars['Time']; - Todo: MergePrismaWithSdlTypes, AllMappedModels>; -}; - -export type requireAuthDirectiveArgs = { - roles?: Maybe>>; -}; - -export type requireAuthDirectiveResolver = DirectiveResolverFn; - -export type skipAuthDirectiveArgs = { }; - -export type skipAuthDirectiveResolver = DirectiveResolverFn; - -export interface BigIntScalarConfig extends GraphQLScalarTypeConfig { - name: 'BigInt'; -} - -export interface ByteScalarConfig extends GraphQLScalarTypeConfig { - name: 'Byte'; -} - -export interface DateScalarConfig extends GraphQLScalarTypeConfig { - name: 'Date'; -} - -export interface DateTimeScalarConfig extends GraphQLScalarTypeConfig { - name: 'DateTime'; -} - -export interface JSONScalarConfig extends GraphQLScalarTypeConfig { - name: 'JSON'; -} - -export interface JSONObjectScalarConfig extends GraphQLScalarTypeConfig { - name: 'JSONObject'; -} - -export type MutationResolvers = { - createTodo: Resolver, ParentType, ContextType, RequireFields>; - renameTodo: Resolver, ParentType, ContextType, RequireFields>; - updateTodoStatus: Resolver, ParentType, ContextType, RequireFields>; -}; - -export type MutationRelationResolvers = { - createTodo?: RequiredResolverFn, ParentType, ContextType, RequireFields>; - renameTodo?: RequiredResolverFn, ParentType, ContextType, RequireFields>; - updateTodoStatus?: RequiredResolverFn, ParentType, ContextType, RequireFields>; -}; - -export type QueryResolvers = { - currentUser: OptArgsResolverFn, ParentType, ContextType>; - redwood: OptArgsResolverFn, ParentType, ContextType>; - todos: OptArgsResolverFn>>, ParentType, ContextType>; - todosCount: OptArgsResolverFn; -}; - -export type QueryRelationResolvers = { - currentUser?: RequiredResolverFn, ParentType, ContextType>; - redwood?: RequiredResolverFn, ParentType, ContextType>; - todos?: RequiredResolverFn>>, ParentType, ContextType>; - todosCount?: RequiredResolverFn; -}; - -export type RedwoodResolvers = { - currentUser: OptArgsResolverFn, ParentType, ContextType>; - prismaVersion: OptArgsResolverFn, ParentType, ContextType>; - version: OptArgsResolverFn, ParentType, ContextType>; - __isTypeOf?: IsTypeOfResolverFn; -}; - -export type RedwoodRelationResolvers = { - currentUser?: RequiredResolverFn, ParentType, ContextType>; - prismaVersion?: RequiredResolverFn, ParentType, ContextType>; - version?: RequiredResolverFn, ParentType, ContextType>; - __isTypeOf?: IsTypeOfResolverFn; -}; - -export interface TimeScalarConfig extends GraphQLScalarTypeConfig { - name: 'Time'; -} - -export type TodoResolvers = { - body: OptArgsResolverFn; - id: OptArgsResolverFn; - status: OptArgsResolverFn; - __isTypeOf?: IsTypeOfResolverFn; -}; - -export type TodoRelationResolvers = { - body?: RequiredResolverFn; - id?: RequiredResolverFn; - status?: RequiredResolverFn; - __isTypeOf?: IsTypeOfResolverFn; -}; - -export type Resolvers = { - BigInt: GraphQLScalarType; - Byte: GraphQLScalarType; - Date: GraphQLScalarType; - DateTime: GraphQLScalarType; - JSON: GraphQLScalarType; - JSONObject: GraphQLScalarType; - Mutation: MutationResolvers; - Query: QueryResolvers; - Redwood: RedwoodResolvers; - Time: GraphQLScalarType; - Todo: TodoResolvers; -}; - -export type DirectiveResolvers = { - requireAuth: requireAuthDirectiveResolver; - skipAuth: skipAuthDirectiveResolver; -}; -" -`; - -exports[`Generate gql typedefs web 1`] = ` -"import { Prisma } from "@prisma/client" -export type Maybe = T | null; -export type InputMaybe = Maybe; -export type Exact = { [K in keyof T]: T[K] }; -export type MakeOptional = Omit & { [SubKey in K]?: Maybe }; -export type MakeMaybe = Omit & { [SubKey in K]: Maybe }; -/** All built-in and custom scalars, mapped to their actual values */ -export type Scalars = { - ID: string; - String: string; - Boolean: boolean; - Int: number; - Float: number; - BigInt: number; - Byte: Buffer; - Date: string; - DateTime: string; - JSON: Prisma.JsonValue; - JSONObject: Prisma.JsonObject; - Time: string; -}; - -export type Mutation = { - __typename?: 'Mutation'; - createTodo?: Maybe; - renameTodo?: Maybe; - updateTodoStatus?: Maybe; -}; - - -export type MutationcreateTodoArgs = { - body: Scalars['String']; -}; - - -export type MutationrenameTodoArgs = { - body: Scalars['String']; - id: Scalars['Int']; -}; - - -export type MutationupdateTodoStatusArgs = { - id: Scalars['Int']; - status: Scalars['String']; -}; - -/** About the Redwood queries. */ -export type Query = { - __typename?: 'Query'; - currentUser?: Maybe; - /** Fetches the Redwood root schema. */ - redwood?: Maybe; - todos?: Maybe>>; - todosCount: Scalars['Int']; -}; - -/** - * The RedwoodJS Root Schema - * - * Defines details about RedwoodJS such as the current user and version information. - */ -export type Redwood = { - __typename?: 'Redwood'; - /** The current user. */ - currentUser?: Maybe; - /** The version of Prisma. */ - prismaVersion?: Maybe; - /** The version of Redwood. */ - version?: Maybe; -}; - -export type Todo = { - __typename?: 'Todo'; - body: Scalars['String']; - id: Scalars['Int']; - status: Scalars['String']; -}; - -export type AddTodo_CreateTodoVariables = Exact<{ - body: Scalars['String']; -}>; - - -export type AddTodo_CreateTodo = { __typename?: 'Mutation', createTodo?: { __typename: 'Todo', id: number, body: string, status: string } | null }; - -export type NumTodosCell_GetCountVariables = Exact<{ [key: string]: never; }>; - - -export type NumTodosCell_GetCount = { __typename?: 'Query', todosCount: number }; - -export type TodoListCell_GetTodosVariables = Exact<{ [key: string]: never; }>; - - -export type TodoListCell_GetTodos = { __typename?: 'Query', todos?: Array<{ __typename?: 'Todo', id: number, body: string, status: string } | null> | null }; - -export type TodoListCell_CheckTodoVariables = Exact<{ - id: Scalars['Int']; - status: Scalars['String']; -}>; - - -export type TodoListCell_CheckTodo = { __typename?: 'Mutation', updateTodoStatus?: { __typename: 'Todo', id: number, status: string } | null }; -" -`; diff --git a/packages/internal/dist/__tests__/__snapshots__/graphqlSchema.test.ts.snap b/packages/internal/dist/__tests__/__snapshots__/graphqlSchema.test.ts.snap deleted file mode 100644 index 32dbd0c8536b..000000000000 --- a/packages/internal/dist/__tests__/__snapshots__/graphqlSchema.test.ts.snap +++ /dev/null @@ -1,130 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`Generates GraphQL schema 1`] = ` -"directive @requireAuth(roles: [String]) on FIELD_DEFINITION - -directive @skipAuth on FIELD_DEFINITION - -scalar BigInt - -scalar Byte - -scalar Date - -scalar DateTime - -scalar JSON - -scalar JSONObject - -type Mutation { - createTodo(body: String!): Todo - renameTodo(body: String!, id: Int!): Todo - updateTodoStatus(id: Int!, status: String!): Todo -} - -"""About the Redwood queries.""" -type Query { - currentUser: JSON - - """Fetches the Redwood root schema.""" - redwood: Redwood - todos: [Todo] - todosCount: Int! -} - -""" -The RedwoodJS Root Schema - -Defines details about RedwoodJS such as the current user and version information. -""" -type Redwood { - """The current user.""" - currentUser: JSON - - """The version of Prisma.""" - prismaVersion: String - - """The version of Redwood.""" - version: String -} - -scalar Time - -type Todo { - body: String! - id: Int! - status: String! -}" -`; - -exports[`Includes live query directive if serverful and realtime 1`] = ` -"""" -Instruction for establishing a live connection that is updated once the underlying data changes. -""" -directive @live( - """Whether the query should be live or not.""" - if: Boolean = true - - """ - Propose a desired throttle interval ot the server in order to receive updates to at most once per "throttle" milliseconds. The server must not accept this value. - """ - throttle: Int -) on QUERY - -directive @requireAuth(roles: [String]) on FIELD_DEFINITION - -directive @skipAuth on FIELD_DEFINITION - -scalar BigInt - -scalar Byte - -scalar Date - -scalar DateTime - -scalar JSON - -scalar JSONObject - -type Mutation { - createTodo(body: String!): Todo - renameTodo(body: String!, id: Int!): Todo - updateTodoStatus(id: Int!, status: String!): Todo -} - -"""About the Redwood queries.""" -type Query { - currentUser: JSON - - """Fetches the Redwood root schema.""" - redwood: Redwood - todos: [Todo] - todosCount: Int! -} - -""" -The RedwoodJS Root Schema - -Defines details about RedwoodJS such as the current user and version information. -""" -type Redwood { - """The current user.""" - currentUser: JSON - - """The version of Prisma.""" - prismaVersion: String - - """The version of Redwood.""" - version: String -} - -scalar Time - -type Todo { - body: String! - id: Int! - status: String! -}" -`; diff --git a/packages/internal/dist/__tests__/__snapshots__/possibleTypes.test.ts.snap b/packages/internal/dist/__tests__/__snapshots__/possibleTypes.test.ts.snap deleted file mode 100644 index d4225af91356..000000000000 --- a/packages/internal/dist/__tests__/__snapshots__/possibleTypes.test.ts.snap +++ /dev/null @@ -1,17 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`Generate gql possible types web from the GraphQL Schema > when toml has graphql possible types turned om > when there are union types 1`] = ` -"export interface PossibleTypesResultData { - possibleTypes: { - [key: string]: string[] - } -} -const result: PossibleTypesResultData = { - possibleTypes: { - Groceries: ['Fruit', 'Vegetable'], - Grocery: ['Fruit', 'Vegetable'], - }, -} -export default result -" -`; diff --git a/packages/internal/dist/__tests__/__snapshots__/typeDefinitions.test.ts.snap b/packages/internal/dist/__tests__/__snapshots__/typeDefinitions.test.ts.snap deleted file mode 100644 index 5e448ff75f3c..000000000000 --- a/packages/internal/dist/__tests__/__snapshots__/typeDefinitions.test.ts.snap +++ /dev/null @@ -1,36 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`generates global page imports source maps 1`] = ` -{ - "file": "web-routesPages.d.ts", - "mappings": ";;;;;;;;;;;;AAAA;ACQA;ACRA;ACKA;ACLA;ACAA;ACAA;ACAA", - "names": [], - "sources": [ - "../../../web/src/pages/BarPage/BarPage.tsx", - "../../../web/src/pages/FatalErrorPage/FatalErrorPage.js", - "../../../web/src/pages/FooPage/FooPage.tsx", - "../../../web/src/pages/HomePage/HomePage.tsx", - "../../../web/src/pages/NotFoundPage/NotFoundPage.js", - "../../../web/src/pages/PrivatePage/PrivatePage.tsx", - "../../../web/src/pages/TypeScriptPage/TypeScriptPage.tsx", - "../../../web/src/pages/admin/EditUserPage/EditUserPage.jsx", - ], - "version": 3, -} -`; - -exports[`generates source maps for the router routes 1`] = ` -{ - "file": "web-routerRoutes.d.ts", - "mappings": ";;;;;;IAiBM;IACA;IACA;IAEE;IACA;IAGA;IAGA;IAGA", - "names": [], - "sources": [ - "../../../web/src/Routes.js", - ], - "version": 3, -} -`; - -exports[`mirror path for directory named modules 1`] = `".redwood/types/mirror/web/src/graphql"`; - -exports[`mirror path for directory named modules 2`] = `"../../packages/internal/index.d.ts"`; diff --git a/packages/internal/dist/__tests__/__snapshots__/validateSchemaForReservedNames.test.ts.snap b/packages/internal/dist/__tests__/__snapshots__/validateSchemaForReservedNames.test.ts.snap deleted file mode 100644 index 5b84a5cbec47..000000000000 --- a/packages/internal/dist/__tests__/__snapshots__/validateSchemaForReservedNames.test.ts.snap +++ /dev/null @@ -1,19 +0,0 @@ -// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html - -exports[`SDL with no reserved names used > SDL is invalid > because uses a reserved name as a type 1`] = ` -[TypeError: The type named 'Float' is a reserved GraphQL name. -Please rename it to something more specific, like: ApplicationFloat. -] -`; - -exports[`SDL with no reserved names used > because uses a reserved name as an input 1`] = ` -[TypeError: The input type named 'Float' is a reserved GraphQL name. -Please rename it to something more specific, like: ApplicationFloat. -] -`; - -exports[`SDL with no reserved names used > because uses a reserved name as an interface 1`] = ` -[TypeError: The interface named 'Float' is a reserved GraphQL name. -Please rename it to something more specific, like: ApplicationFloat. -] -`; diff --git a/packages/internal/dist/__tests__/fixtures/.redwood/schema.graphql b/packages/internal/dist/__tests__/fixtures/.redwood/schema.graphql deleted file mode 100644 index 58b0ebd56fe0..000000000000 --- a/packages/internal/dist/__tests__/fixtures/.redwood/schema.graphql +++ /dev/null @@ -1,31 +0,0 @@ -scalar BigInt - -scalar Date - -scalar DateTime - -scalar JSON - -scalar JSONObject - -type Mutation { - createTodo(body: String!): Todo -} - -type Query { - redwood: Redwood -} - -type Redwood { - currentUser: JSON - prismaVersion: String - version: String -} - -scalar Time - -type Todo { - body: String! - id: Int! - status: String! -} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/api/db/schema.prisma b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/api/db/schema.prisma deleted file mode 100644 index 86078a61db0f..000000000000 --- a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/api/db/schema.prisma +++ /dev/null @@ -1,21 +0,0 @@ -datasource sqlite { - url = "file:./dev.sqlite" - provider = "sqlite" -} - -generator photonjs { - provider = "prisma-client-js" -} - -model Book { - id Int @id @default(autoincrement()) - title String @unique - Shelf Shelf? @relation(fields: [shelfId], references: [id]) - shelfId Int? -} - -model Shelf { - id Int @id @default(autoincrement()) - name String @unique - books Book[] -} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/redwood.toml b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/redwood.toml deleted file mode 100644 index f68d0d5de4db..000000000000 --- a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/bookshelf/redwood.toml +++ /dev/null @@ -1,10 +0,0 @@ -[web] - port = 8910 - apiProxyPath = "/api/functions" - -[api] - port = 8911 - [api.paths] - functions = './api/src/functions' - graphql = './api/src/graphql' - generated = './api/generated' diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/.redwood/schema.graphql b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/.redwood/schema.graphql deleted file mode 100644 index 911f3095cc3c..000000000000 --- a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/.redwood/schema.graphql +++ /dev/null @@ -1,21 +0,0 @@ -scalar BigInt - -scalar Date - -scalar DateTime - -scalar JSON - -scalar JSONObject - -scalar Time - -type Query { - redwood: Redwood -} - -type Redwood { - currentUser: JSON - prismaVersion: String - version: String -} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/redwood.toml b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/redwood.toml deleted file mode 100644 index efd2d2d4d26e..000000000000 --- a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/invalidQueryType/redwood.toml +++ /dev/null @@ -1,2 +0,0 @@ -[web] - port = 8910 diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/.redwood/schema.graphql b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/.redwood/schema.graphql deleted file mode 100644 index 2fb83f8e2c30..000000000000 --- a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/.redwood/schema.graphql +++ /dev/null @@ -1,25 +0,0 @@ -scalar BigInt - -scalar Date - -scalar DateTime - -scalar JSON - -scalar JSONObject - -scalar Time - -type Mutation { - createTodo(body: String!): Todo -} - -type Query { - redwood: Redwood -} - -type Redwood { - currentUser: JSON - prismaVersion: String - version: String -} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/redwood.toml b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/redwood.toml deleted file mode 100644 index efd2d2d4d26e..000000000000 --- a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/missingType/redwood.toml +++ /dev/null @@ -1,2 +0,0 @@ -[web] - port = 8910 diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/.redwood/schema.graphql b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/.redwood/schema.graphql deleted file mode 100644 index 0c301b6ddb26..000000000000 --- a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/.redwood/schema.graphql +++ /dev/null @@ -1,31 +0,0 @@ -scalar BigInt - -scalar Date - -scalar DateTime - -scalar JSON - -scalar JSONObject - -scalar Time - -type Mutation { - createTodo(body: String!): Todo -} - -type Query { - redwood: Redwood -} - -type Redwood { - currentUser: JSON - prismaVersion: String - version: String -} - -type Todo { - id: String! - task: String! - # done: Boolean -} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/redwood.toml b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/redwood.toml deleted file mode 100644 index efd2d2d4d26e..000000000000 --- a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/nonExistingField/redwood.toml +++ /dev/null @@ -1,2 +0,0 @@ -[web] - port = 8910 diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/api/db/schema.prisma b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/api/db/schema.prisma deleted file mode 100644 index 86078a61db0f..000000000000 --- a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/api/db/schema.prisma +++ /dev/null @@ -1,21 +0,0 @@ -datasource sqlite { - url = "file:./dev.sqlite" - provider = "sqlite" -} - -generator photonjs { - provider = "prisma-client-js" -} - -model Book { - id Int @id @default(autoincrement()) - title String @unique - Shelf Shelf? @relation(fields: [shelfId], references: [id]) - shelfId Int? -} - -model Shelf { - id Int @id @default(autoincrement()) - name String @unique - books Book[] -} diff --git a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/redwood.toml b/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/redwood.toml deleted file mode 100644 index f68d0d5de4db..000000000000 --- a/packages/internal/dist/__tests__/fixtures/graphqlCodeGen/realtime/redwood.toml +++ /dev/null @@ -1,10 +0,0 @@ -[web] - port = 8910 - apiProxyPath = "/api/functions" - -[api] - port = 8911 - [api.paths] - functions = './api/src/functions' - graphql = './api/src/graphql' - generated = './api/generated' diff --git a/packages/internal/dist/__tests__/fixtures/nestedPages/redwood.toml b/packages/internal/dist/__tests__/fixtures/nestedPages/redwood.toml deleted file mode 100644 index 2b820da9bd63..000000000000 --- a/packages/internal/dist/__tests__/fixtures/nestedPages/redwood.toml +++ /dev/null @@ -1,16 +0,0 @@ -# This file contains the configuration settings for your Redwood app. -# This file is also what makes your Redwood app a Redwood app. -# If you remove it and try to run `yarn rw dev`, you'll get an error. -# -# For the full list of options, see the "App Configuration: redwood.toml" doc: -# https://redwoodjs.com/docs/app-configuration-redwood-toml - -[web] - title = "RedwoodJS.com" - port = 8910 - apiUrl = "/.netlify/functions" - includeEnvironmentVariables = [] # any ENV vars that should be available to the web side, see https://redwoodjs.com/docs/environment-variables#web -[api] - port = 8911 -[browser] - open = true diff --git a/packages/internal/dist/__tests__/fixtures/nestedPages/web/src/index.html b/packages/internal/dist/__tests__/fixtures/nestedPages/web/src/index.html deleted file mode 100644 index 902339287ed9..000000000000 --- a/packages/internal/dist/__tests__/fixtures/nestedPages/web/src/index.html +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - -
- - <%= prerenderPlaceholder %> -
- - - diff --git a/packages/internal/dist/__tests__/fixtures/redwood.empty.toml b/packages/internal/dist/__tests__/fixtures/redwood.empty.toml deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/packages/internal/dist/__tests__/fixtures/redwood.toml b/packages/internal/dist/__tests__/fixtures/redwood.toml deleted file mode 100644 index 4d99ef23dee6..000000000000 --- a/packages/internal/dist/__tests__/fixtures/redwood.toml +++ /dev/null @@ -1,2 +0,0 @@ -[web] - port = 8888 \ No newline at end of file diff --git a/packages/internal/dist/__tests__/fixtures/redwood.withEnv.toml b/packages/internal/dist/__tests__/fixtures/redwood.withEnv.toml deleted file mode 100644 index 04c024ecf53c..000000000000 --- a/packages/internal/dist/__tests__/fixtures/redwood.withEnv.toml +++ /dev/null @@ -1,9 +0,0 @@ -[web] - title = "App running on ${APP_ENV}" - port = "${PORT:8910}" - apiUrl = "${API_URL:/.redwood/functions}" # you can customise graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths - includeEnvironmentVariables = [] # any ENV vars that should be available to the web side, see https://redwoodjs.com/docs/environment-variables#web -[api] - port = 8911 -[browser] - open = true From 69bf57abda33c968b27c2780455fd58faf0a8593 Mon Sep 17 00:00:00 2001 From: Josh GM Walker <56300765+Josh-Walker-GM@users.noreply.github.com> Date: Sun, 18 Aug 2024 00:46:50 +0100 Subject: [PATCH 4/8] modified dist --- packages/internal/dist/ast.js | 190 ++++---- packages/internal/dist/build/api.js | 113 +++-- packages/internal/dist/cliLogger.js | 48 +- packages/internal/dist/dev.js | 48 +- packages/internal/dist/files.js | 308 ++++++------ .../internal/dist/generate/clientPreset.js | 73 +-- packages/internal/dist/generate/generate.js | 104 ++-- .../internal/dist/generate/graphqlCodeGen.js | 352 +++++++------- .../internal/dist/generate/graphqlSchema.js | 151 +++--- .../plugins/rw-typescript-resolvers/index.js | 121 ++--- .../rw-typescript-resolvers/visitor.js | 133 +++-- .../internal/dist/generate/possibleTypes.js | 129 +++-- packages/internal/dist/generate/templates.js | 73 ++- .../dist/generate/trustedDocuments.js | 111 +++-- .../internal/dist/generate/typeDefinitions.js | 454 +++++++++--------- packages/internal/dist/generate/types.js | 20 +- packages/internal/dist/generate/watch.js | 169 ++++--- packages/internal/dist/gql.js | 106 ++-- packages/internal/dist/index.js | 160 ++---- packages/internal/dist/jsx.js | 103 ++-- packages/internal/dist/jsxAttributeValue.js | 134 +++--- packages/internal/dist/project.js | 93 +++- packages/internal/dist/routes.js | 143 +++--- packages/internal/dist/ts2js.js | 219 ++++----- packages/internal/dist/validateSchema.js | 225 +++++---- 25 files changed, 1990 insertions(+), 1790 deletions(-) diff --git a/packages/internal/dist/ast.js b/packages/internal/dist/ast.js index 43d80c175c46..5fd5084e598f 100644 --- a/packages/internal/dist/ast.js +++ b/packages/internal/dist/ast.js @@ -1,57 +1,80 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var ast_exports = {}; +__export(ast_exports, { + fileToAst: () => fileToAst, + getCellGqlQuery: () => getCellGqlQuery, + getDefaultExportLocation: () => getDefaultExportLocation, + getGqlQueries: () => getGqlQueries, + getNamedExports: () => getNamedExports, + hasDefaultExport: () => hasDefaultExport }); -exports.hasDefaultExport = exports.getNamedExports = exports.getGqlQueries = exports.getDefaultExportLocation = exports.getCellGqlQuery = exports.fileToAst = void 0; -require("core-js/modules/es.array.push.js"); -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/find")); -var _fs = _interopRequireDefault(require("fs")); -var _path = _interopRequireDefault(require("path")); -var _core = require("@babel/core"); -var _parser = require("@babel/parser"); -var _traverse = _interopRequireDefault(require("@babel/traverse")); -var _chalk = _interopRequireDefault(require("chalk")); -var _projectConfig = require("@redwoodjs/project-config"); -var _files = require("./files"); -const fileToAst = filePath => { - var _context; - const code = _fs.default.readFileSync(filePath, 'utf-8'); - - // use jsx plugin for web files, because in JS, the .jsx extension is not used - const isJsxFile = _path.default.extname(filePath).match(/[jt]sx$/) || (0, _files.isFileInsideFolder)(filePath, (0, _projectConfig.getPaths)().web.base); - const plugins = (0, _filter.default)(_context = ['typescript', 'nullishCoalescingOperator', 'objectRestSpread', isJsxFile && 'jsx']).call(_context, Boolean); +module.exports = __toCommonJS(ast_exports); +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var import_core = require("@babel/core"); +var import_parser = require("@babel/parser"); +var import_traverse = __toESM(require("@babel/traverse")); +var import_chalk = __toESM(require("chalk")); +var import_project_config = require("@redwoodjs/project-config"); +var import_files = require("./files"); +const fileToAst = (filePath) => { + const code = import_fs.default.readFileSync(filePath, "utf-8"); + const isJsxFile = import_path.default.extname(filePath).match(/[jt]sx$/) || (0, import_files.isFileInsideFolder)(filePath, (0, import_project_config.getPaths)().web.base); + const plugins = [ + "typescript", + "nullishCoalescingOperator", + "objectRestSpread", + isJsxFile && "jsx" + ].filter(Boolean); try { - return (0, _parser.parse)(code, { - sourceType: 'module', + return (0, import_parser.parse)(code, { + sourceType: "module", plugins }); } catch (e) { - console.error(_chalk.default.red(`Error parsing: ${filePath}`)); + console.error(import_chalk.default.red(`Error parsing: ${filePath}`)); console.error(e); - throw new Error(e?.message); // we throw, so typescript doesn't complain about returning + throw new Error(e?.message); } }; -exports.fileToAst = fileToAst; -/** - * get all the named exports in a given piece of code. - */ -const getNamedExports = ast => { +const getNamedExports = (ast) => { const namedExports = []; - (0, _traverse.default)(ast, { - ExportNamedDeclaration(path) { - // Re-exports from other modules - // Eg: export { a, b } from './module' - const specifiers = path.node?.specifiers; + (0, import_traverse.default)(ast, { + ExportNamedDeclaration(path2) { + const specifiers = path2.node?.specifiers; if (specifiers.length) { for (const s of specifiers) { const id = s.exported; namedExports.push({ name: id.name, - type: 're-export', + type: "re-export", location: { line: id.loc?.start.line ?? 1, column: id.loc?.start.column ?? 0 @@ -60,33 +83,33 @@ const getNamedExports = ast => { } return; } - const declaration = path.node.declaration; + const declaration = path2.node.declaration; if (!declaration) { return; } - if (declaration.type === 'VariableDeclaration') { + if (declaration.type === "VariableDeclaration") { const id = declaration.declarations[0].id; namedExports.push({ name: id.name, - type: 'variable', + type: "variable", location: { line: id.loc?.start.line ?? 1, column: id.loc?.start.column ?? 0 } }); - } else if (declaration.type === 'FunctionDeclaration') { + } else if (declaration.type === "FunctionDeclaration") { namedExports.push({ name: declaration?.id?.name, - type: 'function', + type: "function", location: { line: declaration?.id?.loc?.start.line ?? 1, column: declaration?.id?.loc?.start.column ?? 0 } }); - } else if (declaration.type === 'ClassDeclaration') { + } else if (declaration.type === "ClassDeclaration") { namedExports.push({ name: declaration?.id?.name, - type: 'class', + type: "class", location: { line: declaration?.id?.loc?.start.line ?? 1, column: declaration?.id?.loc?.start.column ?? 0 @@ -97,34 +120,25 @@ const getNamedExports = ast => { }); return namedExports; }; - -/** - * get all the gql queries from the supplied code - */ -exports.getNamedExports = getNamedExports; -const getGqlQueries = ast => { +const getGqlQueries = (ast) => { const gqlQueries = []; - (0, _traverse.default)(ast, { - TaggedTemplateExpression(path) { - const gqlTag = path.node.tag; - if (gqlTag.type === 'Identifier' && gqlTag.name === 'gql') { - gqlQueries.push(path.node.quasi.quasis[0].value.raw); + (0, import_traverse.default)(ast, { + TaggedTemplateExpression(path2) { + const gqlTag = path2.node.tag; + if (gqlTag.type === "Identifier" && gqlTag.name === "gql") { + gqlQueries.push(path2.node.quasi.quasis[0].value.raw); } } }); return gqlQueries; }; -exports.getGqlQueries = getGqlQueries; -const getCellGqlQuery = ast => { - let cellQuery = undefined; - (0, _traverse.default)(ast, { - ExportNamedDeclaration({ - node - }) { - if (node.exportKind === 'value' && _core.types.isVariableDeclaration(node.declaration)) { - var _context2; - const exportedQueryNode = (0, _find.default)(_context2 = node.declaration.declarations).call(_context2, d => { - return _core.types.isIdentifier(d.id) && d.id.name === 'QUERY' && _core.types.isTaggedTemplateExpression(d.init); +const getCellGqlQuery = (ast) => { + let cellQuery = void 0; + (0, import_traverse.default)(ast, { + ExportNamedDeclaration({ node }) { + if (node.exportKind === "value" && import_core.types.isVariableDeclaration(node.declaration)) { + const exportedQueryNode = node.declaration.declarations.find((d) => { + return import_core.types.isIdentifier(d.id) && d.id.name === "QUERY" && import_core.types.isTaggedTemplateExpression(d.init); }); if (exportedQueryNode) { const templateExpression = exportedQueryNode.init; @@ -136,10 +150,9 @@ const getCellGqlQuery = ast => { }); return cellQuery; }; -exports.getCellGqlQuery = getCellGqlQuery; -const hasDefaultExport = ast => { +const hasDefaultExport = (ast) => { let exported = false; - (0, _traverse.default)(ast, { + (0, import_traverse.default)(ast, { ExportDefaultDeclaration() { exported = true; return; @@ -147,30 +160,21 @@ const hasDefaultExport = ast => { }); return exported; }; -exports.hasDefaultExport = hasDefaultExport; -const getDefaultExportLocation = ast => { - // Get the default export +const getDefaultExportLocation = (ast) => { let defaultExport; - (0, _traverse.default)(ast, { - ExportDefaultDeclaration(path) { - defaultExport = path.node; + (0, import_traverse.default)(ast, { + ExportDefaultDeclaration(path2) { + defaultExport = path2.node; } }); if (!defaultExport) { return null; } - - // Handle the case were we're exporting a variable declared elsewhere - // as we will want to find the location of that declaration instead - if (_core.types.isIdentifier(defaultExport.declaration) && _core.types.isFile(ast)) { - var _context3; - // Directly search the program body for the declaration of the identifier - // to avoid picking up other identifiers with the same name in the file + if (import_core.types.isIdentifier(defaultExport.declaration) && import_core.types.isFile(ast)) { const exportedName = defaultExport.declaration.name; - const declaration = (0, _find.default)(_context3 = ast.program.body).call(_context3, node => { - var _context4; - return _core.types.isVariableDeclaration(node) && (0, _find.default)(_context4 = node.declarations).call(_context4, d => { - return _core.types.isVariableDeclarator(d) && _core.types.isIdentifier(d.id) && d.id.name === exportedName; + const declaration = ast.program.body.find((node) => { + return import_core.types.isVariableDeclaration(node) && node.declarations.find((d) => { + return import_core.types.isVariableDeclarator(d) && import_core.types.isIdentifier(d.id) && d.id.name === exportedName; }); }); return { @@ -183,4 +187,12 @@ const getDefaultExportLocation = ast => { column: defaultExport.loc?.start.column ?? 0 }; }; -exports.getDefaultExportLocation = getDefaultExportLocation; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + fileToAst, + getCellGqlQuery, + getDefaultExportLocation, + getGqlQueries, + getNamedExports, + hasDefaultExport +}); diff --git a/packages/internal/dist/build/api.js b/packages/internal/dist/build/api.js index 2aed9d2e083a..f295df5c4846 100644 --- a/packages/internal/dist/build/api.js +++ b/packages/internal/dist/build/api.js @@ -1,74 +1,94 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var api_exports = {}; +__export(api_exports, { + buildApi: () => buildApi, + cleanApiBuild: () => cleanApiBuild, + rebuildApi: () => rebuildApi, + transpileApi: () => transpileApi }); -exports.transpileApi = exports.rebuildApi = exports.cleanApiBuild = exports.buildApi = void 0; -var _esbuild = require("esbuild"); -var _fsExtra = _interopRequireDefault(require("fs-extra")); -var _babelConfig = require("@redwoodjs/babel-config"); -var _projectConfig = require("@redwoodjs/project-config"); -var _files = require("../files"); +module.exports = __toCommonJS(api_exports); +var import_esbuild = require("esbuild"); +var import_fs_extra = __toESM(require("fs-extra")); +var import_babel_config = require("@redwoodjs/babel-config"); +var import_project_config = require("@redwoodjs/project-config"); +var import_files = require("../files"); let BUILD_CTX = null; const buildApi = async () => { - // Reset the build context for rebuilding - // No need to wait for promise to resolve BUILD_CTX?.dispose(); BUILD_CTX = null; - return transpileApi((0, _files.findApiFiles)()); + return transpileApi((0, import_files.findApiFiles)()); }; -exports.buildApi = buildApi; const rebuildApi = async () => { - const apiFiles = (0, _files.findApiFiles)(); + const apiFiles = (0, import_files.findApiFiles)(); if (!BUILD_CTX) { - BUILD_CTX = await (0, _esbuild.context)(getEsbuildOptions(apiFiles)); + BUILD_CTX = await (0, import_esbuild.context)(getEsbuildOptions(apiFiles)); } return BUILD_CTX.rebuild(); }; -exports.rebuildApi = rebuildApi; const cleanApiBuild = async () => { - const rwjsPaths = (0, _projectConfig.getPaths)(); - return _fsExtra.default.remove(rwjsPaths.api.dist); + const rwjsPaths = (0, import_project_config.getPaths)(); + return import_fs_extra.default.remove(rwjsPaths.api.dist); }; -exports.cleanApiBuild = cleanApiBuild; const runRwBabelTransformsPlugin = { - name: 'rw-esbuild-babel-transform', - setup(build) { - const rwjsConfig = (0, _projectConfig.getConfig)(); - build.onLoad({ - filter: /\.(js|ts|tsx|jsx)$/ - }, async args => { - // @TODO Implement LRU cache? Unsure how much of a performance benefit its going to be - // Generate a CRC of file contents, then save it to LRU cache with a limit - // without LRU cache, the memory usage can become unbound - const transformedCode = await (0, _babelConfig.transformWithBabel)(args.path, (0, _babelConfig.getApiSideBabelPlugins)({ - openTelemetry: rwjsConfig.experimental.opentelemetry.enabled && rwjsConfig.experimental.opentelemetry.wrapApi, - projectIsEsm: (0, _projectConfig.projectSideIsEsm)('api') - })); + name: "rw-esbuild-babel-transform", + setup(build2) { + const rwjsConfig = (0, import_project_config.getConfig)(); + build2.onLoad({ filter: /\.(js|ts|tsx|jsx)$/ }, async (args) => { + const transformedCode = await (0, import_babel_config.transformWithBabel)( + args.path, + (0, import_babel_config.getApiSideBabelPlugins)({ + openTelemetry: rwjsConfig.experimental.opentelemetry.enabled && rwjsConfig.experimental.opentelemetry.wrapApi, + projectIsEsm: (0, import_project_config.projectSideIsEsm)("api") + }) + ); if (transformedCode?.code) { return { contents: transformedCode.code, - loader: 'js' + loader: "js" }; } throw new Error(`Could not transform file: ${args.path}`); }); } }; -const transpileApi = async files => { - return (0, _esbuild.build)(getEsbuildOptions(files)); +const transpileApi = async (files) => { + return (0, import_esbuild.build)(getEsbuildOptions(files)); }; -exports.transpileApi = transpileApi; function getEsbuildOptions(files) { - const rwjsPaths = (0, _projectConfig.getPaths)(); - const format = (0, _projectConfig.projectSideIsEsm)('api') ? 'esm' : 'cjs'; + const rwjsPaths = (0, import_project_config.getPaths)(); + const format = (0, import_project_config.projectSideIsEsm)("api") ? "esm" : "cjs"; return { absWorkingDir: rwjsPaths.api.base, entryPoints: files, - platform: 'node', - target: 'node20', + platform: "node", + target: "node20", format, allowOverwrite: true, bundle: false, @@ -79,4 +99,11 @@ function getEsbuildOptions(files) { // (setting it to 'external' will ONLY generate the file, but won't add the comment) sourcemap: true }; -} \ No newline at end of file +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + buildApi, + cleanApiBuild, + rebuildApi, + transpileApi +}); diff --git a/packages/internal/dist/cliLogger.js b/packages/internal/dist/cliLogger.js index 4e904834e85e..afb16b610b84 100644 --- a/packages/internal/dist/cliLogger.js +++ b/packages/internal/dist/cliLogger.js @@ -1,20 +1,36 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -_Object$defineProperty(exports, "__esModule", { - value: true +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var cliLogger_exports = {}; +__export(cliLogger_exports, { + cliLogger: () => cliLogger }); -exports.cliLogger = void 0; -var _logger = require("@redwoodjs/api/logger"); -// Can't use color in the createLogger logger - so use a simpler set of log fns -const logLevel = _logger.defaultLoggerOptions.level; -/** - * An alternative to createLogger which supports the same logging levels - * but allows for full ANSI when printing to the console. - */ -const cliLogger = function (...data) { +module.exports = __toCommonJS(cliLogger_exports); +var import_logger = require("@redwoodjs/api/logger"); +const logLevel = import_logger.defaultLoggerOptions.level; +const cliLogger = function(...data) { console.log(...data); }; -exports.cliLogger = cliLogger; -cliLogger.trace = logLevel === 'trace' ? console.log : () => {}; -cliLogger.debug = logLevel === 'trace' || logLevel === 'debug' ? console.log : () => {}; \ No newline at end of file +cliLogger.trace = logLevel === "trace" ? console.log : () => { +}; +cliLogger.debug = logLevel === "trace" || logLevel === "debug" ? console.log : () => { +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + cliLogger +}); diff --git a/packages/internal/dist/dev.js b/packages/internal/dist/dev.js index 4eae0425bc63..842c658bdea0 100644 --- a/packages/internal/dist/dev.js +++ b/packages/internal/dist/dev.js @@ -1,13 +1,41 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var dev_exports = {}; +__export(dev_exports, { + shutdownPort: () => shutdownPort }); -exports.shutdownPort = void 0; -var _killPort = _interopRequireDefault(require("kill-port")); -const shutdownPort = (port, method = 'tcp') => { - return (0, _killPort.default)(port, method); +module.exports = __toCommonJS(dev_exports); +var import_kill_port = __toESM(require("kill-port")); +const shutdownPort = (port, method = "tcp") => { + return (0, import_kill_port.default)(port, method); }; -exports.shutdownPort = shutdownPort; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + shutdownPort +}); diff --git a/packages/internal/dist/files.js b/packages/internal/dist/files.js index 9530b867510e..557a202c365c 100644 --- a/packages/internal/dist/files.js +++ b/packages/internal/dist/files.js @@ -1,245 +1,223 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var files_exports = {}; +__export(files_exports, { + findApiDistFunctions: () => findApiDistFunctions, + findApiFiles: () => findApiFiles, + findApiServerFunctions: () => findApiServerFunctions, + findCells: () => findCells, + findDirectoryNamedModules: () => findDirectoryNamedModules, + findGraphQLSchemas: () => findGraphQLSchemas, + findPages: () => findPages, + findRouteHooksSrc: () => findRouteHooksSrc, + findScripts: () => findScripts, + findWebFiles: () => findWebFiles, + isApiFunction: () => isApiFunction, + isCellFile: () => isCellFile, + isDirectoryNamedModuleFile: () => isDirectoryNamedModuleFile, + isFileInsideFolder: () => isFileInsideFolder, + isGraphQLSchemaFile: () => isGraphQLSchemaFile, + isPageFile: () => isPageFile }); -exports.isPageFile = exports.isGraphQLSchemaFile = exports.isFileInsideFolder = exports.isDirectoryNamedModuleFile = exports.isCellFile = exports.isApiFunction = exports.findWebFiles = exports.findScripts = exports.findRouteHooksSrc = exports.findPages = exports.findGraphQLSchemas = exports.findDirectoryNamedModules = exports.findCells = exports.findApiServerFunctions = exports.findApiFiles = exports.findApiDistFunctions = void 0; -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -var _endsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/ends-with")); -var _findIndex = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/find-index")); -var _startsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/starts-with")); -var _path = _interopRequireDefault(require("path")); -var _fastGlob = _interopRequireDefault(require("fast-glob")); -var _projectConfig = require("@redwoodjs/project-config"); -var _ast = require("./ast"); -const findCells = (cwd = (0, _projectConfig.getPaths)().web.src) => { - const modules = _fastGlob.default.sync('**/*Cell.{js,jsx,ts,tsx}', { +module.exports = __toCommonJS(files_exports); +var import_path = __toESM(require("path")); +var import_fast_glob = __toESM(require("fast-glob")); +var import_project_config = require("@redwoodjs/project-config"); +var import_ast = require("./ast"); +const findCells = (cwd = (0, import_project_config.getPaths)().web.src) => { + const modules = import_fast_glob.default.sync("**/*Cell.{js,jsx,ts,tsx}", { cwd, absolute: true, - ignore: ['node_modules'] + ignore: ["node_modules"] }); - return (0, _filter.default)(modules).call(modules, isCellFile); + return modules.filter(isCellFile); }; -exports.findCells = findCells; -const findPages = (cwd = (0, _projectConfig.getPaths)().web.pages) => { - const modules = _fastGlob.default.sync('**/*Page.{tsx,js,jsx}', { +const findPages = (cwd = (0, import_project_config.getPaths)().web.pages) => { + const modules = import_fast_glob.default.sync("**/*Page.{tsx,js,jsx}", { cwd, absolute: true, - ignore: ['node_modules'] + ignore: ["node_modules"] }); - return (0, _filter.default)(modules).call(modules, isPageFile); -}; - -/** - * This function finds all modules in the 'web' and 'api' directories excluding 'node_modules' and Cell files. - * Cell files are also directory named modules but they have their special type mirror file, so they are ignored. - * - * @param {string} cwd - The directory path to start searching from. By default, it is the base path of the project. - * @returns {Array} modules - An array of absolute paths for the found modules. - * - * @example - * // Assuming the base directory of your project is '/Users/user/myproject' - * findDirectoryNamedModules('/Users/user/myproject'); - * // This will return an array with the absolute paths of all matching files, e.g.: - * // ['/Users/user/myproject/web/src/components/Author/Author.tsx', '/Users/user/myproject/web/src/pages/AboutPage/AboutPage.tsx'] - */ -exports.findPages = findPages; -const findDirectoryNamedModules = (cwd = (0, _projectConfig.getPaths)().base) => { - var _context; - const modules = _fastGlob.default.sync('(api|web)/src/**/*.{ts,js,jsx,tsx}', { + return modules.filter(isPageFile); +}; +const findDirectoryNamedModules = (cwd = (0, import_project_config.getPaths)().base) => { + const modules = import_fast_glob.default.sync("(api|web)/src/**/*.{ts,js,jsx,tsx}", { cwd, absolute: true, - ignore: ['node_modules'] + ignore: ["node_modules"] }); - return (0, _filter.default)(_context = (0, _filter.default)(modules).call(modules, isDirectoryNamedModuleFile)).call(_context, p => !isCellFile(p)); -}; -exports.findDirectoryNamedModules = findDirectoryNamedModules; -const findGraphQLSchemas = (cwd = (0, _projectConfig.getPaths)().api.graphql) => { - var _context2; - return (0, _filter.default)(_context2 = _fastGlob.default.sync('**/*.sdl.{ts,js}', { - cwd, - absolute: true - })).call(_context2, isGraphQLSchemaFile); -}; -exports.findGraphQLSchemas = findGraphQLSchemas; -const ignoreApiFiles = ['**/*.test.{js,ts}', '**/*.scenarios.{js,ts}', '**/*.fixtures.{js,ts}', '**/*.d.ts']; -const findApiFiles = (cwd = (0, _projectConfig.getPaths)().api.src) => { - const files = _fastGlob.default.sync('**/*.{js,ts,jsx,tsx}', { + return modules.filter(isDirectoryNamedModuleFile).filter((p) => !isCellFile(p)); +}; +const findGraphQLSchemas = (cwd = (0, import_project_config.getPaths)().api.graphql) => { + return import_fast_glob.default.sync("**/*.sdl.{ts,js}", { cwd, absolute: true }).filter(isGraphQLSchemaFile); +}; +const ignoreApiFiles = [ + "**/*.test.{js,ts}", + "**/*.scenarios.{js,ts}", + "**/*.fixtures.{js,ts}", + "**/*.d.ts" +]; +const findApiFiles = (cwd = (0, import_project_config.getPaths)().api.src) => { + const files = import_fast_glob.default.sync("**/*.{js,ts,jsx,tsx}", { cwd, absolute: true, ignore: ignoreApiFiles }); return files; }; -exports.findApiFiles = findApiFiles; -const findWebFiles = (cwd = (0, _projectConfig.getPaths)().web.src) => { - const files = _fastGlob.default.sync('**/*.{js,ts,jsx,tsx}', { +const findWebFiles = (cwd = (0, import_project_config.getPaths)().web.src) => { + const files = import_fast_glob.default.sync("**/*.{js,ts,jsx,tsx}", { cwd, absolute: true, - ignore: ['**/*.test.{js,ts,tsx,jsx}', '**/*.fixtures.{js,ts,tsx,jsx}', '**/*.mock.{js,ts,tsx,jsx}', '**/*.d.ts'] + ignore: [ + "**/*.test.{js,ts,tsx,jsx}", + "**/*.fixtures.{js,ts,tsx,jsx}", + "**/*.mock.{js,ts,tsx,jsx}", + "**/*.d.ts" + ] }); return files; }; -exports.findWebFiles = findWebFiles; -const findApiServerFunctions = (cwd = (0, _projectConfig.getPaths)().api.functions) => { - const files = _fastGlob.default.sync('**/*.{js,ts}', { +const findApiServerFunctions = (cwd = (0, import_project_config.getPaths)().api.functions) => { + const files = import_fast_glob.default.sync("**/*.{js,ts}", { cwd, absolute: true, deep: 2, // We don't support deeply nested api functions. ignore: ignoreApiFiles }); - return (0, _filter.default)(files).call(files, f => isApiFunction(f, cwd)); + return files.filter((f) => isApiFunction(f, cwd)); }; -exports.findApiServerFunctions = findApiServerFunctions; -const findApiDistFunctions = (cwd = (0, _projectConfig.getPaths)().api.base) => { - return _fastGlob.default.sync('dist/functions/**/*.{ts,js}', { +const findApiDistFunctions = (cwd = (0, import_project_config.getPaths)().api.base) => { + return import_fast_glob.default.sync("dist/functions/**/*.{ts,js}", { cwd, deep: 2, // We don't support deeply nested api functions, to maximise compatibility with deployment providers absolute: true }); }; -exports.findApiDistFunctions = findApiDistFunctions; -const findRouteHooksSrc = (cwd = (0, _projectConfig.getPaths)().web.src) => { - return _fastGlob.default.sync('**/*.routeHooks.{js,ts,tsx,jsx}', { +const findRouteHooksSrc = (cwd = (0, import_project_config.getPaths)().web.src) => { + return import_fast_glob.default.sync("**/*.routeHooks.{js,ts,tsx,jsx}", { absolute: true, cwd }); }; -exports.findRouteHooksSrc = findRouteHooksSrc; -const isCellFile = p => { - const { - dir, - name - } = _path.default.parse(p); - - // If the path isn't on the web side it cannot be a cell - if (!isFileInsideFolder(p, (0, _projectConfig.getPaths)().web.src)) { +const isCellFile = (p) => { + const { dir, name } = import_path.default.parse(p); + if (!isFileInsideFolder(p, (0, import_project_config.getPaths)().web.src)) { return false; } - - // A Cell must be a directory named module. - if (!(0, _endsWith.default)(dir).call(dir, name)) { + if (!dir.endsWith(name)) { return false; } - const ast = (0, _ast.fileToAst)(p); - - // A Cell should not have a default export. - if ((0, _ast.hasDefaultExport)(ast)) { + const ast = (0, import_ast.fileToAst)(p); + if ((0, import_ast.hasDefaultExport)(ast)) { return false; } - - // A Cell must export QUERY and Success. - const exports = (0, _ast.getNamedExports)(ast); - const exportedQUERY = (0, _findIndex.default)(exports).call(exports, v => v.name === 'QUERY') !== -1; - const exportedSuccess = (0, _findIndex.default)(exports).call(exports, v => v.name === 'Success') !== -1; + const exports2 = (0, import_ast.getNamedExports)(ast); + const exportedQUERY = exports2.findIndex((v) => v.name === "QUERY") !== -1; + const exportedSuccess = exports2.findIndex((v) => v.name === "Success") !== -1; if (!exportedQUERY && !exportedSuccess) { return false; } return true; }; -exports.isCellFile = isCellFile; -const findScripts = (cwd = (0, _projectConfig.getPaths)().scripts) => { - return _fastGlob.default.sync('./**/*.{js,jsx,ts,tsx}', { +const findScripts = (cwd = (0, import_project_config.getPaths)().scripts) => { + return import_fast_glob.default.sync("./**/*.{js,jsx,ts,tsx}", { cwd, absolute: true, - ignore: ['node_modules'] + ignore: ["node_modules"] }); }; -exports.findScripts = findScripts; -const isPageFile = p => { - const { - name - } = _path.default.parse(p); - - // A page must end with "Page.{jsx,js,tsx}". - if (!(0, _endsWith.default)(name).call(name, 'Page')) { +const isPageFile = (p) => { + const { name } = import_path.default.parse(p); + if (!name.endsWith("Page")) { return false; } - - // A page should be in the `web/src/pages` directory. - if (!isFileInsideFolder(p, (0, _projectConfig.getPaths)().web.pages)) { + if (!isFileInsideFolder(p, (0, import_project_config.getPaths)().web.pages)) { return false; } - - // A Page should have a default export. - const ast = (0, _ast.fileToAst)(p); - if (!(0, _ast.hasDefaultExport)(ast)) { + const ast = (0, import_ast.fileToAst)(p); + if (!(0, import_ast.hasDefaultExport)(ast)) { return false; } return true; }; -/** - * This function checks if the given path belongs to a directory named module. - * A directory named module is where the filename (without extension) is the same as the directory it is in. - * - * @param {string} p - The absolute path of the file. - * @returns {boolean} - Returns true if the path belongs to a directory named module, false otherwise. - * - * @example - * isDirectoryNamedModuleFile('/Users/user/myproject/web/src/components/Author/Author.tsx'); - * // Returns: true - * - * isDirectoryNamedModuleFile('/Users/user/myproject/web/src/components/Author/AuthorInfo.tsx'); - * // Returns: false - */ -exports.isPageFile = isPageFile; -const isDirectoryNamedModuleFile = p => { - const { - dir, - name - } = _path.default.parse(p); - return (0, _endsWith.default)(dir).call(dir, name); -}; -exports.isDirectoryNamedModuleFile = isDirectoryNamedModuleFile; -const isGraphQLSchemaFile = p => { +const isDirectoryNamedModuleFile = (p) => { + const { dir, name } = import_path.default.parse(p); + return dir.endsWith(name); +}; +const isGraphQLSchemaFile = (p) => { if (!p.match(/\.sdl\.(ts|js)$/)?.[0]) { return false; } - const ast = (0, _ast.fileToAst)(p); - const exports = (0, _ast.getNamedExports)(ast); - return (0, _findIndex.default)(exports).call(exports, v => v.name === 'schema') !== -1; -}; - -/** - * The following patterns are supported for api functions: - * - * 1. a module at the top level: `/graphql.js` - * 2. a module in a folder with a module of the same name: `/health/health.js` - * 3. a module in a folder named index: `/x/index.js` - */ -exports.isGraphQLSchemaFile = isGraphQLSchemaFile; + const ast = (0, import_ast.fileToAst)(p); + const exports2 = (0, import_ast.getNamedExports)(ast); + return exports2.findIndex((v) => v.name === "schema") !== -1; +}; const isApiFunction = (p, functionsPath) => { - p = _path.default.relative(functionsPath, p); - const { - dir, - name - } = _path.default.parse(p); + p = import_path.default.relative(functionsPath, p); + const { dir, name } = import_path.default.parse(p); if (dir === name) { - // Directory named module return true; - } else if (dir === '') { - // Module in the functions root + } else if (dir === "") { return true; - } else if (dir.length && name === 'index') { - // Directory with an `index.js` file + } else if (dir.length && name === "index") { return true; } return false; }; -exports.isApiFunction = isApiFunction; const isFileInsideFolder = (filePath, folderPath) => { - const { - dir - } = _path.default.parse(filePath); - const relativePathFromFolder = _path.default.relative(folderPath, dir); - if (!relativePathFromFolder || (0, _startsWith.default)(relativePathFromFolder).call(relativePathFromFolder, '..') || _path.default.isAbsolute(relativePathFromFolder)) { + const { dir } = import_path.default.parse(filePath); + const relativePathFromFolder = import_path.default.relative(folderPath, dir); + if (!relativePathFromFolder || relativePathFromFolder.startsWith("..") || import_path.default.isAbsolute(relativePathFromFolder)) { return false; } else { return true; } }; -exports.isFileInsideFolder = isFileInsideFolder; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + findApiDistFunctions, + findApiFiles, + findApiServerFunctions, + findCells, + findDirectoryNamedModules, + findGraphQLSchemas, + findPages, + findRouteHooksSrc, + findScripts, + findWebFiles, + isApiFunction, + isCellFile, + isDirectoryNamedModuleFile, + isFileInsideFolder, + isGraphQLSchemaFile, + isPageFile +}); diff --git a/packages/internal/dist/generate/clientPreset.js b/packages/internal/dist/generate/clientPreset.js index 4dc1aa061654..aa8e631b506a 100644 --- a/packages/internal/dist/generate/clientPreset.js +++ b/packages/internal/dist/generate/clientPreset.js @@ -1,46 +1,55 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var clientPreset_exports = {}; +__export(clientPreset_exports, { + generateClientPreset: () => generateClientPreset, + shouldGenerateTrustedDocuments: () => shouldGenerateTrustedDocuments }); -exports.shouldGenerateTrustedDocuments = exports.generateClientPreset = void 0; -require("core-js/modules/es.array.push.js"); -var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); -var _cli = require("@graphql-codegen/cli"); -var _clientPreset = require("@graphql-codegen/client-preset"); -var _projectConfig = require("@redwoodjs/project-config"); -var _trustedDocuments = require("./trustedDocuments"); +module.exports = __toCommonJS(clientPreset_exports); +var import_cli = require("@graphql-codegen/cli"); +var import_client_preset = require("@graphql-codegen/client-preset"); +var import_project_config = require("@redwoodjs/project-config"); +var import_trustedDocuments = require("./trustedDocuments"); const shouldGenerateTrustedDocuments = () => { - const config = (0, _projectConfig.getConfig)(); + const config = (0, import_project_config.getConfig)(); return config.graphql.trustedDocuments; }; -exports.shouldGenerateTrustedDocuments = shouldGenerateTrustedDocuments; const generateClientPreset = async () => { let generatedFiles = []; let clientPresetFiles = []; const errors = []; if (!shouldGenerateTrustedDocuments()) { - return { - clientPresetFiles, - trustedDocumentsStoreFile: [], - errors - }; + return { clientPresetFiles, trustedDocumentsStoreFile: [], errors }; } - const documentsGlob = `${(0, _projectConfig.getPaths)().web.src}/**/!(*.d).{ts,tsx,js,jsx}`; + const documentsGlob = `${(0, import_project_config.getPaths)().web.src}/**/!(*.d).{ts,tsx,js,jsx}`; const config = { - schema: (0, _projectConfig.getPaths)().generated.schema, + schema: (0, import_project_config.getPaths)().generated.schema, documents: documentsGlob, silent: true, // Plays nicely with cli task output generates: { - [`${(0, _projectConfig.getPaths)().web.src}/graphql/`]: { - preset: 'client', + [`${(0, import_project_config.getPaths)().web.src}/graphql/`]: { + preset: "client", presetConfig: { persistedDocuments: true }, - documentTransforms: [_clientPreset.addTypenameSelectionDocumentTransform], + documentTransforms: [import_client_preset.addTypenameSelectionDocumentTransform], config: { // DO NOT USE documentMode: 'string', } @@ -48,10 +57,10 @@ const generateClientPreset = async () => { } }; try { - generatedFiles = await (0, _cli.generate)(config, true); - clientPresetFiles = (0, _map.default)(generatedFiles).call(generatedFiles, f => f.filename); - const trustedDocumentsStoreFile = await (0, _trustedDocuments.trustedDocumentsStore)(generatedFiles); - (0, _trustedDocuments.replaceGqlTagWithTrustedDocumentGraphql)(generatedFiles); + generatedFiles = await (0, import_cli.generate)(config, true); + clientPresetFiles = generatedFiles.map((f) => f.filename); + const trustedDocumentsStoreFile = await (0, import_trustedDocuments.trustedDocumentsStore)(generatedFiles); + (0, import_trustedDocuments.replaceGqlTagWithTrustedDocumentGraphql)(generatedFiles); return { clientPresetFiles, trustedDocumentsStoreFile, @@ -59,7 +68,7 @@ const generateClientPreset = async () => { }; } catch (e) { errors.push({ - message: 'Error: Could not generate GraphQL client preset', + message: "Error: Could not generate GraphQL client preset", error: e }); return { @@ -69,4 +78,8 @@ const generateClientPreset = async () => { }; } }; -exports.generateClientPreset = generateClientPreset; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + generateClientPreset, + shouldGenerateTrustedDocuments +}); diff --git a/packages/internal/dist/generate/generate.js b/packages/internal/dist/generate/generate.js index ad7ce76f710b..a1a5dd114b7a 100755 --- a/packages/internal/dist/generate/generate.js +++ b/packages/internal/dist/generate/generate.js @@ -1,81 +1,91 @@ #!/usr/bin/env node "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var generate_exports = {}; +__export(generate_exports, { + generate: () => generate, + run: () => run }); -exports.run = exports.generate = void 0; -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -require("core-js/modules/es.array.push.js"); -var _projectConfig = require("@redwoodjs/project-config"); -var _clientPreset = require("./clientPreset"); -var _graphqlSchema = require("./graphqlSchema"); -var _possibleTypes = require("./possibleTypes"); -var _typeDefinitions = require("./typeDefinitions"); +module.exports = __toCommonJS(generate_exports); +var import_project_config = require("@redwoodjs/project-config"); +var import_clientPreset = require("./clientPreset"); +var import_graphqlSchema = require("./graphqlSchema"); +var import_possibleTypes = require("./possibleTypes"); +var import_typeDefinitions = require("./typeDefinitions"); const generate = async () => { - var _context; - const config = (0, _projectConfig.getConfig)(); - const { - schemaPath, - errors: generateGraphQLSchemaErrors - } = await (0, _graphqlSchema.generateGraphQLSchema)(); - const { - typeDefFiles, - errors: generateTypeDefsErrors - } = await (0, _typeDefinitions.generateTypeDefs)(); + const config = (0, import_project_config.getConfig)(); + const { schemaPath, errors: generateGraphQLSchemaErrors } = await (0, import_graphqlSchema.generateGraphQLSchema)(); + const { typeDefFiles, errors: generateTypeDefsErrors } = await (0, import_typeDefinitions.generateTypeDefs)(); const clientPresetFiles = []; - const { - possibleTypesFiles, - errors: generatePossibleTypesErrors - } = await (0, _possibleTypes.generatePossibleTypes)(); + const { possibleTypesFiles, errors: generatePossibleTypesErrors } = await (0, import_possibleTypes.generatePossibleTypes)(); if (config.graphql.trustedDocuments) { - const preset = await (0, _clientPreset.generateClientPreset)(); + const preset = await (0, import_clientPreset.generateClientPreset)(); clientPresetFiles.push(...preset.clientPresetFiles); } let files = []; - if (schemaPath !== '') { + if (schemaPath !== "") { files.push(schemaPath); } - files = (0, _filter.default)(_context = [...files, ...typeDefFiles, ...clientPresetFiles, ...possibleTypesFiles]).call(_context, x => typeof x === 'string'); + files = [ + ...files, + ...typeDefFiles, + ...clientPresetFiles, + ...possibleTypesFiles + ].filter((x) => typeof x === "string"); return { files, - errors: [...generateGraphQLSchemaErrors, ...generateTypeDefsErrors, ...generatePossibleTypesErrors] + errors: [ + ...generateGraphQLSchemaErrors, + ...generateTypeDefsErrors, + ...generatePossibleTypesErrors + ] }; }; -exports.generate = generate; const run = async () => { - console.log('Generating...'); + console.log("Generating..."); console.log(); - const { - files, - errors - } = await generate(); - const rwjsPaths = (0, _projectConfig.getPaths)(); + const { files, errors } = await generate(); + const rwjsPaths = (0, import_project_config.getPaths)(); for (const f of files) { - console.log('-', f.replace(rwjsPaths.base + '/', '')); + console.log("-", f.replace(rwjsPaths.base + "/", "")); } console.log(); if (errors.length === 0) { - console.log('... done.'); + console.log("... done."); console.log(); return; } process.exitCode ||= 1; - console.log('... done with errors.'); + console.log("... done with errors."); console.log(); - for (const { - message, - error - } of errors) { + for (const { message, error } of errors) { console.error(message); console.log(); console.error(error); console.log(); } }; -exports.run = run; if (require.main === module) { run(); -} \ No newline at end of file +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + generate, + run +}); diff --git a/packages/internal/dist/generate/graphqlCodeGen.js b/packages/internal/dist/generate/graphqlCodeGen.js index 788cfed5584b..18641fbaf705 100644 --- a/packages/internal/dist/generate/graphqlCodeGen.js +++ b/packages/internal/dist/generate/graphqlCodeGen.js @@ -1,56 +1,69 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard").default; -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var graphqlCodeGen_exports = {}; +__export(graphqlCodeGen_exports, { + generateTypeDefGraphQLApi: () => generateTypeDefGraphQLApi, + generateTypeDefGraphQLWeb: () => generateTypeDefGraphQLWeb, + getLoadDocumentsOptions: () => getLoadDocumentsOptions, + getResolverFnType: () => getResolverFnType }); -exports.generateTypeDefGraphQLWeb = exports.generateTypeDefGraphQLApi = void 0; -exports.getLoadDocumentsOptions = getLoadDocumentsOptions; -exports.getResolverFnType = void 0; -require("core-js/modules/es.array.push.js"); -var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/concat")); -var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); -var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/keys")); -var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/for-each")); -var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -var _values = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/values")); -var _reduce = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/reduce")); -var _fs = _interopRequireDefault(require("fs")); -var _path = _interopRequireDefault(require("path")); -var addPlugin = _interopRequireWildcard(require("@graphql-codegen/add")); -var _cli = require("@graphql-codegen/cli"); -var _core = require("@graphql-codegen/core"); -var typescriptPlugin = _interopRequireWildcard(require("@graphql-codegen/typescript")); -var typescriptOperations = _interopRequireWildcard(require("@graphql-codegen/typescript-operations")); -var _codeFileLoader = require("@graphql-tools/code-file-loader"); -var _graphqlFileLoader = require("@graphql-tools/graphql-file-loader"); -var _load = require("@graphql-tools/load"); -var _execa = _interopRequireDefault(require("execa")); -var _graphql = require("graphql"); -var _projectConfig = require("@redwoodjs/project-config"); -var _project = require("../project"); -var rwTypescriptResolvers = _interopRequireWildcard(require("./plugins/rw-typescript-resolvers")); -var CodegenSide = /*#__PURE__*/function (CodegenSide) { - CodegenSide[CodegenSide["API"] = 0] = "API"; - CodegenSide[CodegenSide["WEB"] = 1] = "WEB"; - return CodegenSide; -}(CodegenSide || {}); +module.exports = __toCommonJS(graphqlCodeGen_exports); +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var addPlugin = __toESM(require("@graphql-codegen/add")); +var import_cli = require("@graphql-codegen/cli"); +var import_core = require("@graphql-codegen/core"); +var typescriptPlugin = __toESM(require("@graphql-codegen/typescript")); +var typescriptOperations = __toESM(require("@graphql-codegen/typescript-operations")); +var import_code_file_loader = require("@graphql-tools/code-file-loader"); +var import_graphql_file_loader = require("@graphql-tools/graphql-file-loader"); +var import_load = require("@graphql-tools/load"); +var import_execa = __toESM(require("execa")); +var import_graphql = require("graphql"); +var import_project_config = require("@redwoodjs/project-config"); +var import_project = require("../project"); +var rwTypescriptResolvers = __toESM(require("./plugins/rw-typescript-resolvers")); +var CodegenSide = /* @__PURE__ */ ((CodegenSide2) => { + CodegenSide2[CodegenSide2["API"] = 0] = "API"; + CodegenSide2[CodegenSide2["WEB"] = 1] = "WEB"; + return CodegenSide2; +})(CodegenSide || {}); const generateTypeDefGraphQLApi = async () => { - var _context; - const config = (0, _projectConfig.getConfig)(); + const config = (0, import_project_config.getConfig)(); const errors = []; if (config.experimental.useSDLCodeGenForGraphQLTypes) { - const paths = (0, _projectConfig.getPaths)(); - const sdlCodegen = await import('@sdl-codegen/node'); + const paths = (0, import_project_config.getPaths)(); + const sdlCodegen = await import("@sdl-codegen/node"); const dtsFiles = []; try { - const output = sdlCodegen.runFullCodegen('redwood', { - paths - }); - (0, _concat.default)(dtsFiles).call(dtsFiles, output.paths); + const output = sdlCodegen.runFullCodegen("redwood", { paths }); + dtsFiles.concat(output.paths); } catch (e) { if (e instanceof Error) { errors.push({ @@ -64,35 +77,48 @@ const generateTypeDefGraphQLApi = async () => { errors }; } - const filename = _path.default.join((0, _projectConfig.getPaths)().api.types, 'graphql.d.ts'); + const filename = import_path.default.join((0, import_project_config.getPaths)().api.types, "graphql.d.ts"); const prismaModels = await getPrismaModels(); - const prismaImports = (0, _map.default)(_context = (0, _keys.default)(prismaModels)).call(_context, key => { + const prismaImports = Object.keys(prismaModels).map((key) => { return `${key} as Prisma${key}`; }); - const extraPlugins = [{ - name: 'add', - options: { - content: ['import { Prisma } from "@prisma/client"', "import { MergePrismaWithSdlTypes, MakeRelationsOptional } from '@redwoodjs/api'", `import { ${prismaImports.join(', ')} } from '@prisma/client'`], - placement: 'prepend' + const extraPlugins = [ + { + name: "add", + options: { + content: [ + 'import { Prisma } from "@prisma/client"', + "import { MergePrismaWithSdlTypes, MakeRelationsOptional } from '@redwoodjs/api'", + `import { ${prismaImports.join(", ")} } from '@prisma/client'` + ], + placement: "prepend" + }, + codegenPlugin: addPlugin + }, + { + name: "print-mapped-models", + options: {}, + codegenPlugin: printMappedModelsPlugin }, - codegenPlugin: addPlugin - }, { - name: 'print-mapped-models', - options: {}, - codegenPlugin: printMappedModelsPlugin - }, { - name: 'typescript-resolvers', - options: {}, - codegenPlugin: rwTypescriptResolvers - }]; + { + name: "typescript-resolvers", + options: {}, + codegenPlugin: rwTypescriptResolvers + } + ]; try { return { - typeDefFiles: await runCodegenGraphQL([], extraPlugins, filename, CodegenSide.API), + typeDefFiles: await runCodegenGraphQL( + [], + extraPlugins, + filename, + 0 /* API */ + ), errors }; } catch (e) { errors.push({ - message: 'Error: Could not generate GraphQL type definitions (api)', + message: "Error: Could not generate GraphQL type definitions (api)", error: e }); return { @@ -101,42 +127,48 @@ const generateTypeDefGraphQLApi = async () => { }; } }; -exports.generateTypeDefGraphQLApi = generateTypeDefGraphQLApi; const generateTypeDefGraphQLWeb = async () => { - const filename = _path.default.join((0, _projectConfig.getPaths)().web.types, 'graphql.d.ts'); + const filename = import_path.default.join((0, import_project_config.getPaths)().web.types, "graphql.d.ts"); const options = getLoadDocumentsOptions(filename); - const documentsGlob = './web/src/**/!(*.d).{ts,tsx,js,jsx}'; + const documentsGlob = "./web/src/**/!(*.d).{ts,tsx,js,jsx}"; let documents; try { - documents = await (0, _load.loadDocuments)([documentsGlob], options); + documents = await (0, import_load.loadDocuments)([documentsGlob], options); } catch { - // No GraphQL documents present, no need to try to run codegen return { typeDefFiles: [], errors: [] }; } - const extraPlugins = [{ - name: 'add', - options: { - content: 'import { Prisma } from "@prisma/client"', - placement: 'prepend' + const extraPlugins = [ + { + name: "add", + options: { + content: 'import { Prisma } from "@prisma/client"', + placement: "prepend" + }, + codegenPlugin: addPlugin }, - codegenPlugin: addPlugin - }, { - name: 'typescript-operations', - options: {}, - codegenPlugin: typescriptOperations - }]; + { + name: "typescript-operations", + options: {}, + codegenPlugin: typescriptOperations + } + ]; const errors = []; try { return { - typeDefFiles: await runCodegenGraphQL(documents, extraPlugins, filename, CodegenSide.WEB), + typeDefFiles: await runCodegenGraphQL( + documents, + extraPlugins, + filename, + 1 /* WEB */ + ), errors }; } catch (e) { errors.push({ - message: 'Error: Could not generate GraphQL type definitions (web)', + message: "Error: Could not generate GraphQL type definitions (web)", error: e }); return { @@ -145,112 +177,73 @@ const generateTypeDefGraphQLWeb = async () => { }; } }; - -/** - * This is the function used internally by generateTypeDefGraphQLApi and generateTypeDefGraphQLWeb - * And contains the base configuration for generating gql types with codegen - * - * Named a little differently to make it easier to spot - */ -exports.generateTypeDefGraphQLWeb = generateTypeDefGraphQLWeb; async function runCodegenGraphQL(documents, extraPlugins, filename, side) { - const userCodegenConfig = await (0, _cli.loadCodegenConfig)({ - configFilePath: (0, _projectConfig.getPaths)().base + const userCodegenConfig = await (0, import_cli.loadCodegenConfig)({ + configFilePath: (0, import_project_config.getPaths)().base }); - - // Merge in user codegen config with the rw built-in one const mergedConfig = { - ...(await getPluginConfig(side)), + ...await getPluginConfig(side), ...userCodegenConfig?.config?.config }; const options = getCodegenOptions(documents, mergedConfig, extraPlugins); - const output = await (0, _core.codegen)(options); - _fs.default.mkdirSync(_path.default.dirname(filename), { - recursive: true - }); - _fs.default.writeFileSync(filename, output); + const output = await (0, import_core.codegen)(options); + import_fs.default.mkdirSync(import_path.default.dirname(filename), { recursive: true }); + import_fs.default.writeFileSync(filename, output); return [filename]; } function getLoadDocumentsOptions(filename) { const loadTypedefsConfig = { - cwd: (0, _projectConfig.getPaths)().base, - ignore: [_path.default.join(process.cwd(), filename)], - loaders: [new _codeFileLoader.CodeFileLoader()], + cwd: (0, import_project_config.getPaths)().base, + ignore: [import_path.default.join(process.cwd(), filename)], + loaders: [new import_code_file_loader.CodeFileLoader()], sort: true }; return loadTypedefsConfig; } async function getPrismaClient(hasGenerated = false) { - const { - default: localPrisma - } = await import('@prisma/client'); - - // @ts-expect-error I believe this type will only exist if the prisma client has been generated + const { default: localPrisma } = await import("@prisma/client"); if (!localPrisma.ModelName) { if (hasGenerated) { - return { - ModelName: {} - }; + return { ModelName: {} }; } else { - var _context2; - _execa.default.sync('yarn rw prisma generate', { - shell: true - }); - - // Purge Prisma Client from node's require cache, so that the newly - // generated client gets picked up by any script that uses it - (0, _forEach.default)(_context2 = (0, _keys.default)(require.cache)).call(_context2, key => { - if ((0, _includes.default)(key).call(key, '/node_modules/@prisma/client/') || (0, _includes.default)(key).call(key, '/node_modules/.prisma/client/')) { + import_execa.default.sync("yarn rw prisma generate", { shell: true }); + Object.keys(require.cache).forEach((key) => { + if (key.includes("/node_modules/@prisma/client/") || key.includes("/node_modules/.prisma/client/")) { delete require.cache[key]; } }); return getPrismaClient(true); } } - - // @ts-expect-error See above, the generated client should contain a ModelName property that - // satisfies Record return localPrisma; } async function getPrismaModels() { - // Extract the models from the prisma client and use those to - // set up internal redirects for the return values in resolvers. const localPrisma = await getPrismaClient(); const prismaModels = localPrisma.ModelName; - - // This isn't really something you'd put in the GraphQL API, so - // we can skip the model. if (prismaModels.RW_DataMigration) { delete prismaModels.RW_DataMigration; } return prismaModels; } async function getPluginConfig(side) { - var _context3; const prismaModels = await getPrismaModels(); - (0, _forEach.default)(_context3 = (0, _keys.default)(prismaModels)).call(_context3, key => { - /** creates an object like this - * { - * Post: MergePrismaWithSdlTypes, AllMappedModels>> - * ... - * } - */ + Object.keys(prismaModels).forEach((key) => { prismaModels[key] = `MergePrismaWithSdlTypes, AllMappedModels>`; }); const pluginConfig = { makeResolverTypeCallable: true, - namingConvention: 'keep', + namingConvention: "keep", // to allow camelCased query names scalars: { // We need these, otherwise these scalars are mapped to any - BigInt: 'number', + BigInt: "number", // @Note: DateTime fields can be valid Date-strings, or the Date object in the api side. They're always strings on the web side. - DateTime: side === CodegenSide.WEB ? 'string' : 'Date | string', - Date: side === CodegenSide.WEB ? 'string' : 'Date | string', - JSON: 'Prisma.JsonValue', - JSONObject: 'Prisma.JsonObject', - Time: side === CodegenSide.WEB ? 'string' : 'Date | string', - Byte: 'Buffer' + DateTime: side === 1 /* WEB */ ? "string" : "Date | string", + Date: side === 1 /* WEB */ ? "string" : "Date | string", + JSON: "Prisma.JsonValue", + JSONObject: "Prisma.JsonObject", + Time: side === 1 /* WEB */ ? "string" : "Date | string", + Byte: "Buffer" }, // prevent type names being PetQueryQuery, RW generators already append // Query/Mutation/etc @@ -269,9 +262,8 @@ async function getPluginConfig(side) { return pluginConfig; } const getResolverFnType = () => { - const tsConfig = (0, _project.getTsConfigs)(); + const tsConfig = (0, import_project.getTsConfigs)(); if (tsConfig.api?.compilerOptions?.strict) { - // In strict mode, bring a world of pain to the tests return `( args: TArgs, obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } @@ -283,51 +275,36 @@ const getResolverFnType = () => { ) => TResult | Promise`; } }; -exports.getResolverFnType = getResolverFnType; -/** - * Codgen plugin that just lists all the SDL models that are also mapped Prisma models - * We use a plugin, because its possible to have Prisma models that do not have an SDL model - * so we can't just list all the Prisma models, even if they're included in the mappers object. - * - * Example: - * type AllMappedModels = MaybeOrArrayOfMaybe - * - * Note that the types are SDL types, not Prisma types. - * We do not include SDL-only types in this list. - */ const printMappedModelsPlugin = { plugin: (schema, _documents, config) => { - var _context4, _context5, _context6; - // this way we can make sure relation types are not required - const sdlTypesWhichAreMapped = (0, _map.default)(_context4 = (0, _filter.default)(_context5 = (0, _filter.default)(_context6 = (0, _values.default)(schema.getTypeMap())).call(_context6, type => { - return type.astNode?.kind === _graphql.Kind.OBJECT_TYPE_DEFINITION; - })).call(_context5, objectDefType => { + const sdlTypesWhichAreMapped = Object.values(schema.getTypeMap()).filter((type) => { + return type.astNode?.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION; + }).filter((objectDefType) => { const modelName = objectDefType.astNode?.name.value; - return modelName && modelName in config.mappers // Only keep the mapped Prisma models - ; - })).call(_context4, objectDefType => objectDefType.astNode?.name.value); - return `type MaybeOrArrayOfMaybe = T | Maybe | Maybe[];\ntype AllMappedModels = MaybeOrArrayOfMaybe<${sdlTypesWhichAreMapped.join(' | ')}>`; + return modelName && modelName in config.mappers; + }).map((objectDefType) => objectDefType.astNode?.name.value); + return `type MaybeOrArrayOfMaybe = T | Maybe | Maybe[]; +type AllMappedModels = MaybeOrArrayOfMaybe<${sdlTypesWhichAreMapped.join( + " | " + )}>`; } }; function getCodegenOptions(documents, config, extraPlugins) { - const plugins = [{ - typescript: { - enumsAsTypes: true - } - }, ...(0, _map.default)(extraPlugins).call(extraPlugins, plugin => ({ - [plugin.name]: plugin.options - }))]; + const plugins = [ + { typescript: { enumsAsTypes: true } }, + ...extraPlugins.map((plugin) => ({ [plugin.name]: plugin.options })) + ]; const pluginMap = { typescript: typescriptPlugin, - ...(0, _reduce.default)(extraPlugins).call(extraPlugins, (acc, cur) => ({ - ...acc, - [cur.name]: cur.codegenPlugin - }), {}) + ...extraPlugins.reduce( + (acc, cur) => ({ ...acc, [cur.name]: cur.codegenPlugin }), + {} + ) }; const options = { // The typescript plugin returns a string instead of writing to a file, so // `filename` is not used - filename: '', + filename: "", // `schemaAst` is used instead of `schema` if `schemaAst` is defined, and // `schema` isn't. In the source for GenerateOptions they have this // comment: @@ -335,9 +312,9 @@ function getCodegenOptions(documents, config, extraPlugins) { // version // When that happens we'll have have to remove our `schema` line, and // rename `schemaAst` to `schema` - schema: undefined, - schemaAst: (0, _load.loadSchemaSync)((0, _projectConfig.getPaths)().generated.schema, { - loaders: [new _graphqlFileLoader.GraphQLFileLoader()], + schema: void 0, + schemaAst: (0, import_load.loadSchemaSync)((0, import_project_config.getPaths)().generated.schema, { + loaders: [new import_graphql_file_loader.GraphQLFileLoader()], sort: true }), documents, @@ -347,4 +324,11 @@ function getCodegenOptions(documents, config, extraPlugins) { pluginContext: {} }; return options; -} \ No newline at end of file +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + generateTypeDefGraphQLApi, + generateTypeDefGraphQLWeb, + getLoadDocumentsOptions, + getResolverFnType +}); diff --git a/packages/internal/dist/generate/graphqlSchema.js b/packages/internal/dist/generate/graphqlSchema.js index 172611dffd23..1eb13a115b46 100644 --- a/packages/internal/dist/generate/graphqlSchema.js +++ b/packages/internal/dist/generate/graphqlSchema.js @@ -1,47 +1,61 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard").default; -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var graphqlSchema_exports = {}; +__export(graphqlSchema_exports, { + generateGraphQLSchema: () => generateGraphQLSchema }); -exports.generateGraphQLSchema = void 0; -require("core-js/modules/es.array.push.js"); -var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/keys")); -var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); -var _fs = _interopRequireDefault(require("fs")); -var _core = require("@graphql-codegen/core"); -var schemaAstPlugin = _interopRequireWildcard(require("@graphql-codegen/schema-ast")); -var _codeFileLoader = require("@graphql-tools/code-file-loader"); -var _load = require("@graphql-tools/load"); -var _internals = require("@prisma/internals"); -var _chalk = _interopRequireDefault(require("chalk")); -var _graphql = require("graphql"); -var _terminalLink = _interopRequireDefault(require("terminal-link")); -var _graphqlServer = require("@redwoodjs/graphql-server"); -var _projectConfig = require("@redwoodjs/project-config"); +module.exports = __toCommonJS(graphqlSchema_exports); +var import_fs = __toESM(require("fs")); +var import_core = require("@graphql-codegen/core"); +var schemaAstPlugin = __toESM(require("@graphql-codegen/schema-ast")); +var import_code_file_loader = require("@graphql-tools/code-file-loader"); +var import_load = require("@graphql-tools/load"); +var import_internals = require("@prisma/internals"); +var import_chalk = __toESM(require("chalk")); +var import_graphql = require("graphql"); +var import_terminal_link = __toESM(require("terminal-link")); +var import_graphql_server = require("@redwoodjs/graphql-server"); +var import_project_config = require("@redwoodjs/project-config"); const generateGraphQLSchema = async () => { - const redwoodProjectPaths = (0, _projectConfig.getPaths)(); + const redwoodProjectPaths = (0, import_project_config.getPaths)(); const schemaPointerMap = { - [(0, _graphql.print)(_graphqlServer.rootSchema.schema)]: {}, - 'graphql/**/*.sdl.{js,ts}': {}, - 'directives/**/*.{js,ts}': {}, - 'subscriptions/**/*.{js,ts}': {} + [(0, import_graphql.print)(import_graphql_server.rootSchema.schema)]: {}, + "graphql/**/*.sdl.{js,ts}": {}, + "directives/**/*.{js,ts}": {}, + "subscriptions/**/*.{js,ts}": {} }; - - // If we're serverful and the user is using realtime, we need to include the live directive for realtime support. - // Note the `ERR_ prefix in`ERR_MODULE_NOT_FOUND`. Since we're using `await import`, - // if the package (here, `@redwoodjs/realtime`) can't be found, it throws this error, with the prefix. - // Whereas `require('@redwoodjs/realtime')` would throw `MODULE_NOT_FOUND`. - if ((0, _projectConfig.resolveFile)(`${(0, _projectConfig.getPaths)().api.src}/server`)) { + if ((0, import_project_config.resolveFile)(`${(0, import_project_config.getPaths)().api.src}/server`)) { try { - const { - liveDirectiveTypeDefs - } = await import('@redwoodjs/realtime'); + const { liveDirectiveTypeDefs } = await import("@redwoodjs/realtime"); schemaPointerMap[liveDirectiveTypeDefs] = {}; } catch (error) { - if (error.code !== 'ERR_MODULE_NOT_FOUND') { + if (error.code !== "ERR_MODULE_NOT_FOUND") { throw error; } } @@ -52,48 +66,62 @@ const generateGraphQLSchema = async () => { convertExtensions: true, includeSources: true, cwd: redwoodProjectPaths.api.src, - schema: (0, _keys.default)(schemaPointerMap), + schema: Object.keys(schemaPointerMap), generates: { [redwoodProjectPaths.generated.schema]: { - plugins: ['schema-ast'] + plugins: ["schema-ast"] } }, silent: false, errorsOnly: false, pluginContext: {}, - loaders: [new _codeFileLoader.CodeFileLoader()] + loaders: [new import_code_file_loader.CodeFileLoader()] }; let loadedSchema; const errors = []; try { - loadedSchema = await (0, _load.loadSchema)(schemaPointerMap, loadSchemaConfig); + loadedSchema = await (0, import_load.loadSchema)(schemaPointerMap, loadSchemaConfig); } catch (e) { if (e instanceof Error) { const match = e.message.match(/Unknown type: "(\w+)"/); const name = match?.[1]; - const schemaPrisma = (await (0, _internals.getSchema)(redwoodProjectPaths.api.dbSchema)).toString(); + const schemaPrisma = (await (0, import_internals.getSchema)(redwoodProjectPaths.api.dbSchema)).toString(); const errorObject = { message: `Schema loading failed. ${e.message}`, error: e }; errors.push(errorObject); - if (name && (0, _includes.default)(schemaPrisma).call(schemaPrisma, `model ${name}`)) { - // Not all SDLs need to be backed by a DB model, but if they are we can - // provide a more helpful error message - - errorObject.message = [errorObject.message, '', ` ${_chalk.default.bgYellow(` ${_chalk.default.black.bold('Heads up')} `)}`, '', _chalk.default.yellow(` It looks like you have a ${name} model in your Prisma schema.`), _chalk.default.yellow(` If it's part of a relation, you may have to generate SDL or scaffolding for ${name} too.`), _chalk.default.yellow(` So, if you haven't done that yet, ignore this error message and run the SDL or scaffold generator for ${name} now.`), '', _chalk.default.yellow(` See the ${(0, _terminalLink.default)('Troubleshooting Generators', 'https://redwoodjs.com/docs/schema-relations#troubleshooting-generators')} section in our docs for more help.`)].join('\n'); + if (name && schemaPrisma.includes(`model ${name}`)) { + errorObject.message = [ + errorObject.message, + "", + ` ${import_chalk.default.bgYellow(` ${import_chalk.default.black.bold("Heads up")} `)}`, + "", + import_chalk.default.yellow( + ` It looks like you have a ${name} model in your Prisma schema.` + ), + import_chalk.default.yellow( + ` If it's part of a relation, you may have to generate SDL or scaffolding for ${name} too.` + ), + import_chalk.default.yellow( + ` So, if you haven't done that yet, ignore this error message and run the SDL or scaffold generator for ${name} now.` + ), + "", + import_chalk.default.yellow( + ` See the ${(0, import_terminal_link.default)( + "Troubleshooting Generators", + "https://redwoodjs.com/docs/schema-relations#troubleshooting-generators" + )} section in our docs for more help.` + ) + ].join("\n"); } } } const options = { config: {}, // no extra config needed for merged schema file generation - plugins: [{ - 'schema-ast': {} - }], - pluginMap: { - 'schema-ast': schemaAstPlugin - }, + plugins: [{ "schema-ast": {} }], + pluginMap: { "schema-ast": schemaAstPlugin }, schema: {}, schemaAst: loadedSchema, filename: redwoodProjectPaths.generated.schema, @@ -101,12 +129,9 @@ const generateGraphQLSchema = async () => { }; if (loadedSchema) { try { - const schema = await (0, _core.codegen)(options); - _fs.default.writeFileSync(redwoodProjectPaths.generated.schema, schema); - return { - schemaPath: redwoodProjectPaths.generated.schema, - errors - }; + const schema = await (0, import_core.codegen)(options); + import_fs.default.writeFileSync(redwoodProjectPaths.generated.schema, schema); + return { schemaPath: redwoodProjectPaths.generated.schema, errors }; } catch (e) { errors.push({ message: `GraphQL Schema codegen failed`, @@ -114,9 +139,9 @@ const generateGraphQLSchema = async () => { }); } } - return { - schemaPath: '', - errors - }; + return { schemaPath: "", errors }; }; -exports.generateGraphQLSchema = generateGraphQLSchema; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + generateGraphQLSchema +}); diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js index 2c69d137c8f9..70cc0bf6a26a 100644 --- a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js +++ b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js @@ -1,50 +1,37 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true -}); -_Object$defineProperty(exports, "RwTypeScriptResolversVisitor", { - enumerable: true, - get: function () { - return _visitor.RwTypeScriptResolversVisitor; - } -}); -_Object$defineProperty(exports, "TypeScriptResolversPluginConfig", { - enumerable: true, - get: function () { - return _typescriptResolvers.TypeScriptResolversPluginConfig; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var rw_typescript_resolvers_exports = {}; +__export(rw_typescript_resolvers_exports, { + RwTypeScriptResolversVisitor: () => import_visitor.RwTypeScriptResolversVisitor, + TypeScriptResolversPluginConfig: () => import_typescript_resolvers.TypeScriptResolversPluginConfig, + plugin: () => plugin }); -exports.plugin = void 0; -var _indexOf = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/index-of")); -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -var _findIndex = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/find-index")); -var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/slice")); -require("core-js/modules/es.array.push.js"); -var _pluginHelpers = require("@graphql-codegen/plugin-helpers"); -var _typescriptResolvers = require("@graphql-codegen/typescript-resolvers"); -var _visitor = require("./visitor"); +module.exports = __toCommonJS(rw_typescript_resolvers_exports); +var import_plugin_helpers = require("@graphql-codegen/plugin-helpers"); +var import_typescript_resolvers = require("@graphql-codegen/typescript-resolvers"); +var import_visitor = require("./visitor"); const plugin = (schema, _documents, config) => { - var _context, _context2; - // This is the key change compared to the standard typescript-resolver - // plugin implementation - we use our own Visitor here. - const visitor = new _visitor.RwTypeScriptResolversVisitor(config, schema); - - // runs visitor - const visitorResult = (0, _pluginHelpers.oldVisit)((0, _pluginHelpers.getCachedDocumentNodeFromSchema)(schema), { + const visitor = new import_visitor.RwTypeScriptResolversVisitor(config, schema); + const visitorResult = (0, import_plugin_helpers.oldVisit)((0, import_plugin_helpers.getCachedDocumentNodeFromSchema)(schema), { leave: visitor }); - - // `content` here is the output of the original plugin, including the - // original visitor - const { - prepend, - content - } = (0, _typescriptResolvers.plugin)(schema, [], config); - - // A few types needed for our own RW-specific solution + const { prepend, content } = (0, import_typescript_resolvers.plugin)(schema, [], config); prepend.push(`export type OptArgsResolverFn = ( args?: TArgs, obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } @@ -54,39 +41,27 @@ const plugin = (schema, _documents, config) => { args: TArgs, obj: { root: TParent; context: TContext; info: GraphQLResolveInfo } ) => TResult | Promise`); - - // `content` is constructed like this: - // content: [ - // header, - // resolversTypeMapping, - // resolversParentTypeMapping, - // <--- `visitorResultStart` below - // ...visitorResult.definitions.filter( - // (d: unknown) => typeof d === 'string' - // ), - // <--- `visitorResultEnd` below - // getRootResolver(), - // getAllDirectiveResolvers(), - // ].join('\n'), - // We want to replace `visitorResult` with our own result. - // We assume that the original visitorResult begins with the same text as our - // `visitorResult`. We use this to find where we should start replacing content - // We then execute `getRootResolver()` to know what that looks like, and find - // the first line of that output. This is where we'll end our replacement. - // Then we just replace whatever is between those two things with our own - // result - - const splitContent = content.split('\n'); - const visitorResultStart = (0, _indexOf.default)(splitContent).call(splitContent, (0, _filter.default)(_context = visitorResult.definitions).call(_context, d => typeof d === 'string')[0].split('\n')[0]); - const splitRootResolver = visitor.getRootResolver().split('\n'); - const visitorResultEnd = (0, _findIndex.default)(splitContent).call(splitContent, (line, index) => line === splitRootResolver[0] && splitContent[index + 1] === splitRootResolver[1]); - - // Building up `content` with the original visitor content replaced by our - // visitor content - const newContent = [...(0, _slice.default)(splitContent).call(splitContent, 0, visitorResultStart), ...(0, _filter.default)(_context2 = visitorResult.definitions).call(_context2, d => typeof d === 'string'), ...(0, _slice.default)(splitContent).call(splitContent, visitorResultEnd)]; + const splitContent = content.split("\n"); + const visitorResultStart = splitContent.indexOf( + visitorResult.definitions.filter((d) => typeof d === "string")[0].split("\n")[0] + ); + const splitRootResolver = visitor.getRootResolver().split("\n"); + const visitorResultEnd = splitContent.findIndex( + (line, index) => line === splitRootResolver[0] && splitContent[index + 1] === splitRootResolver[1] + ); + const newContent = [ + ...splitContent.slice(0, visitorResultStart), + ...visitorResult.definitions.filter((d) => typeof d === "string"), + ...splitContent.slice(visitorResultEnd) + ]; return { prepend, - content: newContent.join('\n') + content: newContent.join("\n") }; }; -exports.plugin = plugin; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + RwTypeScriptResolversVisitor, + TypeScriptResolversPluginConfig, + plugin +}); diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js index 7819d09af151..1f6e9bf8f17f 100644 --- a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js +++ b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js @@ -1,101 +1,84 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var visitor_exports = {}; +__export(visitor_exports, { + RwTypeScriptResolversVisitor: () => RwTypeScriptResolversVisitor }); -exports.RwTypeScriptResolversVisitor = void 0; -require("core-js/modules/es.array.push.js"); -var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); -var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); -var _typescriptResolvers = require("@graphql-codegen/typescript-resolvers"); -var _visitorPluginCommon = require("@graphql-codegen/visitor-plugin-common"); -class RwTypeScriptResolversVisitor extends _typescriptResolvers.TypeScriptResolversVisitor { +module.exports = __toCommonJS(visitor_exports); +var import_typescript_resolvers = require("@graphql-codegen/typescript-resolvers"); +var import_visitor_plugin_common = require("@graphql-codegen/visitor-plugin-common"); +class RwTypeScriptResolversVisitor extends import_typescript_resolvers.TypeScriptResolversVisitor { constructor(pluginConfig, schema) { super(pluginConfig, schema); } FieldDefinition(node, key, parent) { const hasArguments = node.arguments && node.arguments.length > 0; const superFieldDefinition = super.FieldDefinition(node, key, parent); - return parentName => { - // We're reusing pretty much all of the logic in the original plugin - // Visitor implementation by calling the `super` method here + return (parentName) => { const fieldDef = superFieldDefinition(parentName); - - // If this field doesn't take any arguments, and it is a resolver, then - // we switch to using the OptArgsResolver type instead, so that the user - // isn't forced to pass in arguments that aren't going to be used anyway - if (!hasArguments && fieldDef?.includes(': Resolver<')) { - return fieldDef.replace(': Resolver<', ': OptArgsResolverFn<'); + if (!hasArguments && fieldDef?.includes(": Resolver<")) { + return fieldDef.replace(": Resolver<", ": OptArgsResolverFn<"); } return fieldDef; }; } - // Original implementation is here: // https://github.com/dotansimha/graphql-code-generator/blob/c6c60a3078f3797af435c3852220d8898964031d/packages/plugins/other/visitor-plugin-common/src/base-resolvers-visitor.ts#L1091 ObjectTypeDefinition(node) { - var _context, _context2; - // Call the original implementation to get a block of resolvers const originalBlock = super.ObjectTypeDefinition(node); - - // The rest of this function is pretty much a copy/paste of the original - // function. We're duplicating every block to get RequiredResolver types - // for use with what we call "relation resolvers" (The stuff at the bottom - // of service files for models that have relations) const name = this.convertName(node, { suffix: this.config.resolverTypeSuffix }); const typeName = node.name; const parentType = this.getParentTypeToUse(typeName); - const fieldsContent = (0, _map.default)(_context = node.fields || []).call(_context, f => f(node.name)); - const isRootType = (0, _includes.default)(_context2 = [this.schema.getQueryType()?.name, this.schema.getMutationType()?.name, this.schema.getSubscriptionType()?.name]).call(_context2, typeName); + const fieldsContent = (node.fields || []).map((f) => f(node.name)); + const isRootType = [ + this.schema.getQueryType()?.name, + this.schema.getMutationType()?.name, + this.schema.getSubscriptionType()?.name + ].includes(typeName); if (!isRootType) { - fieldsContent.push((0, _visitorPluginCommon.indent)(`${this.config.internalResolversPrefix}isTypeOf?: IsTypeOfResolverFn${this.getPunctuation('type')}`)); + fieldsContent.push( + (0, import_visitor_plugin_common.indent)( + `${this.config.internalResolversPrefix}isTypeOf?: IsTypeOfResolverFn${this.getPunctuation( + "type" + )}` + ) + ); } - - // This is what's different compared to the implementation I copy/pasted - // We create a new block with a different type called - // "ModelRelationResolver" where "Model" is the name of a prisma model. - // We also replace all Resolver types with RequiredResolverFn types where - // all arguments are required - // - // 1. We start by creating a DeclarationBlock. So something on the form - // X = {} - // 2. Begin by defining X. It should be an exported type. - // 3. `name` is our resolvers, so like 'PostResolvers', 'RedwoodResolvers', - // 'QueryResolvers' etc. - // Replace 'Resolvers' with 'RelationResolvers' to construct our type name. - // Also set the generics for the type - // 4. Time to generate our Block, i.e. what goes inside {} in the X = {} that - // we started with. - // 5. `fieldsContent` is something like - // [ - // " contact: Resolver, ParentType, ContextType, RequireFields>;", - // " contacts: OptArgsResolverFn, ParentType, ContextType>;", - // " post: Resolver, ParentType, ContextType, RequireFields>;", - // " posts: OptArgsResolverFn, ParentType, ContextType>;", - // " redwood: OptArgsResolverFn, ParentType, ContextType>;", - // " user: Resolver, ParentType, ContextType, RequireFields>;" - // ] - // Here the type name needs to be replaced by 'RequiredResolverFn'. We - // do that by running a regex `replace()` on the string - // 6. Finally we join the array with '\n' and we'll have something that - // looks like the type below that we can return together whatever the - // original implementation of this function returned (this is a - // different example than the one above) - // export type PostRelationResolvers = { - // author?: RequiredResolverFn; - // authorId?: RequiredResolverFn; - // body?: RequiredResolverFn; - // createdAt?: RequiredResolverFn; - // id?: RequiredResolverFn; - // title?: RequiredResolverFn; - // __isTypeOf?: IsTypeOfResolverFn; - // }; - const blockRelationsResolver = new _visitorPluginCommon.DeclarationBlock(this._declarationBlockConfig).export().asKind('type').withName(name.replace('Resolvers', 'RelationResolvers'), ``).withBlock((0, _map.default)(fieldsContent).call(fieldsContent, content => content.replace(/: (?:OptArgs)?Resolver(?:Fn)?/, '?: RequiredResolverFn')).join('\n')); - return originalBlock + '\n' + blockRelationsResolver.string; + const blockRelationsResolver = new import_visitor_plugin_common.DeclarationBlock( + this._declarationBlockConfig + ).export().asKind("type").withName( + name.replace("Resolvers", "RelationResolvers"), + `` + ).withBlock( + fieldsContent.map( + (content) => content.replace( + /: (?:OptArgs)?Resolver(?:Fn)?/, + "?: RequiredResolverFn" + ) + ).join("\n") + ); + return originalBlock + "\n" + blockRelationsResolver.string; } } -exports.RwTypeScriptResolversVisitor = RwTypeScriptResolversVisitor; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + RwTypeScriptResolversVisitor +}); diff --git a/packages/internal/dist/generate/possibleTypes.js b/packages/internal/dist/generate/possibleTypes.js index 49c4e3218392..c91763dc4dc5 100644 --- a/packages/internal/dist/generate/possibleTypes.js +++ b/packages/internal/dist/generate/possibleTypes.js @@ -1,63 +1,59 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireWildcard = require("@babel/runtime-corejs3/helpers/interopRequireWildcard").default; -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var possibleTypes_exports = {}; +__export(possibleTypes_exports, { + generatePossibleTypes: () => generatePossibleTypes }); -exports.generatePossibleTypes = void 0; -require("core-js/modules/es.array.push.js"); -var _fs = _interopRequireDefault(require("fs")); -var _path = _interopRequireDefault(require("path")); -var fragmentMatcher = _interopRequireWildcard(require("@graphql-codegen/fragment-matcher")); -var _graphqlFileLoader = require("@graphql-tools/graphql-file-loader"); -var _load = require("@graphql-tools/load"); -var _prettier = require("prettier"); -var _projectConfig = require("@redwoodjs/project-config"); -var _graphqlCodeGen = require("./graphqlCodeGen"); -/** - * Generate possible types from fragments and union types - * - * In order to use fragments with unions and interfaces in Apollo Client, - * you need to tell the client how to discriminate between the different - * types that implement or belong to a supertype. - * - * You pass a possibleTypes option to the InMemoryCache constructor - * to specify these relationships in your schema. - * - * This object maps the name of an interface or union type (the supertype) - * to the types that implement or belong to it (the subtypes). - * - * For example: - * - * ```ts - * possibleTypes: { - * Character: ["Jedi", "Droid"], - * Test: ["PassingTest", "FailingTest", "SkippedTest"], - * Snake: ["Viper", "Python"], - * Groceries: ['Fruit', 'Vegetable'], - * }, - * ``` - * - * @see https://www.apollographql.com/docs/react/data/fragments/#using-fragments-with-unions-and-interfaces - **/ +module.exports = __toCommonJS(possibleTypes_exports); +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var fragmentMatcher = __toESM(require("@graphql-codegen/fragment-matcher")); +var import_graphql_file_loader = require("@graphql-tools/graphql-file-loader"); +var import_load = require("@graphql-tools/load"); +var import_prettier = require("prettier"); +var import_project_config = require("@redwoodjs/project-config"); +var import_graphqlCodeGen = require("./graphqlCodeGen"); const generatePossibleTypes = async () => { - const config = (0, _projectConfig.getConfig)(); + const config = (0, import_project_config.getConfig)(); if (!config.graphql.fragments) { return { possibleTypesFiles: [], errors: [] }; } - const filename = _path.default.join((0, _projectConfig.getPaths)().web.graphql, 'possibleTypes.ts'); - const options = (0, _graphqlCodeGen.getLoadDocumentsOptions)(filename); - const documentsGlob = './web/src/**/!(*.d).{ts,tsx,js,jsx}'; + const filename = import_path.default.join((0, import_project_config.getPaths)().web.graphql, "possibleTypes.ts"); + const options = (0, import_graphqlCodeGen.getLoadDocumentsOptions)(filename); + const documentsGlob = "./web/src/**/!(*.d).{ts,tsx,js,jsx}"; let documents; try { - documents = await (0, _load.loadDocuments)([documentsGlob], options); + documents = await (0, import_load.loadDocuments)([documentsGlob], options); } catch { - // No GraphQL documents present, no need to try to generate possibleTypes return { possibleTypesFiles: [], errors: [] @@ -70,32 +66,32 @@ const generatePossibleTypes = async () => { const info = { outputFile: filename }; - const schema = (0, _load.loadSchemaSync)((0, _projectConfig.getPaths)().generated.schema, { - loaders: [new _graphqlFileLoader.GraphQLFileLoader()], + const schema = (0, import_load.loadSchemaSync)((0, import_project_config.getPaths)().generated.schema, { + loaders: [new import_graphql_file_loader.GraphQLFileLoader()], sort: true }); - const possibleTypes = await fragmentMatcher.plugin(schema, documents, pluginConfig, info); + const possibleTypes = await fragmentMatcher.plugin( + schema, + documents, + pluginConfig, + info + ); files.push(filename); - const output = await (0, _prettier.format)(possibleTypes.toString(), { - trailingComma: 'es5', + const output = await (0, import_prettier.format)(possibleTypes.toString(), { + trailingComma: "es5", bracketSpacing: true, tabWidth: 2, semi: false, singleQuote: true, - arrowParens: 'always', - parser: 'typescript' - }); - _fs.default.mkdirSync(_path.default.dirname(filename), { - recursive: true + arrowParens: "always", + parser: "typescript" }); - _fs.default.writeFileSync(filename, output); - return { - possibleTypesFiles: [filename], - errors - }; + import_fs.default.mkdirSync(import_path.default.dirname(filename), { recursive: true }); + import_fs.default.writeFileSync(filename, output); + return { possibleTypesFiles: [filename], errors }; } catch (e) { errors.push({ - message: 'Error: Could not generate GraphQL possible types (web)', + message: "Error: Could not generate GraphQL possible types (web)", error: e }); return { @@ -104,4 +100,7 @@ const generatePossibleTypes = async () => { }; } }; -exports.generatePossibleTypes = generatePossibleTypes; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + generatePossibleTypes +}); diff --git a/packages/internal/dist/generate/templates.js b/packages/internal/dist/generate/templates.js index f5a0b211c0ac..3e095fd747fa 100644 --- a/packages/internal/dist/generate/templates.js +++ b/packages/internal/dist/generate/templates.js @@ -1,26 +1,61 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var templates_exports = {}; +__export(templates_exports, { + writeTemplate: () => writeTemplate }); -exports.writeTemplate = void 0; -var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/keys")); -var _fs = _interopRequireDefault(require("fs")); -var _path = _interopRequireDefault(require("path")); -/** - * Write the contents of the template to the destination and interpolate the variables. - * The template is a string that uses standard es6 template literals which allow embded expression. - */ +module.exports = __toCommonJS(templates_exports); +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); const writeTemplate = (templatePath, destination, templateValues = {}) => { - const templateString = _fs.default.readFileSync(_path.default.join(__dirname, templatePath), 'utf-8'); + const templateString = import_fs.default.readFileSync( + import_path.default.join(__dirname, templatePath), + "utf-8" + ); const template = templatized(templateString, templateValues); - _fs.default.writeFileSync(destination, '// This file was generated by RedwoodJS\n' + template); + import_fs.default.writeFileSync( + destination, + "// This file was generated by RedwoodJS\n" + template + ); }; -exports.writeTemplate = writeTemplate; const templatized = (template, vars = {}) => { - // eslint-disable-next-line @typescript-eslint/no-implied-eval - const handler = new Function('vars', ['const tagged = ( ' + (0, _keys.default)(vars).join(', ') + ' ) =>', '`' + template + '`', 'return tagged(...Object.values(vars))'].join('\n')); + const handler = new Function( + "vars", + [ + "const tagged = ( " + Object.keys(vars).join(", ") + " ) =>", + "`" + template + "`", + "return tagged(...Object.values(vars))" + ].join("\n") + ); return handler(vars); -}; \ No newline at end of file +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + writeTemplate +}); diff --git a/packages/internal/dist/generate/trustedDocuments.js b/packages/internal/dist/generate/trustedDocuments.js index 0865e2227637..7d45f9c2302b 100644 --- a/packages/internal/dist/generate/trustedDocuments.js +++ b/packages/internal/dist/generate/trustedDocuments.js @@ -1,55 +1,74 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var trustedDocuments_exports = {}; +__export(trustedDocuments_exports, { + replaceGqlTagWithTrustedDocumentGraphql: () => replaceGqlTagWithTrustedDocumentGraphql, + trustedDocumentsStore: () => trustedDocumentsStore }); -exports.trustedDocumentsStore = exports.replaceGqlTagWithTrustedDocumentGraphql = void 0; -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -var _endsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/ends-with")); -var _fs = _interopRequireDefault(require("fs")); -var _path = _interopRequireDefault(require("path")); -var _prettier = require("prettier"); -var _projectConfig = require("@redwoodjs/project-config"); -// Copy the persisted-documents.json to api side as a trustedDocumentsStore -const trustedDocumentsStore = async generatedFiles => { - let trustedDocumentsStoreFile = ''; - const output = (0, _filter.default)(generatedFiles).call(generatedFiles, f => { - var _context; - return (0, _endsWith.default)(_context = f.filename).call(_context, 'persisted-documents.json'); - }); +module.exports = __toCommonJS(trustedDocuments_exports); +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var import_prettier = require("prettier"); +var import_project_config = require("@redwoodjs/project-config"); +const trustedDocumentsStore = async (generatedFiles) => { + let trustedDocumentsStoreFile = ""; + const output = generatedFiles.filter( + (f) => f.filename.endsWith("persisted-documents.json") + ); const storeFile = output[0]; if (storeFile?.content) { - const content = await (0, _prettier.format)(`export const store = ${storeFile.content}`, { - trailingComma: 'es5', + const content = await (0, import_prettier.format)(`export const store = ${storeFile.content}`, { + trailingComma: "es5", bracketSpacing: true, tabWidth: 2, semi: false, singleQuote: true, - arrowParens: 'always', - parser: 'typescript' + arrowParens: "always", + parser: "typescript" }); - trustedDocumentsStoreFile = _path.default.join((0, _projectConfig.getPaths)().api.lib, 'trustedDocumentsStore.ts'); - _fs.default.mkdirSync(_path.default.dirname(trustedDocumentsStoreFile), { - recursive: true - }); - _fs.default.writeFileSync(trustedDocumentsStoreFile, content); + trustedDocumentsStoreFile = import_path.default.join( + (0, import_project_config.getPaths)().api.lib, + "trustedDocumentsStore.ts" + ); + import_fs.default.mkdirSync(import_path.default.dirname(trustedDocumentsStoreFile), { recursive: true }); + import_fs.default.writeFileSync(trustedDocumentsStoreFile, content); } return trustedDocumentsStoreFile; }; - -// Add the gql function to the generated graphql.ts file -// that is used by trusted documents -exports.trustedDocumentsStore = trustedDocumentsStore; -const replaceGqlTagWithTrustedDocumentGraphql = async generatedFiles => { - const gqlFileOutput = (0, _filter.default)(generatedFiles).call(generatedFiles, f => { - var _context2; - return (0, _endsWith.default)(_context2 = f.filename).call(_context2, 'gql.ts'); - }); +const replaceGqlTagWithTrustedDocumentGraphql = async (generatedFiles) => { + const gqlFileOutput = generatedFiles.filter( + (f) => f.filename.endsWith("gql.ts") + ); const gqlFile = gqlFileOutput[0]; if (gqlFile?.content) { - gqlFile.content += `\n + gqlFile.content += ` + export function gql(source: string | TemplateStringsArray) { if (typeof source === 'string') { return graphql(source) @@ -57,16 +76,20 @@ const replaceGqlTagWithTrustedDocumentGraphql = async generatedFiles => { return graphql(source.join('\\n')) }`; - const content = await (0, _prettier.format)(gqlFile.content, { - trailingComma: 'es5', + const content = await (0, import_prettier.format)(gqlFile.content, { + trailingComma: "es5", bracketSpacing: true, tabWidth: 2, semi: true, singleQuote: false, - arrowParens: 'always', - parser: 'typescript' + arrowParens: "always", + parser: "typescript" }); - _fs.default.writeFileSync(gqlFile.filename, content); + import_fs.default.writeFileSync(gqlFile.filename, content); } }; -exports.replaceGqlTagWithTrustedDocumentGraphql = replaceGqlTagWithTrustedDocumentGraphql; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + replaceGqlTagWithTrustedDocumentGraphql, + trustedDocumentsStore +}); diff --git a/packages/internal/dist/generate/typeDefinitions.js b/packages/internal/dist/generate/typeDefinitions.js index 9a524b29273b..39291dfe8cc6 100644 --- a/packages/internal/dist/generate/typeDefinitions.js +++ b/packages/internal/dist/generate/typeDefinitions.js @@ -1,279 +1,276 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var typeDefinitions_exports = {}; +__export(typeDefinitions_exports, { + generateMirrorCell: () => generateMirrorCell, + generateMirrorCells: () => generateMirrorCells, + generateMirrorDirectoryNamedModule: () => generateMirrorDirectoryNamedModule, + generateMirrorDirectoryNamedModules: () => generateMirrorDirectoryNamedModules, + generateTypeDefCurrentUser: () => generateTypeDefCurrentUser, + generateTypeDefGlobImports: () => generateTypeDefGlobImports, + generateTypeDefGlobalContext: () => generateTypeDefGlobalContext, + generateTypeDefRouterPages: () => generateTypeDefRouterPages, + generateTypeDefRouterRoutes: () => generateTypeDefRouterRoutes, + generateTypeDefScenarios: () => generateTypeDefScenarios, + generateTypeDefTestMocks: () => generateTypeDefTestMocks, + generateTypeDefs: () => generateTypeDefs, + generateViteClientTypesDirective: () => generateViteClientTypesDirective, + mirrorPathForCell: () => mirrorPathForCell, + mirrorPathForDirectoryNamedModules: () => mirrorPathForDirectoryNamedModules }); -exports.mirrorPathForDirectoryNamedModules = exports.mirrorPathForCell = exports.generateViteClientTypesDirective = exports.generateTypeDefs = exports.generateTypeDefTestMocks = exports.generateTypeDefScenarios = exports.generateTypeDefRouterRoutes = exports.generateTypeDefRouterPages = exports.generateTypeDefGlobalContext = exports.generateTypeDefGlobImports = exports.generateTypeDefCurrentUser = exports.generateMirrorDirectoryNamedModules = exports.generateMirrorDirectoryNamedModule = exports.generateMirrorCells = exports.generateMirrorCell = void 0; -require("core-js/modules/es.array.push.js"); -require("core-js/modules/esnext.json.parse.js"); -var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); -var _startsWith = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/starts-with")); -var _stringify = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/json/stringify")); -var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/find")); -var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -var _flat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/flat")); -var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/keys")); -var _fs = _interopRequireDefault(require("fs")); -var _path = _interopRequireDefault(require("path")); -var _sourceMap = require("source-map"); -var _projectConfig = require("@redwoodjs/project-config"); -var _ast = require("../ast"); -var _files = require("../files"); -var _gql = require("../gql"); -var _jsx = require("../jsx"); -var _graphqlCodeGen = require("./graphqlCodeGen"); -var _templates = require("./templates"); -// TODO: -// Common return format for CLI output: -// ['type', 'relative path to base'] - -// Note for contributors: -// -// The functions in this file generate type definitions of which there are two types: -// -// 1. Mirror types: Create a virtual directory that allows us to type -// cells and directory named modules. -// 2. Types based on contents of other files -// -// When generating a new type definition that targets a particular side, -// you must prefix the generated filename -// with "web-" or "api-" to target inclusion for that side, -// or use "all-" for both. This is controlled by the user's "tsconfig.json" -// file. - -/** - * Generate all the types for a RedwoodJS project - * and return the generated path to files, so they're logged - */ +module.exports = __toCommonJS(typeDefinitions_exports); +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var import_source_map = require("source-map"); +var import_project_config = require("@redwoodjs/project-config"); +var import_ast = require("../ast"); +var import_files = require("../files"); +var import_gql = require("../gql"); +var import_jsx = require("../jsx"); +var import_graphqlCodeGen = require("./graphqlCodeGen"); +var import_templates = require("./templates"); const generateTypeDefs = async () => { - // Return all the paths so they can be printed - const { - typeDefFiles: gqlApiTypeDefFiles, - errors: apiErrors - } = await (0, _graphqlCodeGen.generateTypeDefGraphQLApi)(); - const { - typeDefFiles: gqlWebTypeDefFiles, - errors: webErrors - } = await (0, _graphqlCodeGen.generateTypeDefGraphQLWeb)(); + const { typeDefFiles: gqlApiTypeDefFiles, errors: apiErrors } = await (0, import_graphqlCodeGen.generateTypeDefGraphQLApi)(); + const { typeDefFiles: gqlWebTypeDefFiles, errors: webErrors } = await (0, import_graphqlCodeGen.generateTypeDefGraphQLWeb)(); return { - typeDefFiles: [...generateMirrorDirectoryNamedModules(), ...generateMirrorCells(), ...generateTypeDefRouterPages(), ...generateTypeDefCurrentUser(), ...generateTypeDefRouterRoutes(), ...generateTypeDefGlobImports(), ...generateTypeDefGlobalContext(), ...generateTypeDefScenarios(), ...generateTypeDefTestMocks(), ...generateStubStorybookTypes(), ...generateViteClientTypesDirective(), ...gqlApiTypeDefFiles, ...gqlWebTypeDefFiles], + typeDefFiles: [ + ...generateMirrorDirectoryNamedModules(), + ...generateMirrorCells(), + ...generateTypeDefRouterPages(), + ...generateTypeDefCurrentUser(), + ...generateTypeDefRouterRoutes(), + ...generateTypeDefGlobImports(), + ...generateTypeDefGlobalContext(), + ...generateTypeDefScenarios(), + ...generateTypeDefTestMocks(), + ...generateStubStorybookTypes(), + ...generateViteClientTypesDirective(), + ...gqlApiTypeDefFiles, + ...gqlWebTypeDefFiles + ], errors: [...apiErrors, ...webErrors] }; }; -exports.generateTypeDefs = generateTypeDefs; const generateMirrorDirectoryNamedModules = () => { - var _context; - const rwjsPaths = (0, _projectConfig.getPaths)(); - return (0, _map.default)(_context = (0, _files.findDirectoryNamedModules)()).call(_context, p => generateMirrorDirectoryNamedModule(p, rwjsPaths)); + const rwjsPaths = (0, import_project_config.getPaths)(); + return (0, import_files.findDirectoryNamedModules)().map( + (p) => generateMirrorDirectoryNamedModule(p, rwjsPaths) + ); }; -exports.generateMirrorDirectoryNamedModules = generateMirrorDirectoryNamedModules; -const mirrorPathForDirectoryNamedModules = (p, rwjsPaths = (0, _projectConfig.getPaths)()) => { - return [_path.default.join(rwjsPaths.generated.types.mirror, _path.default.relative(rwjsPaths.base, _path.default.dirname(p))), 'index.d.ts']; +const mirrorPathForDirectoryNamedModules = (p, rwjsPaths = (0, import_project_config.getPaths)()) => { + return [ + import_path.default.join( + rwjsPaths.generated.types.mirror, + import_path.default.relative(rwjsPaths.base, import_path.default.dirname(p)) + ), + "index.d.ts" + ]; }; -exports.mirrorPathForDirectoryNamedModules = mirrorPathForDirectoryNamedModules; -const generateMirrorDirectoryNamedModule = (p, rwjsPaths = (0, _projectConfig.getPaths)()) => { +const generateMirrorDirectoryNamedModule = (p, rwjsPaths = (0, import_project_config.getPaths)()) => { const [mirrorDir, typeDef] = mirrorPathForDirectoryNamedModules(p, rwjsPaths); - _fs.default.mkdirSync(mirrorDir, { - recursive: true - }); - const typeDefPath = _path.default.join(mirrorDir, typeDef); - const { - name - } = _path.default.parse(p); - (0, _templates.writeTemplate)('templates/mirror-directoryNamedModule.d.ts.template', typeDefPath, { - name - }); - - // We add a source map to allow "go to definition" to avoid ending in the .d.ts file - // We do this for the web side only - if ((0, _startsWith.default)(p).call(p, rwjsPaths.web.src)) { + import_fs.default.mkdirSync(mirrorDir, { recursive: true }); + const typeDefPath = import_path.default.join(mirrorDir, typeDef); + const { name } = import_path.default.parse(p); + (0, import_templates.writeTemplate)( + "templates/mirror-directoryNamedModule.d.ts.template", + typeDefPath, + { name } + ); + if (p.startsWith(rwjsPaths.web.src)) { try { - // Get the line and column where the default export is defined - const fileContents = (0, _ast.fileToAst)(p); - const defaultExportLocation = (0, _ast.getDefaultExportLocation)(fileContents) ?? { + const fileContents = (0, import_ast.fileToAst)(p); + const defaultExportLocation = (0, import_ast.getDefaultExportLocation)(fileContents) ?? { line: 1, column: 0 }; - - // Generate a source map that points to the definition of the default export - const map = new _sourceMap.SourceMapGenerator({ - file: 'index.d.ts' + const map = new import_source_map.SourceMapGenerator({ + file: "index.d.ts" }); map.addMapping({ generated: { line: 4, column: 0 }, - source: _path.default.relative(_path.default.dirname(typeDefPath), p), + source: import_path.default.relative(import_path.default.dirname(typeDefPath), p), original: defaultExportLocation }); - _fs.default.writeFileSync(`${typeDefPath}.map`, (0, _stringify.default)(map.toJSON(), undefined, 2)); + import_fs.default.writeFileSync( + `${typeDefPath}.map`, + JSON.stringify(map.toJSON(), void 0, 2) + ); } catch (error) { - console.error("Couldn't generate a definition map for directory named module at path:", p); + console.error( + "Couldn't generate a definition map for directory named module at path:", + p + ); console.error(error); } } return typeDefPath; }; -exports.generateMirrorDirectoryNamedModule = generateMirrorDirectoryNamedModule; const generateMirrorCells = () => { - var _context2; - const rwjsPaths = (0, _projectConfig.getPaths)(); - return (0, _map.default)(_context2 = (0, _files.findCells)()).call(_context2, p => generateMirrorCell(p, rwjsPaths)); + const rwjsPaths = (0, import_project_config.getPaths)(); + return (0, import_files.findCells)().map((p) => generateMirrorCell(p, rwjsPaths)); }; -exports.generateMirrorCells = generateMirrorCells; -const mirrorPathForCell = (p, rwjsPaths = (0, _projectConfig.getPaths)()) => { - const mirrorDir = _path.default.join(rwjsPaths.generated.types.mirror, _path.default.relative(rwjsPaths.base, _path.default.dirname(p))); - _fs.default.mkdirSync(mirrorDir, { - recursive: true - }); - return [mirrorDir, 'index.d.ts']; +const mirrorPathForCell = (p, rwjsPaths = (0, import_project_config.getPaths)()) => { + const mirrorDir = import_path.default.join( + rwjsPaths.generated.types.mirror, + import_path.default.relative(rwjsPaths.base, import_path.default.dirname(p)) + ); + import_fs.default.mkdirSync(mirrorDir, { recursive: true }); + return [mirrorDir, "index.d.ts"]; }; -exports.mirrorPathForCell = mirrorPathForCell; -const generateMirrorCell = (p, rwjsPaths = (0, _projectConfig.getPaths)()) => { +const generateMirrorCell = (p, rwjsPaths = (0, import_project_config.getPaths)()) => { const [mirrorDir, typeDef] = mirrorPathForCell(p, rwjsPaths); - _fs.default.mkdirSync(mirrorDir, { - recursive: true - }); - const typeDefPath = _path.default.join(mirrorDir, typeDef); - const { - name - } = _path.default.parse(p); - const fileContents = (0, _ast.fileToAst)(p); - const cellQuery = (0, _ast.getCellGqlQuery)(fileContents); + import_fs.default.mkdirSync(mirrorDir, { recursive: true }); + const typeDefPath = import_path.default.join(mirrorDir, typeDef); + const { name } = import_path.default.parse(p); + const fileContents = (0, import_ast.fileToAst)(p); + const cellQuery = (0, import_ast.getCellGqlQuery)(fileContents); if (cellQuery) { - const gqlDoc = (0, _gql.parseGqlQueryToAst)(cellQuery)[0]; - (0, _templates.writeTemplate)('templates/mirror-cell.d.ts.template', typeDefPath, { + const gqlDoc = (0, import_gql.parseGqlQueryToAst)(cellQuery)[0]; + (0, import_templates.writeTemplate)("templates/mirror-cell.d.ts.template", typeDefPath, { name, queryResultType: `${gqlDoc?.name}`, queryVariablesType: `${gqlDoc?.name}Variables` }); } else { - // If for some reason we can't parse the query, generated the mirror cell anyway - (0, _templates.writeTemplate)('templates/mirror-cell.d.ts.template', typeDefPath, { + (0, import_templates.writeTemplate)("templates/mirror-cell.d.ts.template", typeDefPath, { name, - queryResultType: 'any', - queryVariablesType: 'any' + queryResultType: "any", + queryVariablesType: "any" }); } - - // We add a source map to allow "go to definition" to avoid ending in the .d.ts file - // Unlike pages, layouts, components etc. there is no clear definition location so we link - // to the Success component try { - // Get the location of the Success component - const exportedComponents = (0, _ast.getNamedExports)(fileContents); - const successComponent = (0, _find.default)(exportedComponents).call(exportedComponents, x => x.name === 'Success'); - if (successComponent === undefined) { - throw new Error('No Success component found'); + const exportedComponents = (0, import_ast.getNamedExports)(fileContents); + const successComponent = exportedComponents.find( + (x) => x.name === "Success" + ); + if (successComponent === void 0) { + throw new Error("No Success component found"); } - - // Generate the map - const map = new _sourceMap.SourceMapGenerator({ - file: 'index.d.ts' + const map = new import_source_map.SourceMapGenerator({ + file: "index.d.ts" }); map.addMapping({ generated: { line: 12, column: 0 }, - source: _path.default.relative(_path.default.dirname(typeDefPath), p), + source: import_path.default.relative(import_path.default.dirname(typeDefPath), p), original: successComponent.location }); - _fs.default.writeFileSync(`${typeDefPath}.map`, (0, _stringify.default)(map.toJSON(), undefined, 2)); + import_fs.default.writeFileSync( + `${typeDefPath}.map`, + JSON.stringify(map.toJSON(), void 0, 2) + ); } catch (error) { console.error("Couldn't generate a definition map for cell at path:", p); console.error(error); } return typeDefPath; }; -exports.generateMirrorCell = generateMirrorCell; const writeTypeDefIncludeFile = (template, values = {}) => { - const rwjsPaths = (0, _projectConfig.getPaths)(); - const typeDefPath = _path.default.join((0, _includes.default)(rwjsPaths.generated.types), template.replace('.template', '')); - const templateFilename = _path.default.join('templates', template); - (0, _templates.writeTemplate)(templateFilename, typeDefPath, values); + const rwjsPaths = (0, import_project_config.getPaths)(); + const typeDefPath = import_path.default.join( + rwjsPaths.generated.types.includes, + template.replace(".template", "") + ); + const templateFilename = import_path.default.join("templates", template); + (0, import_templates.writeTemplate)(templateFilename, typeDefPath, values); return [typeDefPath]; }; const generateTypeDefRouterRoutes = () => { - var _context3; - const ast = (0, _ast.fileToAst)((0, _projectConfig.getPaths)().web.routes); + const ast = (0, import_ast.fileToAst)((0, import_project_config.getPaths)().web.routes); let hasRootRoute = false; - const routes = (0, _filter.default)(_context3 = (0, _jsx.getJsxElements)(ast, 'Route')).call(_context3, x => { - // All generated "routes" should have a "name" and "path" prop-value - const isValidRoute = typeof x.props?.path !== 'undefined' && typeof x.props?.name !== 'undefined'; - if (isValidRoute && x.props.path === '/') { + const routes = (0, import_jsx.getJsxElements)(ast, "Route").filter((x) => { + const isValidRoute = typeof x.props?.path !== "undefined" && typeof x.props?.name !== "undefined"; + if (isValidRoute && x.props.path === "/") { hasRootRoute = true; } return isValidRoute; }); - - // Generate declaration mapping for improved go-to-definition behaviour try { - const typeDefPath = _path.default.join((0, _includes.default)((0, _projectConfig.getPaths)().generated.types), 'web-routerRoutes.d.ts'); - const map = new _sourceMap.SourceMapGenerator({ - file: 'web-routerRoutes.d.ts' + const typeDefPath = import_path.default.join( + (0, import_project_config.getPaths)().generated.types.includes, + "web-routerRoutes.d.ts" + ); + const map = new import_source_map.SourceMapGenerator({ + file: "web-routerRoutes.d.ts" }); - - // Start line is based on where in the template the - // ` ${name}: (params?: RouteParams<"${path}"> & QueryParams) => "${path}"` - // line is defined const startLine = 7; - - // Map the location of the default export for each page for (let i = 0; i < routes.length; i++) { map.addMapping({ generated: { line: startLine + i, column: 4 }, - source: _path.default.relative(_path.default.dirname(typeDefPath), (0, _projectConfig.getPaths)().web.routes), + source: import_path.default.relative(import_path.default.dirname(typeDefPath), (0, import_project_config.getPaths)().web.routes), original: routes[i].location }); } - _fs.default.writeFileSync(`${typeDefPath}.map`, (0, _stringify.default)(map.toJSON(), undefined, 2)); + import_fs.default.writeFileSync( + `${typeDefPath}.map`, + JSON.stringify(map.toJSON(), void 0, 2) + ); } catch (error) { - console.error("Couldn't generate a definition map for web-routerRoutes.d.ts:"); + console.error( + "Couldn't generate a definition map for web-routerRoutes.d.ts:" + ); console.error(error); } if (!hasRootRoute) { routes.push({ - name: 'splashPage route', - location: { - line: -1, - column: -1 - }, + name: "splashPage route", + location: { line: -1, column: -1 }, props: { - path: '/', - name: 'home' + path: "/", + name: "home" } }); } - return writeTypeDefIncludeFile('web-routerRoutes.d.ts.template', { - routes - }); + return writeTypeDefIncludeFile("web-routerRoutes.d.ts.template", { routes }); }; -exports.generateTypeDefRouterRoutes = generateTypeDefRouterRoutes; const generateTypeDefRouterPages = () => { - const pages = (0, _projectConfig.processPagesDir)(); - - // Generate declaration map for better go-to-definition behaviour + const pages = (0, import_project_config.processPagesDir)(); try { - const typeDefPath = _path.default.join((0, _includes.default)((0, _projectConfig.getPaths)().generated.types), 'web-routesPages.d.ts'); - const map = new _sourceMap.SourceMapGenerator({ - file: 'web-routesPages.d.ts' + const typeDefPath = import_path.default.join( + (0, import_project_config.getPaths)().generated.types.includes, + "web-routesPages.d.ts" + ); + const map = new import_source_map.SourceMapGenerator({ + file: "web-routesPages.d.ts" }); - - // Start line is based on where in the template the ` const ${importName}: typeof ${importName}Type` are defined const startLine = pages.length + 5; - - // Map the location of the default export for each page for (let i = 0; i < pages.length; i++) { - const fileContents = (0, _ast.fileToAst)(pages[i].path); - const defaultExportLocation = (0, _ast.getDefaultExportLocation)(fileContents) ?? { + const fileContents = (0, import_ast.fileToAst)(pages[i].path); + const defaultExportLocation = (0, import_ast.getDefaultExportLocation)(fileContents) ?? { line: 1, column: 0 }; @@ -282,68 +279,91 @@ const generateTypeDefRouterPages = () => { line: startLine + i, column: 0 }, - source: _path.default.relative(_path.default.dirname(typeDefPath), pages[i].path), + source: import_path.default.relative(import_path.default.dirname(typeDefPath), pages[i].path), original: defaultExportLocation }); } - _fs.default.writeFileSync(`${typeDefPath}.map`, (0, _stringify.default)(map.toJSON(), undefined, 2)); + import_fs.default.writeFileSync( + `${typeDefPath}.map`, + JSON.stringify(map.toJSON(), void 0, 2) + ); } catch (error) { - console.error("Couldn't generate a definition map for web-routesPages.d.ts:"); + console.error( + "Couldn't generate a definition map for web-routesPages.d.ts:" + ); console.error(error); } - return writeTypeDefIncludeFile('web-routesPages.d.ts.template', { - pages - }); + return writeTypeDefIncludeFile("web-routesPages.d.ts.template", { pages }); }; -exports.generateTypeDefRouterPages = generateTypeDefRouterPages; const generateTypeDefCurrentUser = () => { - return writeTypeDefIncludeFile('all-currentUser.d.ts.template'); + return writeTypeDefIncludeFile("all-currentUser.d.ts.template"); }; -exports.generateTypeDefCurrentUser = generateTypeDefCurrentUser; const generateTypeDefScenarios = () => { - return writeTypeDefIncludeFile('api-scenarios.d.ts.template'); + return writeTypeDefIncludeFile("api-scenarios.d.ts.template"); }; -exports.generateTypeDefScenarios = generateTypeDefScenarios; const generateTypeDefTestMocks = () => { - var _context4; - return (0, _flat.default)(_context4 = [writeTypeDefIncludeFile('api-test-globals.d.ts.template'), writeTypeDefIncludeFile('web-test-globals.d.ts.template')]).call(_context4); + return [ + writeTypeDefIncludeFile("api-test-globals.d.ts.template"), + writeTypeDefIncludeFile("web-test-globals.d.ts.template") + ].flat(); }; -exports.generateTypeDefTestMocks = generateTypeDefTestMocks; const generateTypeDefGlobImports = () => { - return writeTypeDefIncludeFile('api-globImports.d.ts.template'); + return writeTypeDefIncludeFile("api-globImports.d.ts.template"); }; -exports.generateTypeDefGlobImports = generateTypeDefGlobImports; const generateTypeDefGlobalContext = () => { - return writeTypeDefIncludeFile('api-globalContext.d.ts.template'); + return writeTypeDefIncludeFile("api-globalContext.d.ts.template"); }; -/** - * Typescript does not preserve triple slash directives when outputting js or d.ts files. - * This is a work around so that *.svg, *.png, etc. imports have types. - */ -exports.generateTypeDefGlobalContext = generateTypeDefGlobalContext; const generateViteClientTypesDirective = () => { const viteClientDirective = `/// `; - const redwoodProjectPaths = (0, _projectConfig.getPaths)(); - const viteClientDirectivePath = _path.default.join((0, _includes.default)(redwoodProjectPaths.generated.types), 'web-vite-client.d.ts'); - _fs.default.writeFileSync(viteClientDirectivePath, viteClientDirective); + const redwoodProjectPaths = (0, import_project_config.getPaths)(); + const viteClientDirectivePath = import_path.default.join( + redwoodProjectPaths.generated.types.includes, + "web-vite-client.d.ts" + ); + import_fs.default.writeFileSync(viteClientDirectivePath, viteClientDirective); return [viteClientDirectivePath]; }; -exports.generateViteClientTypesDirective = generateViteClientTypesDirective; function generateStubStorybookTypes() { - var _context5; - const stubStorybookTypesFileContent = `\ -declare module '@storybook/react' { + const stubStorybookTypesFileContent = `declare module '@storybook/react' { export type Meta = any export type StoryObj = any } `; - const redwoodProjectPaths = (0, _projectConfig.getPaths)(); - const packageJson = JSON.parse(_fs.default.readFileSync(_path.default.join(redwoodProjectPaths.base, 'package.json'), 'utf-8')); - const hasCliStorybookVite = (0, _includes.default)(_context5 = (0, _keys.default)(packageJson['devDependencies'])).call(_context5, '@redwoodjs/cli-storybook-vite'); + const redwoodProjectPaths = (0, import_project_config.getPaths)(); + const packageJson = JSON.parse( + import_fs.default.readFileSync( + import_path.default.join(redwoodProjectPaths.base, "package.json"), + "utf-8" + ) + ); + const hasCliStorybookVite = Object.keys( + packageJson["devDependencies"] + ).includes("@redwoodjs/cli-storybook-vite"); if (hasCliStorybookVite) { return []; } - const stubStorybookTypesFilePath = _path.default.join((0, _includes.default)(redwoodProjectPaths.generated.types), 'web-storybook.d.ts'); - _fs.default.writeFileSync(stubStorybookTypesFilePath, stubStorybookTypesFileContent); + const stubStorybookTypesFilePath = import_path.default.join( + redwoodProjectPaths.generated.types.includes, + "web-storybook.d.ts" + ); + import_fs.default.writeFileSync(stubStorybookTypesFilePath, stubStorybookTypesFileContent); return [stubStorybookTypesFilePath]; -} \ No newline at end of file +} +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + generateMirrorCell, + generateMirrorCells, + generateMirrorDirectoryNamedModule, + generateMirrorDirectoryNamedModules, + generateTypeDefCurrentUser, + generateTypeDefGlobImports, + generateTypeDefGlobalContext, + generateTypeDefRouterPages, + generateTypeDefRouterRoutes, + generateTypeDefScenarios, + generateTypeDefTestMocks, + generateTypeDefs, + generateViteClientTypesDirective, + mirrorPathForCell, + mirrorPathForDirectoryNamedModules +}); diff --git a/packages/internal/dist/generate/types.js b/packages/internal/dist/generate/types.js index 16ae9a868a6a..43ae53610554 100644 --- a/packages/internal/dist/generate/types.js +++ b/packages/internal/dist/generate/types.js @@ -1,6 +1,16 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -_Object$defineProperty(exports, "__esModule", { - value: true -}); \ No newline at end of file +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var types_exports = {}; +module.exports = __toCommonJS(types_exports); diff --git a/packages/internal/dist/generate/watch.js b/packages/internal/dist/generate/watch.js index 57fe1009a09e..9866ad4cfae3 100755 --- a/packages/internal/dist/generate/watch.js +++ b/packages/internal/dist/generate/watch.js @@ -1,109 +1,124 @@ #!/usr/bin/env node "use strict"; - -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -var _trim = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/trim")); -var _now = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/date/now")); -var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); -var _fs = _interopRequireDefault(require("fs")); -var _path = _interopRequireDefault(require("path")); -var _chalk = _interopRequireDefault(require("chalk")); -var _chokidar = _interopRequireDefault(require("chokidar")); -var _projectConfig = require("@redwoodjs/project-config"); -var _cliLogger = require("../cliLogger"); -var _files = require("../files"); -var _routes = require("../routes"); -var _clientPreset = require("./clientPreset"); -var _generate = require("./generate"); -var _graphqlCodeGen = require("./graphqlCodeGen"); -var _graphqlSchema = require("./graphqlSchema"); -var _typeDefinitions = require("./typeDefinitions"); -const rwjsPaths = (0, _projectConfig.getPaths)(); -const watcher = _chokidar.default.watch('(web|api)/src/**/*.{ts,js,jsx,tsx}', { +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var import_chalk = __toESM(require("chalk")); +var import_chokidar = __toESM(require("chokidar")); +var import_project_config = require("@redwoodjs/project-config"); +var import_cliLogger = require("../cliLogger"); +var import_files = require("../files"); +var import_routes = require("../routes"); +var import_clientPreset = require("./clientPreset"); +var import_generate = require("./generate"); +var import_graphqlCodeGen = require("./graphqlCodeGen"); +var import_graphqlSchema = require("./graphqlSchema"); +var import_typeDefinitions = require("./typeDefinitions"); +const rwjsPaths = (0, import_project_config.getPaths)(); +const watcher = import_chokidar.default.watch("(web|api)/src/**/*.{ts,js,jsx,tsx}", { persistent: true, - ignored: ['node_modules', '.redwood'], + ignored: ["node_modules", ".redwood"], ignoreInitial: true, cwd: rwjsPaths.base, awaitWriteFinish: true }); const action = { - add: 'Created', - unlink: 'Deleted', - change: 'Modified' + add: "Created", + unlink: "Deleted", + change: "Modified" }; -let routesWarningMessage = ''; -process.stdin.on('data', async data => { - var _context; - const str = (0, _trim.default)(_context = data.toString()).call(_context).toLowerCase(); - if (str === 'g' || str === 'rs') { - (0, _cliLogger.cliLogger)('Re-creating TypeScript definitions and GraphQL schemas'); - await (0, _generate.generate)(); +let routesWarningMessage = ""; +process.stdin.on("data", async (data) => { + const str = data.toString().trim().toLowerCase(); + if (str === "g" || str === "rs") { + (0, import_cliLogger.cliLogger)("Re-creating TypeScript definitions and GraphQL schemas"); + await (0, import_generate.generate)(); } }); -watcher.on('ready', async () => { - const start = (0, _now.default)(); - (0, _cliLogger.cliLogger)('Generating full TypeScript definitions and GraphQL schemas'); - const { - files, - errors - } = await (0, _generate.generate)(); - (0, _cliLogger.cliLogger)(`Done.`); - _cliLogger.cliLogger.debug(`\nCreated ${files.length} in ${(0, _now.default)() - start} ms`); +watcher.on("ready", async () => { + const start = Date.now(); + (0, import_cliLogger.cliLogger)("Generating full TypeScript definitions and GraphQL schemas"); + const { files, errors } = await (0, import_generate.generate)(); + (0, import_cliLogger.cliLogger)(`Done.`); + import_cliLogger.cliLogger.debug(` +Created ${files.length} in ${Date.now() - start} ms`); if (errors.length > 0) { - for (const { - message, - error - } of errors) { + for (const { message, error } of errors) { console.error(message); console.error(error); console.log(); } } - routesWarningMessage = (0, _routes.warningForDuplicateRoutes)(); + routesWarningMessage = (0, import_routes.warningForDuplicateRoutes)(); if (routesWarningMessage) { console.warn(routesWarningMessage); } -}).on('all', async (eventName, p) => { - var _context2; - _cliLogger.cliLogger.trace(`File system change: ${_chalk.default.magenta(eventName)} ${_chalk.default.dim(p)}`); - if (!(0, _includes.default)(_context2 = ['add', 'change', 'unlink']).call(_context2, eventName)) { +}).on("all", async (eventName, p) => { + import_cliLogger.cliLogger.trace( + `File system change: ${import_chalk.default.magenta(eventName)} ${import_chalk.default.dim(p)}` + ); + if (!["add", "change", "unlink"].includes(eventName)) { return; } const eventTigger = eventName; - const absPath = _path.default.join(rwjsPaths.base, p); - - // Track the time in debug - const start = (0, _now.default)(); - const finished = type => _cliLogger.cliLogger.debug(action[eventTigger], type + ':', _chalk.default.dim(p), _chalk.default.dim.italic((0, _now.default)() - start + ' ms')); - if ((0, _includes.default)(absPath).call(absPath, 'Cell') && (0, _files.isCellFile)(absPath)) { - await (0, _graphqlCodeGen.generateTypeDefGraphQLWeb)(); - await (0, _clientPreset.generateClientPreset)(); - if (eventName === 'unlink') { - _fs.default.unlinkSync((0, _typeDefinitions.mirrorPathForCell)(absPath, rwjsPaths)[0]); + const absPath = import_path.default.join(rwjsPaths.base, p); + const start = Date.now(); + const finished = (type) => import_cliLogger.cliLogger.debug( + action[eventTigger], + type + ":", + import_chalk.default.dim(p), + import_chalk.default.dim.italic(Date.now() - start + " ms") + ); + if (absPath.includes("Cell") && (0, import_files.isCellFile)(absPath)) { + await (0, import_graphqlCodeGen.generateTypeDefGraphQLWeb)(); + await (0, import_clientPreset.generateClientPreset)(); + if (eventName === "unlink") { + import_fs.default.unlinkSync((0, import_typeDefinitions.mirrorPathForCell)(absPath, rwjsPaths)[0]); } else { - (0, _typeDefinitions.generateMirrorCell)(absPath, rwjsPaths); + (0, import_typeDefinitions.generateMirrorCell)(absPath, rwjsPaths); } - finished('Cell'); + finished("Cell"); } else if (absPath === rwjsPaths.web.routes) { - (0, _typeDefinitions.generateTypeDefRouterRoutes)(); - routesWarningMessage = (0, _routes.warningForDuplicateRoutes)(); - finished('Routes'); - } else if ((0, _includes.default)(absPath).call(absPath, 'Page') && (0, _files.isPageFile)(absPath)) { - (0, _typeDefinitions.generateTypeDefRouterPages)(); - finished('Page'); - } else if ((0, _files.isDirectoryNamedModuleFile)(absPath)) { - if (eventName === 'unlink') { - _fs.default.unlinkSync((0, _typeDefinitions.mirrorPathForDirectoryNamedModules)(absPath, rwjsPaths)[0]); + (0, import_typeDefinitions.generateTypeDefRouterRoutes)(); + routesWarningMessage = (0, import_routes.warningForDuplicateRoutes)(); + finished("Routes"); + } else if (absPath.includes("Page") && (0, import_files.isPageFile)(absPath)) { + (0, import_typeDefinitions.generateTypeDefRouterPages)(); + finished("Page"); + } else if ((0, import_files.isDirectoryNamedModuleFile)(absPath)) { + if (eventName === "unlink") { + import_fs.default.unlinkSync((0, import_typeDefinitions.mirrorPathForDirectoryNamedModules)(absPath, rwjsPaths)[0]); } else { - (0, _typeDefinitions.generateMirrorDirectoryNamedModule)(absPath, rwjsPaths); + (0, import_typeDefinitions.generateMirrorDirectoryNamedModule)(absPath, rwjsPaths); } - finished('Directory named module'); - } else if ((0, _files.isGraphQLSchemaFile)(absPath)) { - await (0, _graphqlSchema.generateGraphQLSchema)(); - await (0, _graphqlCodeGen.generateTypeDefGraphQLApi)(); - finished('GraphQL Schema'); + finished("Directory named module"); + } else if ((0, import_files.isGraphQLSchemaFile)(absPath)) { + await (0, import_graphqlSchema.generateGraphQLSchema)(); + await (0, import_graphqlCodeGen.generateTypeDefGraphQLApi)(); + finished("GraphQL Schema"); } if (routesWarningMessage) { console.warn(routesWarningMessage); } -}); \ No newline at end of file +}); diff --git a/packages/internal/dist/gql.js b/packages/internal/dist/gql.js index ed34447bbdc9..f1434b84874c 100644 --- a/packages/internal/dist/gql.js +++ b/packages/internal/dist/gql.js @@ -1,31 +1,43 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var gql_exports = {}; +__export(gql_exports, { + listQueryTypeFieldsInProject: () => listQueryTypeFieldsInProject, + parseDocumentAST: () => parseDocumentAST, + parseGqlQueryToAst: () => parseGqlQueryToAst }); -exports.parseGqlQueryToAst = exports.parseDocumentAST = exports.listQueryTypeFieldsInProject = void 0; -require("core-js/modules/es.array.push.js"); -var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/for-each")); -var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/keys")); -var _codeFileLoader = require("@graphql-tools/code-file-loader"); -var _load = require("@graphql-tools/load"); -var _graphql = require("graphql"); -var _graphqlServer = require("@redwoodjs/graphql-server"); -var _projectConfig = require("@redwoodjs/project-config"); -const parseGqlQueryToAst = gqlQuery => { - const ast = (0, _graphql.parse)(gqlQuery); +module.exports = __toCommonJS(gql_exports); +var import_code_file_loader = require("@graphql-tools/code-file-loader"); +var import_load = require("@graphql-tools/load"); +var import_graphql = require("graphql"); +var import_graphql_server = require("@redwoodjs/graphql-server"); +var import_project_config = require("@redwoodjs/project-config"); +const parseGqlQueryToAst = (gqlQuery) => { + const ast = (0, import_graphql.parse)(gqlQuery); return parseDocumentAST(ast); }; -exports.parseGqlQueryToAst = parseGqlQueryToAst; -const parseDocumentAST = document => { +const parseDocumentAST = (document) => { const operations = []; - (0, _graphql.visit)(document, { + (0, import_graphql.visit)(document, { OperationDefinition(node) { - var _context; const fields = []; - (0, _forEach.default)(_context = node.selectionSet.selections).call(_context, field => { + node.selectionSet.selections.forEach((field) => { fields.push(getFields(field)); }); operations.push({ @@ -37,25 +49,22 @@ const parseDocumentAST = document => { }); return operations; }; -exports.parseDocumentAST = parseDocumentAST; -const getFields = field => { - // base +const getFields = (field) => { if (!field.selectionSet) { return field.name.value; } else { const obj = { [field.name.value]: [] }; - const lookAtFieldNode = node => { - node.selectionSet?.selections.forEach(subField => { + const lookAtFieldNode = (node) => { + node.selectionSet?.selections.forEach((subField) => { switch (subField.kind) { - case _graphql.Kind.FIELD: + case import_graphql.Kind.FIELD: obj[field.name.value].push(getFields(subField)); break; - case _graphql.Kind.FRAGMENT_SPREAD: - // TODO: Maybe this will also be needed, right now it's accounted for to not crash in the tests + case import_graphql.Kind.FRAGMENT_SPREAD: break; - case _graphql.Kind.INLINE_FRAGMENT: + case import_graphql.Kind.INLINE_FRAGMENT: lookAtFieldNode(subField); } }); @@ -67,28 +76,33 @@ const getFields = field => { const listQueryTypeFieldsInProject = async () => { try { const schemaPointerMap = { - [(0, _graphql.print)(_graphqlServer.rootSchema.schema)]: {}, - 'graphql/**/*.sdl.{js,ts}': {}, - 'directives/**/*.{js,ts}': {}, - 'subscriptions/**/*.{js,ts}': {} + [(0, import_graphql.print)(import_graphql_server.rootSchema.schema)]: {}, + "graphql/**/*.sdl.{js,ts}": {}, + "directives/**/*.{js,ts}": {}, + "subscriptions/**/*.{js,ts}": {} }; - const mergedSchema = await (0, _load.loadSchema)(schemaPointerMap, { - loaders: [new _codeFileLoader.CodeFileLoader({ - noRequire: true, - pluckConfig: { - globalGqlIdentifierName: 'gql' - } - })], - cwd: (0, _projectConfig.getPaths)().api.src, + const mergedSchema = await (0, import_load.loadSchema)(schemaPointerMap, { + loaders: [ + new import_code_file_loader.CodeFileLoader({ + noRequire: true, + pluckConfig: { + globalGqlIdentifierName: "gql" + } + }) + ], + cwd: (0, import_project_config.getPaths)().api.src, assumeValidSDL: true }); const queryTypeFields = mergedSchema.getQueryType()?.getFields(); - - // Return empty array if no schema found - return (0, _keys.default)(queryTypeFields ?? {}); + return Object.keys(queryTypeFields ?? {}); } catch (e) { console.error(e); return []; } }; -exports.listQueryTypeFieldsInProject = listQueryTypeFieldsInProject; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + listQueryTypeFieldsInProject, + parseDocumentAST, + parseGqlQueryToAst +}); diff --git a/packages/internal/dist/index.js b/packages/internal/dist/index.js index 2c88d795f598..88cc38e106b0 100644 --- a/packages/internal/dist/index.js +++ b/packages/internal/dist/index.js @@ -1,119 +1,49 @@ "use strict"; - -var _context, _context2, _context3, _context4, _context5, _context6, _context7; -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _forEachInstanceProperty = require("@babel/runtime-corejs3/core-js/instance/for-each"); -var _Object$keys = require("@babel/runtime-corejs3/core-js/object/keys"); -_Object$defineProperty(exports, "__esModule", { - value: true -}); -var _exportNames = { - generate: true, - buildApi: true, - listQueryTypeFieldsInProject: true +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); }; -_Object$defineProperty(exports, "buildApi", { - enumerable: true, - get: function () { - return _api.buildApi; - } -}); -_Object$defineProperty(exports, "generate", { - enumerable: true, - get: function () { - return _generate.generate; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } + return to; +}; +var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var src_exports = {}; +__export(src_exports, { + buildApi: () => import_api.buildApi, + generate: () => import_generate.generate, + listQueryTypeFieldsInProject: () => import_gql.listQueryTypeFieldsInProject +}); +module.exports = __toCommonJS(src_exports); +__reExport(src_exports, require("@redwoodjs/project-config"), module.exports); +__reExport(src_exports, require("./ts2js"), module.exports); +__reExport(src_exports, require("./dev"), module.exports); +__reExport(src_exports, require("./routes"), module.exports); +__reExport(src_exports, require("./files"), module.exports); +var import_generate = require("./generate/generate"); +var import_api = require("./build/api"); +__reExport(src_exports, require("./validateSchema"), module.exports); +__reExport(src_exports, require("@redwoodjs/babel-config"), module.exports); +var import_gql = require("./gql"); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + buildApi, + generate, + listQueryTypeFieldsInProject, + ...require("@redwoodjs/project-config"), + ...require("./ts2js"), + ...require("./dev"), + ...require("./routes"), + ...require("./files"), + ...require("./validateSchema"), + ...require("@redwoodjs/babel-config") }); -_Object$defineProperty(exports, "listQueryTypeFieldsInProject", { - enumerable: true, - get: function () { - return _gql.listQueryTypeFieldsInProject; - } -}); -var _projectConfig = require("@redwoodjs/project-config"); -_forEachInstanceProperty(_context = _Object$keys(_projectConfig)).call(_context, function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _projectConfig[key]) return; - _Object$defineProperty(exports, key, { - enumerable: true, - get: function () { - return _projectConfig[key]; - } - }); -}); -var _ts2js = require("./ts2js"); -_forEachInstanceProperty(_context2 = _Object$keys(_ts2js)).call(_context2, function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _ts2js[key]) return; - _Object$defineProperty(exports, key, { - enumerable: true, - get: function () { - return _ts2js[key]; - } - }); -}); -var _dev = require("./dev"); -_forEachInstanceProperty(_context3 = _Object$keys(_dev)).call(_context3, function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _dev[key]) return; - _Object$defineProperty(exports, key, { - enumerable: true, - get: function () { - return _dev[key]; - } - }); -}); -var _routes = require("./routes"); -_forEachInstanceProperty(_context4 = _Object$keys(_routes)).call(_context4, function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _routes[key]) return; - _Object$defineProperty(exports, key, { - enumerable: true, - get: function () { - return _routes[key]; - } - }); -}); -var _files = require("./files"); -_forEachInstanceProperty(_context5 = _Object$keys(_files)).call(_context5, function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _files[key]) return; - _Object$defineProperty(exports, key, { - enumerable: true, - get: function () { - return _files[key]; - } - }); -}); -var _generate = require("./generate/generate"); -var _api = require("./build/api"); -var _validateSchema = require("./validateSchema"); -_forEachInstanceProperty(_context6 = _Object$keys(_validateSchema)).call(_context6, function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _validateSchema[key]) return; - _Object$defineProperty(exports, key, { - enumerable: true, - get: function () { - return _validateSchema[key]; - } - }); -}); -var _babelConfig = require("@redwoodjs/babel-config"); -_forEachInstanceProperty(_context7 = _Object$keys(_babelConfig)).call(_context7, function (key) { - if (key === "default" || key === "__esModule") return; - if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; - if (key in exports && exports[key] === _babelConfig[key]) return; - _Object$defineProperty(exports, key, { - enumerable: true, - get: function () { - return _babelConfig[key]; - } - }); -}); -var _gql = require("./gql"); \ No newline at end of file diff --git a/packages/internal/dist/jsx.js b/packages/internal/dist/jsx.js index d13bf9570c19..328c3c20eeeb 100644 --- a/packages/internal/dist/jsx.js +++ b/packages/internal/dist/jsx.js @@ -1,66 +1,70 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jsx_exports = {}; +__export(jsx_exports, { + getJsxElements: () => getJsxElements }); -exports.getJsxElements = void 0; -require("core-js/modules/es.array.push.js"); -var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/concat")); -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/for-each")); -var _traverse = _interopRequireDefault(require("@babel/traverse")); -var _jsxAttributeValue = require("./jsxAttributeValue"); -/** - * Extract JSX elements, children and props from static code. - */ +module.exports = __toCommonJS(jsx_exports); +var import_traverse = __toESM(require("@babel/traverse")); +var import_jsxAttributeValue = require("./jsxAttributeValue"); const getJsxElements = (ast, name) => { let elements = []; - (0, _traverse.default)(ast, { + (0, import_traverse.default)(ast, { JSXIdentifier(path) { - if (path.node.name === name && path.parentPath.type === 'JSXOpeningElement') { - if (path?.parentPath?.parentPath?.type === 'JSXElement') { + if (path.node.name === name && path.parentPath.type === "JSXOpeningElement") { + if (path?.parentPath?.parentPath?.type === "JSXElement") { const element = reduceJsxElement([], path.parentPath.parentPath.node); - elements = (0, _concat.default)(elements).call(elements, element); + elements = elements.concat(element); } } } }); return elements; }; - -/** - * Extract attributes (props) from a JSX element. - */ -exports.getJsxElements = getJsxElements; -const getJsxAttributes = jsxElement => { - var _context; - return (0, _filter.default)(_context = jsxElement.openingElement.attributes).call(_context, ({ - type - }) => type === 'JSXAttribute'); +const getJsxAttributes = (jsxElement) => { + return jsxElement.openingElement.attributes.filter( + ({ type }) => type === "JSXAttribute" + ); }; - -/** - * Extract and format props (attributes) from a JSX element. - */ -const getJsxProps = jsxElement => { +const getJsxProps = (jsxElement) => { const attributes = getJsxAttributes(jsxElement); const props = {}; for (const a of attributes) { - if (typeof a.name.name === 'string') { - props[a.name.name] = (0, _jsxAttributeValue.getJsxAttributeValue)(a.value); + if (typeof a.name.name === "string") { + props[a.name.name] = (0, import_jsxAttributeValue.getJsxAttributeValue)(a.value); } } return props; }; - -/** - * Traverse a JSX element tree and place it into a simple JSON format. - */ const reduceJsxElement = (oldNode, currentNode) => { let element = { - name: '', + name: "", props: {}, children: [], location: { @@ -68,9 +72,9 @@ const reduceJsxElement = (oldNode, currentNode) => { column: 0 } }; - if (currentNode.type === 'JSXElement') { + if (currentNode.type === "JSXElement") { const props = getJsxProps(currentNode); - if (currentNode.openingElement.name.type === 'JSXIdentifier') { + if (currentNode.openingElement.name.type === "JSXIdentifier") { element = { name: currentNode.openingElement.name.name, props, @@ -83,9 +87,14 @@ const reduceJsxElement = (oldNode, currentNode) => { oldNode.push(element); } } - if ('children' in currentNode) { - var _context2; - (0, _forEach.default)(_context2 = currentNode.children).call(_context2, node => oldNode.length > 0 ? reduceJsxElement(element.children, node) : reduceJsxElement(oldNode, node)); + if ("children" in currentNode) { + currentNode.children.forEach( + (node) => oldNode.length > 0 ? reduceJsxElement(element.children, node) : reduceJsxElement(oldNode, node) + ); } return oldNode; -}; \ No newline at end of file +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getJsxElements +}); diff --git a/packages/internal/dist/jsxAttributeValue.js b/packages/internal/dist/jsxAttributeValue.js index 5a92f9d56af0..32954aac6c4f 100644 --- a/packages/internal/dist/jsxAttributeValue.js +++ b/packages/internal/dist/jsxAttributeValue.js @@ -1,127 +1,129 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var jsxAttributeValue_exports = {}; +__export(jsxAttributeValue_exports, { + getJsxAttributeValue: () => getJsxAttributeValue }); -exports.getJsxAttributeValue = void 0; -var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); -var _reduce = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/reduce")); -var _sort = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/sort")); -var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/concat")); -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -/* eslint-disable @typescript-eslint/ban-ts-comment */ -// @ts-nocheck This function was adapted from: https://github.com/gglnx/simplified-jsx-to-json/blob/master/index.js#L13 -const getJsxAttributeValue = expression => { - // If the expression is null, this is an implicitly "true" prop, such as readOnly +module.exports = __toCommonJS(jsxAttributeValue_exports); +const getJsxAttributeValue = (expression) => { if (expression === null) { return true; } - if (expression.type === 'StringLiteral') { + if (expression.type === "StringLiteral") { return expression.value; } - if (expression.type === 'JSXExpressionContainer') { + if (expression.type === "JSXExpressionContainer") { return getJsxAttributeValue(expression.expression); } - if (expression.type === 'ArrayExpression') { - var _context; - return (0, _map.default)(_context = expression.elements).call(_context, element => getJsxAttributeValue(element)); + if (expression.type === "ArrayExpression") { + return expression.elements.map((element) => getJsxAttributeValue(element)); } - if (expression.type === 'TemplateLiteral') { - var _context2, _context3, _context4; - const expressions = (0, _map.default)(_context2 = expression.expressions).call(_context2, element => ({ + if (expression.type === "TemplateLiteral") { + const expressions = expression.expressions.map((element) => ({ ...element, value: { raw: element.value, cooked: getJsxAttributeValue(element) } })); - return (0, _reduce.default)(_context3 = (0, _sort.default)(_context4 = (0, _concat.default)(expressions).call(expressions, expression.quasis)).call(_context4, (elementA, elementB) => elementA.start - elementB.start)).call(_context3, (string, element) => `${string}${element.value.cooked.toString()}`, ''); + return expressions.concat(expression.quasis).sort((elementA, elementB) => elementA.start - elementB.start).reduce( + (string, element) => `${string}${element.value.cooked.toString()}`, + "" + ); } - if (expression.type === 'ObjectExpression') { - var _context5, _context6, _context7; - const entries = (0, _reduce.default)(_context5 = (0, _filter.default)(_context6 = (0, _map.default)(_context7 = expression.properties).call(_context7, property => { + if (expression.type === "ObjectExpression") { + const entries = expression.properties.map((property) => { const key = getJsxAttributeValue(property.key); const value = getJsxAttributeValue(property.value); - if (key === undefined || value === undefined) { + if (key === void 0 || value === void 0) { return null; } - return { - key, - value - }; - })).call(_context6, property => property)).call(_context5, (properties, property) => { - return { - ...properties, - [property.key]: property.value - }; + return { key, value }; + }).filter((property) => property).reduce((properties, property) => { + return { ...properties, [property.key]: property.value }; }, {}); return entries; } - if (expression.type === 'Identifier') { + if (expression.type === "Identifier") { return expression.name; } - if (expression.type === 'BinaryExpression') { + if (expression.type === "BinaryExpression") { switch (expression.operator) { - case '+': + case "+": return getJsxAttributeValue(expression.left) + getJsxAttributeValue(expression.right); - case '-': + case "-": return getJsxAttributeValue(expression.left) - getJsxAttributeValue(expression.right); - case '*': + case "*": return getJsxAttributeValue(expression.left) * getJsxAttributeValue(expression.right); - case '**': + case "**": return getJsxAttributeValue(expression.left) ** getJsxAttributeValue(expression.right); - case '/': + case "/": return getJsxAttributeValue(expression.left) / getJsxAttributeValue(expression.right); - case '%': + case "%": return getJsxAttributeValue(expression.left) % getJsxAttributeValue(expression.right); - case '==': + case "==": return getJsxAttributeValue(expression.left) == getJsxAttributeValue(expression.right); - case '===': + case "===": return getJsxAttributeValue(expression.left) === getJsxAttributeValue(expression.right); - case '!=': + case "!=": return getJsxAttributeValue(expression.left) != getJsxAttributeValue(expression.right); - case '!==': + case "!==": return getJsxAttributeValue(expression.left) !== getJsxAttributeValue(expression.right); - case '<': + case "<": return getJsxAttributeValue(expression.left) < getJsxAttributeValue(expression.right); - case '<=': + case "<=": return getJsxAttributeValue(expression.left) <= getJsxAttributeValue(expression.right); - case '>': + case ">": return getJsxAttributeValue(expression.left) > getJsxAttributeValue(expression.right); - case '>=': + case ">=": return getJsxAttributeValue(expression.left) >= getJsxAttributeValue(expression.right); - case '<<': + case "<<": return getJsxAttributeValue(expression.left) << getJsxAttributeValue(expression.right); - case '>>': + case ">>": return getJsxAttributeValue(expression.left) >> getJsxAttributeValue(expression.right); - case '>>>': + case ">>>": return getJsxAttributeValue(expression.left) >>> getJsxAttributeValue(expression.right); - case '|': + case "|": return getJsxAttributeValue(expression.left) | getJsxAttributeValue(expression.right); - case '&': + case "&": return getJsxAttributeValue(expression.left) & getJsxAttributeValue(expression.right); - case '^': + case "^": return getJsxAttributeValue(expression.left) ^ getJsxAttributeValue(expression.right); default: return `BinaryExpression with "${expression.operator}" is not supported`; } } - if (expression.type === 'UnaryExpression') { + if (expression.type === "UnaryExpression") { switch (expression.operator) { - case '+': + case "+": return +getJsxAttributeValue(expression.argument); - case '-': + case "-": return -getJsxAttributeValue(expression.argument); - case '~': + case "~": return ~getJsxAttributeValue(expression.argument); default: return `UnaryExpression with "${expression.operator}" is not supported`; } } - - // Unsupported type return `${expression.type} is not supported`; }; -exports.getJsxAttributeValue = getJsxAttributeValue; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getJsxAttributeValue +}); diff --git a/packages/internal/dist/project.js b/packages/internal/dist/project.js index 06cbaea165ac..577720ca0a7d 100644 --- a/packages/internal/dist/project.js +++ b/packages/internal/dist/project.js @@ -1,39 +1,82 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var project_exports = {}; +__export(project_exports, { + getTsConfigs: () => getTsConfigs, + isRealtimeSetup: () => isRealtimeSetup, + isServerFileSetup: () => isServerFileSetup, + isTypeScriptProject: () => isTypeScriptProject }); -exports.isTypeScriptProject = exports.isServerFileSetup = exports.isRealtimeSetup = exports.getTsConfigs = void 0; -var _fs = _interopRequireDefault(require("fs")); -var _path = _interopRequireDefault(require("path")); -var _typescript = require("typescript"); -var _projectConfig = require("@redwoodjs/project-config"); +module.exports = __toCommonJS(project_exports); +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var import_typescript = require("typescript"); +var import_project_config = require("@redwoodjs/project-config"); const getTsConfigs = () => { - const rwPaths = (0, _projectConfig.getPaths)(); - const apiTsConfigPath = _path.default.join(rwPaths.api.base, 'tsconfig.json'); - const webTsConfigPath = _path.default.join(rwPaths.web.base, 'tsconfig.json'); - const apiTsConfig = _fs.default.existsSync(apiTsConfigPath) ? (0, _typescript.parseConfigFileTextToJson)(apiTsConfigPath, _fs.default.readFileSync(apiTsConfigPath, 'utf-8')) : null; - const webTsConfig = _fs.default.existsSync(webTsConfigPath) ? (0, _typescript.parseConfigFileTextToJson)(webTsConfigPath, _fs.default.readFileSync(webTsConfigPath, 'utf-8')) : null; + const rwPaths = (0, import_project_config.getPaths)(); + const apiTsConfigPath = import_path.default.join(rwPaths.api.base, "tsconfig.json"); + const webTsConfigPath = import_path.default.join(rwPaths.web.base, "tsconfig.json"); + const apiTsConfig = import_fs.default.existsSync(apiTsConfigPath) ? (0, import_typescript.parseConfigFileTextToJson)( + apiTsConfigPath, + import_fs.default.readFileSync(apiTsConfigPath, "utf-8") + ) : null; + const webTsConfig = import_fs.default.existsSync(webTsConfigPath) ? (0, import_typescript.parseConfigFileTextToJson)( + webTsConfigPath, + import_fs.default.readFileSync(webTsConfigPath, "utf-8") + ) : null; return { api: apiTsConfig?.config ?? null, web: webTsConfig?.config ?? null }; }; -exports.getTsConfigs = getTsConfigs; const isTypeScriptProject = () => { - const paths = (0, _projectConfig.getPaths)(); - return _fs.default.existsSync(_path.default.join(paths.web.base, 'tsconfig.json')) || _fs.default.existsSync(_path.default.join(paths.api.base, 'tsconfig.json')); + const paths = (0, import_project_config.getPaths)(); + return import_fs.default.existsSync(import_path.default.join(paths.web.base, "tsconfig.json")) || import_fs.default.existsSync(import_path.default.join(paths.api.base, "tsconfig.json")); }; -exports.isTypeScriptProject = isTypeScriptProject; const isServerFileSetup = () => { - const serverFilePath = _path.default.join((0, _projectConfig.getPaths)().api.src, `server.${isTypeScriptProject() ? 'ts' : 'js'}`); - return _fs.default.existsSync(serverFilePath); + const serverFilePath = import_path.default.join( + (0, import_project_config.getPaths)().api.src, + `server.${isTypeScriptProject() ? "ts" : "js"}` + ); + return import_fs.default.existsSync(serverFilePath); }; -exports.isServerFileSetup = isServerFileSetup; const isRealtimeSetup = () => { - const realtimePath = _path.default.join((0, _projectConfig.getPaths)().api.lib, `realtime.${isTypeScriptProject() ? 'ts' : 'js'}`); - return _fs.default.existsSync(realtimePath); + const realtimePath = import_path.default.join( + (0, import_project_config.getPaths)().api.lib, + `realtime.${isTypeScriptProject() ? "ts" : "js"}` + ); + return import_fs.default.existsSync(realtimePath); }; -exports.isRealtimeSetup = isRealtimeSetup; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getTsConfigs, + isRealtimeSetup, + isServerFileSetup, + isTypeScriptProject +}); diff --git a/packages/internal/dist/routes.js b/packages/internal/dist/routes.js index 9d298bd82217..7308e33914c3 100644 --- a/packages/internal/dist/routes.js +++ b/packages/internal/dist/routes.js @@ -1,95 +1,101 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var routes_exports = {}; +__export(routes_exports, { + getDuplicateRoutes: () => getDuplicateRoutes, + getProjectRoutes: () => getProjectRoutes, + warningForDuplicateRoutes: () => warningForDuplicateRoutes }); -exports.getDuplicateRoutes = getDuplicateRoutes; -exports.getProjectRoutes = void 0; -exports.warningForDuplicateRoutes = warningForDuplicateRoutes; -require("core-js/modules/es.array.push.js"); -var _set = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/set")); -var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/for-each")); -var _trimEnd = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/trim-end")); -var _path = _interopRequireDefault(require("path")); -var _chalk = _interopRequireDefault(require("chalk")); -var _projectConfig = require("@redwoodjs/project-config"); -var _router = require("@redwoodjs/router"); -var _index = require("@redwoodjs/structure/dist/index.js"); -/** - * Returns an array of routes which conflict on their defined names - */ +module.exports = __toCommonJS(routes_exports); +var import_path = __toESM(require("path")); +var import_chalk = __toESM(require("chalk")); +var import_project_config = require("@redwoodjs/project-config"); +var import_router = require("@redwoodjs/router"); +var import_dist = require("@redwoodjs/structure/dist/index.js"); function getDuplicateRoutes() { - var _context; const duplicateRoutes = []; - const allRoutes = (0, _index.getProject)((0, _projectConfig.getPaths)().base).router.routes; - const uniqueNames = new _set.default((0, _map.default)(_context = (0, _filter.default)(allRoutes).call(allRoutes, route => route.name !== undefined)).call(_context, route => route.name)); - (0, _forEach.default)(uniqueNames).call(uniqueNames, name => { - const routesWithName = (0, _filter.default)(allRoutes).call(allRoutes, route => { + const allRoutes = (0, import_dist.getProject)((0, import_project_config.getPaths)().base).router.routes; + const uniqueNames = new Set( + allRoutes.filter((route) => route.name !== void 0).map((route) => route.name) + ); + uniqueNames.forEach((name) => { + const routesWithName = allRoutes.filter((route) => { return route.name === name; }); if (routesWithName.length > 1) { - duplicateRoutes.push(...(0, _map.default)(routesWithName).call(routesWithName, route => { - return { - name: route.name, - page: route.page_identifier_str, - path: route.path - }; - })); + duplicateRoutes.push( + ...routesWithName.map((route) => { + return { + name: route.name, + page: route.page_identifier_str, + path: route.path + }; + }) + ); } }); return duplicateRoutes; } - -/** - * Detects any potential duplicate routes and returns a formatted warning message - * @see {@link getDuplicateRoutes} for how duplicate routes are detected - * @return {string} Warning message when duplicate routes found, empty string if not - */ function warningForDuplicateRoutes() { const duplicatedRoutes = getDuplicateRoutes(); - let message = ''; + let message = ""; if (duplicatedRoutes.length > 0) { - message += _chalk.default.keyword('orange')(`Warning: ${duplicatedRoutes.length} duplicate routes have been detected, only the route(s) closest to the top of the file will be used.\n`); - (0, _forEach.default)(duplicatedRoutes).call(duplicatedRoutes, route => { - message += ` ${_chalk.default.keyword('orange')('->')} Name: "${route.name}", Path: "${route.path}", Page: "${route.page}"\n`; + message += import_chalk.default.keyword("orange")( + `Warning: ${duplicatedRoutes.length} duplicate routes have been detected, only the route(s) closest to the top of the file will be used. +` + ); + duplicatedRoutes.forEach((route) => { + message += ` ${import_chalk.default.keyword("orange")("->")} Name: "${route.name}", Path: "${route.path}", Page: "${route.page}" +`; }); } - return (0, _trimEnd.default)(message).call(message); + return message.trimEnd(); } const getProjectRoutes = () => { - const rwProject = (0, _index.getProject)((0, _projectConfig.getPaths)().base); + const rwProject = (0, import_dist.getProject)((0, import_project_config.getPaths)().base); const routes = rwProject.getRouter().routes; - - // @ts-expect-error "Bundle" is not found but is in the Spec type? - return (0, _map.default)(routes).call(routes, route => { - const { - matchRegexString, - routeParams - } = route.isNotFound ? { - matchRegexString: null, - routeParams: null - } : (0, _router.getRouteRegexAndParams)(route.path); + return routes.map((route) => { + const { matchRegexString, routeParams } = route.isNotFound ? { matchRegexString: null, routeParams: null } : (0, import_router.getRouteRegexAndParams)(route.path); return { - name: route.isNotFound ? 'NotFoundPage' : route.name, - pathDefinition: route.isNotFound ? 'notfound' : route.path, + name: route.isNotFound ? "NotFoundPage" : route.name, + pathDefinition: route.isNotFound ? "notfound" : route.path, hasParams: route.hasParameters, id: route.id, isNotFound: route.isNotFound, filePath: route.page?.filePath, - relativeFilePath: route.page?.filePath ? _path.default.relative((0, _projectConfig.getPaths)().web.src, route.page?.filePath) : undefined, - routeHooks: (0, _projectConfig.getRouteHookForPage)(route.page?.filePath), + relativeFilePath: route.page?.filePath ? import_path.default.relative((0, import_project_config.getPaths)().web.src, route.page?.filePath) : void 0, + routeHooks: (0, import_project_config.getRouteHookForPage)(route.page?.filePath), renderMode: route.renderMode, - matchRegexString: matchRegexString, + matchRegexString, paramNames: routeParams, // TODO (STREAMING) deal with permanent/temp later - redirect: route.redirect ? { - to: route.redirect, - permanent: false - } : null, + redirect: route.redirect ? { to: route.redirect, permanent: false } : null, isPrivate: route.isPrivate, unauthenticated: route.unauthenticated, roles: route.roles, @@ -97,4 +103,9 @@ const getProjectRoutes = () => { }; }); }; -exports.getProjectRoutes = getProjectRoutes; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + getDuplicateRoutes, + getProjectRoutes, + warningForDuplicateRoutes +}); diff --git a/packages/internal/dist/ts2js.js b/packages/internal/dist/ts2js.js index a2721a32528a..399bb4e1594d 100644 --- a/packages/internal/dist/ts2js.js +++ b/packages/internal/dist/ts2js.js @@ -1,156 +1,159 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var ts2js_exports = {}; +__export(ts2js_exports, { + convertTsFilesToJs: () => convertTsFilesToJs, + convertTsProjectToJs: () => convertTsProjectToJs, + convertTsScriptsToJs: () => convertTsScriptsToJs, + getPrettierConfig: () => getPrettierConfig, + prettify: () => prettify, + transformTSToJS: () => transformTSToJS, + typeScriptSourceFiles: () => typeScriptSourceFiles }); -exports.typeScriptSourceFiles = exports.transformTSToJS = exports.prettify = exports.getPrettierConfig = exports.convertTsScriptsToJs = exports.convertTsProjectToJs = exports.convertTsFilesToJs = void 0; -var _fs = _interopRequireDefault(require("fs")); -var _path = _interopRequireDefault(require("path")); -var _core = require("@babel/core"); -var _fastGlob = _interopRequireDefault(require("fast-glob")); -var _prettier = require("prettier"); -var _projectConfig = require("@redwoodjs/project-config"); -/** - * Converts all the TypeScript files in the `api` and `web` sides to JavaScript. - * - * @param {string} cwd - The base path to the project. - */ -const convertTsProjectToJs = (cwd = (0, _projectConfig.getPaths)().base) => { +module.exports = __toCommonJS(ts2js_exports); +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var import_core = require("@babel/core"); +var import_fast_glob = __toESM(require("fast-glob")); +var import_prettier = require("prettier"); +var import_project_config = require("@redwoodjs/project-config"); +const convertTsProjectToJs = (cwd = (0, import_project_config.getPaths)().base) => { const files = typeScriptSourceFiles(cwd); convertTsFilesToJs(cwd, files); }; - -/** - * Converts all the TypeScript files in the `api` and `web` sides to JavaScript. - * - * @param {string} cwd - The base path to the project. - */ -exports.convertTsProjectToJs = convertTsProjectToJs; -const convertTsScriptsToJs = (cwd = (0, _projectConfig.getPaths)().base) => { - const files = typeScriptSourceFiles(cwd, 'scripts/*.{ts,tsx}'); +const convertTsScriptsToJs = (cwd = (0, import_project_config.getPaths)().base) => { + const files = typeScriptSourceFiles(cwd, "scripts/*.{ts,tsx}"); convertTsFilesToJs(cwd, files); }; - -/** - * Converts TypeScript files to JavaScript. - * - * @param {string} cwd - Current directory - * @param {string[]} files - Collection of files to convert - */ -exports.convertTsScriptsToJs = convertTsScriptsToJs; const convertTsFilesToJs = async (cwd, files) => { if (files.length === 0) { - console.log('No TypeScript files found to convert to JS in this project.'); + console.log("No TypeScript files found to convert to JS in this project."); } for (const f of files) { const code = await transformTSToJS(f); if (code) { - _fs.default.writeFileSync(_path.default.join(cwd, f.replace('.tsx', '.jsx').replace('.ts', '.js')), code, 'utf8'); - _fs.default.unlinkSync(_path.default.join(cwd, f)); + import_fs.default.writeFileSync( + import_path.default.join(cwd, f.replace(".tsx", ".jsx").replace(".ts", ".js")), + code, + "utf8" + ); + import_fs.default.unlinkSync(import_path.default.join(cwd, f)); } } - if (_fs.default.existsSync(_path.default.join(cwd, 'api/tsconfig.json'))) { - _fs.default.renameSync(_path.default.join(cwd, 'api/tsconfig.json'), _path.default.join(cwd, 'api/jsconfig.json')); + if (import_fs.default.existsSync(import_path.default.join(cwd, "api/tsconfig.json"))) { + import_fs.default.renameSync( + import_path.default.join(cwd, "api/tsconfig.json"), + import_path.default.join(cwd, "api/jsconfig.json") + ); } - if (_fs.default.existsSync(_path.default.join(cwd, 'web/tsconfig.json'))) { - _fs.default.renameSync(_path.default.join(cwd, 'web/tsconfig.json'), _path.default.join(cwd, 'web/jsconfig.json')); + if (import_fs.default.existsSync(import_path.default.join(cwd, "web/tsconfig.json"))) { + import_fs.default.renameSync( + import_path.default.join(cwd, "web/tsconfig.json"), + import_path.default.join(cwd, "web/jsconfig.json") + ); } - if (_fs.default.existsSync(_path.default.join(cwd, 'scripts/tsconfig.json'))) { - _fs.default.renameSync(_path.default.join(cwd, 'scripts/tsconfig.json'), _path.default.join(cwd, 'scripts/jsconfig.json')); + if (import_fs.default.existsSync(import_path.default.join(cwd, "scripts/tsconfig.json"))) { + import_fs.default.renameSync( + import_path.default.join(cwd, "scripts/tsconfig.json"), + import_path.default.join(cwd, "scripts/jsconfig.json") + ); } }; - -/** - * Get all the source code from a Redwood project - */ -exports.convertTsFilesToJs = convertTsFilesToJs; -const typeScriptSourceFiles = (cwd, globPattern = '{api,web}/src/**/*.{ts,tsx}') => { +const typeScriptSourceFiles = (cwd, globPattern = "{api,web}/src/**/*.{ts,tsx}") => { console.log(globPattern); - // TODO: When sides are expanded read the `api` and `web` string instead - // of hard-coding them. - return _fastGlob.default.sync(globPattern, { + return import_fast_glob.default.sync(globPattern, { cwd, - ignore: ['node_modules'] + ignore: ["node_modules"] }); }; - -/** - * Read the contents of a TypeScript file, transpile it to JavaScript, - * but leave the JSX intact and format via Prettier. - * - * @param {string} file - The path to the TypeScript file. - */ -exports.typeScriptSourceFiles = typeScriptSourceFiles; -const transformTSToJS = file => { - const tsCode = _fs.default.readFileSync(file, 'utf8'); - const filename = _path.default.basename(file); - const result = (0, _core.transform)(tsCode, { +const transformTSToJS = (file) => { + const tsCode = import_fs.default.readFileSync(file, "utf8"); + const filename = import_path.default.basename(file); + const result = (0, import_core.transform)(tsCode, { filename, - cwd: (0, _projectConfig.getPaths)().base, + cwd: (0, import_project_config.getPaths)().base, configFile: false, - plugins: [['@babel/plugin-transform-typescript', { - isTSX: true, - allExtensions: true - }]], + plugins: [ + [ + "@babel/plugin-transform-typescript", + { + isTSX: true, + allExtensions: true + } + ] + ], retainLines: true }); if (!result?.code) { - return undefined; + return void 0; } - return prettify(result.code, filename.replace(/\.ts$/, '.js')); + return prettify(result.code, filename.replace(/\.ts$/, ".js")); }; -exports.transformTSToJS = transformTSToJS; const getPrettierConfig = async () => { try { - const { - default: prettierConfig - } = await import(`file://${_path.default.join((0, _projectConfig.getPaths)().base, 'prettier.config.js')}`); + const { default: prettierConfig } = await import(`file://${import_path.default.join((0, import_project_config.getPaths)().base, "prettier.config.js")}`); return prettierConfig; } catch { - return undefined; + return void 0; } }; - -/** - * Determine the prettier parser based off of the extension. - * - * See: https://prettier.io/docs/en/options.html#parser - * @param {string} filename - */ -exports.getPrettierConfig = getPrettierConfig; -const prettierParser = filename => { - switch (_path.default.extname(filename.replace('.template', ''))) { - case '.css': - return 'css'; - case '.js': - return 'babel'; - case '.ts': - case '.tsx': - return 'babel-ts'; +const prettierParser = (filename) => { + switch (import_path.default.extname(filename.replace(".template", ""))) { + case ".css": + return "css"; + case ".js": + return "babel"; + case ".ts": + case ".tsx": + return "babel-ts"; default: - return undefined; + return void 0; } }; - -/** - * Prettify `code` according to the extension in `filename`. - * This will also read a user's `prettier.config.js` file if it exists. - * - * @param {string} code - * @param {string} filename - */ const prettify = async (code, filename) => { const parser = prettierParser(filename); - // Return unformatted code if we could not determine the parser. - if (typeof parser === 'undefined') { + if (typeof parser === "undefined") { return code; } const prettierConfig = await getPrettierConfig(); - return (0, _prettier.format)(code, { + return (0, import_prettier.format)(code, { ...prettierConfig, parser }); }; -exports.prettify = prettify; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + convertTsFilesToJs, + convertTsProjectToJs, + convertTsScriptsToJs, + getPrettierConfig, + prettify, + transformTSToJS, + typeScriptSourceFiles +}); diff --git a/packages/internal/dist/validateSchema.js b/packages/internal/dist/validateSchema.js index 8d4f71b3ce0f..3994edaa35bc 100644 --- a/packages/internal/dist/validateSchema.js +++ b/packages/internal/dist/validateSchema.js @@ -1,108 +1,109 @@ "use strict"; - -var _Object$defineProperty = require("@babel/runtime-corejs3/core-js/object/define-property"); -var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault").default; -_Object$defineProperty(exports, "__esModule", { - value: true +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var validateSchema_exports = {}; +__export(validateSchema_exports, { + DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE: () => DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE, + DIRECTIVE_REQUIRED_ERROR_MESSAGE: () => DIRECTIVE_REQUIRED_ERROR_MESSAGE, + RESERVED_TYPES: () => RESERVED_TYPES, + loadAndValidateSdls: () => loadAndValidateSdls, + validateSchema: () => validateSchema }); -exports.loadAndValidateSdls = exports.RESERVED_TYPES = exports.DIRECTIVE_REQUIRED_ERROR_MESSAGE = exports.DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE = void 0; -exports.validateSchema = validateSchema; -var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/includes")); -var _values = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/values")); -var _forEach = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/for-each")); -var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/map")); -var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/instance/filter")); -var _values2 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js/object/values")); -require("core-js/modules/es.array.push.js"); -var _codeFileLoader = require("@graphql-tools/code-file-loader"); -var _load = require("@graphql-tools/load"); -var _merge = require("@graphql-tools/merge"); -var _graphql = require("graphql"); -var _graphqlServer = require("@redwoodjs/graphql-server"); -var _projectConfig = require("@redwoodjs/project-config"); -var _project = require("./project"); -const DIRECTIVE_REQUIRED_ERROR_MESSAGE = exports.DIRECTIVE_REQUIRED_ERROR_MESSAGE = 'You must specify one of @requireAuth, @skipAuth or a custom directive'; -const DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE = exports.DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE = 'Please check that the requireAuth roles is a string or an array of strings.'; - -/** - * These are names that are commonly used in GraphQL schemas as scalars - * and would cause a conflict if used as a type name. - * - * Note: Query, Mutation, and Subscription are not included here because - * they are checked for separately. - */ -const RESERVED_TYPES = exports.RESERVED_TYPES = ['Int', 'Float', 'Boolean', 'String', 'DateTime', 'ID', 'uid', 'as']; -function validateSchema(schemaDocumentNode, typesToCheck = ['Query', 'Mutation']) { +module.exports = __toCommonJS(validateSchema_exports); +var import_code_file_loader = require("@graphql-tools/code-file-loader"); +var import_load = require("@graphql-tools/load"); +var import_merge = require("@graphql-tools/merge"); +var import_graphql = require("graphql"); +var import_graphql_server = require("@redwoodjs/graphql-server"); +var import_project_config = require("@redwoodjs/project-config"); +var import_project = require("./project"); +const DIRECTIVE_REQUIRED_ERROR_MESSAGE = "You must specify one of @requireAuth, @skipAuth or a custom directive"; +const DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE = "Please check that the requireAuth roles is a string or an array of strings."; +const RESERVED_TYPES = [ + "Int", + "Float", + "Boolean", + "String", + "DateTime", + "ID", + "uid", + "as" +]; +function validateSchema(schemaDocumentNode, typesToCheck = ["Query", "Mutation"]) { const validationOutput = []; const reservedNameValidationOutput = []; const directiveRoleValidationOutput = []; - - // Is Subscriptions are enabled with Redwood Realtime, then enforce a rule - // that a Subscription type needs to have a authentication directive applied, - // just as Query and Mutation requires - if ((0, _project.isServerFileSetup)() && (0, _project.isRealtimeSetup)()) { - typesToCheck.push('Subscription'); + if ((0, import_project.isServerFileSetup)() && (0, import_project.isRealtimeSetup)()) { + typesToCheck.push("Subscription"); } - (0, _graphql.visit)(schemaDocumentNode, { + (0, import_graphql.visit)(schemaDocumentNode, { InterfaceTypeDefinition(typeNode) { - // Warn that an interface definition in the SDL is using a reserved GraphQL type - if ((0, _includes.default)(RESERVED_TYPES).call(RESERVED_TYPES, typeNode.name.value)) { + if (RESERVED_TYPES.includes(typeNode.name.value)) { reservedNameValidationOutput.push({ - objectType: 'interface', + objectType: "interface", name: typeNode.name.value }); } }, InputObjectTypeDefinition(typeNode) { - // Warn that an input definition in the SDL is using a reserved GraphQL type - if ((0, _includes.default)(RESERVED_TYPES).call(RESERVED_TYPES, typeNode.name.value)) { + if (RESERVED_TYPES.includes(typeNode.name.value)) { reservedNameValidationOutput.push({ - objectType: 'input type', + objectType: "input type", name: typeNode.name.value }); } }, ObjectTypeDefinition(typeNode) { - // Warn that a type definition in the SDL is using a reserved GraphQL type - if ((0, _includes.default)(RESERVED_TYPES).call(RESERVED_TYPES, typeNode.name.value)) { + if (RESERVED_TYPES.includes(typeNode.name.value)) { reservedNameValidationOutput.push({ - objectType: 'type', + objectType: "type", name: typeNode.name.value }); } - if ((0, _includes.default)(typesToCheck).call(typesToCheck, typeNode.name.value)) { + if (typesToCheck.includes(typeNode.name.value)) { for (const field of typeNode.fields || []) { const fieldName = field.name.value; const fieldTypeName = typeNode.name.value; - const isRedwoodQuery = fieldName === 'redwood' && fieldTypeName === 'Query'; - const isCurrentUserQuery = fieldName === 'currentUser' && fieldTypeName === 'Query'; - // skip validation for redwood query and currentUser + const isRedwoodQuery = fieldName === "redwood" && fieldTypeName === "Query"; + const isCurrentUserQuery = fieldName === "currentUser" && fieldTypeName === "Query"; if (!(isRedwoodQuery || isCurrentUserQuery)) { const hasDirective = field.directives?.length; if (!hasDirective) { validationOutput.push(`${fieldName} ${fieldTypeName}`); } - - // we want to check that the requireAuth directive roles argument value - // is a string or an array of strings - field.directives?.forEach(directive => { - if (directive.name.value === 'requireAuth') { - directive.arguments?.forEach(arg => { - if (arg.name.value === 'roles') { - if (arg.value.kind !== _graphql.Kind.STRING && arg.value.kind !== _graphql.Kind.LIST) { + field.directives?.forEach((directive) => { + if (directive.name.value === "requireAuth") { + directive.arguments?.forEach((arg) => { + if (arg.name.value === "roles") { + if (arg.value.kind !== import_graphql.Kind.STRING && arg.value.kind !== import_graphql.Kind.LIST) { directiveRoleValidationOutput.push({ - fieldName: fieldName, + fieldName, invalid: arg.value.kind }); } - - // check list (array) - if (arg.value.kind === _graphql.Kind.LIST) { - const invalidValues = (0, _values.default)(arg.value)?.filter(val => val.kind !== _graphql.Kind.STRING); + if (arg.value.kind === import_graphql.Kind.LIST) { + const invalidValues = arg.value.values?.filter( + (val) => val.kind !== import_graphql.Kind.STRING + ); if (invalidValues.length > 0) { - (0, _forEach.default)(invalidValues).call(invalidValues, invalid => { + invalidValues.forEach((invalid) => { directiveRoleValidationOutput.push({ - fieldName: fieldName, + fieldName, invalid: invalid.kind }); }); @@ -118,41 +119,75 @@ function validateSchema(schemaDocumentNode, typesToCheck = ['Query', 'Mutation'] } }); if (validationOutput.length > 0) { - const fieldsWithoutDirectives = (0, _map.default)(validationOutput).call(validationOutput, field => `- ${field}`); - throw new Error(`${DIRECTIVE_REQUIRED_ERROR_MESSAGE} for\n${fieldsWithoutDirectives.join('\n')} \n`); + const fieldsWithoutDirectives = validationOutput.map( + (field) => `- ${field}` + ); + throw new Error( + `${DIRECTIVE_REQUIRED_ERROR_MESSAGE} for +${fieldsWithoutDirectives.join( + "\n" + )} +` + ); } if (directiveRoleValidationOutput.length > 0) { - const fieldWithInvalidRoleValues = (0, _map.default)(directiveRoleValidationOutput).call(directiveRoleValidationOutput, field => `- ${field.fieldName} has an invalid ${field.invalid}`); - throw new RangeError(`${DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE}\n\n${fieldWithInvalidRoleValues.join('\n')} \n\nFor example: @requireAuth(roles: "admin") or @requireAuth(roles: ["admin", "editor"])`); + const fieldWithInvalidRoleValues = directiveRoleValidationOutput.map( + (field) => `- ${field.fieldName} has an invalid ${field.invalid}` + ); + throw new RangeError( + `${DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE} + +${fieldWithInvalidRoleValues.join( + "\n" + )} + +For example: @requireAuth(roles: "admin") or @requireAuth(roles: ["admin", "editor"])` + ); } if (reservedNameValidationOutput.length > 0) { - const reservedNameMsg = (0, _map.default)(reservedNameValidationOutput).call(reservedNameValidationOutput, output => { - return `The ${output.objectType} named '${output.name}' is a reserved GraphQL name.\nPlease rename it to something more specific, like: Application${output.name}.\n`; - }); - throw new TypeError(reservedNameMsg.join('\n')); + const reservedNameMsg = reservedNameValidationOutput.map( + (output) => { + return `The ${output.objectType} named '${output.name}' is a reserved GraphQL name. +Please rename it to something more specific, like: Application${output.name}. +`; + } + ); + throw new TypeError(reservedNameMsg.join("\n")); } } const loadAndValidateSdls = async () => { - var _context, _context2; - const projectTypeSrc = await (0, _load.loadTypedefs)(['graphql/**/*.sdl.{js,ts}', 'directives/**/*.{js,ts}', 'subscriptions/**/*.{js,ts}'], { - loaders: [new _codeFileLoader.CodeFileLoader({ - noRequire: true, - pluckConfig: { - globalGqlIdentifierName: 'gql' - } - })], - cwd: (0, _projectConfig.getPaths)().api.src - }); - - // The output of the above function doesn't give us the documents directly - const projectDocumentNodes = (0, _filter.default)(_context = (0, _map.default)(_context2 = (0, _values2.default)(projectTypeSrc)).call(_context2, ({ - document - }) => document)).call(_context, documentNode => { + const projectTypeSrc = await (0, import_load.loadTypedefs)( + [ + "graphql/**/*.sdl.{js,ts}", + "directives/**/*.{js,ts}", + "subscriptions/**/*.{js,ts}" + ], + { + loaders: [ + new import_code_file_loader.CodeFileLoader({ + noRequire: true, + pluckConfig: { + globalGqlIdentifierName: "gql" + } + }) + ], + cwd: (0, import_project_config.getPaths)().api.src + } + ); + const projectDocumentNodes = Object.values(projectTypeSrc).map(({ document }) => document).filter((documentNode) => { return !!documentNode; }); - - // Merge in the rootSchema with JSON scalars, etc. - const mergedDocumentNode = (0, _merge.mergeTypeDefs)([_graphqlServer.rootSchema.schema, projectDocumentNodes]); + const mergedDocumentNode = (0, import_merge.mergeTypeDefs)([ + import_graphql_server.rootSchema.schema, + projectDocumentNodes + ]); validateSchema(mergedDocumentNode); }; -exports.loadAndValidateSdls = loadAndValidateSdls; \ No newline at end of file +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE, + DIRECTIVE_REQUIRED_ERROR_MESSAGE, + RESERVED_TYPES, + loadAndValidateSdls, + validateSchema +}); From 9439b0305f322c3b37047794b0ce590a1b8fedab Mon Sep 17 00:00:00 2001 From: Josh GM Walker <56300765+Josh-Walker-GM@users.noreply.github.com> Date: Sun, 18 Aug 2024 00:47:30 +0100 Subject: [PATCH 5/8] add exports for everything we use in fw --- packages/internal/package.json | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/packages/internal/package.json b/packages/internal/package.json index 7c0b5de33279..3282c3d6810c 100644 --- a/packages/internal/package.json +++ b/packages/internal/package.json @@ -8,6 +8,48 @@ }, "license": "MIT", "type": "commonjs", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./dist/dev": { + "types": "./dist/dev.d.ts", + "default": "./dist/dev.js" + }, + "./dist/files": { + "types": "./dist/files.d.ts", + "default": "./dist/files.js" + }, + "./dist/files.js": { + "types": "./dist/files.d.ts", + "default": "./dist/files.js" + }, + "./dist/gql": { + "types": "./dist/gql.d.ts", + "default": "./dist/gql.js" + }, + "./dist/routes.js": { + "types": "./dist/routes.d.ts", + "default": "./dist/routes.js" + }, + "./dist/ts2js": { + "types": "./dist/ts2js.d.ts", + "default": "./dist/ts2js.js" + }, + "./dist/validateSchema": { + "types": "./dist/validateSchema.d.ts", + "default": "./dist/validateSchema.js" + }, + "./dist/build/api": { + "types": "./dist/build/api.d.ts", + "default": "./dist/build/api.js" + }, + "./dist/generate/generate": { + "types": "./dist/generate/generate.d.ts", + "default": "./dist/generate/generate.js" + } + }, "main": "dist/index.js", "types": "dist/index.d.ts", "bin": { From d1a2b879aaadc7d2c9a1eb1d7ab322d520a6874f Mon Sep 17 00:00:00 2001 From: Josh GM Walker <56300765+Josh-Walker-GM@users.noreply.github.com> Date: Sun, 18 Aug 2024 02:39:09 +0100 Subject: [PATCH 6/8] add copy assets --- packages/internal/build.mts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/internal/build.mts b/packages/internal/build.mts index 16175a6725c0..ecc19f75a3c8 100644 --- a/packages/internal/build.mts +++ b/packages/internal/build.mts @@ -1,3 +1,7 @@ -import { build } from '@redwoodjs/framework-tools' +import { build, copyAssets } from '@redwoodjs/framework-tools' await build() +await copyAssets({ + buildFileUrl: import.meta.url, + patterns: ['generate/templates/**/*.template'], +}) From cdbd6ae2be2d4f84f567f2d5e2abfc1813e97ae3 Mon Sep 17 00:00:00 2001 From: Josh GM Walker <56300765+Josh-Walker-GM@users.noreply.github.com> Date: Sun, 18 Aug 2024 02:41:04 +0100 Subject: [PATCH 7/8] untrack dist --- .gitignore | 2 - packages/internal/dist/ast.d.ts | 26 -- packages/internal/dist/ast.d.ts.map | 1 - packages/internal/dist/ast.js | 198 ---------- packages/internal/dist/build/api.d.ts | 6 - packages/internal/dist/build/api.d.ts.map | 1 - packages/internal/dist/build/api.js | 109 ------ packages/internal/dist/cliLogger.d.ts | 11 - packages/internal/dist/cliLogger.d.ts.map | 1 - packages/internal/dist/cliLogger.js | 36 -- packages/internal/dist/dev.d.ts | 2 - packages/internal/dist/dev.d.ts.map | 1 - packages/internal/dist/dev.js | 41 -- packages/internal/dist/files.d.ts | 51 --- packages/internal/dist/files.d.ts.map | 1 - packages/internal/dist/files.js | 223 ----------- .../internal/dist/generate/clientPreset.d.ts | 17 - .../dist/generate/clientPreset.d.ts.map | 1 - .../internal/dist/generate/clientPreset.js | 85 ---- packages/internal/dist/generate/generate.d.ts | 10 - .../internal/dist/generate/generate.d.ts.map | 1 - packages/internal/dist/generate/generate.js | 91 ----- .../dist/generate/graphqlCodeGen.d.ts | 16 - .../dist/generate/graphqlCodeGen.d.ts.map | 1 - .../internal/dist/generate/graphqlCodeGen.js | 334 ---------------- .../internal/dist/generate/graphqlSchema.d.ts | 8 - .../dist/generate/graphqlSchema.d.ts.map | 1 - .../internal/dist/generate/graphqlSchema.js | 147 ------- .../rw-typescript-resolvers/index.d.ts | 6 - .../rw-typescript-resolvers/index.d.ts.map | 1 - .../plugins/rw-typescript-resolvers/index.js | 67 ---- .../rw-typescript-resolvers/visitor.d.ts | 9 - .../rw-typescript-resolvers/visitor.d.ts.map | 1 - .../rw-typescript-resolvers/visitor.js | 84 ---- .../internal/dist/generate/possibleTypes.d.ts | 36 -- .../dist/generate/possibleTypes.d.ts.map | 1 - .../internal/dist/generate/possibleTypes.js | 106 ----- .../internal/dist/generate/templates.d.ts | 6 - .../internal/dist/generate/templates.d.ts.map | 1 - packages/internal/dist/generate/templates.js | 61 --- .../templates/all-currentUser.d.ts.template | 28 -- .../templates/api-globImports.d.ts.template | 9 - .../templates/api-globalContext.d.ts.template | 7 - .../templates/api-scenarios.d.ts.template | 10 - .../templates/api-test-globals.d.ts.template | 5 - .../templates/mirror-cell.d.ts.template | 13 - .../mirror-directoryNamedModule.d.ts.template | 5 - .../templates/web-routerRoutes.d.ts.template | 20 - .../templates/web-routesPages.d.ts.template | 13 - .../templates/web-test-globals.d.ts.template | 7 - .../dist/generate/trustedDocuments.d.ts | 3 - .../dist/generate/trustedDocuments.d.ts.map | 1 - .../dist/generate/trustedDocuments.js | 95 ----- .../dist/generate/typeDefinitions.d.ts | 30 -- .../dist/generate/typeDefinitions.d.ts.map | 1 - .../internal/dist/generate/typeDefinitions.js | 369 ------------------ packages/internal/dist/generate/types.d.ts | 6 - .../internal/dist/generate/types.d.ts.map | 1 - packages/internal/dist/generate/types.js | 16 - packages/internal/dist/generate/watch.d.ts | 3 - .../internal/dist/generate/watch.d.ts.map | 1 - packages/internal/dist/generate/watch.js | 124 ------ packages/internal/dist/gql.d.ts | 14 - packages/internal/dist/gql.d.ts.map | 1 - packages/internal/dist/gql.js | 108 ----- packages/internal/dist/index.d.ts | 11 - packages/internal/dist/index.d.ts.map | 1 - packages/internal/dist/index.js | 49 --- packages/internal/dist/jsx.d.ts | 16 - packages/internal/dist/jsx.d.ts.map | 1 - packages/internal/dist/jsx.js | 100 ----- packages/internal/dist/jsxAttributeValue.d.ts | 2 - .../internal/dist/jsxAttributeValue.d.ts.map | 1 - packages/internal/dist/jsxAttributeValue.js | 129 ------ packages/internal/dist/project.d.ts | 8 - packages/internal/dist/project.d.ts.map | 1 - packages/internal/dist/project.js | 82 ---- packages/internal/dist/routes.d.ts | 42 -- packages/internal/dist/routes.d.ts.map | 1 - packages/internal/dist/routes.js | 111 ------ packages/internal/dist/ts2js.d.ts | 40 -- packages/internal/dist/ts2js.d.ts.map | 1 - packages/internal/dist/ts2js.js | 159 -------- packages/internal/dist/validateSchema.d.ts | 14 - .../internal/dist/validateSchema.d.ts.map | 1 - packages/internal/dist/validateSchema.js | 193 --------- 86 files changed, 3654 deletions(-) delete mode 100644 packages/internal/dist/ast.d.ts delete mode 100644 packages/internal/dist/ast.d.ts.map delete mode 100644 packages/internal/dist/ast.js delete mode 100644 packages/internal/dist/build/api.d.ts delete mode 100644 packages/internal/dist/build/api.d.ts.map delete mode 100644 packages/internal/dist/build/api.js delete mode 100644 packages/internal/dist/cliLogger.d.ts delete mode 100644 packages/internal/dist/cliLogger.d.ts.map delete mode 100644 packages/internal/dist/cliLogger.js delete mode 100644 packages/internal/dist/dev.d.ts delete mode 100644 packages/internal/dist/dev.d.ts.map delete mode 100644 packages/internal/dist/dev.js delete mode 100644 packages/internal/dist/files.d.ts delete mode 100644 packages/internal/dist/files.d.ts.map delete mode 100644 packages/internal/dist/files.js delete mode 100644 packages/internal/dist/generate/clientPreset.d.ts delete mode 100644 packages/internal/dist/generate/clientPreset.d.ts.map delete mode 100644 packages/internal/dist/generate/clientPreset.js delete mode 100644 packages/internal/dist/generate/generate.d.ts delete mode 100644 packages/internal/dist/generate/generate.d.ts.map delete mode 100755 packages/internal/dist/generate/generate.js delete mode 100644 packages/internal/dist/generate/graphqlCodeGen.d.ts delete mode 100644 packages/internal/dist/generate/graphqlCodeGen.d.ts.map delete mode 100644 packages/internal/dist/generate/graphqlCodeGen.js delete mode 100644 packages/internal/dist/generate/graphqlSchema.d.ts delete mode 100644 packages/internal/dist/generate/graphqlSchema.d.ts.map delete mode 100644 packages/internal/dist/generate/graphqlSchema.js delete mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts delete mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts.map delete mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js delete mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts delete mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts.map delete mode 100644 packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js delete mode 100644 packages/internal/dist/generate/possibleTypes.d.ts delete mode 100644 packages/internal/dist/generate/possibleTypes.d.ts.map delete mode 100644 packages/internal/dist/generate/possibleTypes.js delete mode 100644 packages/internal/dist/generate/templates.d.ts delete mode 100644 packages/internal/dist/generate/templates.d.ts.map delete mode 100644 packages/internal/dist/generate/templates.js delete mode 100644 packages/internal/dist/generate/templates/all-currentUser.d.ts.template delete mode 100644 packages/internal/dist/generate/templates/api-globImports.d.ts.template delete mode 100644 packages/internal/dist/generate/templates/api-globalContext.d.ts.template delete mode 100644 packages/internal/dist/generate/templates/api-scenarios.d.ts.template delete mode 100644 packages/internal/dist/generate/templates/api-test-globals.d.ts.template delete mode 100644 packages/internal/dist/generate/templates/mirror-cell.d.ts.template delete mode 100644 packages/internal/dist/generate/templates/mirror-directoryNamedModule.d.ts.template delete mode 100644 packages/internal/dist/generate/templates/web-routerRoutes.d.ts.template delete mode 100644 packages/internal/dist/generate/templates/web-routesPages.d.ts.template delete mode 100644 packages/internal/dist/generate/templates/web-test-globals.d.ts.template delete mode 100644 packages/internal/dist/generate/trustedDocuments.d.ts delete mode 100644 packages/internal/dist/generate/trustedDocuments.d.ts.map delete mode 100644 packages/internal/dist/generate/trustedDocuments.js delete mode 100644 packages/internal/dist/generate/typeDefinitions.d.ts delete mode 100644 packages/internal/dist/generate/typeDefinitions.d.ts.map delete mode 100644 packages/internal/dist/generate/typeDefinitions.js delete mode 100644 packages/internal/dist/generate/types.d.ts delete mode 100644 packages/internal/dist/generate/types.d.ts.map delete mode 100644 packages/internal/dist/generate/types.js delete mode 100644 packages/internal/dist/generate/watch.d.ts delete mode 100644 packages/internal/dist/generate/watch.d.ts.map delete mode 100755 packages/internal/dist/generate/watch.js delete mode 100644 packages/internal/dist/gql.d.ts delete mode 100644 packages/internal/dist/gql.d.ts.map delete mode 100644 packages/internal/dist/gql.js delete mode 100644 packages/internal/dist/index.d.ts delete mode 100644 packages/internal/dist/index.d.ts.map delete mode 100644 packages/internal/dist/index.js delete mode 100644 packages/internal/dist/jsx.d.ts delete mode 100644 packages/internal/dist/jsx.d.ts.map delete mode 100644 packages/internal/dist/jsx.js delete mode 100644 packages/internal/dist/jsxAttributeValue.d.ts delete mode 100644 packages/internal/dist/jsxAttributeValue.d.ts.map delete mode 100644 packages/internal/dist/jsxAttributeValue.js delete mode 100644 packages/internal/dist/project.d.ts delete mode 100644 packages/internal/dist/project.d.ts.map delete mode 100644 packages/internal/dist/project.js delete mode 100644 packages/internal/dist/routes.d.ts delete mode 100644 packages/internal/dist/routes.d.ts.map delete mode 100644 packages/internal/dist/routes.js delete mode 100644 packages/internal/dist/ts2js.d.ts delete mode 100644 packages/internal/dist/ts2js.d.ts.map delete mode 100644 packages/internal/dist/ts2js.js delete mode 100644 packages/internal/dist/validateSchema.d.ts delete mode 100644 packages/internal/dist/validateSchema.d.ts.map delete mode 100644 packages/internal/dist/validateSchema.js diff --git a/.gitignore b/.gitignore index 575bca40e1a9..fc106d99ca1f 100644 --- a/.gitignore +++ b/.gitignore @@ -31,5 +31,3 @@ packages/create-redwood-app/create-redwood-app.tgz .nx/cache .nx/workspace-data - -!packages/internal/dist diff --git a/packages/internal/dist/ast.d.ts b/packages/internal/dist/ast.d.ts deleted file mode 100644 index 4e22ecebc793..000000000000 --- a/packages/internal/dist/ast.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { types } from '@babel/core'; -export declare const fileToAst: (filePath: string) => types.Node; -interface NamedExports { - name: string; - type: 're-export' | 'variable' | 'function' | 'class'; - location: { - line: number; - column: number; - }; -} -/** - * get all the named exports in a given piece of code. - */ -export declare const getNamedExports: (ast: types.Node) => NamedExports[]; -/** - * get all the gql queries from the supplied code - */ -export declare const getGqlQueries: (ast: types.Node) => string[]; -export declare const getCellGqlQuery: (ast: types.Node) => undefined; -export declare const hasDefaultExport: (ast: types.Node) => boolean; -export declare const getDefaultExportLocation: (ast: types.Node) => { - line: number; - column: number; -} | null; -export {}; -//# sourceMappingURL=ast.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/ast.d.ts.map b/packages/internal/dist/ast.d.ts.map deleted file mode 100644 index a5c51415205d..000000000000 --- a/packages/internal/dist/ast.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAUnC,eAAO,MAAM,SAAS,aAAc,MAAM,KAAG,KAAK,CAAC,IAyBlD,CAAA;AAED,UAAU,YAAY;IACpB,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,WAAW,GAAG,UAAU,GAAG,UAAU,GAAG,OAAO,CAAA;IACrD,QAAQ,EAAE;QACR,IAAI,EAAE,MAAM,CAAA;QACZ,MAAM,EAAE,MAAM,CAAA;KACf,CAAA;CACF;AACD;;GAEG;AACH,eAAO,MAAM,eAAe,QAAS,KAAK,CAAC,IAAI,KAAG,YAAY,EA4D7D,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,aAAa,QAAS,KAAK,CAAC,IAAI,aAY5C,CAAA;AAED,eAAO,MAAM,eAAe,QAAS,KAAK,CAAC,IAAI,cA4B9C,CAAA;AAED,eAAO,MAAM,gBAAgB,QAAS,KAAK,CAAC,IAAI,KAAG,OASlD,CAAA;AAED,eAAO,MAAM,wBAAwB,QAC9B,KAAK,CAAC,IAAI,KACd;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,IA0CrC,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/ast.js b/packages/internal/dist/ast.js deleted file mode 100644 index 5fd5084e598f..000000000000 --- a/packages/internal/dist/ast.js +++ /dev/null @@ -1,198 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var ast_exports = {}; -__export(ast_exports, { - fileToAst: () => fileToAst, - getCellGqlQuery: () => getCellGqlQuery, - getDefaultExportLocation: () => getDefaultExportLocation, - getGqlQueries: () => getGqlQueries, - getNamedExports: () => getNamedExports, - hasDefaultExport: () => hasDefaultExport -}); -module.exports = __toCommonJS(ast_exports); -var import_fs = __toESM(require("fs")); -var import_path = __toESM(require("path")); -var import_core = require("@babel/core"); -var import_parser = require("@babel/parser"); -var import_traverse = __toESM(require("@babel/traverse")); -var import_chalk = __toESM(require("chalk")); -var import_project_config = require("@redwoodjs/project-config"); -var import_files = require("./files"); -const fileToAst = (filePath) => { - const code = import_fs.default.readFileSync(filePath, "utf-8"); - const isJsxFile = import_path.default.extname(filePath).match(/[jt]sx$/) || (0, import_files.isFileInsideFolder)(filePath, (0, import_project_config.getPaths)().web.base); - const plugins = [ - "typescript", - "nullishCoalescingOperator", - "objectRestSpread", - isJsxFile && "jsx" - ].filter(Boolean); - try { - return (0, import_parser.parse)(code, { - sourceType: "module", - plugins - }); - } catch (e) { - console.error(import_chalk.default.red(`Error parsing: ${filePath}`)); - console.error(e); - throw new Error(e?.message); - } -}; -const getNamedExports = (ast) => { - const namedExports = []; - (0, import_traverse.default)(ast, { - ExportNamedDeclaration(path2) { - const specifiers = path2.node?.specifiers; - if (specifiers.length) { - for (const s of specifiers) { - const id = s.exported; - namedExports.push({ - name: id.name, - type: "re-export", - location: { - line: id.loc?.start.line ?? 1, - column: id.loc?.start.column ?? 0 - } - }); - } - return; - } - const declaration = path2.node.declaration; - if (!declaration) { - return; - } - if (declaration.type === "VariableDeclaration") { - const id = declaration.declarations[0].id; - namedExports.push({ - name: id.name, - type: "variable", - location: { - line: id.loc?.start.line ?? 1, - column: id.loc?.start.column ?? 0 - } - }); - } else if (declaration.type === "FunctionDeclaration") { - namedExports.push({ - name: declaration?.id?.name, - type: "function", - location: { - line: declaration?.id?.loc?.start.line ?? 1, - column: declaration?.id?.loc?.start.column ?? 0 - } - }); - } else if (declaration.type === "ClassDeclaration") { - namedExports.push({ - name: declaration?.id?.name, - type: "class", - location: { - line: declaration?.id?.loc?.start.line ?? 1, - column: declaration?.id?.loc?.start.column ?? 0 - } - }); - } - } - }); - return namedExports; -}; -const getGqlQueries = (ast) => { - const gqlQueries = []; - (0, import_traverse.default)(ast, { - TaggedTemplateExpression(path2) { - const gqlTag = path2.node.tag; - if (gqlTag.type === "Identifier" && gqlTag.name === "gql") { - gqlQueries.push(path2.node.quasi.quasis[0].value.raw); - } - } - }); - return gqlQueries; -}; -const getCellGqlQuery = (ast) => { - let cellQuery = void 0; - (0, import_traverse.default)(ast, { - ExportNamedDeclaration({ node }) { - if (node.exportKind === "value" && import_core.types.isVariableDeclaration(node.declaration)) { - const exportedQueryNode = node.declaration.declarations.find((d) => { - return import_core.types.isIdentifier(d.id) && d.id.name === "QUERY" && import_core.types.isTaggedTemplateExpression(d.init); - }); - if (exportedQueryNode) { - const templateExpression = exportedQueryNode.init; - cellQuery = templateExpression.quasi.quasis[0].value.raw; - } - } - return; - } - }); - return cellQuery; -}; -const hasDefaultExport = (ast) => { - let exported = false; - (0, import_traverse.default)(ast, { - ExportDefaultDeclaration() { - exported = true; - return; - } - }); - return exported; -}; -const getDefaultExportLocation = (ast) => { - let defaultExport; - (0, import_traverse.default)(ast, { - ExportDefaultDeclaration(path2) { - defaultExport = path2.node; - } - }); - if (!defaultExport) { - return null; - } - if (import_core.types.isIdentifier(defaultExport.declaration) && import_core.types.isFile(ast)) { - const exportedName = defaultExport.declaration.name; - const declaration = ast.program.body.find((node) => { - return import_core.types.isVariableDeclaration(node) && node.declarations.find((d) => { - return import_core.types.isVariableDeclarator(d) && import_core.types.isIdentifier(d.id) && d.id.name === exportedName; - }); - }); - return { - line: declaration?.loc?.start.line ?? 1, - column: declaration?.loc?.start.column ?? 0 - }; - } - return { - line: defaultExport.loc?.start.line ?? 1, - column: defaultExport.loc?.start.column ?? 0 - }; -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - fileToAst, - getCellGqlQuery, - getDefaultExportLocation, - getGqlQueries, - getNamedExports, - hasDefaultExport -}); diff --git a/packages/internal/dist/build/api.d.ts b/packages/internal/dist/build/api.d.ts deleted file mode 100644 index 9db86cf79819..000000000000 --- a/packages/internal/dist/build/api.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { BuildOptions } from 'esbuild'; -export declare const buildApi: () => Promise>; -export declare const rebuildApi: () => Promise>; -export declare const cleanApiBuild: () => Promise; -export declare const transpileApi: (files: string[]) => Promise>; -//# sourceMappingURL=api.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/build/api.d.ts.map b/packages/internal/dist/build/api.d.ts.map deleted file mode 100644 index 0d3024d14fed..000000000000 --- a/packages/internal/dist/build/api.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"api.d.ts","sourceRoot":"","sources":["../../src/build/api.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAgB,YAAY,EAAe,MAAM,SAAS,CAAA;AAkBtE,eAAO,MAAM,QAAQ,4DAOpB,CAAA;AAED,eAAO,MAAM,UAAU,4DAQtB,CAAA;AAED,eAAO,MAAM,aAAa,qBAGzB,CAAA;AAiCD,eAAO,MAAM,YAAY,UAAiB,MAAM,EAAE,yDAEjD,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/build/api.js b/packages/internal/dist/build/api.js deleted file mode 100644 index f295df5c4846..000000000000 --- a/packages/internal/dist/build/api.js +++ /dev/null @@ -1,109 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var api_exports = {}; -__export(api_exports, { - buildApi: () => buildApi, - cleanApiBuild: () => cleanApiBuild, - rebuildApi: () => rebuildApi, - transpileApi: () => transpileApi -}); -module.exports = __toCommonJS(api_exports); -var import_esbuild = require("esbuild"); -var import_fs_extra = __toESM(require("fs-extra")); -var import_babel_config = require("@redwoodjs/babel-config"); -var import_project_config = require("@redwoodjs/project-config"); -var import_files = require("../files"); -let BUILD_CTX = null; -const buildApi = async () => { - BUILD_CTX?.dispose(); - BUILD_CTX = null; - return transpileApi((0, import_files.findApiFiles)()); -}; -const rebuildApi = async () => { - const apiFiles = (0, import_files.findApiFiles)(); - if (!BUILD_CTX) { - BUILD_CTX = await (0, import_esbuild.context)(getEsbuildOptions(apiFiles)); - } - return BUILD_CTX.rebuild(); -}; -const cleanApiBuild = async () => { - const rwjsPaths = (0, import_project_config.getPaths)(); - return import_fs_extra.default.remove(rwjsPaths.api.dist); -}; -const runRwBabelTransformsPlugin = { - name: "rw-esbuild-babel-transform", - setup(build2) { - const rwjsConfig = (0, import_project_config.getConfig)(); - build2.onLoad({ filter: /\.(js|ts|tsx|jsx)$/ }, async (args) => { - const transformedCode = await (0, import_babel_config.transformWithBabel)( - args.path, - (0, import_babel_config.getApiSideBabelPlugins)({ - openTelemetry: rwjsConfig.experimental.opentelemetry.enabled && rwjsConfig.experimental.opentelemetry.wrapApi, - projectIsEsm: (0, import_project_config.projectSideIsEsm)("api") - }) - ); - if (transformedCode?.code) { - return { - contents: transformedCode.code, - loader: "js" - }; - } - throw new Error(`Could not transform file: ${args.path}`); - }); - } -}; -const transpileApi = async (files) => { - return (0, import_esbuild.build)(getEsbuildOptions(files)); -}; -function getEsbuildOptions(files) { - const rwjsPaths = (0, import_project_config.getPaths)(); - const format = (0, import_project_config.projectSideIsEsm)("api") ? "esm" : "cjs"; - return { - absWorkingDir: rwjsPaths.api.base, - entryPoints: files, - platform: "node", - target: "node20", - format, - allowOverwrite: true, - bundle: false, - plugins: [runRwBabelTransformsPlugin], - outdir: rwjsPaths.api.dist, - // setting this to 'true' will generate an external sourcemap x.js.map - // AND set the sourceMappingURL comment - // (setting it to 'external' will ONLY generate the file, but won't add the comment) - sourcemap: true - }; -} -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - buildApi, - cleanApiBuild, - rebuildApi, - transpileApi -}); diff --git a/packages/internal/dist/cliLogger.d.ts b/packages/internal/dist/cliLogger.d.ts deleted file mode 100644 index 10099b5eccae..000000000000 --- a/packages/internal/dist/cliLogger.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -type CLog = (typeof console)['log']; -/** - * An alternative to createLogger which supports the same logging levels - * but allows for full ANSI when printing to the console. - */ -export declare const cliLogger: CLog & { - trace: CLog; - debug: CLog; -}; -export {}; -//# sourceMappingURL=cliLogger.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/cliLogger.d.ts.map b/packages/internal/dist/cliLogger.d.ts.map deleted file mode 100644 index 3f31bd88c0a6..000000000000 --- a/packages/internal/dist/cliLogger.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"cliLogger.d.ts","sourceRoot":"","sources":["../src/cliLogger.ts"],"names":[],"mappings":"AAIA,KAAK,IAAI,GAAG,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,CAAC,CAAA;AAEnC;;;GAGG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,GAAG;IAC7B,KAAK,EAAE,IAAI,CAAA;IACX,KAAK,EAAE,IAAI,CAAA;CAGZ,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/cliLogger.js b/packages/internal/dist/cliLogger.js deleted file mode 100644 index afb16b610b84..000000000000 --- a/packages/internal/dist/cliLogger.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var cliLogger_exports = {}; -__export(cliLogger_exports, { - cliLogger: () => cliLogger -}); -module.exports = __toCommonJS(cliLogger_exports); -var import_logger = require("@redwoodjs/api/logger"); -const logLevel = import_logger.defaultLoggerOptions.level; -const cliLogger = function(...data) { - console.log(...data); -}; -cliLogger.trace = logLevel === "trace" ? console.log : () => { -}; -cliLogger.debug = logLevel === "trace" || logLevel === "debug" ? console.log : () => { -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - cliLogger -}); diff --git a/packages/internal/dist/dev.d.ts b/packages/internal/dist/dev.d.ts deleted file mode 100644 index 3d421ce30ab7..000000000000 --- a/packages/internal/dist/dev.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare const shutdownPort: (port: number, method?: "tcp" | "udp") => Promise; -//# sourceMappingURL=dev.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/dev.d.ts.map b/packages/internal/dist/dev.d.ts.map deleted file mode 100644 index edc2c122317e..000000000000 --- a/packages/internal/dist/dev.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../src/dev.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,YAAY,SAAU,MAAM,WAAU,KAAK,GAAG,KAAK,kBAE/D,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/dev.js b/packages/internal/dist/dev.js deleted file mode 100644 index 842c658bdea0..000000000000 --- a/packages/internal/dist/dev.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var dev_exports = {}; -__export(dev_exports, { - shutdownPort: () => shutdownPort -}); -module.exports = __toCommonJS(dev_exports); -var import_kill_port = __toESM(require("kill-port")); -const shutdownPort = (port, method = "tcp") => { - return (0, import_kill_port.default)(port, method); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - shutdownPort -}); diff --git a/packages/internal/dist/files.d.ts b/packages/internal/dist/files.d.ts deleted file mode 100644 index f73a2903b6aa..000000000000 --- a/packages/internal/dist/files.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -export declare const findCells: (cwd?: string) => string[]; -export declare const findPages: (cwd?: string) => string[]; -/** - * This function finds all modules in the 'web' and 'api' directories excluding 'node_modules' and Cell files. - * Cell files are also directory named modules but they have their special type mirror file, so they are ignored. - * - * @param {string} cwd - The directory path to start searching from. By default, it is the base path of the project. - * @returns {Array} modules - An array of absolute paths for the found modules. - * - * @example - * // Assuming the base directory of your project is '/Users/user/myproject' - * findDirectoryNamedModules('/Users/user/myproject'); - * // This will return an array with the absolute paths of all matching files, e.g.: - * // ['/Users/user/myproject/web/src/components/Author/Author.tsx', '/Users/user/myproject/web/src/pages/AboutPage/AboutPage.tsx'] - */ -export declare const findDirectoryNamedModules: (cwd?: string) => string[]; -export declare const findGraphQLSchemas: (cwd?: string) => string[]; -export declare const findApiFiles: (cwd?: string) => string[]; -export declare const findWebFiles: (cwd?: string) => string[]; -export declare const findApiServerFunctions: (cwd?: string) => string[]; -export declare const findApiDistFunctions: (cwd?: string) => string[]; -export declare const findRouteHooksSrc: (cwd?: string) => string[]; -export declare const isCellFile: (p: string) => boolean; -export declare const findScripts: (cwd?: string) => string[]; -export declare const isPageFile: (p: string) => boolean; -/** - * This function checks if the given path belongs to a directory named module. - * A directory named module is where the filename (without extension) is the same as the directory it is in. - * - * @param {string} p - The absolute path of the file. - * @returns {boolean} - Returns true if the path belongs to a directory named module, false otherwise. - * - * @example - * isDirectoryNamedModuleFile('/Users/user/myproject/web/src/components/Author/Author.tsx'); - * // Returns: true - * - * isDirectoryNamedModuleFile('/Users/user/myproject/web/src/components/Author/AuthorInfo.tsx'); - * // Returns: false - */ -export declare const isDirectoryNamedModuleFile: (p: string) => boolean; -export declare const isGraphQLSchemaFile: (p: string) => boolean; -/** - * The following patterns are supported for api functions: - * - * 1. a module at the top level: `/graphql.js` - * 2. a module in a folder with a module of the same name: `/health/health.js` - * 3. a module in a folder named index: `/x/index.js` - */ -export declare const isApiFunction: (p: string, functionsPath: string) => boolean; -export declare const isFileInsideFolder: (filePath: string, folderPath: string) => boolean; -//# sourceMappingURL=files.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/files.d.ts.map b/packages/internal/dist/files.d.ts.map deleted file mode 100644 index 821f958a15b4..000000000000 --- a/packages/internal/dist/files.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"files.d.ts","sourceRoot":"","sources":["../src/files.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,SAAS,SAAS,MAAM,aAOpC,CAAA;AAED,eAAO,MAAM,SAAS,SAAS,MAAM,aAQpC,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,yBAAyB,SAAS,MAAM,aAUpD,CAAA;AAED,eAAO,MAAM,kBAAkB,SAAS,MAAM,aAI7C,CAAA;AASD,eAAO,MAAM,YAAY,SAAS,MAAM,aAOvC,CAAA;AAED,eAAO,MAAM,YAAY,SAAS,MAAM,aAYvC,CAAA;AAED,eAAO,MAAM,sBAAsB,SAC5B,MAAM,aAUZ,CAAA;AAED,eAAO,MAAM,oBAAoB,SAAS,MAAM,aAM/C,CAAA;AAED,eAAO,MAAM,iBAAiB,SAAS,MAAM,aAK5C,CAAA;AAED,eAAO,MAAM,UAAU,MAAO,MAAM,YA6BnC,CAAA;AAED,eAAO,MAAM,WAAW,SAAS,MAAM,aAMtC,CAAA;AAED,eAAO,MAAM,UAAU,MAAO,MAAM,YAoBnC,CAAA;AACD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,0BAA0B,MAAO,MAAM,YAGnD,CAAA;AAED,eAAO,MAAM,mBAAmB,MAAO,MAAM,YAQ5C,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,MAAO,MAAM,iBAAiB,MAAM,YAc7D,CAAA;AAED,eAAO,MAAM,kBAAkB,aAAc,MAAM,cAAc,MAAM,YAYtE,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/files.js b/packages/internal/dist/files.js deleted file mode 100644 index 557a202c365c..000000000000 --- a/packages/internal/dist/files.js +++ /dev/null @@ -1,223 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var files_exports = {}; -__export(files_exports, { - findApiDistFunctions: () => findApiDistFunctions, - findApiFiles: () => findApiFiles, - findApiServerFunctions: () => findApiServerFunctions, - findCells: () => findCells, - findDirectoryNamedModules: () => findDirectoryNamedModules, - findGraphQLSchemas: () => findGraphQLSchemas, - findPages: () => findPages, - findRouteHooksSrc: () => findRouteHooksSrc, - findScripts: () => findScripts, - findWebFiles: () => findWebFiles, - isApiFunction: () => isApiFunction, - isCellFile: () => isCellFile, - isDirectoryNamedModuleFile: () => isDirectoryNamedModuleFile, - isFileInsideFolder: () => isFileInsideFolder, - isGraphQLSchemaFile: () => isGraphQLSchemaFile, - isPageFile: () => isPageFile -}); -module.exports = __toCommonJS(files_exports); -var import_path = __toESM(require("path")); -var import_fast_glob = __toESM(require("fast-glob")); -var import_project_config = require("@redwoodjs/project-config"); -var import_ast = require("./ast"); -const findCells = (cwd = (0, import_project_config.getPaths)().web.src) => { - const modules = import_fast_glob.default.sync("**/*Cell.{js,jsx,ts,tsx}", { - cwd, - absolute: true, - ignore: ["node_modules"] - }); - return modules.filter(isCellFile); -}; -const findPages = (cwd = (0, import_project_config.getPaths)().web.pages) => { - const modules = import_fast_glob.default.sync("**/*Page.{tsx,js,jsx}", { - cwd, - absolute: true, - ignore: ["node_modules"] - }); - return modules.filter(isPageFile); -}; -const findDirectoryNamedModules = (cwd = (0, import_project_config.getPaths)().base) => { - const modules = import_fast_glob.default.sync("(api|web)/src/**/*.{ts,js,jsx,tsx}", { - cwd, - absolute: true, - ignore: ["node_modules"] - }); - return modules.filter(isDirectoryNamedModuleFile).filter((p) => !isCellFile(p)); -}; -const findGraphQLSchemas = (cwd = (0, import_project_config.getPaths)().api.graphql) => { - return import_fast_glob.default.sync("**/*.sdl.{ts,js}", { cwd, absolute: true }).filter(isGraphQLSchemaFile); -}; -const ignoreApiFiles = [ - "**/*.test.{js,ts}", - "**/*.scenarios.{js,ts}", - "**/*.fixtures.{js,ts}", - "**/*.d.ts" -]; -const findApiFiles = (cwd = (0, import_project_config.getPaths)().api.src) => { - const files = import_fast_glob.default.sync("**/*.{js,ts,jsx,tsx}", { - cwd, - absolute: true, - ignore: ignoreApiFiles - }); - return files; -}; -const findWebFiles = (cwd = (0, import_project_config.getPaths)().web.src) => { - const files = import_fast_glob.default.sync("**/*.{js,ts,jsx,tsx}", { - cwd, - absolute: true, - ignore: [ - "**/*.test.{js,ts,tsx,jsx}", - "**/*.fixtures.{js,ts,tsx,jsx}", - "**/*.mock.{js,ts,tsx,jsx}", - "**/*.d.ts" - ] - }); - return files; -}; -const findApiServerFunctions = (cwd = (0, import_project_config.getPaths)().api.functions) => { - const files = import_fast_glob.default.sync("**/*.{js,ts}", { - cwd, - absolute: true, - deep: 2, - // We don't support deeply nested api functions. - ignore: ignoreApiFiles - }); - return files.filter((f) => isApiFunction(f, cwd)); -}; -const findApiDistFunctions = (cwd = (0, import_project_config.getPaths)().api.base) => { - return import_fast_glob.default.sync("dist/functions/**/*.{ts,js}", { - cwd, - deep: 2, - // We don't support deeply nested api functions, to maximise compatibility with deployment providers - absolute: true - }); -}; -const findRouteHooksSrc = (cwd = (0, import_project_config.getPaths)().web.src) => { - return import_fast_glob.default.sync("**/*.routeHooks.{js,ts,tsx,jsx}", { - absolute: true, - cwd - }); -}; -const isCellFile = (p) => { - const { dir, name } = import_path.default.parse(p); - if (!isFileInsideFolder(p, (0, import_project_config.getPaths)().web.src)) { - return false; - } - if (!dir.endsWith(name)) { - return false; - } - const ast = (0, import_ast.fileToAst)(p); - if ((0, import_ast.hasDefaultExport)(ast)) { - return false; - } - const exports2 = (0, import_ast.getNamedExports)(ast); - const exportedQUERY = exports2.findIndex((v) => v.name === "QUERY") !== -1; - const exportedSuccess = exports2.findIndex((v) => v.name === "Success") !== -1; - if (!exportedQUERY && !exportedSuccess) { - return false; - } - return true; -}; -const findScripts = (cwd = (0, import_project_config.getPaths)().scripts) => { - return import_fast_glob.default.sync("./**/*.{js,jsx,ts,tsx}", { - cwd, - absolute: true, - ignore: ["node_modules"] - }); -}; -const isPageFile = (p) => { - const { name } = import_path.default.parse(p); - if (!name.endsWith("Page")) { - return false; - } - if (!isFileInsideFolder(p, (0, import_project_config.getPaths)().web.pages)) { - return false; - } - const ast = (0, import_ast.fileToAst)(p); - if (!(0, import_ast.hasDefaultExport)(ast)) { - return false; - } - return true; -}; -const isDirectoryNamedModuleFile = (p) => { - const { dir, name } = import_path.default.parse(p); - return dir.endsWith(name); -}; -const isGraphQLSchemaFile = (p) => { - if (!p.match(/\.sdl\.(ts|js)$/)?.[0]) { - return false; - } - const ast = (0, import_ast.fileToAst)(p); - const exports2 = (0, import_ast.getNamedExports)(ast); - return exports2.findIndex((v) => v.name === "schema") !== -1; -}; -const isApiFunction = (p, functionsPath) => { - p = import_path.default.relative(functionsPath, p); - const { dir, name } = import_path.default.parse(p); - if (dir === name) { - return true; - } else if (dir === "") { - return true; - } else if (dir.length && name === "index") { - return true; - } - return false; -}; -const isFileInsideFolder = (filePath, folderPath) => { - const { dir } = import_path.default.parse(filePath); - const relativePathFromFolder = import_path.default.relative(folderPath, dir); - if (!relativePathFromFolder || relativePathFromFolder.startsWith("..") || import_path.default.isAbsolute(relativePathFromFolder)) { - return false; - } else { - return true; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - findApiDistFunctions, - findApiFiles, - findApiServerFunctions, - findCells, - findDirectoryNamedModules, - findGraphQLSchemas, - findPages, - findRouteHooksSrc, - findScripts, - findWebFiles, - isApiFunction, - isCellFile, - isDirectoryNamedModuleFile, - isFileInsideFolder, - isGraphQLSchemaFile, - isPageFile -}); diff --git a/packages/internal/dist/generate/clientPreset.d.ts b/packages/internal/dist/generate/clientPreset.d.ts deleted file mode 100644 index 99f808bc32ed..000000000000 --- a/packages/internal/dist/generate/clientPreset.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -export declare const shouldGenerateTrustedDocuments: () => boolean; -export declare const generateClientPreset: () => Promise<{ - clientPresetFiles: string[]; - trustedDocumentsStoreFile: never[]; - errors: { - message: string; - error: unknown; - }[]; -} | { - clientPresetFiles: string[]; - trustedDocumentsStoreFile: string; - errors: { - message: string; - error: unknown; - }[]; -}>; -//# sourceMappingURL=clientPreset.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/clientPreset.d.ts.map b/packages/internal/dist/generate/clientPreset.d.ts.map deleted file mode 100644 index 37a9ef416c4a..000000000000 --- a/packages/internal/dist/generate/clientPreset.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"clientPreset.d.ts","sourceRoot":"","sources":["../../src/generate/clientPreset.ts"],"names":[],"mappings":"AAYA,eAAO,MAAM,8BAA8B,QAAO,OAIjD,CAAA;AAED,eAAO,MAAM,oBAAoB;;;;iBAIN,MAAM;eAAS,OAAO;;;;;;iBAAtB,MAAM;eAAS,OAAO;;EAoDhD,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/clientPreset.js b/packages/internal/dist/generate/clientPreset.js deleted file mode 100644 index aa8e631b506a..000000000000 --- a/packages/internal/dist/generate/clientPreset.js +++ /dev/null @@ -1,85 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var clientPreset_exports = {}; -__export(clientPreset_exports, { - generateClientPreset: () => generateClientPreset, - shouldGenerateTrustedDocuments: () => shouldGenerateTrustedDocuments -}); -module.exports = __toCommonJS(clientPreset_exports); -var import_cli = require("@graphql-codegen/cli"); -var import_client_preset = require("@graphql-codegen/client-preset"); -var import_project_config = require("@redwoodjs/project-config"); -var import_trustedDocuments = require("./trustedDocuments"); -const shouldGenerateTrustedDocuments = () => { - const config = (0, import_project_config.getConfig)(); - return config.graphql.trustedDocuments; -}; -const generateClientPreset = async () => { - let generatedFiles = []; - let clientPresetFiles = []; - const errors = []; - if (!shouldGenerateTrustedDocuments()) { - return { clientPresetFiles, trustedDocumentsStoreFile: [], errors }; - } - const documentsGlob = `${(0, import_project_config.getPaths)().web.src}/**/!(*.d).{ts,tsx,js,jsx}`; - const config = { - schema: (0, import_project_config.getPaths)().generated.schema, - documents: documentsGlob, - silent: true, - // Plays nicely with cli task output - generates: { - [`${(0, import_project_config.getPaths)().web.src}/graphql/`]: { - preset: "client", - presetConfig: { - persistedDocuments: true - }, - documentTransforms: [import_client_preset.addTypenameSelectionDocumentTransform], - config: { - // DO NOT USE documentMode: 'string', - } - } - } - }; - try { - generatedFiles = await (0, import_cli.generate)(config, true); - clientPresetFiles = generatedFiles.map((f) => f.filename); - const trustedDocumentsStoreFile = await (0, import_trustedDocuments.trustedDocumentsStore)(generatedFiles); - (0, import_trustedDocuments.replaceGqlTagWithTrustedDocumentGraphql)(generatedFiles); - return { - clientPresetFiles, - trustedDocumentsStoreFile, - errors - }; - } catch (e) { - errors.push({ - message: "Error: Could not generate GraphQL client preset", - error: e - }); - return { - clientPresetFiles, - trustedDocumentsStoreFile: [], - errors - }; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - generateClientPreset, - shouldGenerateTrustedDocuments -}); diff --git a/packages/internal/dist/generate/generate.d.ts b/packages/internal/dist/generate/generate.d.ts deleted file mode 100644 index 365271fa7684..000000000000 --- a/packages/internal/dist/generate/generate.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env node -export declare const generate: () => Promise<{ - files: string[]; - errors: { - message: string; - error: unknown; - }[]; -}>; -export declare const run: () => Promise; -//# sourceMappingURL=generate.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/generate.d.ts.map b/packages/internal/dist/generate/generate.d.ts.map deleted file mode 100644 index 5a885232157f..000000000000 --- a/packages/internal/dist/generate/generate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../src/generate/generate.ts"],"names":[],"mappings":";AASA,eAAO,MAAM,QAAQ;;;;;;EAsCpB,CAAA;AAED,eAAO,MAAM,GAAG,qBA4Bf,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/generate.js b/packages/internal/dist/generate/generate.js deleted file mode 100755 index a1a5dd114b7a..000000000000 --- a/packages/internal/dist/generate/generate.js +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env node -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var generate_exports = {}; -__export(generate_exports, { - generate: () => generate, - run: () => run -}); -module.exports = __toCommonJS(generate_exports); -var import_project_config = require("@redwoodjs/project-config"); -var import_clientPreset = require("./clientPreset"); -var import_graphqlSchema = require("./graphqlSchema"); -var import_possibleTypes = require("./possibleTypes"); -var import_typeDefinitions = require("./typeDefinitions"); -const generate = async () => { - const config = (0, import_project_config.getConfig)(); - const { schemaPath, errors: generateGraphQLSchemaErrors } = await (0, import_graphqlSchema.generateGraphQLSchema)(); - const { typeDefFiles, errors: generateTypeDefsErrors } = await (0, import_typeDefinitions.generateTypeDefs)(); - const clientPresetFiles = []; - const { possibleTypesFiles, errors: generatePossibleTypesErrors } = await (0, import_possibleTypes.generatePossibleTypes)(); - if (config.graphql.trustedDocuments) { - const preset = await (0, import_clientPreset.generateClientPreset)(); - clientPresetFiles.push(...preset.clientPresetFiles); - } - let files = []; - if (schemaPath !== "") { - files.push(schemaPath); - } - files = [ - ...files, - ...typeDefFiles, - ...clientPresetFiles, - ...possibleTypesFiles - ].filter((x) => typeof x === "string"); - return { - files, - errors: [ - ...generateGraphQLSchemaErrors, - ...generateTypeDefsErrors, - ...generatePossibleTypesErrors - ] - }; -}; -const run = async () => { - console.log("Generating..."); - console.log(); - const { files, errors } = await generate(); - const rwjsPaths = (0, import_project_config.getPaths)(); - for (const f of files) { - console.log("-", f.replace(rwjsPaths.base + "/", "")); - } - console.log(); - if (errors.length === 0) { - console.log("... done."); - console.log(); - return; - } - process.exitCode ||= 1; - console.log("... done with errors."); - console.log(); - for (const { message, error } of errors) { - console.error(message); - console.log(); - console.error(error); - console.log(); - } -}; -if (require.main === module) { - run(); -} -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - generate, - run -}); diff --git a/packages/internal/dist/generate/graphqlCodeGen.d.ts b/packages/internal/dist/generate/graphqlCodeGen.d.ts deleted file mode 100644 index 0d26cab92744..000000000000 --- a/packages/internal/dist/generate/graphqlCodeGen.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { LoadTypedefsOptions } from '@graphql-tools/load'; -type TypeDefResult = { - typeDefFiles: string[]; - errors: { - message: string; - error: unknown; - }[]; -}; -export declare const generateTypeDefGraphQLApi: () => Promise; -export declare const generateTypeDefGraphQLWeb: () => Promise; -export declare function getLoadDocumentsOptions(filename: string): LoadTypedefsOptions<{ - cwd: string; -}>; -export declare const getResolverFnType: () => "(\n args: TArgs,\n obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo }\n ) => TResult | Promise" | "(\n args?: TArgs,\n obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo }\n ) => TResult | Promise"; -export {}; -//# sourceMappingURL=graphqlCodeGen.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/graphqlCodeGen.d.ts.map b/packages/internal/dist/generate/graphqlCodeGen.d.ts.map deleted file mode 100644 index ee814b8c51db..000000000000 --- a/packages/internal/dist/generate/graphqlCodeGen.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"graphqlCodeGen.d.ts","sourceRoot":"","sources":["../../src/generate/graphqlCodeGen.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAA;AAc9D,KAAK,aAAa,GAAG;IACnB,YAAY,EAAE,MAAM,EAAE,CAAA;IACtB,MAAM,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,EAAE,CAAA;CAC9C,CAAA;AAED,eAAO,MAAM,yBAAyB,QAAa,OAAO,CAAC,aAAa,CAgFvE,CAAA;AAED,eAAO,MAAM,yBAAyB,QAAa,OAAO,CAAC,aAAa,CAwDvE,CAAA;AAiCD,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,MAAM;SACD,MAAM;GAQ5D;AA+FD,eAAO,MAAM,iBAAiB,4RAe7B,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/graphqlCodeGen.js b/packages/internal/dist/generate/graphqlCodeGen.js deleted file mode 100644 index 18641fbaf705..000000000000 --- a/packages/internal/dist/generate/graphqlCodeGen.js +++ /dev/null @@ -1,334 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var graphqlCodeGen_exports = {}; -__export(graphqlCodeGen_exports, { - generateTypeDefGraphQLApi: () => generateTypeDefGraphQLApi, - generateTypeDefGraphQLWeb: () => generateTypeDefGraphQLWeb, - getLoadDocumentsOptions: () => getLoadDocumentsOptions, - getResolverFnType: () => getResolverFnType -}); -module.exports = __toCommonJS(graphqlCodeGen_exports); -var import_fs = __toESM(require("fs")); -var import_path = __toESM(require("path")); -var addPlugin = __toESM(require("@graphql-codegen/add")); -var import_cli = require("@graphql-codegen/cli"); -var import_core = require("@graphql-codegen/core"); -var typescriptPlugin = __toESM(require("@graphql-codegen/typescript")); -var typescriptOperations = __toESM(require("@graphql-codegen/typescript-operations")); -var import_code_file_loader = require("@graphql-tools/code-file-loader"); -var import_graphql_file_loader = require("@graphql-tools/graphql-file-loader"); -var import_load = require("@graphql-tools/load"); -var import_execa = __toESM(require("execa")); -var import_graphql = require("graphql"); -var import_project_config = require("@redwoodjs/project-config"); -var import_project = require("../project"); -var rwTypescriptResolvers = __toESM(require("./plugins/rw-typescript-resolvers")); -var CodegenSide = /* @__PURE__ */ ((CodegenSide2) => { - CodegenSide2[CodegenSide2["API"] = 0] = "API"; - CodegenSide2[CodegenSide2["WEB"] = 1] = "WEB"; - return CodegenSide2; -})(CodegenSide || {}); -const generateTypeDefGraphQLApi = async () => { - const config = (0, import_project_config.getConfig)(); - const errors = []; - if (config.experimental.useSDLCodeGenForGraphQLTypes) { - const paths = (0, import_project_config.getPaths)(); - const sdlCodegen = await import("@sdl-codegen/node"); - const dtsFiles = []; - try { - const output = sdlCodegen.runFullCodegen("redwood", { paths }); - dtsFiles.concat(output.paths); - } catch (e) { - if (e instanceof Error) { - errors.push({ - message: e.message, - error: e - }); - } - } - return { - typeDefFiles: dtsFiles, - errors - }; - } - const filename = import_path.default.join((0, import_project_config.getPaths)().api.types, "graphql.d.ts"); - const prismaModels = await getPrismaModels(); - const prismaImports = Object.keys(prismaModels).map((key) => { - return `${key} as Prisma${key}`; - }); - const extraPlugins = [ - { - name: "add", - options: { - content: [ - 'import { Prisma } from "@prisma/client"', - "import { MergePrismaWithSdlTypes, MakeRelationsOptional } from '@redwoodjs/api'", - `import { ${prismaImports.join(", ")} } from '@prisma/client'` - ], - placement: "prepend" - }, - codegenPlugin: addPlugin - }, - { - name: "print-mapped-models", - options: {}, - codegenPlugin: printMappedModelsPlugin - }, - { - name: "typescript-resolvers", - options: {}, - codegenPlugin: rwTypescriptResolvers - } - ]; - try { - return { - typeDefFiles: await runCodegenGraphQL( - [], - extraPlugins, - filename, - 0 /* API */ - ), - errors - }; - } catch (e) { - errors.push({ - message: "Error: Could not generate GraphQL type definitions (api)", - error: e - }); - return { - typeDefFiles: [], - errors - }; - } -}; -const generateTypeDefGraphQLWeb = async () => { - const filename = import_path.default.join((0, import_project_config.getPaths)().web.types, "graphql.d.ts"); - const options = getLoadDocumentsOptions(filename); - const documentsGlob = "./web/src/**/!(*.d).{ts,tsx,js,jsx}"; - let documents; - try { - documents = await (0, import_load.loadDocuments)([documentsGlob], options); - } catch { - return { - typeDefFiles: [], - errors: [] - }; - } - const extraPlugins = [ - { - name: "add", - options: { - content: 'import { Prisma } from "@prisma/client"', - placement: "prepend" - }, - codegenPlugin: addPlugin - }, - { - name: "typescript-operations", - options: {}, - codegenPlugin: typescriptOperations - } - ]; - const errors = []; - try { - return { - typeDefFiles: await runCodegenGraphQL( - documents, - extraPlugins, - filename, - 1 /* WEB */ - ), - errors - }; - } catch (e) { - errors.push({ - message: "Error: Could not generate GraphQL type definitions (web)", - error: e - }); - return { - typeDefFiles: [], - errors - }; - } -}; -async function runCodegenGraphQL(documents, extraPlugins, filename, side) { - const userCodegenConfig = await (0, import_cli.loadCodegenConfig)({ - configFilePath: (0, import_project_config.getPaths)().base - }); - const mergedConfig = { - ...await getPluginConfig(side), - ...userCodegenConfig?.config?.config - }; - const options = getCodegenOptions(documents, mergedConfig, extraPlugins); - const output = await (0, import_core.codegen)(options); - import_fs.default.mkdirSync(import_path.default.dirname(filename), { recursive: true }); - import_fs.default.writeFileSync(filename, output); - return [filename]; -} -function getLoadDocumentsOptions(filename) { - const loadTypedefsConfig = { - cwd: (0, import_project_config.getPaths)().base, - ignore: [import_path.default.join(process.cwd(), filename)], - loaders: [new import_code_file_loader.CodeFileLoader()], - sort: true - }; - return loadTypedefsConfig; -} -async function getPrismaClient(hasGenerated = false) { - const { default: localPrisma } = await import("@prisma/client"); - if (!localPrisma.ModelName) { - if (hasGenerated) { - return { ModelName: {} }; - } else { - import_execa.default.sync("yarn rw prisma generate", { shell: true }); - Object.keys(require.cache).forEach((key) => { - if (key.includes("/node_modules/@prisma/client/") || key.includes("/node_modules/.prisma/client/")) { - delete require.cache[key]; - } - }); - return getPrismaClient(true); - } - } - return localPrisma; -} -async function getPrismaModels() { - const localPrisma = await getPrismaClient(); - const prismaModels = localPrisma.ModelName; - if (prismaModels.RW_DataMigration) { - delete prismaModels.RW_DataMigration; - } - return prismaModels; -} -async function getPluginConfig(side) { - const prismaModels = await getPrismaModels(); - Object.keys(prismaModels).forEach((key) => { - prismaModels[key] = `MergePrismaWithSdlTypes, AllMappedModels>`; - }); - const pluginConfig = { - makeResolverTypeCallable: true, - namingConvention: "keep", - // to allow camelCased query names - scalars: { - // We need these, otherwise these scalars are mapped to any - BigInt: "number", - // @Note: DateTime fields can be valid Date-strings, or the Date object in the api side. They're always strings on the web side. - DateTime: side === 1 /* WEB */ ? "string" : "Date | string", - Date: side === 1 /* WEB */ ? "string" : "Date | string", - JSON: "Prisma.JsonValue", - JSONObject: "Prisma.JsonObject", - Time: side === 1 /* WEB */ ? "string" : "Date | string", - Byte: "Buffer" - }, - // prevent type names being PetQueryQuery, RW generators already append - // Query/Mutation/etc - omitOperationSuffix: true, - showUnusedMappers: false, - customResolverFn: getResolverFnType(), - mappers: prismaModels, - avoidOptionals: { - // We do this, so that service tests can call resolvers without doing a null check - // see https://github.com/redwoodjs/redwood/pull/6222#issuecomment-1230156868 - // Look at type or source https://shrtm.nu/2BA0 for possible config, not well documented - resolvers: true - }, - contextType: `@redwoodjs/graphql-server/dist/types#RedwoodGraphQLContext` - }; - return pluginConfig; -} -const getResolverFnType = () => { - const tsConfig = (0, import_project.getTsConfigs)(); - if (tsConfig.api?.compilerOptions?.strict) { - return `( - args: TArgs, - obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } - ) => TResult | Promise`; - } else { - return `( - args?: TArgs, - obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } - ) => TResult | Promise`; - } -}; -const printMappedModelsPlugin = { - plugin: (schema, _documents, config) => { - const sdlTypesWhichAreMapped = Object.values(schema.getTypeMap()).filter((type) => { - return type.astNode?.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION; - }).filter((objectDefType) => { - const modelName = objectDefType.astNode?.name.value; - return modelName && modelName in config.mappers; - }).map((objectDefType) => objectDefType.astNode?.name.value); - return `type MaybeOrArrayOfMaybe = T | Maybe | Maybe[]; -type AllMappedModels = MaybeOrArrayOfMaybe<${sdlTypesWhichAreMapped.join( - " | " - )}>`; - } -}; -function getCodegenOptions(documents, config, extraPlugins) { - const plugins = [ - { typescript: { enumsAsTypes: true } }, - ...extraPlugins.map((plugin) => ({ [plugin.name]: plugin.options })) - ]; - const pluginMap = { - typescript: typescriptPlugin, - ...extraPlugins.reduce( - (acc, cur) => ({ ...acc, [cur.name]: cur.codegenPlugin }), - {} - ) - }; - const options = { - // The typescript plugin returns a string instead of writing to a file, so - // `filename` is not used - filename: "", - // `schemaAst` is used instead of `schema` if `schemaAst` is defined, and - // `schema` isn't. In the source for GenerateOptions they have this - // comment: - // Remove schemaAst and change schema to GraphQLSchema in the next major - // version - // When that happens we'll have have to remove our `schema` line, and - // rename `schemaAst` to `schema` - schema: void 0, - schemaAst: (0, import_load.loadSchemaSync)((0, import_project_config.getPaths)().generated.schema, { - loaders: [new import_graphql_file_loader.GraphQLFileLoader()], - sort: true - }), - documents, - config, - plugins, - pluginMap, - pluginContext: {} - }; - return options; -} -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - generateTypeDefGraphQLApi, - generateTypeDefGraphQLWeb, - getLoadDocumentsOptions, - getResolverFnType -}); diff --git a/packages/internal/dist/generate/graphqlSchema.d.ts b/packages/internal/dist/generate/graphqlSchema.d.ts deleted file mode 100644 index 837890635876..000000000000 --- a/packages/internal/dist/generate/graphqlSchema.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export declare const generateGraphQLSchema: () => Promise<{ - schemaPath: string; - errors: { - message: string; - error: unknown; - }[]; -}>; -//# sourceMappingURL=graphqlSchema.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/graphqlSchema.d.ts.map b/packages/internal/dist/generate/graphqlSchema.d.ts.map deleted file mode 100644 index 9187eff6ad01..000000000000 --- a/packages/internal/dist/generate/graphqlSchema.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"graphqlSchema.d.ts","sourceRoot":"","sources":["../../src/generate/graphqlSchema.ts"],"names":[],"mappings":"AAiBA,eAAO,MAAM,qBAAqB;;;iBA4CP,MAAM;eAAS,OAAO;;EAyEhD,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/graphqlSchema.js b/packages/internal/dist/generate/graphqlSchema.js deleted file mode 100644 index 1eb13a115b46..000000000000 --- a/packages/internal/dist/generate/graphqlSchema.js +++ /dev/null @@ -1,147 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var graphqlSchema_exports = {}; -__export(graphqlSchema_exports, { - generateGraphQLSchema: () => generateGraphQLSchema -}); -module.exports = __toCommonJS(graphqlSchema_exports); -var import_fs = __toESM(require("fs")); -var import_core = require("@graphql-codegen/core"); -var schemaAstPlugin = __toESM(require("@graphql-codegen/schema-ast")); -var import_code_file_loader = require("@graphql-tools/code-file-loader"); -var import_load = require("@graphql-tools/load"); -var import_internals = require("@prisma/internals"); -var import_chalk = __toESM(require("chalk")); -var import_graphql = require("graphql"); -var import_terminal_link = __toESM(require("terminal-link")); -var import_graphql_server = require("@redwoodjs/graphql-server"); -var import_project_config = require("@redwoodjs/project-config"); -const generateGraphQLSchema = async () => { - const redwoodProjectPaths = (0, import_project_config.getPaths)(); - const schemaPointerMap = { - [(0, import_graphql.print)(import_graphql_server.rootSchema.schema)]: {}, - "graphql/**/*.sdl.{js,ts}": {}, - "directives/**/*.{js,ts}": {}, - "subscriptions/**/*.{js,ts}": {} - }; - if ((0, import_project_config.resolveFile)(`${(0, import_project_config.getPaths)().api.src}/server`)) { - try { - const { liveDirectiveTypeDefs } = await import("@redwoodjs/realtime"); - schemaPointerMap[liveDirectiveTypeDefs] = {}; - } catch (error) { - if (error.code !== "ERR_MODULE_NOT_FOUND") { - throw error; - } - } - } - const loadSchemaConfig = { - assumeValidSDL: true, - sort: true, - convertExtensions: true, - includeSources: true, - cwd: redwoodProjectPaths.api.src, - schema: Object.keys(schemaPointerMap), - generates: { - [redwoodProjectPaths.generated.schema]: { - plugins: ["schema-ast"] - } - }, - silent: false, - errorsOnly: false, - pluginContext: {}, - loaders: [new import_code_file_loader.CodeFileLoader()] - }; - let loadedSchema; - const errors = []; - try { - loadedSchema = await (0, import_load.loadSchema)(schemaPointerMap, loadSchemaConfig); - } catch (e) { - if (e instanceof Error) { - const match = e.message.match(/Unknown type: "(\w+)"/); - const name = match?.[1]; - const schemaPrisma = (await (0, import_internals.getSchema)(redwoodProjectPaths.api.dbSchema)).toString(); - const errorObject = { - message: `Schema loading failed. ${e.message}`, - error: e - }; - errors.push(errorObject); - if (name && schemaPrisma.includes(`model ${name}`)) { - errorObject.message = [ - errorObject.message, - "", - ` ${import_chalk.default.bgYellow(` ${import_chalk.default.black.bold("Heads up")} `)}`, - "", - import_chalk.default.yellow( - ` It looks like you have a ${name} model in your Prisma schema.` - ), - import_chalk.default.yellow( - ` If it's part of a relation, you may have to generate SDL or scaffolding for ${name} too.` - ), - import_chalk.default.yellow( - ` So, if you haven't done that yet, ignore this error message and run the SDL or scaffold generator for ${name} now.` - ), - "", - import_chalk.default.yellow( - ` See the ${(0, import_terminal_link.default)( - "Troubleshooting Generators", - "https://redwoodjs.com/docs/schema-relations#troubleshooting-generators" - )} section in our docs for more help.` - ) - ].join("\n"); - } - } - } - const options = { - config: {}, - // no extra config needed for merged schema file generation - plugins: [{ "schema-ast": {} }], - pluginMap: { "schema-ast": schemaAstPlugin }, - schema: {}, - schemaAst: loadedSchema, - filename: redwoodProjectPaths.generated.schema, - documents: [] - }; - if (loadedSchema) { - try { - const schema = await (0, import_core.codegen)(options); - import_fs.default.writeFileSync(redwoodProjectPaths.generated.schema, schema); - return { schemaPath: redwoodProjectPaths.generated.schema, errors }; - } catch (e) { - errors.push({ - message: `GraphQL Schema codegen failed`, - error: e - }); - } - } - return { schemaPath: "", errors }; -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - generateGraphQLSchema -}); diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts deleted file mode 100644 index c307534e9ddc..000000000000 --- a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import type { Types, PluginFunction } from '@graphql-codegen/plugin-helpers'; -import { TypeScriptResolversPluginConfig } from '@graphql-codegen/typescript-resolvers'; -import { RwTypeScriptResolversVisitor } from './visitor'; -export declare const plugin: PluginFunction; -export { RwTypeScriptResolversVisitor, TypeScriptResolversPluginConfig }; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts.map b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts.map deleted file mode 100644 index 574554a69213..000000000000 --- a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/generate/plugins/rw-typescript-resolvers/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAA;AAK5E,OAAO,EACL,+BAA+B,EAEhC,MAAM,uCAAuC,CAAA;AAG9C,OAAO,EAAE,4BAA4B,EAAE,MAAM,WAAW,CAAA;AAExD,eAAO,MAAM,MAAM,EAAE,cAAc,CACjC,+BAA+B,EAC/B,KAAK,CAAC,mBAAmB,CAgF1B,CAAA;AAED,OAAO,EAAE,4BAA4B,EAAE,+BAA+B,EAAE,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js deleted file mode 100644 index 70cc0bf6a26a..000000000000 --- a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/index.js +++ /dev/null @@ -1,67 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var rw_typescript_resolvers_exports = {}; -__export(rw_typescript_resolvers_exports, { - RwTypeScriptResolversVisitor: () => import_visitor.RwTypeScriptResolversVisitor, - TypeScriptResolversPluginConfig: () => import_typescript_resolvers.TypeScriptResolversPluginConfig, - plugin: () => plugin -}); -module.exports = __toCommonJS(rw_typescript_resolvers_exports); -var import_plugin_helpers = require("@graphql-codegen/plugin-helpers"); -var import_typescript_resolvers = require("@graphql-codegen/typescript-resolvers"); -var import_visitor = require("./visitor"); -const plugin = (schema, _documents, config) => { - const visitor = new import_visitor.RwTypeScriptResolversVisitor(config, schema); - const visitorResult = (0, import_plugin_helpers.oldVisit)((0, import_plugin_helpers.getCachedDocumentNodeFromSchema)(schema), { - leave: visitor - }); - const { prepend, content } = (0, import_typescript_resolvers.plugin)(schema, [], config); - prepend.push(`export type OptArgsResolverFn = ( - args?: TArgs, - obj?: { root: TParent; context: TContext; info: GraphQLResolveInfo } - ) => TResult | Promise - - export type RequiredResolverFn = ( - args: TArgs, - obj: { root: TParent; context: TContext; info: GraphQLResolveInfo } - ) => TResult | Promise`); - const splitContent = content.split("\n"); - const visitorResultStart = splitContent.indexOf( - visitorResult.definitions.filter((d) => typeof d === "string")[0].split("\n")[0] - ); - const splitRootResolver = visitor.getRootResolver().split("\n"); - const visitorResultEnd = splitContent.findIndex( - (line, index) => line === splitRootResolver[0] && splitContent[index + 1] === splitRootResolver[1] - ); - const newContent = [ - ...splitContent.slice(0, visitorResultStart), - ...visitorResult.definitions.filter((d) => typeof d === "string"), - ...splitContent.slice(visitorResultEnd) - ]; - return { - prepend, - content: newContent.join("\n") - }; -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - RwTypeScriptResolversVisitor, - TypeScriptResolversPluginConfig, - plugin -}); diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts deleted file mode 100644 index 6a730fdd98e9..000000000000 --- a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { TypeScriptResolversPluginConfig } from '@graphql-codegen/typescript-resolvers'; -import { TypeScriptResolversVisitor } from '@graphql-codegen/typescript-resolvers'; -import type { FieldDefinitionNode, GraphQLSchema, ObjectTypeDefinitionNode } from 'graphql'; -export declare class RwTypeScriptResolversVisitor extends TypeScriptResolversVisitor { - constructor(pluginConfig: TypeScriptResolversPluginConfig, schema: GraphQLSchema); - FieldDefinition(node: FieldDefinitionNode, key: string | number, parent: any): (parentName: string) => string | null; - ObjectTypeDefinition(node: ObjectTypeDefinitionNode): string; -} -//# sourceMappingURL=visitor.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts.map b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts.map deleted file mode 100644 index 7d95193d7cb0..000000000000 --- a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"visitor.d.ts","sourceRoot":"","sources":["../../../../src/generate/plugins/rw-typescript-resolvers/visitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,uCAAuC,CAAA;AAC5F,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAA;AAKlF,OAAO,KAAK,EACV,mBAAmB,EACnB,aAAa,EACb,wBAAwB,EACzB,MAAM,SAAS,CAAA;AAEhB,qBAAa,4BAA6B,SAAQ,0BAA0B;gBAExE,YAAY,EAAE,+BAA+B,EAC7C,MAAM,EAAE,aAAa;IAKvB,eAAe,CACb,IAAI,EAAE,mBAAmB,EACzB,GAAG,EAAE,MAAM,GAAG,MAAM,EACpB,MAAM,EAAE,GAAG,GACV,CAAC,UAAU,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI;IAuBxC,oBAAoB,CAAC,IAAI,EAAE,wBAAwB,GAAG,MAAM;CAgG7D"} \ No newline at end of file diff --git a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js b/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js deleted file mode 100644 index 1f6e9bf8f17f..000000000000 --- a/packages/internal/dist/generate/plugins/rw-typescript-resolvers/visitor.js +++ /dev/null @@ -1,84 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var visitor_exports = {}; -__export(visitor_exports, { - RwTypeScriptResolversVisitor: () => RwTypeScriptResolversVisitor -}); -module.exports = __toCommonJS(visitor_exports); -var import_typescript_resolvers = require("@graphql-codegen/typescript-resolvers"); -var import_visitor_plugin_common = require("@graphql-codegen/visitor-plugin-common"); -class RwTypeScriptResolversVisitor extends import_typescript_resolvers.TypeScriptResolversVisitor { - constructor(pluginConfig, schema) { - super(pluginConfig, schema); - } - FieldDefinition(node, key, parent) { - const hasArguments = node.arguments && node.arguments.length > 0; - const superFieldDefinition = super.FieldDefinition(node, key, parent); - return (parentName) => { - const fieldDef = superFieldDefinition(parentName); - if (!hasArguments && fieldDef?.includes(": Resolver<")) { - return fieldDef.replace(": Resolver<", ": OptArgsResolverFn<"); - } - return fieldDef; - }; - } - // Original implementation is here: - // https://github.com/dotansimha/graphql-code-generator/blob/c6c60a3078f3797af435c3852220d8898964031d/packages/plugins/other/visitor-plugin-common/src/base-resolvers-visitor.ts#L1091 - ObjectTypeDefinition(node) { - const originalBlock = super.ObjectTypeDefinition(node); - const name = this.convertName(node, { - suffix: this.config.resolverTypeSuffix - }); - const typeName = node.name; - const parentType = this.getParentTypeToUse(typeName); - const fieldsContent = (node.fields || []).map((f) => f(node.name)); - const isRootType = [ - this.schema.getQueryType()?.name, - this.schema.getMutationType()?.name, - this.schema.getSubscriptionType()?.name - ].includes(typeName); - if (!isRootType) { - fieldsContent.push( - (0, import_visitor_plugin_common.indent)( - `${this.config.internalResolversPrefix}isTypeOf?: IsTypeOfResolverFn${this.getPunctuation( - "type" - )}` - ) - ); - } - const blockRelationsResolver = new import_visitor_plugin_common.DeclarationBlock( - this._declarationBlockConfig - ).export().asKind("type").withName( - name.replace("Resolvers", "RelationResolvers"), - `` - ).withBlock( - fieldsContent.map( - (content) => content.replace( - /: (?:OptArgs)?Resolver(?:Fn)?/, - "?: RequiredResolverFn" - ) - ).join("\n") - ); - return originalBlock + "\n" + blockRelationsResolver.string; - } -} -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - RwTypeScriptResolversVisitor -}); diff --git a/packages/internal/dist/generate/possibleTypes.d.ts b/packages/internal/dist/generate/possibleTypes.d.ts deleted file mode 100644 index 346b4038efd5..000000000000 --- a/packages/internal/dist/generate/possibleTypes.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -type PossibleTypesResult = { - possibleTypesFiles: string[]; - errors: { - message: string; - error: unknown; - }[]; -}; -/** - * Generate possible types from fragments and union types - * - * In order to use fragments with unions and interfaces in Apollo Client, - * you need to tell the client how to discriminate between the different - * types that implement or belong to a supertype. - * - * You pass a possibleTypes option to the InMemoryCache constructor - * to specify these relationships in your schema. - * - * This object maps the name of an interface or union type (the supertype) - * to the types that implement or belong to it (the subtypes). - * - * For example: - * - * ```ts - * possibleTypes: { - * Character: ["Jedi", "Droid"], - * Test: ["PassingTest", "FailingTest", "SkippedTest"], - * Snake: ["Viper", "Python"], - * Groceries: ['Fruit', 'Vegetable'], - * }, - * ``` - * - * @see https://www.apollographql.com/docs/react/data/fragments/#using-fragments-with-unions-and-interfaces - **/ -export declare const generatePossibleTypes: () => Promise; -export {}; -//# sourceMappingURL=possibleTypes.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/possibleTypes.d.ts.map b/packages/internal/dist/generate/possibleTypes.d.ts.map deleted file mode 100644 index b08b915d8042..000000000000 --- a/packages/internal/dist/generate/possibleTypes.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"possibleTypes.d.ts","sourceRoot":"","sources":["../../src/generate/possibleTypes.ts"],"names":[],"mappings":"AAYA,KAAK,mBAAmB,GAAG;IACzB,kBAAkB,EAAE,MAAM,EAAE,CAAA;IAC5B,MAAM,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,EAAE,CAAA;CAC9C,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;IAyBI;AACJ,eAAO,MAAM,qBAAqB,QAAa,OAAO,CAAC,mBAAmB,CAyEzE,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/possibleTypes.js b/packages/internal/dist/generate/possibleTypes.js deleted file mode 100644 index c91763dc4dc5..000000000000 --- a/packages/internal/dist/generate/possibleTypes.js +++ /dev/null @@ -1,106 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var possibleTypes_exports = {}; -__export(possibleTypes_exports, { - generatePossibleTypes: () => generatePossibleTypes -}); -module.exports = __toCommonJS(possibleTypes_exports); -var import_fs = __toESM(require("fs")); -var import_path = __toESM(require("path")); -var fragmentMatcher = __toESM(require("@graphql-codegen/fragment-matcher")); -var import_graphql_file_loader = require("@graphql-tools/graphql-file-loader"); -var import_load = require("@graphql-tools/load"); -var import_prettier = require("prettier"); -var import_project_config = require("@redwoodjs/project-config"); -var import_graphqlCodeGen = require("./graphqlCodeGen"); -const generatePossibleTypes = async () => { - const config = (0, import_project_config.getConfig)(); - if (!config.graphql.fragments) { - return { - possibleTypesFiles: [], - errors: [] - }; - } - const filename = import_path.default.join((0, import_project_config.getPaths)().web.graphql, "possibleTypes.ts"); - const options = (0, import_graphqlCodeGen.getLoadDocumentsOptions)(filename); - const documentsGlob = "./web/src/**/!(*.d).{ts,tsx,js,jsx}"; - let documents; - try { - documents = await (0, import_load.loadDocuments)([documentsGlob], options); - } catch { - return { - possibleTypesFiles: [], - errors: [] - }; - } - const errors = []; - try { - const files = []; - const pluginConfig = {}; - const info = { - outputFile: filename - }; - const schema = (0, import_load.loadSchemaSync)((0, import_project_config.getPaths)().generated.schema, { - loaders: [new import_graphql_file_loader.GraphQLFileLoader()], - sort: true - }); - const possibleTypes = await fragmentMatcher.plugin( - schema, - documents, - pluginConfig, - info - ); - files.push(filename); - const output = await (0, import_prettier.format)(possibleTypes.toString(), { - trailingComma: "es5", - bracketSpacing: true, - tabWidth: 2, - semi: false, - singleQuote: true, - arrowParens: "always", - parser: "typescript" - }); - import_fs.default.mkdirSync(import_path.default.dirname(filename), { recursive: true }); - import_fs.default.writeFileSync(filename, output); - return { possibleTypesFiles: [filename], errors }; - } catch (e) { - errors.push({ - message: "Error: Could not generate GraphQL possible types (web)", - error: e - }); - return { - possibleTypesFiles: [], - errors - }; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - generatePossibleTypes -}); diff --git a/packages/internal/dist/generate/templates.d.ts b/packages/internal/dist/generate/templates.d.ts deleted file mode 100644 index b8c393d463ca..000000000000 --- a/packages/internal/dist/generate/templates.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Write the contents of the template to the destination and interpolate the variables. - * The template is a string that uses standard es6 template literals which allow embded expression. - */ -export declare const writeTemplate: (templatePath: string, destination: string, templateValues?: Record) => void; -//# sourceMappingURL=templates.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/templates.d.ts.map b/packages/internal/dist/generate/templates.d.ts.map deleted file mode 100644 index f320a52ae0c3..000000000000 --- a/packages/internal/dist/generate/templates.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/generate/templates.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,eAAO,MAAM,aAAa,iBACV,MAAM,eACP,MAAM,mBACH,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,SAYxC,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/templates.js b/packages/internal/dist/generate/templates.js deleted file mode 100644 index 3e095fd747fa..000000000000 --- a/packages/internal/dist/generate/templates.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var templates_exports = {}; -__export(templates_exports, { - writeTemplate: () => writeTemplate -}); -module.exports = __toCommonJS(templates_exports); -var import_fs = __toESM(require("fs")); -var import_path = __toESM(require("path")); -const writeTemplate = (templatePath, destination, templateValues = {}) => { - const templateString = import_fs.default.readFileSync( - import_path.default.join(__dirname, templatePath), - "utf-8" - ); - const template = templatized(templateString, templateValues); - import_fs.default.writeFileSync( - destination, - "// This file was generated by RedwoodJS\n" + template - ); -}; -const templatized = (template, vars = {}) => { - const handler = new Function( - "vars", - [ - "const tagged = ( " + Object.keys(vars).join(", ") + " ) =>", - "`" + template + "`", - "return tagged(...Object.values(vars))" - ].join("\n") - ); - return handler(vars); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - writeTemplate -}); diff --git a/packages/internal/dist/generate/templates/all-currentUser.d.ts.template b/packages/internal/dist/generate/templates/all-currentUser.d.ts.template deleted file mode 100644 index c9138e88b2a6..000000000000 --- a/packages/internal/dist/generate/templates/all-currentUser.d.ts.template +++ /dev/null @@ -1,28 +0,0 @@ -import '@redwoodjs/api' -import '@redwoodjs/auth' - -import { getCurrentUser } from '../../../api/src/lib/auth' - -export type InferredCurrentUser = Awaited> - -type UndefinedRoles = { - /** - * ⚠️ Heads-Up: This is undefined unless roles key is returned from {@link getCurrentUser()} - * - * You may take a look at https://redwoodjs.com/docs/tutorial/chapter7/rbac for a tutorial on - * how to add fully-fledged RBAC (Role-based Access Control) to your database model. - */ - roles?: unknown | unknown[] -} - -type Overwrite = Omit & U - -declare module '@redwoodjs/context' { - interface GlobalContext { - currentUser?: Overwrite - } -} - -declare module '@redwoodjs/auth' { - interface CurrentUser extends InferredCurrentUser {} -} diff --git a/packages/internal/dist/generate/templates/api-globImports.d.ts.template b/packages/internal/dist/generate/templates/api-globImports.d.ts.template deleted file mode 100644 index ada756867205..000000000000 --- a/packages/internal/dist/generate/templates/api-globImports.d.ts.template +++ /dev/null @@ -1,9 +0,0 @@ -declare module 'src/services/**/*.{js,ts}' -declare module 'src/directives/**/*.{js,ts}' -declare module 'src/graphql/**/*.sdl.{js,ts}' -declare module 'src/subscriptions/**/*.{js,ts}' - - -declare module 'api/src/services/**/*.{js,ts}' -declare module 'api/src/directives/**/*.{js,ts}' -declare module 'api/src/graphql/**/*.sdl.{js,ts}' diff --git a/packages/internal/dist/generate/templates/api-globalContext.d.ts.template b/packages/internal/dist/generate/templates/api-globalContext.d.ts.template deleted file mode 100644 index c13d883e4e16..000000000000 --- a/packages/internal/dist/generate/templates/api-globalContext.d.ts.template +++ /dev/null @@ -1,7 +0,0 @@ -import type { GlobalContext } from "@redwoodjs/context" - -export {} - -declare global { - const context: GlobalContext -} diff --git a/packages/internal/dist/generate/templates/api-scenarios.d.ts.template b/packages/internal/dist/generate/templates/api-scenarios.d.ts.template deleted file mode 100644 index 8be4f6182462..000000000000 --- a/packages/internal/dist/generate/templates/api-scenarios.d.ts.template +++ /dev/null @@ -1,10 +0,0 @@ -import type { Scenario, DefineScenario, DescribeScenario } from '@redwoodjs/testing/api' - -declare global { - /** - * Note that the scenario name must match the exports in your {model}.scenarios.ts file - */ - const scenario: Scenario - const describeScenario: DescribeScenario - const defineScenario: DefineScenario -} diff --git a/packages/internal/dist/generate/templates/api-test-globals.d.ts.template b/packages/internal/dist/generate/templates/api-test-globals.d.ts.template deleted file mode 100644 index 575e28d6c111..000000000000 --- a/packages/internal/dist/generate/templates/api-test-globals.d.ts.template +++ /dev/null @@ -1,5 +0,0 @@ -import type { CurrentUser } from '@redwoodjs/auth' - -declare global { - const mockCurrentUser: (currentUser: CurrentUser) => void -} diff --git a/packages/internal/dist/generate/templates/mirror-cell.d.ts.template b/packages/internal/dist/generate/templates/mirror-cell.d.ts.template deleted file mode 100644 index fba45262cc26..000000000000 --- a/packages/internal/dist/generate/templates/mirror-cell.d.ts.template +++ /dev/null @@ -1,13 +0,0 @@ -import * as Cell from './${name}' -import type { CellProps } from '@redwoodjs/web' -import type { ${queryResultType}, ${queryVariablesType} } from 'types/graphql' - -type SuccessType = typeof Cell.Success - -export * from './${name}' - -type CellInputs = CellProps - -export default function (props: CellInputs): ReturnType - -//# sourceMappingURL=index.d.ts.map diff --git a/packages/internal/dist/generate/templates/mirror-directoryNamedModule.d.ts.template b/packages/internal/dist/generate/templates/mirror-directoryNamedModule.d.ts.template deleted file mode 100644 index 1fe40a46da59..000000000000 --- a/packages/internal/dist/generate/templates/mirror-directoryNamedModule.d.ts.template +++ /dev/null @@ -1,5 +0,0 @@ -import { default as DEFAULT } from './${name}' -export default DEFAULT -export * from './${name}' - -//# sourceMappingURL=index.d.ts.map diff --git a/packages/internal/dist/generate/templates/web-routerRoutes.d.ts.template b/packages/internal/dist/generate/templates/web-routerRoutes.d.ts.template deleted file mode 100644 index 2c6bca1f1548..000000000000 --- a/packages/internal/dist/generate/templates/web-routerRoutes.d.ts.template +++ /dev/null @@ -1,20 +0,0 @@ -import { RouteParams, QueryParams } from '@redwoodjs/router' - -declare module '@redwoodjs/router' { - interface AvailableRoutes { - // Only "" components with a "name" and "path" prop will be populated here. -${routes.map( - ({ props: { name, path }}) => { - return ` ${name}: (params?: RouteParams<"${path}"> & QueryParams) => "${path}"` - } -).join('\n')} - } - - export function useRoutePaths(): Record - export function useRoutePath(routeName: keyof AvailableRoutes): string - - /** Gets the name of the current route (as defined in your Routes file) */ - export function useRouteName(): keyof AvailableRoutes | undefined -} - -//# sourceMappingURL=web-routerRoutes.d.ts.map diff --git a/packages/internal/dist/generate/templates/web-routesPages.d.ts.template b/packages/internal/dist/generate/templates/web-routesPages.d.ts.template deleted file mode 100644 index 2b99077d7b16..000000000000 --- a/packages/internal/dist/generate/templates/web-routesPages.d.ts.template +++ /dev/null @@ -1,13 +0,0 @@ -${pages - .map(({ importName, importPath }) => { - return `import ${importName}Type from '${importPath}'` - }) - .join('\n')} - -declare global { -${pages.map(({ importName }) => { - return ` const ${importName}: typeof ${importName}Type` -}).join('\n')} -} - -//# sourceMappingURL=web-routesPages.d.ts.map diff --git a/packages/internal/dist/generate/templates/web-test-globals.d.ts.template b/packages/internal/dist/generate/templates/web-test-globals.d.ts.template deleted file mode 100644 index 74023a6f73a1..000000000000 --- a/packages/internal/dist/generate/templates/web-test-globals.d.ts.template +++ /dev/null @@ -1,7 +0,0 @@ -// Import other mocking function globals -import '@redwoodjs/testing' -import { InferredCurrentUser } from './all-currentUser' - -declare global { - const mockCurrentUser: (currentUser: InferredCurrentUser) => void -} diff --git a/packages/internal/dist/generate/trustedDocuments.d.ts b/packages/internal/dist/generate/trustedDocuments.d.ts deleted file mode 100644 index 7063723d63ea..000000000000 --- a/packages/internal/dist/generate/trustedDocuments.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -export declare const trustedDocumentsStore: (generatedFiles: any) => Promise; -export declare const replaceGqlTagWithTrustedDocumentGraphql: (generatedFiles: any) => Promise; -//# sourceMappingURL=trustedDocuments.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/trustedDocuments.d.ts.map b/packages/internal/dist/generate/trustedDocuments.d.ts.map deleted file mode 100644 index 44800ce29411..000000000000 --- a/packages/internal/dist/generate/trustedDocuments.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"trustedDocuments.d.ts","sourceRoot":"","sources":["../../src/generate/trustedDocuments.ts"],"names":[],"mappings":"AAUA,eAAO,MAAM,qBAAqB,mBAA0B,GAAG,oBA8B9D,CAAA;AAID,eAAO,MAAM,uCAAuC,mBAClC,GAAG,kBA8BpB,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/trustedDocuments.js b/packages/internal/dist/generate/trustedDocuments.js deleted file mode 100644 index 7d45f9c2302b..000000000000 --- a/packages/internal/dist/generate/trustedDocuments.js +++ /dev/null @@ -1,95 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var trustedDocuments_exports = {}; -__export(trustedDocuments_exports, { - replaceGqlTagWithTrustedDocumentGraphql: () => replaceGqlTagWithTrustedDocumentGraphql, - trustedDocumentsStore: () => trustedDocumentsStore -}); -module.exports = __toCommonJS(trustedDocuments_exports); -var import_fs = __toESM(require("fs")); -var import_path = __toESM(require("path")); -var import_prettier = require("prettier"); -var import_project_config = require("@redwoodjs/project-config"); -const trustedDocumentsStore = async (generatedFiles) => { - let trustedDocumentsStoreFile = ""; - const output = generatedFiles.filter( - (f) => f.filename.endsWith("persisted-documents.json") - ); - const storeFile = output[0]; - if (storeFile?.content) { - const content = await (0, import_prettier.format)(`export const store = ${storeFile.content}`, { - trailingComma: "es5", - bracketSpacing: true, - tabWidth: 2, - semi: false, - singleQuote: true, - arrowParens: "always", - parser: "typescript" - }); - trustedDocumentsStoreFile = import_path.default.join( - (0, import_project_config.getPaths)().api.lib, - "trustedDocumentsStore.ts" - ); - import_fs.default.mkdirSync(import_path.default.dirname(trustedDocumentsStoreFile), { recursive: true }); - import_fs.default.writeFileSync(trustedDocumentsStoreFile, content); - } - return trustedDocumentsStoreFile; -}; -const replaceGqlTagWithTrustedDocumentGraphql = async (generatedFiles) => { - const gqlFileOutput = generatedFiles.filter( - (f) => f.filename.endsWith("gql.ts") - ); - const gqlFile = gqlFileOutput[0]; - if (gqlFile?.content) { - gqlFile.content += ` - - export function gql(source: string | TemplateStringsArray) { - if (typeof source === 'string') { - return graphql(source) - } - - return graphql(source.join('\\n')) - }`; - const content = await (0, import_prettier.format)(gqlFile.content, { - trailingComma: "es5", - bracketSpacing: true, - tabWidth: 2, - semi: true, - singleQuote: false, - arrowParens: "always", - parser: "typescript" - }); - import_fs.default.writeFileSync(gqlFile.filename, content); - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - replaceGqlTagWithTrustedDocumentGraphql, - trustedDocumentsStore -}); diff --git a/packages/internal/dist/generate/typeDefinitions.d.ts b/packages/internal/dist/generate/typeDefinitions.d.ts deleted file mode 100644 index 59ce425b20da..000000000000 --- a/packages/internal/dist/generate/typeDefinitions.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Generate all the types for a RedwoodJS project - * and return the generated path to files, so they're logged - */ -export declare const generateTypeDefs: () => Promise<{ - typeDefFiles: string[]; - errors: { - message: string; - error: unknown; - }[]; -}>; -export declare const generateMirrorDirectoryNamedModules: () => string[]; -export declare const mirrorPathForDirectoryNamedModules: (p: string, rwjsPaths?: import("@redwoodjs/project-config").Paths) => string[]; -export declare const generateMirrorDirectoryNamedModule: (p: string, rwjsPaths?: import("@redwoodjs/project-config").Paths) => string; -export declare const generateMirrorCells: () => string[]; -export declare const mirrorPathForCell: (p: string, rwjsPaths?: import("@redwoodjs/project-config").Paths) => string[]; -export declare const generateMirrorCell: (p: string, rwjsPaths?: import("@redwoodjs/project-config").Paths) => string; -export declare const generateTypeDefRouterRoutes: () => string[]; -export declare const generateTypeDefRouterPages: () => string[]; -export declare const generateTypeDefCurrentUser: () => string[]; -export declare const generateTypeDefScenarios: () => string[]; -export declare const generateTypeDefTestMocks: () => string[]; -export declare const generateTypeDefGlobImports: () => string[]; -export declare const generateTypeDefGlobalContext: () => string[]; -/** - * Typescript does not preserve triple slash directives when outputting js or d.ts files. - * This is a work around so that *.svg, *.png, etc. imports have types. - */ -export declare const generateViteClientTypesDirective: () => string[]; -//# sourceMappingURL=typeDefinitions.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/typeDefinitions.d.ts.map b/packages/internal/dist/generate/typeDefinitions.d.ts.map deleted file mode 100644 index 38e05b5f67d0..000000000000 --- a/packages/internal/dist/generate/typeDefinitions.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"typeDefinitions.d.ts","sourceRoot":"","sources":["../../src/generate/typeDefinitions.ts"],"names":[],"mappings":"AAyCA;;;GAGG;AACH,eAAO,MAAM,gBAAgB;;;;;;EAyB5B,CAAA;AAED,eAAO,MAAM,mCAAmC,gBAK/C,CAAA;AAED,eAAO,MAAM,kCAAkC,MAC1C,MAAM,oEAUV,CAAA;AAED,eAAO,MAAM,kCAAkC,MAC1C,MAAM,kEAqDV,CAAA;AAED,eAAO,MAAM,mBAAmB,gBAG/B,CAAA;AAED,eAAO,MAAM,iBAAiB,MAAO,MAAM,oEAQ1C,CAAA;AAED,eAAO,MAAM,kBAAkB,MAAO,MAAM,kEA8D3C,CAAA;AAiBD,eAAO,MAAM,2BAA2B,gBAmEvC,CAAA;AAED,eAAO,MAAM,0BAA0B,gBA8CtC,CAAA;AAED,eAAO,MAAM,0BAA0B,gBAEtC,CAAA;AAED,eAAO,MAAM,wBAAwB,gBAEpC,CAAA;AAED,eAAO,MAAM,wBAAwB,gBAKpC,CAAA;AAED,eAAO,MAAM,0BAA0B,gBAEtC,CAAA;AAED,eAAO,MAAM,4BAA4B,gBAExC,CAAA;AACD;;;GAGG;AACH,eAAO,MAAM,gCAAgC,gBAW5C,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/generate/typeDefinitions.js b/packages/internal/dist/generate/typeDefinitions.js deleted file mode 100644 index 39291dfe8cc6..000000000000 --- a/packages/internal/dist/generate/typeDefinitions.js +++ /dev/null @@ -1,369 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var typeDefinitions_exports = {}; -__export(typeDefinitions_exports, { - generateMirrorCell: () => generateMirrorCell, - generateMirrorCells: () => generateMirrorCells, - generateMirrorDirectoryNamedModule: () => generateMirrorDirectoryNamedModule, - generateMirrorDirectoryNamedModules: () => generateMirrorDirectoryNamedModules, - generateTypeDefCurrentUser: () => generateTypeDefCurrentUser, - generateTypeDefGlobImports: () => generateTypeDefGlobImports, - generateTypeDefGlobalContext: () => generateTypeDefGlobalContext, - generateTypeDefRouterPages: () => generateTypeDefRouterPages, - generateTypeDefRouterRoutes: () => generateTypeDefRouterRoutes, - generateTypeDefScenarios: () => generateTypeDefScenarios, - generateTypeDefTestMocks: () => generateTypeDefTestMocks, - generateTypeDefs: () => generateTypeDefs, - generateViteClientTypesDirective: () => generateViteClientTypesDirective, - mirrorPathForCell: () => mirrorPathForCell, - mirrorPathForDirectoryNamedModules: () => mirrorPathForDirectoryNamedModules -}); -module.exports = __toCommonJS(typeDefinitions_exports); -var import_fs = __toESM(require("fs")); -var import_path = __toESM(require("path")); -var import_source_map = require("source-map"); -var import_project_config = require("@redwoodjs/project-config"); -var import_ast = require("../ast"); -var import_files = require("../files"); -var import_gql = require("../gql"); -var import_jsx = require("../jsx"); -var import_graphqlCodeGen = require("./graphqlCodeGen"); -var import_templates = require("./templates"); -const generateTypeDefs = async () => { - const { typeDefFiles: gqlApiTypeDefFiles, errors: apiErrors } = await (0, import_graphqlCodeGen.generateTypeDefGraphQLApi)(); - const { typeDefFiles: gqlWebTypeDefFiles, errors: webErrors } = await (0, import_graphqlCodeGen.generateTypeDefGraphQLWeb)(); - return { - typeDefFiles: [ - ...generateMirrorDirectoryNamedModules(), - ...generateMirrorCells(), - ...generateTypeDefRouterPages(), - ...generateTypeDefCurrentUser(), - ...generateTypeDefRouterRoutes(), - ...generateTypeDefGlobImports(), - ...generateTypeDefGlobalContext(), - ...generateTypeDefScenarios(), - ...generateTypeDefTestMocks(), - ...generateStubStorybookTypes(), - ...generateViteClientTypesDirective(), - ...gqlApiTypeDefFiles, - ...gqlWebTypeDefFiles - ], - errors: [...apiErrors, ...webErrors] - }; -}; -const generateMirrorDirectoryNamedModules = () => { - const rwjsPaths = (0, import_project_config.getPaths)(); - return (0, import_files.findDirectoryNamedModules)().map( - (p) => generateMirrorDirectoryNamedModule(p, rwjsPaths) - ); -}; -const mirrorPathForDirectoryNamedModules = (p, rwjsPaths = (0, import_project_config.getPaths)()) => { - return [ - import_path.default.join( - rwjsPaths.generated.types.mirror, - import_path.default.relative(rwjsPaths.base, import_path.default.dirname(p)) - ), - "index.d.ts" - ]; -}; -const generateMirrorDirectoryNamedModule = (p, rwjsPaths = (0, import_project_config.getPaths)()) => { - const [mirrorDir, typeDef] = mirrorPathForDirectoryNamedModules(p, rwjsPaths); - import_fs.default.mkdirSync(mirrorDir, { recursive: true }); - const typeDefPath = import_path.default.join(mirrorDir, typeDef); - const { name } = import_path.default.parse(p); - (0, import_templates.writeTemplate)( - "templates/mirror-directoryNamedModule.d.ts.template", - typeDefPath, - { name } - ); - if (p.startsWith(rwjsPaths.web.src)) { - try { - const fileContents = (0, import_ast.fileToAst)(p); - const defaultExportLocation = (0, import_ast.getDefaultExportLocation)(fileContents) ?? { - line: 1, - column: 0 - }; - const map = new import_source_map.SourceMapGenerator({ - file: "index.d.ts" - }); - map.addMapping({ - generated: { - line: 4, - column: 0 - }, - source: import_path.default.relative(import_path.default.dirname(typeDefPath), p), - original: defaultExportLocation - }); - import_fs.default.writeFileSync( - `${typeDefPath}.map`, - JSON.stringify(map.toJSON(), void 0, 2) - ); - } catch (error) { - console.error( - "Couldn't generate a definition map for directory named module at path:", - p - ); - console.error(error); - } - } - return typeDefPath; -}; -const generateMirrorCells = () => { - const rwjsPaths = (0, import_project_config.getPaths)(); - return (0, import_files.findCells)().map((p) => generateMirrorCell(p, rwjsPaths)); -}; -const mirrorPathForCell = (p, rwjsPaths = (0, import_project_config.getPaths)()) => { - const mirrorDir = import_path.default.join( - rwjsPaths.generated.types.mirror, - import_path.default.relative(rwjsPaths.base, import_path.default.dirname(p)) - ); - import_fs.default.mkdirSync(mirrorDir, { recursive: true }); - return [mirrorDir, "index.d.ts"]; -}; -const generateMirrorCell = (p, rwjsPaths = (0, import_project_config.getPaths)()) => { - const [mirrorDir, typeDef] = mirrorPathForCell(p, rwjsPaths); - import_fs.default.mkdirSync(mirrorDir, { recursive: true }); - const typeDefPath = import_path.default.join(mirrorDir, typeDef); - const { name } = import_path.default.parse(p); - const fileContents = (0, import_ast.fileToAst)(p); - const cellQuery = (0, import_ast.getCellGqlQuery)(fileContents); - if (cellQuery) { - const gqlDoc = (0, import_gql.parseGqlQueryToAst)(cellQuery)[0]; - (0, import_templates.writeTemplate)("templates/mirror-cell.d.ts.template", typeDefPath, { - name, - queryResultType: `${gqlDoc?.name}`, - queryVariablesType: `${gqlDoc?.name}Variables` - }); - } else { - (0, import_templates.writeTemplate)("templates/mirror-cell.d.ts.template", typeDefPath, { - name, - queryResultType: "any", - queryVariablesType: "any" - }); - } - try { - const exportedComponents = (0, import_ast.getNamedExports)(fileContents); - const successComponent = exportedComponents.find( - (x) => x.name === "Success" - ); - if (successComponent === void 0) { - throw new Error("No Success component found"); - } - const map = new import_source_map.SourceMapGenerator({ - file: "index.d.ts" - }); - map.addMapping({ - generated: { - line: 12, - column: 0 - }, - source: import_path.default.relative(import_path.default.dirname(typeDefPath), p), - original: successComponent.location - }); - import_fs.default.writeFileSync( - `${typeDefPath}.map`, - JSON.stringify(map.toJSON(), void 0, 2) - ); - } catch (error) { - console.error("Couldn't generate a definition map for cell at path:", p); - console.error(error); - } - return typeDefPath; -}; -const writeTypeDefIncludeFile = (template, values = {}) => { - const rwjsPaths = (0, import_project_config.getPaths)(); - const typeDefPath = import_path.default.join( - rwjsPaths.generated.types.includes, - template.replace(".template", "") - ); - const templateFilename = import_path.default.join("templates", template); - (0, import_templates.writeTemplate)(templateFilename, typeDefPath, values); - return [typeDefPath]; -}; -const generateTypeDefRouterRoutes = () => { - const ast = (0, import_ast.fileToAst)((0, import_project_config.getPaths)().web.routes); - let hasRootRoute = false; - const routes = (0, import_jsx.getJsxElements)(ast, "Route").filter((x) => { - const isValidRoute = typeof x.props?.path !== "undefined" && typeof x.props?.name !== "undefined"; - if (isValidRoute && x.props.path === "/") { - hasRootRoute = true; - } - return isValidRoute; - }); - try { - const typeDefPath = import_path.default.join( - (0, import_project_config.getPaths)().generated.types.includes, - "web-routerRoutes.d.ts" - ); - const map = new import_source_map.SourceMapGenerator({ - file: "web-routerRoutes.d.ts" - }); - const startLine = 7; - for (let i = 0; i < routes.length; i++) { - map.addMapping({ - generated: { - line: startLine + i, - column: 4 - }, - source: import_path.default.relative(import_path.default.dirname(typeDefPath), (0, import_project_config.getPaths)().web.routes), - original: routes[i].location - }); - } - import_fs.default.writeFileSync( - `${typeDefPath}.map`, - JSON.stringify(map.toJSON(), void 0, 2) - ); - } catch (error) { - console.error( - "Couldn't generate a definition map for web-routerRoutes.d.ts:" - ); - console.error(error); - } - if (!hasRootRoute) { - routes.push({ - name: "splashPage route", - location: { line: -1, column: -1 }, - props: { - path: "/", - name: "home" - } - }); - } - return writeTypeDefIncludeFile("web-routerRoutes.d.ts.template", { routes }); -}; -const generateTypeDefRouterPages = () => { - const pages = (0, import_project_config.processPagesDir)(); - try { - const typeDefPath = import_path.default.join( - (0, import_project_config.getPaths)().generated.types.includes, - "web-routesPages.d.ts" - ); - const map = new import_source_map.SourceMapGenerator({ - file: "web-routesPages.d.ts" - }); - const startLine = pages.length + 5; - for (let i = 0; i < pages.length; i++) { - const fileContents = (0, import_ast.fileToAst)(pages[i].path); - const defaultExportLocation = (0, import_ast.getDefaultExportLocation)(fileContents) ?? { - line: 1, - column: 0 - }; - map.addMapping({ - generated: { - line: startLine + i, - column: 0 - }, - source: import_path.default.relative(import_path.default.dirname(typeDefPath), pages[i].path), - original: defaultExportLocation - }); - } - import_fs.default.writeFileSync( - `${typeDefPath}.map`, - JSON.stringify(map.toJSON(), void 0, 2) - ); - } catch (error) { - console.error( - "Couldn't generate a definition map for web-routesPages.d.ts:" - ); - console.error(error); - } - return writeTypeDefIncludeFile("web-routesPages.d.ts.template", { pages }); -}; -const generateTypeDefCurrentUser = () => { - return writeTypeDefIncludeFile("all-currentUser.d.ts.template"); -}; -const generateTypeDefScenarios = () => { - return writeTypeDefIncludeFile("api-scenarios.d.ts.template"); -}; -const generateTypeDefTestMocks = () => { - return [ - writeTypeDefIncludeFile("api-test-globals.d.ts.template"), - writeTypeDefIncludeFile("web-test-globals.d.ts.template") - ].flat(); -}; -const generateTypeDefGlobImports = () => { - return writeTypeDefIncludeFile("api-globImports.d.ts.template"); -}; -const generateTypeDefGlobalContext = () => { - return writeTypeDefIncludeFile("api-globalContext.d.ts.template"); -}; -const generateViteClientTypesDirective = () => { - const viteClientDirective = `/// `; - const redwoodProjectPaths = (0, import_project_config.getPaths)(); - const viteClientDirectivePath = import_path.default.join( - redwoodProjectPaths.generated.types.includes, - "web-vite-client.d.ts" - ); - import_fs.default.writeFileSync(viteClientDirectivePath, viteClientDirective); - return [viteClientDirectivePath]; -}; -function generateStubStorybookTypes() { - const stubStorybookTypesFileContent = `declare module '@storybook/react' { - export type Meta = any - export type StoryObj = any -} -`; - const redwoodProjectPaths = (0, import_project_config.getPaths)(); - const packageJson = JSON.parse( - import_fs.default.readFileSync( - import_path.default.join(redwoodProjectPaths.base, "package.json"), - "utf-8" - ) - ); - const hasCliStorybookVite = Object.keys( - packageJson["devDependencies"] - ).includes("@redwoodjs/cli-storybook-vite"); - if (hasCliStorybookVite) { - return []; - } - const stubStorybookTypesFilePath = import_path.default.join( - redwoodProjectPaths.generated.types.includes, - "web-storybook.d.ts" - ); - import_fs.default.writeFileSync(stubStorybookTypesFilePath, stubStorybookTypesFileContent); - return [stubStorybookTypesFilePath]; -} -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - generateMirrorCell, - generateMirrorCells, - generateMirrorDirectoryNamedModule, - generateMirrorDirectoryNamedModules, - generateTypeDefCurrentUser, - generateTypeDefGlobImports, - generateTypeDefGlobalContext, - generateTypeDefRouterPages, - generateTypeDefRouterRoutes, - generateTypeDefScenarios, - generateTypeDefTestMocks, - generateTypeDefs, - generateViteClientTypesDirective, - mirrorPathForCell, - mirrorPathForDirectoryNamedModules -}); diff --git a/packages/internal/dist/generate/types.d.ts b/packages/internal/dist/generate/types.d.ts deleted file mode 100644 index 1399078f83bc..000000000000 --- a/packages/internal/dist/generate/types.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -export interface GeneratedFile { - filename: string; - content: string; - hooks: string; -} -//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/types.d.ts.map b/packages/internal/dist/generate/types.d.ts.map deleted file mode 100644 index 05de179f3f58..000000000000 --- a/packages/internal/dist/generate/types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/generate/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,aAAa;IAC5B,QAAQ,EAAE,MAAM,CAAA;IAChB,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,MAAM,CAAA;CACd"} \ No newline at end of file diff --git a/packages/internal/dist/generate/types.js b/packages/internal/dist/generate/types.js deleted file mode 100644 index 43ae53610554..000000000000 --- a/packages/internal/dist/generate/types.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var types_exports = {}; -module.exports = __toCommonJS(types_exports); diff --git a/packages/internal/dist/generate/watch.d.ts b/packages/internal/dist/generate/watch.d.ts deleted file mode 100644 index 7137bb385e77..000000000000 --- a/packages/internal/dist/generate/watch.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env node -export {}; -//# sourceMappingURL=watch.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/generate/watch.d.ts.map b/packages/internal/dist/generate/watch.d.ts.map deleted file mode 100644 index c47f7e57e158..000000000000 --- a/packages/internal/dist/generate/watch.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"watch.d.ts","sourceRoot":"","sources":["../../src/generate/watch.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/packages/internal/dist/generate/watch.js b/packages/internal/dist/generate/watch.js deleted file mode 100755 index 9866ad4cfae3..000000000000 --- a/packages/internal/dist/generate/watch.js +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env node -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var import_fs = __toESM(require("fs")); -var import_path = __toESM(require("path")); -var import_chalk = __toESM(require("chalk")); -var import_chokidar = __toESM(require("chokidar")); -var import_project_config = require("@redwoodjs/project-config"); -var import_cliLogger = require("../cliLogger"); -var import_files = require("../files"); -var import_routes = require("../routes"); -var import_clientPreset = require("./clientPreset"); -var import_generate = require("./generate"); -var import_graphqlCodeGen = require("./graphqlCodeGen"); -var import_graphqlSchema = require("./graphqlSchema"); -var import_typeDefinitions = require("./typeDefinitions"); -const rwjsPaths = (0, import_project_config.getPaths)(); -const watcher = import_chokidar.default.watch("(web|api)/src/**/*.{ts,js,jsx,tsx}", { - persistent: true, - ignored: ["node_modules", ".redwood"], - ignoreInitial: true, - cwd: rwjsPaths.base, - awaitWriteFinish: true -}); -const action = { - add: "Created", - unlink: "Deleted", - change: "Modified" -}; -let routesWarningMessage = ""; -process.stdin.on("data", async (data) => { - const str = data.toString().trim().toLowerCase(); - if (str === "g" || str === "rs") { - (0, import_cliLogger.cliLogger)("Re-creating TypeScript definitions and GraphQL schemas"); - await (0, import_generate.generate)(); - } -}); -watcher.on("ready", async () => { - const start = Date.now(); - (0, import_cliLogger.cliLogger)("Generating full TypeScript definitions and GraphQL schemas"); - const { files, errors } = await (0, import_generate.generate)(); - (0, import_cliLogger.cliLogger)(`Done.`); - import_cliLogger.cliLogger.debug(` -Created ${files.length} in ${Date.now() - start} ms`); - if (errors.length > 0) { - for (const { message, error } of errors) { - console.error(message); - console.error(error); - console.log(); - } - } - routesWarningMessage = (0, import_routes.warningForDuplicateRoutes)(); - if (routesWarningMessage) { - console.warn(routesWarningMessage); - } -}).on("all", async (eventName, p) => { - import_cliLogger.cliLogger.trace( - `File system change: ${import_chalk.default.magenta(eventName)} ${import_chalk.default.dim(p)}` - ); - if (!["add", "change", "unlink"].includes(eventName)) { - return; - } - const eventTigger = eventName; - const absPath = import_path.default.join(rwjsPaths.base, p); - const start = Date.now(); - const finished = (type) => import_cliLogger.cliLogger.debug( - action[eventTigger], - type + ":", - import_chalk.default.dim(p), - import_chalk.default.dim.italic(Date.now() - start + " ms") - ); - if (absPath.includes("Cell") && (0, import_files.isCellFile)(absPath)) { - await (0, import_graphqlCodeGen.generateTypeDefGraphQLWeb)(); - await (0, import_clientPreset.generateClientPreset)(); - if (eventName === "unlink") { - import_fs.default.unlinkSync((0, import_typeDefinitions.mirrorPathForCell)(absPath, rwjsPaths)[0]); - } else { - (0, import_typeDefinitions.generateMirrorCell)(absPath, rwjsPaths); - } - finished("Cell"); - } else if (absPath === rwjsPaths.web.routes) { - (0, import_typeDefinitions.generateTypeDefRouterRoutes)(); - routesWarningMessage = (0, import_routes.warningForDuplicateRoutes)(); - finished("Routes"); - } else if (absPath.includes("Page") && (0, import_files.isPageFile)(absPath)) { - (0, import_typeDefinitions.generateTypeDefRouterPages)(); - finished("Page"); - } else if ((0, import_files.isDirectoryNamedModuleFile)(absPath)) { - if (eventName === "unlink") { - import_fs.default.unlinkSync((0, import_typeDefinitions.mirrorPathForDirectoryNamedModules)(absPath, rwjsPaths)[0]); - } else { - (0, import_typeDefinitions.generateMirrorDirectoryNamedModule)(absPath, rwjsPaths); - } - finished("Directory named module"); - } else if ((0, import_files.isGraphQLSchemaFile)(absPath)) { - await (0, import_graphqlSchema.generateGraphQLSchema)(); - await (0, import_graphqlCodeGen.generateTypeDefGraphQLApi)(); - finished("GraphQL Schema"); - } - if (routesWarningMessage) { - console.warn(routesWarningMessage); - } -}); diff --git a/packages/internal/dist/gql.d.ts b/packages/internal/dist/gql.d.ts deleted file mode 100644 index a65a4c669b68..000000000000 --- a/packages/internal/dist/gql.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { DocumentNode, OperationTypeNode } from 'graphql'; -interface Operation { - operation: OperationTypeNode; - name: string | undefined; - fields: (string | Field)[]; -} -interface Field { - string: (string | Field)[]; -} -export declare const parseGqlQueryToAst: (gqlQuery: string) => Operation[]; -export declare const parseDocumentAST: (document: DocumentNode) => Operation[]; -export declare const listQueryTypeFieldsInProject: () => Promise; -export {}; -//# sourceMappingURL=gql.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/gql.d.ts.map b/packages/internal/dist/gql.d.ts.map deleted file mode 100644 index 0d953fde9c40..000000000000 --- a/packages/internal/dist/gql.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"gql.d.ts","sourceRoot":"","sources":["../src/gql.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,YAAY,EAIZ,iBAAiB,EAClB,MAAM,SAAS,CAAA;AAMhB,UAAU,SAAS;IACjB,SAAS,EAAE,iBAAiB,CAAA;IAC5B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAA;IACxB,MAAM,EAAE,CAAC,MAAM,GAAG,KAAK,CAAC,EAAE,CAAA;CAC3B;AAED,UAAU,KAAK;IACb,MAAM,EAAE,CAAC,MAAM,GAAG,KAAK,CAAC,EAAE,CAAA;CAC3B;AAED,eAAO,MAAM,kBAAkB,aAAc,MAAM,gBAGlD,CAAA;AAED,eAAO,MAAM,gBAAgB,aAAc,YAAY,gBAoBtD,CAAA;AAgCD,eAAO,MAAM,4BAA4B,yBA8BxC,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/gql.js b/packages/internal/dist/gql.js deleted file mode 100644 index f1434b84874c..000000000000 --- a/packages/internal/dist/gql.js +++ /dev/null @@ -1,108 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var gql_exports = {}; -__export(gql_exports, { - listQueryTypeFieldsInProject: () => listQueryTypeFieldsInProject, - parseDocumentAST: () => parseDocumentAST, - parseGqlQueryToAst: () => parseGqlQueryToAst -}); -module.exports = __toCommonJS(gql_exports); -var import_code_file_loader = require("@graphql-tools/code-file-loader"); -var import_load = require("@graphql-tools/load"); -var import_graphql = require("graphql"); -var import_graphql_server = require("@redwoodjs/graphql-server"); -var import_project_config = require("@redwoodjs/project-config"); -const parseGqlQueryToAst = (gqlQuery) => { - const ast = (0, import_graphql.parse)(gqlQuery); - return parseDocumentAST(ast); -}; -const parseDocumentAST = (document) => { - const operations = []; - (0, import_graphql.visit)(document, { - OperationDefinition(node) { - const fields = []; - node.selectionSet.selections.forEach((field) => { - fields.push(getFields(field)); - }); - operations.push({ - operation: node.operation, - name: node.name?.value, - fields - }); - } - }); - return operations; -}; -const getFields = (field) => { - if (!field.selectionSet) { - return field.name.value; - } else { - const obj = { - [field.name.value]: [] - }; - const lookAtFieldNode = (node) => { - node.selectionSet?.selections.forEach((subField) => { - switch (subField.kind) { - case import_graphql.Kind.FIELD: - obj[field.name.value].push(getFields(subField)); - break; - case import_graphql.Kind.FRAGMENT_SPREAD: - break; - case import_graphql.Kind.INLINE_FRAGMENT: - lookAtFieldNode(subField); - } - }); - }; - lookAtFieldNode(field); - return obj; - } -}; -const listQueryTypeFieldsInProject = async () => { - try { - const schemaPointerMap = { - [(0, import_graphql.print)(import_graphql_server.rootSchema.schema)]: {}, - "graphql/**/*.sdl.{js,ts}": {}, - "directives/**/*.{js,ts}": {}, - "subscriptions/**/*.{js,ts}": {} - }; - const mergedSchema = await (0, import_load.loadSchema)(schemaPointerMap, { - loaders: [ - new import_code_file_loader.CodeFileLoader({ - noRequire: true, - pluckConfig: { - globalGqlIdentifierName: "gql" - } - }) - ], - cwd: (0, import_project_config.getPaths)().api.src, - assumeValidSDL: true - }); - const queryTypeFields = mergedSchema.getQueryType()?.getFields(); - return Object.keys(queryTypeFields ?? {}); - } catch (e) { - console.error(e); - return []; - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - listQueryTypeFieldsInProject, - parseDocumentAST, - parseGqlQueryToAst -}); diff --git a/packages/internal/dist/index.d.ts b/packages/internal/dist/index.d.ts deleted file mode 100644 index dd0c86c08f03..000000000000 --- a/packages/internal/dist/index.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -export * from '@redwoodjs/project-config'; -export * from './ts2js'; -export * from './dev'; -export * from './routes'; -export * from './files'; -export { generate } from './generate/generate'; -export { buildApi } from './build/api'; -export * from './validateSchema'; -export * from '@redwoodjs/babel-config'; -export { listQueryTypeFieldsInProject } from './gql'; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/index.d.ts.map b/packages/internal/dist/index.d.ts.map deleted file mode 100644 index 3b25161fd1e9..000000000000 --- a/packages/internal/dist/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,2BAA2B,CAAA;AAEzC,cAAc,SAAS,CAAA;AACvB,cAAc,OAAO,CAAA;AACrB,cAAc,UAAU,CAAA;AAExB,cAAc,SAAS,CAAA;AACvB,OAAO,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAC9C,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAA;AAEtC,cAAc,kBAAkB,CAAA;AAGhC,cAAc,yBAAyB,CAAA;AAEvC,OAAO,EAAE,4BAA4B,EAAE,MAAM,OAAO,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/index.js b/packages/internal/dist/index.js deleted file mode 100644 index 88cc38e106b0..000000000000 --- a/packages/internal/dist/index.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var src_exports = {}; -__export(src_exports, { - buildApi: () => import_api.buildApi, - generate: () => import_generate.generate, - listQueryTypeFieldsInProject: () => import_gql.listQueryTypeFieldsInProject -}); -module.exports = __toCommonJS(src_exports); -__reExport(src_exports, require("@redwoodjs/project-config"), module.exports); -__reExport(src_exports, require("./ts2js"), module.exports); -__reExport(src_exports, require("./dev"), module.exports); -__reExport(src_exports, require("./routes"), module.exports); -__reExport(src_exports, require("./files"), module.exports); -var import_generate = require("./generate/generate"); -var import_api = require("./build/api"); -__reExport(src_exports, require("./validateSchema"), module.exports); -__reExport(src_exports, require("@redwoodjs/babel-config"), module.exports); -var import_gql = require("./gql"); -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - buildApi, - generate, - listQueryTypeFieldsInProject, - ...require("@redwoodjs/project-config"), - ...require("./ts2js"), - ...require("./dev"), - ...require("./routes"), - ...require("./files"), - ...require("./validateSchema"), - ...require("@redwoodjs/babel-config") -}); diff --git a/packages/internal/dist/jsx.d.ts b/packages/internal/dist/jsx.d.ts deleted file mode 100644 index 2381f2ff146e..000000000000 --- a/packages/internal/dist/jsx.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { types } from '@babel/core'; -interface JsxElement { - name: string; - props: Record; - children?: JsxElement[]; - location: { - line: number; - column: number; - }; -} -/** - * Extract JSX elements, children and props from static code. - */ -export declare const getJsxElements: (ast: types.Node, name: string) => JsxElement[]; -export {}; -//# sourceMappingURL=jsx.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/jsx.d.ts.map b/packages/internal/dist/jsx.d.ts.map deleted file mode 100644 index 097c46e23aba..000000000000 --- a/packages/internal/dist/jsx.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"jsx.d.ts","sourceRoot":"","sources":["../src/jsx.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAA;AAKxC,UAAU,UAAU;IAClB,IAAI,EAAE,MAAM,CAAA;IACZ,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC1B,QAAQ,CAAC,EAAE,UAAU,EAAE,CAAA;IACvB,QAAQ,EAAE;QACR,IAAI,EAAE,MAAM,CAAA;QACZ,MAAM,EAAE,MAAM,CAAA;KACf,CAAA;CACF;AACD;;GAEG;AACH,eAAO,MAAM,cAAc,QAAS,KAAK,CAAC,IAAI,QAAQ,MAAM,iBAgB3D,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/jsx.js b/packages/internal/dist/jsx.js deleted file mode 100644 index 328c3c20eeeb..000000000000 --- a/packages/internal/dist/jsx.js +++ /dev/null @@ -1,100 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var jsx_exports = {}; -__export(jsx_exports, { - getJsxElements: () => getJsxElements -}); -module.exports = __toCommonJS(jsx_exports); -var import_traverse = __toESM(require("@babel/traverse")); -var import_jsxAttributeValue = require("./jsxAttributeValue"); -const getJsxElements = (ast, name) => { - let elements = []; - (0, import_traverse.default)(ast, { - JSXIdentifier(path) { - if (path.node.name === name && path.parentPath.type === "JSXOpeningElement") { - if (path?.parentPath?.parentPath?.type === "JSXElement") { - const element = reduceJsxElement([], path.parentPath.parentPath.node); - elements = elements.concat(element); - } - } - } - }); - return elements; -}; -const getJsxAttributes = (jsxElement) => { - return jsxElement.openingElement.attributes.filter( - ({ type }) => type === "JSXAttribute" - ); -}; -const getJsxProps = (jsxElement) => { - const attributes = getJsxAttributes(jsxElement); - const props = {}; - for (const a of attributes) { - if (typeof a.name.name === "string") { - props[a.name.name] = (0, import_jsxAttributeValue.getJsxAttributeValue)(a.value); - } - } - return props; -}; -const reduceJsxElement = (oldNode, currentNode) => { - let element = { - name: "", - props: {}, - children: [], - location: { - line: 1, - column: 0 - } - }; - if (currentNode.type === "JSXElement") { - const props = getJsxProps(currentNode); - if (currentNode.openingElement.name.type === "JSXIdentifier") { - element = { - name: currentNode.openingElement.name.name, - props, - children: [], - location: { - line: currentNode.openingElement.loc?.start.line ?? 1, - column: currentNode.openingElement.loc?.start.column ?? 0 - } - }; - oldNode.push(element); - } - } - if ("children" in currentNode) { - currentNode.children.forEach( - (node) => oldNode.length > 0 ? reduceJsxElement(element.children, node) : reduceJsxElement(oldNode, node) - ); - } - return oldNode; -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - getJsxElements -}); diff --git a/packages/internal/dist/jsxAttributeValue.d.ts b/packages/internal/dist/jsxAttributeValue.d.ts deleted file mode 100644 index 915ee794738c..000000000000 --- a/packages/internal/dist/jsxAttributeValue.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export declare const getJsxAttributeValue: (expression: any) => any; -//# sourceMappingURL=jsxAttributeValue.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/jsxAttributeValue.d.ts.map b/packages/internal/dist/jsxAttributeValue.d.ts.map deleted file mode 100644 index 7df800d13bbe..000000000000 --- a/packages/internal/dist/jsxAttributeValue.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"jsxAttributeValue.d.ts","sourceRoot":"","sources":["../src/jsxAttributeValue.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,oBAAoB,eAAgB,GAAG,KAAG,GAsLtD,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/jsxAttributeValue.js b/packages/internal/dist/jsxAttributeValue.js deleted file mode 100644 index 32954aac6c4f..000000000000 --- a/packages/internal/dist/jsxAttributeValue.js +++ /dev/null @@ -1,129 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var jsxAttributeValue_exports = {}; -__export(jsxAttributeValue_exports, { - getJsxAttributeValue: () => getJsxAttributeValue -}); -module.exports = __toCommonJS(jsxAttributeValue_exports); -const getJsxAttributeValue = (expression) => { - if (expression === null) { - return true; - } - if (expression.type === "StringLiteral") { - return expression.value; - } - if (expression.type === "JSXExpressionContainer") { - return getJsxAttributeValue(expression.expression); - } - if (expression.type === "ArrayExpression") { - return expression.elements.map((element) => getJsxAttributeValue(element)); - } - if (expression.type === "TemplateLiteral") { - const expressions = expression.expressions.map((element) => ({ - ...element, - value: { - raw: element.value, - cooked: getJsxAttributeValue(element) - } - })); - return expressions.concat(expression.quasis).sort((elementA, elementB) => elementA.start - elementB.start).reduce( - (string, element) => `${string}${element.value.cooked.toString()}`, - "" - ); - } - if (expression.type === "ObjectExpression") { - const entries = expression.properties.map((property) => { - const key = getJsxAttributeValue(property.key); - const value = getJsxAttributeValue(property.value); - if (key === void 0 || value === void 0) { - return null; - } - return { key, value }; - }).filter((property) => property).reduce((properties, property) => { - return { ...properties, [property.key]: property.value }; - }, {}); - return entries; - } - if (expression.type === "Identifier") { - return expression.name; - } - if (expression.type === "BinaryExpression") { - switch (expression.operator) { - case "+": - return getJsxAttributeValue(expression.left) + getJsxAttributeValue(expression.right); - case "-": - return getJsxAttributeValue(expression.left) - getJsxAttributeValue(expression.right); - case "*": - return getJsxAttributeValue(expression.left) * getJsxAttributeValue(expression.right); - case "**": - return getJsxAttributeValue(expression.left) ** getJsxAttributeValue(expression.right); - case "/": - return getJsxAttributeValue(expression.left) / getJsxAttributeValue(expression.right); - case "%": - return getJsxAttributeValue(expression.left) % getJsxAttributeValue(expression.right); - case "==": - return getJsxAttributeValue(expression.left) == getJsxAttributeValue(expression.right); - case "===": - return getJsxAttributeValue(expression.left) === getJsxAttributeValue(expression.right); - case "!=": - return getJsxAttributeValue(expression.left) != getJsxAttributeValue(expression.right); - case "!==": - return getJsxAttributeValue(expression.left) !== getJsxAttributeValue(expression.right); - case "<": - return getJsxAttributeValue(expression.left) < getJsxAttributeValue(expression.right); - case "<=": - return getJsxAttributeValue(expression.left) <= getJsxAttributeValue(expression.right); - case ">": - return getJsxAttributeValue(expression.left) > getJsxAttributeValue(expression.right); - case ">=": - return getJsxAttributeValue(expression.left) >= getJsxAttributeValue(expression.right); - case "<<": - return getJsxAttributeValue(expression.left) << getJsxAttributeValue(expression.right); - case ">>": - return getJsxAttributeValue(expression.left) >> getJsxAttributeValue(expression.right); - case ">>>": - return getJsxAttributeValue(expression.left) >>> getJsxAttributeValue(expression.right); - case "|": - return getJsxAttributeValue(expression.left) | getJsxAttributeValue(expression.right); - case "&": - return getJsxAttributeValue(expression.left) & getJsxAttributeValue(expression.right); - case "^": - return getJsxAttributeValue(expression.left) ^ getJsxAttributeValue(expression.right); - default: - return `BinaryExpression with "${expression.operator}" is not supported`; - } - } - if (expression.type === "UnaryExpression") { - switch (expression.operator) { - case "+": - return +getJsxAttributeValue(expression.argument); - case "-": - return -getJsxAttributeValue(expression.argument); - case "~": - return ~getJsxAttributeValue(expression.argument); - default: - return `UnaryExpression with "${expression.operator}" is not supported`; - } - } - return `${expression.type} is not supported`; -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - getJsxAttributeValue -}); diff --git a/packages/internal/dist/project.d.ts b/packages/internal/dist/project.d.ts deleted file mode 100644 index 9e44608a8cb9..000000000000 --- a/packages/internal/dist/project.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -export declare const getTsConfigs: () => { - api: any; - web: any; -}; -export declare const isTypeScriptProject: () => boolean; -export declare const isServerFileSetup: () => boolean; -export declare const isRealtimeSetup: () => boolean; -//# sourceMappingURL=project.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/project.d.ts.map b/packages/internal/dist/project.d.ts.map deleted file mode 100644 index 2e71db234292..000000000000 --- a/packages/internal/dist/project.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"project.d.ts","sourceRoot":"","sources":["../src/project.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,YAAY;;;CAuBxB,CAAA;AAED,eAAO,MAAM,mBAAmB,eAM/B,CAAA;AAED,eAAO,MAAM,iBAAiB,eAO7B,CAAA;AAED,eAAO,MAAM,eAAe,eAO3B,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/project.js b/packages/internal/dist/project.js deleted file mode 100644 index 577720ca0a7d..000000000000 --- a/packages/internal/dist/project.js +++ /dev/null @@ -1,82 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var project_exports = {}; -__export(project_exports, { - getTsConfigs: () => getTsConfigs, - isRealtimeSetup: () => isRealtimeSetup, - isServerFileSetup: () => isServerFileSetup, - isTypeScriptProject: () => isTypeScriptProject -}); -module.exports = __toCommonJS(project_exports); -var import_fs = __toESM(require("fs")); -var import_path = __toESM(require("path")); -var import_typescript = require("typescript"); -var import_project_config = require("@redwoodjs/project-config"); -const getTsConfigs = () => { - const rwPaths = (0, import_project_config.getPaths)(); - const apiTsConfigPath = import_path.default.join(rwPaths.api.base, "tsconfig.json"); - const webTsConfigPath = import_path.default.join(rwPaths.web.base, "tsconfig.json"); - const apiTsConfig = import_fs.default.existsSync(apiTsConfigPath) ? (0, import_typescript.parseConfigFileTextToJson)( - apiTsConfigPath, - import_fs.default.readFileSync(apiTsConfigPath, "utf-8") - ) : null; - const webTsConfig = import_fs.default.existsSync(webTsConfigPath) ? (0, import_typescript.parseConfigFileTextToJson)( - webTsConfigPath, - import_fs.default.readFileSync(webTsConfigPath, "utf-8") - ) : null; - return { - api: apiTsConfig?.config ?? null, - web: webTsConfig?.config ?? null - }; -}; -const isTypeScriptProject = () => { - const paths = (0, import_project_config.getPaths)(); - return import_fs.default.existsSync(import_path.default.join(paths.web.base, "tsconfig.json")) || import_fs.default.existsSync(import_path.default.join(paths.api.base, "tsconfig.json")); -}; -const isServerFileSetup = () => { - const serverFilePath = import_path.default.join( - (0, import_project_config.getPaths)().api.src, - `server.${isTypeScriptProject() ? "ts" : "js"}` - ); - return import_fs.default.existsSync(serverFilePath); -}; -const isRealtimeSetup = () => { - const realtimePath = import_path.default.join( - (0, import_project_config.getPaths)().api.lib, - `realtime.${isTypeScriptProject() ? "ts" : "js"}` - ); - return import_fs.default.existsSync(realtimePath); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - getTsConfigs, - isRealtimeSetup, - isServerFileSetup, - isTypeScriptProject -}); diff --git a/packages/internal/dist/routes.d.ts b/packages/internal/dist/routes.d.ts deleted file mode 100644 index f02b1a85beac..000000000000 --- a/packages/internal/dist/routes.d.ts +++ /dev/null @@ -1,42 +0,0 @@ -export interface RouteInformation { - name?: string; - path?: string; - page?: string; -} -/** - * Returns an array of routes which conflict on their defined names - */ -export declare function getDuplicateRoutes(): RouteInformation[]; -/** - * Detects any potential duplicate routes and returns a formatted warning message - * @see {@link getDuplicateRoutes} for how duplicate routes are detected - * @return {string} Warning message when duplicate routes found, empty string if not - */ -export declare function warningForDuplicateRoutes(): string; -export interface RWRouteManifestItem { - name: string; - pathDefinition: string; - matchRegexString: string | null; - routeHooks: string | null; - bundle: string | null; - hasParams: boolean; - relativeFilePath: string; - redirect: { - to: string; - permanent: boolean; - } | null; - isPrivate: boolean; - unauthenticated: string | null; - roles: string | string[] | null; - pageIdentifier: string | null; -} -export interface RouteSpec extends RWRouteManifestItem { - id: string; - isNotFound: boolean; - filePath: string | undefined; - isPrivate: boolean; - unauthenticated: string | null; - relativeFilePath: string; -} -export declare const getProjectRoutes: () => RouteSpec[]; -//# sourceMappingURL=routes.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/routes.d.ts.map b/packages/internal/dist/routes.d.ts.map deleted file mode 100644 index 9b1f96b51473..000000000000 --- a/packages/internal/dist/routes.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AASA,MAAM,WAAW,gBAAgB;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;CACd;AAED;;GAEG;AACH,wBAAgB,kBAAkB,uBAyBjC;AAED;;;;GAIG;AACH,wBAAgB,yBAAyB,WAcxC;AAED,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,MAAM,CAAA;IACZ,cAAc,EAAE,MAAM,CAAA;IACtB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAA;IAC/B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IACrB,SAAS,EAAE,OAAO,CAAA;IAClB,gBAAgB,EAAE,MAAM,CAAA;IACxB,QAAQ,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,OAAO,CAAA;KAAE,GAAG,IAAI,CAAA;IACnD,SAAS,EAAE,OAAO,CAAA;IAClB,eAAe,EAAE,MAAM,GAAG,IAAI,CAAA;IAC9B,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,IAAI,CAAA;IAC/B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAA;CAE9B;AAED,MAAM,WAAW,SAAU,SAAQ,mBAAmB;IACpD,EAAE,EAAE,MAAM,CAAA;IACV,UAAU,EAAE,OAAO,CAAA;IACnB,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAA;IAC5B,SAAS,EAAE,OAAO,CAAA;IAClB,eAAe,EAAE,MAAM,GAAG,IAAI,CAAA;IAC9B,gBAAgB,EAAE,MAAM,CAAA;CACzB;AAED,eAAO,MAAM,gBAAgB,QAAO,SAAS,EAkC5C,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/routes.js b/packages/internal/dist/routes.js deleted file mode 100644 index 7308e33914c3..000000000000 --- a/packages/internal/dist/routes.js +++ /dev/null @@ -1,111 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var routes_exports = {}; -__export(routes_exports, { - getDuplicateRoutes: () => getDuplicateRoutes, - getProjectRoutes: () => getProjectRoutes, - warningForDuplicateRoutes: () => warningForDuplicateRoutes -}); -module.exports = __toCommonJS(routes_exports); -var import_path = __toESM(require("path")); -var import_chalk = __toESM(require("chalk")); -var import_project_config = require("@redwoodjs/project-config"); -var import_router = require("@redwoodjs/router"); -var import_dist = require("@redwoodjs/structure/dist/index.js"); -function getDuplicateRoutes() { - const duplicateRoutes = []; - const allRoutes = (0, import_dist.getProject)((0, import_project_config.getPaths)().base).router.routes; - const uniqueNames = new Set( - allRoutes.filter((route) => route.name !== void 0).map((route) => route.name) - ); - uniqueNames.forEach((name) => { - const routesWithName = allRoutes.filter((route) => { - return route.name === name; - }); - if (routesWithName.length > 1) { - duplicateRoutes.push( - ...routesWithName.map((route) => { - return { - name: route.name, - page: route.page_identifier_str, - path: route.path - }; - }) - ); - } - }); - return duplicateRoutes; -} -function warningForDuplicateRoutes() { - const duplicatedRoutes = getDuplicateRoutes(); - let message = ""; - if (duplicatedRoutes.length > 0) { - message += import_chalk.default.keyword("orange")( - `Warning: ${duplicatedRoutes.length} duplicate routes have been detected, only the route(s) closest to the top of the file will be used. -` - ); - duplicatedRoutes.forEach((route) => { - message += ` ${import_chalk.default.keyword("orange")("->")} Name: "${route.name}", Path: "${route.path}", Page: "${route.page}" -`; - }); - } - return message.trimEnd(); -} -const getProjectRoutes = () => { - const rwProject = (0, import_dist.getProject)((0, import_project_config.getPaths)().base); - const routes = rwProject.getRouter().routes; - return routes.map((route) => { - const { matchRegexString, routeParams } = route.isNotFound ? { matchRegexString: null, routeParams: null } : (0, import_router.getRouteRegexAndParams)(route.path); - return { - name: route.isNotFound ? "NotFoundPage" : route.name, - pathDefinition: route.isNotFound ? "notfound" : route.path, - hasParams: route.hasParameters, - id: route.id, - isNotFound: route.isNotFound, - filePath: route.page?.filePath, - relativeFilePath: route.page?.filePath ? import_path.default.relative((0, import_project_config.getPaths)().web.src, route.page?.filePath) : void 0, - routeHooks: (0, import_project_config.getRouteHookForPage)(route.page?.filePath), - renderMode: route.renderMode, - matchRegexString, - paramNames: routeParams, - // TODO (STREAMING) deal with permanent/temp later - redirect: route.redirect ? { to: route.redirect, permanent: false } : null, - isPrivate: route.isPrivate, - unauthenticated: route.unauthenticated, - roles: route.roles, - pageIdentifier: route.page_identifier_str - }; - }); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - getDuplicateRoutes, - getProjectRoutes, - warningForDuplicateRoutes -}); diff --git a/packages/internal/dist/ts2js.d.ts b/packages/internal/dist/ts2js.d.ts deleted file mode 100644 index f4507a369e24..000000000000 --- a/packages/internal/dist/ts2js.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Converts all the TypeScript files in the `api` and `web` sides to JavaScript. - * - * @param {string} cwd - The base path to the project. - */ -export declare const convertTsProjectToJs: (cwd?: string) => void; -/** - * Converts all the TypeScript files in the `api` and `web` sides to JavaScript. - * - * @param {string} cwd - The base path to the project. - */ -export declare const convertTsScriptsToJs: (cwd?: string) => void; -/** - * Converts TypeScript files to JavaScript. - * - * @param {string} cwd - Current directory - * @param {string[]} files - Collection of files to convert - */ -export declare const convertTsFilesToJs: (cwd: string, files: string[]) => Promise; -/** - * Get all the source code from a Redwood project - */ -export declare const typeScriptSourceFiles: (cwd: string, globPattern?: string) => string[]; -/** - * Read the contents of a TypeScript file, transpile it to JavaScript, - * but leave the JSX intact and format via Prettier. - * - * @param {string} file - The path to the TypeScript file. - */ -export declare const transformTSToJS: (file: string) => Promise | undefined; -export declare const getPrettierConfig: () => Promise; -/** - * Prettify `code` according to the extension in `filename`. - * This will also read a user's `prettier.config.js` file if it exists. - * - * @param {string} code - * @param {string} filename - */ -export declare const prettify: (code: string, filename: string) => Promise; -//# sourceMappingURL=ts2js.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/ts2js.d.ts.map b/packages/internal/dist/ts2js.d.ts.map deleted file mode 100644 index ecd2e79ca64c..000000000000 --- a/packages/internal/dist/ts2js.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ts2js.d.ts","sourceRoot":"","sources":["../src/ts2js.ts"],"names":[],"mappings":"AASA;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,wBAGhC,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,wBAGhC,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,kBAAkB,QAAe,MAAM,SAAS,MAAM,EAAE,kBAkCpE,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,qBAAqB,QAC3B,MAAM,mCAUZ,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,eAAe,SAAU,MAAM,gCAwB3C,CAAA;AAED,eAAO,MAAM,iBAAiB,oBAS7B,CAAA;AAsBD;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ,SAAgB,MAAM,YAAY,MAAM,oBAa5D,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/ts2js.js b/packages/internal/dist/ts2js.js deleted file mode 100644 index 399bb4e1594d..000000000000 --- a/packages/internal/dist/ts2js.js +++ /dev/null @@ -1,159 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var ts2js_exports = {}; -__export(ts2js_exports, { - convertTsFilesToJs: () => convertTsFilesToJs, - convertTsProjectToJs: () => convertTsProjectToJs, - convertTsScriptsToJs: () => convertTsScriptsToJs, - getPrettierConfig: () => getPrettierConfig, - prettify: () => prettify, - transformTSToJS: () => transformTSToJS, - typeScriptSourceFiles: () => typeScriptSourceFiles -}); -module.exports = __toCommonJS(ts2js_exports); -var import_fs = __toESM(require("fs")); -var import_path = __toESM(require("path")); -var import_core = require("@babel/core"); -var import_fast_glob = __toESM(require("fast-glob")); -var import_prettier = require("prettier"); -var import_project_config = require("@redwoodjs/project-config"); -const convertTsProjectToJs = (cwd = (0, import_project_config.getPaths)().base) => { - const files = typeScriptSourceFiles(cwd); - convertTsFilesToJs(cwd, files); -}; -const convertTsScriptsToJs = (cwd = (0, import_project_config.getPaths)().base) => { - const files = typeScriptSourceFiles(cwd, "scripts/*.{ts,tsx}"); - convertTsFilesToJs(cwd, files); -}; -const convertTsFilesToJs = async (cwd, files) => { - if (files.length === 0) { - console.log("No TypeScript files found to convert to JS in this project."); - } - for (const f of files) { - const code = await transformTSToJS(f); - if (code) { - import_fs.default.writeFileSync( - import_path.default.join(cwd, f.replace(".tsx", ".jsx").replace(".ts", ".js")), - code, - "utf8" - ); - import_fs.default.unlinkSync(import_path.default.join(cwd, f)); - } - } - if (import_fs.default.existsSync(import_path.default.join(cwd, "api/tsconfig.json"))) { - import_fs.default.renameSync( - import_path.default.join(cwd, "api/tsconfig.json"), - import_path.default.join(cwd, "api/jsconfig.json") - ); - } - if (import_fs.default.existsSync(import_path.default.join(cwd, "web/tsconfig.json"))) { - import_fs.default.renameSync( - import_path.default.join(cwd, "web/tsconfig.json"), - import_path.default.join(cwd, "web/jsconfig.json") - ); - } - if (import_fs.default.existsSync(import_path.default.join(cwd, "scripts/tsconfig.json"))) { - import_fs.default.renameSync( - import_path.default.join(cwd, "scripts/tsconfig.json"), - import_path.default.join(cwd, "scripts/jsconfig.json") - ); - } -}; -const typeScriptSourceFiles = (cwd, globPattern = "{api,web}/src/**/*.{ts,tsx}") => { - console.log(globPattern); - return import_fast_glob.default.sync(globPattern, { - cwd, - ignore: ["node_modules"] - }); -}; -const transformTSToJS = (file) => { - const tsCode = import_fs.default.readFileSync(file, "utf8"); - const filename = import_path.default.basename(file); - const result = (0, import_core.transform)(tsCode, { - filename, - cwd: (0, import_project_config.getPaths)().base, - configFile: false, - plugins: [ - [ - "@babel/plugin-transform-typescript", - { - isTSX: true, - allExtensions: true - } - ] - ], - retainLines: true - }); - if (!result?.code) { - return void 0; - } - return prettify(result.code, filename.replace(/\.ts$/, ".js")); -}; -const getPrettierConfig = async () => { - try { - const { default: prettierConfig } = await import(`file://${import_path.default.join((0, import_project_config.getPaths)().base, "prettier.config.js")}`); - return prettierConfig; - } catch { - return void 0; - } -}; -const prettierParser = (filename) => { - switch (import_path.default.extname(filename.replace(".template", ""))) { - case ".css": - return "css"; - case ".js": - return "babel"; - case ".ts": - case ".tsx": - return "babel-ts"; - default: - return void 0; - } -}; -const prettify = async (code, filename) => { - const parser = prettierParser(filename); - if (typeof parser === "undefined") { - return code; - } - const prettierConfig = await getPrettierConfig(); - return (0, import_prettier.format)(code, { - ...prettierConfig, - parser - }); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - convertTsFilesToJs, - convertTsProjectToJs, - convertTsScriptsToJs, - getPrettierConfig, - prettify, - transformTSToJS, - typeScriptSourceFiles -}); diff --git a/packages/internal/dist/validateSchema.d.ts b/packages/internal/dist/validateSchema.d.ts deleted file mode 100644 index 4245885c343c..000000000000 --- a/packages/internal/dist/validateSchema.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { DocumentNode } from 'graphql'; -export declare const DIRECTIVE_REQUIRED_ERROR_MESSAGE = "You must specify one of @requireAuth, @skipAuth or a custom directive"; -export declare const DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE = "Please check that the requireAuth roles is a string or an array of strings."; -/** - * These are names that are commonly used in GraphQL schemas as scalars - * and would cause a conflict if used as a type name. - * - * Note: Query, Mutation, and Subscription are not included here because - * they are checked for separately. - */ -export declare const RESERVED_TYPES: string[]; -export declare function validateSchema(schemaDocumentNode: DocumentNode, typesToCheck?: string[]): void; -export declare const loadAndValidateSdls: () => Promise; -//# sourceMappingURL=validateSchema.d.ts.map \ No newline at end of file diff --git a/packages/internal/dist/validateSchema.d.ts.map b/packages/internal/dist/validateSchema.d.ts.map deleted file mode 100644 index 4058f525fbba..000000000000 --- a/packages/internal/dist/validateSchema.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"validateSchema.d.ts","sourceRoot":"","sources":["../src/validateSchema.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAA4B,MAAM,SAAS,CAAA;AAQrE,eAAO,MAAM,gCAAgC,0EAC4B,CAAA;AAEzE,eAAO,MAAM,0CAA0C,gFACwB,CAAA;AAE/E;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,UAS1B,CAAA;AAED,wBAAgB,cAAc,CAC5B,kBAAkB,EAAE,YAAY,EAChC,YAAY,GAAE,MAAM,EAA0B,QAmI/C;AAED,eAAO,MAAM,mBAAmB,qBAkC/B,CAAA"} \ No newline at end of file diff --git a/packages/internal/dist/validateSchema.js b/packages/internal/dist/validateSchema.js deleted file mode 100644 index 3994edaa35bc..000000000000 --- a/packages/internal/dist/validateSchema.js +++ /dev/null @@ -1,193 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var validateSchema_exports = {}; -__export(validateSchema_exports, { - DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE: () => DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE, - DIRECTIVE_REQUIRED_ERROR_MESSAGE: () => DIRECTIVE_REQUIRED_ERROR_MESSAGE, - RESERVED_TYPES: () => RESERVED_TYPES, - loadAndValidateSdls: () => loadAndValidateSdls, - validateSchema: () => validateSchema -}); -module.exports = __toCommonJS(validateSchema_exports); -var import_code_file_loader = require("@graphql-tools/code-file-loader"); -var import_load = require("@graphql-tools/load"); -var import_merge = require("@graphql-tools/merge"); -var import_graphql = require("graphql"); -var import_graphql_server = require("@redwoodjs/graphql-server"); -var import_project_config = require("@redwoodjs/project-config"); -var import_project = require("./project"); -const DIRECTIVE_REQUIRED_ERROR_MESSAGE = "You must specify one of @requireAuth, @skipAuth or a custom directive"; -const DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE = "Please check that the requireAuth roles is a string or an array of strings."; -const RESERVED_TYPES = [ - "Int", - "Float", - "Boolean", - "String", - "DateTime", - "ID", - "uid", - "as" -]; -function validateSchema(schemaDocumentNode, typesToCheck = ["Query", "Mutation"]) { - const validationOutput = []; - const reservedNameValidationOutput = []; - const directiveRoleValidationOutput = []; - if ((0, import_project.isServerFileSetup)() && (0, import_project.isRealtimeSetup)()) { - typesToCheck.push("Subscription"); - } - (0, import_graphql.visit)(schemaDocumentNode, { - InterfaceTypeDefinition(typeNode) { - if (RESERVED_TYPES.includes(typeNode.name.value)) { - reservedNameValidationOutput.push({ - objectType: "interface", - name: typeNode.name.value - }); - } - }, - InputObjectTypeDefinition(typeNode) { - if (RESERVED_TYPES.includes(typeNode.name.value)) { - reservedNameValidationOutput.push({ - objectType: "input type", - name: typeNode.name.value - }); - } - }, - ObjectTypeDefinition(typeNode) { - if (RESERVED_TYPES.includes(typeNode.name.value)) { - reservedNameValidationOutput.push({ - objectType: "type", - name: typeNode.name.value - }); - } - if (typesToCheck.includes(typeNode.name.value)) { - for (const field of typeNode.fields || []) { - const fieldName = field.name.value; - const fieldTypeName = typeNode.name.value; - const isRedwoodQuery = fieldName === "redwood" && fieldTypeName === "Query"; - const isCurrentUserQuery = fieldName === "currentUser" && fieldTypeName === "Query"; - if (!(isRedwoodQuery || isCurrentUserQuery)) { - const hasDirective = field.directives?.length; - if (!hasDirective) { - validationOutput.push(`${fieldName} ${fieldTypeName}`); - } - field.directives?.forEach((directive) => { - if (directive.name.value === "requireAuth") { - directive.arguments?.forEach((arg) => { - if (arg.name.value === "roles") { - if (arg.value.kind !== import_graphql.Kind.STRING && arg.value.kind !== import_graphql.Kind.LIST) { - directiveRoleValidationOutput.push({ - fieldName, - invalid: arg.value.kind - }); - } - if (arg.value.kind === import_graphql.Kind.LIST) { - const invalidValues = arg.value.values?.filter( - (val) => val.kind !== import_graphql.Kind.STRING - ); - if (invalidValues.length > 0) { - invalidValues.forEach((invalid) => { - directiveRoleValidationOutput.push({ - fieldName, - invalid: invalid.kind - }); - }); - } - } - } - }); - } - }); - } - } - } - } - }); - if (validationOutput.length > 0) { - const fieldsWithoutDirectives = validationOutput.map( - (field) => `- ${field}` - ); - throw new Error( - `${DIRECTIVE_REQUIRED_ERROR_MESSAGE} for -${fieldsWithoutDirectives.join( - "\n" - )} -` - ); - } - if (directiveRoleValidationOutput.length > 0) { - const fieldWithInvalidRoleValues = directiveRoleValidationOutput.map( - (field) => `- ${field.fieldName} has an invalid ${field.invalid}` - ); - throw new RangeError( - `${DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE} - -${fieldWithInvalidRoleValues.join( - "\n" - )} - -For example: @requireAuth(roles: "admin") or @requireAuth(roles: ["admin", "editor"])` - ); - } - if (reservedNameValidationOutput.length > 0) { - const reservedNameMsg = reservedNameValidationOutput.map( - (output) => { - return `The ${output.objectType} named '${output.name}' is a reserved GraphQL name. -Please rename it to something more specific, like: Application${output.name}. -`; - } - ); - throw new TypeError(reservedNameMsg.join("\n")); - } -} -const loadAndValidateSdls = async () => { - const projectTypeSrc = await (0, import_load.loadTypedefs)( - [ - "graphql/**/*.sdl.{js,ts}", - "directives/**/*.{js,ts}", - "subscriptions/**/*.{js,ts}" - ], - { - loaders: [ - new import_code_file_loader.CodeFileLoader({ - noRequire: true, - pluckConfig: { - globalGqlIdentifierName: "gql" - } - }) - ], - cwd: (0, import_project_config.getPaths)().api.src - } - ); - const projectDocumentNodes = Object.values(projectTypeSrc).map(({ document }) => document).filter((documentNode) => { - return !!documentNode; - }); - const mergedDocumentNode = (0, import_merge.mergeTypeDefs)([ - import_graphql_server.rootSchema.schema, - projectDocumentNodes - ]); - validateSchema(mergedDocumentNode); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - DIRECTIVE_INVALID_ROLE_TYPES_ERROR_MESSAGE, - DIRECTIVE_REQUIRED_ERROR_MESSAGE, - RESERVED_TYPES, - loadAndValidateSdls, - validateSchema -}); From 2cdf10405fda0bf252e1acbbab81f64daf6387be Mon Sep 17 00:00:00 2001 From: Josh GM Walker <56300765+Josh-Walker-GM@users.noreply.github.com> Date: Sun, 18 Aug 2024 03:05:36 +0100 Subject: [PATCH 8/8] add package.json to exports --- packages/internal/package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/internal/package.json b/packages/internal/package.json index 3282c3d6810c..eaedd313d24a 100644 --- a/packages/internal/package.json +++ b/packages/internal/package.json @@ -13,6 +13,7 @@ "types": "./dist/index.d.ts", "default": "./dist/index.js" }, + "./package.json": "./package.json", "./dist/dev": { "types": "./dist/dev.d.ts", "default": "./dist/dev.js"