diff --git a/.vscode/settings.json b/.vscode/settings.json
index 1471fb96..e9b55746 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -1,3 +1,25 @@
{
- "eslint.validate": ["json"]
+ "eslint.validate": [
+ "json"
+ ],
+ "workbench.colorCustomizations": {
+ "activityBar.activeBackground": "#93e6fc",
+ "activityBar.background": "#93e6fc",
+ "activityBar.foreground": "#15202b",
+ "activityBar.inactiveForeground": "#15202b99",
+ "activityBarBadge.background": "#fa45d4",
+ "activityBarBadge.foreground": "#15202b",
+ "commandCenter.border": "#15202b99",
+ "sash.hoverBorder": "#93e6fc",
+ "statusBar.background": "#61dafb",
+ "statusBar.foreground": "#15202b",
+ "statusBarItem.hoverBackground": "#2fcefa",
+ "statusBarItem.remoteBackground": "#61dafb",
+ "statusBarItem.remoteForeground": "#15202b",
+ "titleBar.activeBackground": "#61dafb",
+ "titleBar.activeForeground": "#15202b",
+ "titleBar.inactiveBackground": "#61dafb99",
+ "titleBar.inactiveForeground": "#15202b99"
+ },
+ "peacock.color": "#61dafb"
}
diff --git a/docs/src/content/docs/assets/dungeon-game-architecture.png b/docs/src/content/docs/assets/dungeon-game-architecture.png
index 0d2992f3..f03b864c 100644
Binary files a/docs/src/content/docs/assets/dungeon-game-architecture.png and b/docs/src/content/docs/assets/dungeon-game-architecture.png differ
diff --git a/docs/src/content/docs/en/get_started/concepts.mdx b/docs/src/content/docs/en/get_started/concepts.mdx
index 9314f6db..19f9efa6 100644
--- a/docs/src/content/docs/en/get_started/concepts.mdx
+++ b/docs/src/content/docs/en/get_started/concepts.mdx
@@ -1,6 +1,6 @@
---
title: Concepts
-description: Key concepts.
+description: Key concepts
---
import { Image } from 'astro:assets';
@@ -9,9 +9,9 @@ import typeSafetyGif from '@assets/type-safety.gif';
import websiteGeneratorGif from '@assets/website-generator.gif';
import generatorsJpg from '@assets/generators.png';
-The `@aws/nx-plugin` is an [Nx](https://nx.dev/) plugin that provides a toolkit for simplifying the process of building and deploying full-stack applications on AWS. It provides developers with pre-configured templates for both application and IaC code, significantly reducing the time spent on setup and configuration. The plugin handles the complexity of AWS service integration while maintaining flexibility for customization.
+The `@aws/nx-plugin` is an [Nx](https://nx.dev/) plugin that provides a toolkit for simplifying the process of building and deploying full-stack applications on AWS. It provides developers with pre-configured templates for both application and Infrastructure-as-Code (IaC) code, significantly reducing the time spent on setup and configuration. The plugin handles the complexity of AWS services integration while maintaining flexibility for customization.
-Users simplify pick and choose which components they want from the list of available [Generators](#generators), provide any configuration options and have the `@aws/nx-plugin` generate the required starter code. Several generators exist within this toolkit which can create APIs, websites, infrastructure and even do more sophistacted things like integrated a frontend to a backend (including updating existing files via AST transforms!) with type-safe clients.
+Users can pick and choose which components they want from the list of available [generators](#generators), provide any configuration options and have the `@aws/nx-plugin` generate the required starter code. You can use specific generators within this toolkit to create APIs, websites, infrastructure and sophistacted things like integrating a frontend with a backend (including updating existing files via Abstract Syntax Tree (AST) transforms) with type-safe clients.
@@ -27,43 +27,44 @@ Together, these features make Nx particularly effective for managing monorepos a
## Generators
-All components available in this plugin as implemented as [Generators](https://nx.dev/features/generate-code) which enable the automation of repetitive tasks and allow consistent scaffolding of both new and existing projects.
+All components available in this plugin are implemented as [Generators](https://nx.dev/features/generate-code) which automate repetitive tasks and allow consistent scaffolding of both new and existing projects.
-Generators can be invoked via the [Nx CLI](https://nx.dev/features/generate-code#invoke-generators) or the [Nx Console IDE plugin](https://nx.dev/getting-started/editor-setup).
+You can invoke generators via the [Nx CLI](https://nx.dev/features/generate-code#invoke-generators) or the [Nx Console IDE plugin](https://nx.dev/getting-started/editor-setup).
## Open for modification
-All code generated is your code, meaning it is free to be edited as you see fit. This drastically simplifies the developer experience as if you don't like something in the generated code, you are free to modify it.
+All code generated is your code, meaning it is free to be edited as you see fit. This drastically simplifies the developer experience, as if you don't like something in the generated code, you are free to modify it.
## Minimal dependencies
-The `@aws/nx-plugin` strives to keep the number of dependencies to a minimum and as such the global requirements for getting started boil down to what generators you invoke.
+The `@aws/nx-plugin` strives to keep the number of dependencies to a minimum, so the global requirements for getting started depend on the generators you invoke.
-As an example, any Typescript based generator will only require [Node](https://nodejs.org/en/download) to be installed. For Python based projects, [UV](https://docs.astral.sh/uv/) is the only requirement.
+For example:
+
+- Any Typescript based generator will only require [Node](https://nodejs.org/en/download) to be installed.
+- For Python based projects, [UV](https://docs.astral.sh/uv/) is the only requirement.
## Single version policy
-The default monorepo setup uses a [single version policy](https://nx.dev/concepts/decisions/dependency-management#single-version-policy) for both Node and Python based project.
+The default monorepo setup uses a [single version policy](https://nx.dev/concepts/decisions/dependency-management#single-version-policy) for both Node and Python based projects.
-This means that all projects within your monorepo will be using the same version of dependencies by default, reducing issues related to packages in the same monorepo running into version mismatch issues.
+This means that all projects within your monorepo use the same version of dependencies by default, reducing issues related to packages in the same monorepo running into version mismatch issues.
-From a Node perspective this means a single lockfile at the root with a single `node_modules` containing all dependencies. If you need to add a new dependency, you do it in the root `package.json`.
+For Node based projects, a single lockfile at the root with a single `node_modules` contains all dependencies. If you need to add a new dependency, add it in the root `package.json`.
-From a Python perspective, this means a single `.venv` in the root of the monorepo with all dependencies installed into it. Each Python project however will have it's own `pyproject.toml`, but the versions of those dependencies are managed by the uv workspace and subsequently written out to the `uv.lock` file in the root.
+For Python based projects, a single `.venv` in the root of the monorepo contains all dependencies installed into it. Each Python project however will have it's own `pyproject.toml`, but the versions of those dependencies are managed by the uv workspace and subsequently written out to the `uv.lock` file in the root.
## Type safety
-The `@aws/nx-plugin` employs type-safety to simplify the developer experience via IDE completions, whilst also eliminating runtime errors which would only occur in a non type-safe implementation. As such, all components that are vended will be type-safe by default.
+The `@aws/nx-plugin` uses type-safety to simplify the developer experience via IDE completions, whilst also eliminating runtime errors which would only occur in a non type-safe implementation. By default, all components that are vended are type-safe.
diff --git a/docs/src/content/docs/en/get_started/quick-start.mdx b/docs/src/content/docs/en/get_started/quick-start.mdx
index 4c881f7a..3f889bb4 100644
--- a/docs/src/content/docs/en/get_started/quick-start.mdx
+++ b/docs/src/content/docs/en/get_started/quick-start.mdx
@@ -10,25 +10,25 @@ import InstallCommand from '@components/install-command.astro';
import RunGenerator from '@components/run-generator.astro';
import NxCommands from '@components/nx-commands.astro';
-This guide walks you through the basics of installing and using `@aws/nx-plugin` to rapidly build projects on AWS.
+This guide walks you through the basics of installing and using the `@aws/nx-plugin` to rapidly build projects on AWS.
:::tip
-For a more in-depth tutorial for building a full-stack application, check out the Dungeon Adventure Tutorial.
+For an in-depth tutorial for building a full-stack application, refer to the Dungeon Adventure Tutorial.
:::
## Prerequisites
-The following global dependencies are needed before proceeding:
+Before proceeding, install these global dependencies:
-## Step 1: Initialize a New Nx Workspace
+## Step 1: Initialize a new Nx Workspace
-Run the following command to create an Nx workspace with the package manager of your choice:
+To create an Nx workspace with the package manager of your choice, run the following command :
-Once complete, navigate to the project directory:
+Navigate to the project directory:
```sh
cd my-project
@@ -36,13 +36,14 @@ cd my-project
## Step 2: Add the Nx Plugin for AWS
-Install the plugin with:
+Install the plugin using your package manager.
## Step 3: Use Generators to Scaffold your Project
-We'll add a tRPC API, React Website, Cognito Authentication, and CDK Infrastructure in this quick-start guide. Depending on the type of project you're building, you can choose any combination of generators to quickly bootstrap your project. Check out the __Guides__ in the navigation bar to the left to see the full list of options.
+For the purposes of this quick start guide, we will add a tRPC API, React website, Cognito authentication, and CDK infrastructure to our project.
+Depending on the type of project you're building, you can choose any combination of generators to bootstrap your project. To see the full list of options, refer to the __Guides__ section in the navigation bar on the left.
### Add a tRPC API
@@ -60,7 +61,7 @@ This scaffolds a new React website in `packages/demo-website`.
-This sets up the necessary infrastructure and React code to add Cognito Authentication to your website.
+This sets up the necessary infrastructure and React code to add Cognito authentication to your website.
### Connect Frontend to Backend
@@ -74,7 +75,7 @@ This configures the necessary providers to ensure your website can call your tRP
This configures a CDK App which you can use to deploy your infrastructure on AWS.
-## Step 4: Define Cloud Resources and Deploy to AWS
+## Step 4: Define Cloud resources and deploy to AWS
Open `packages/infra/src/stacks/application-stack.ts` and add the following code:
@@ -95,34 +96,33 @@ export class ApplicationStack extends cdk.Stack {
}
}
```
+__Note__: This is all the CDK we need to write to deploy our full stack application.
-This is all the CDK we need to write to deploy our full stack application.
+### Build and deploy the infrastructure
-### Build and Deploy the Infrastructure
-
-Next, run the following command to build your project:
+To build your project, run the following command:
:::tip
-If you encounter any lint errors, you can run the following command to automatically fix them.
+If you encounter any lint errors, run the following command to automatically fix them.
:::
-## Step 5: Run the Frontend Locally
+## Step 5: Run the frontend locally
-1. Fetch the `runtime-config.json` file:
+1. Fetch the `runtime-config.json` file
-2. Start the local website server
+2. Start the local web server
-Your website will be available at `http://localhost:4200`.
+You can preview your website at `http://localhost:4200` in a browser.
---
diff --git a/docs/src/content/docs/en/get_started/tutorials/dungeon-game/1.mdx b/docs/src/content/docs/en/get_started/tutorials/dungeon-game/1.mdx
index 7b771a4b..04cb1a57 100644
--- a/docs/src/content/docs/en/get_started/tutorials/dungeon-game/1.mdx
+++ b/docs/src/content/docs/en/get_started/tutorials/dungeon-game/1.mdx
@@ -19,13 +19,16 @@ import nxGraphPng from '@assets/nx-graph.png'
import gameSelectPng from '@assets/game-select.png'
import gameConversationPng from '@assets/game-conversation.png'
-## Module 1: Monorepo setup
+## Module 1: Set up your Monorepo
-We are going to start by creating a new monorepo. From within your desired directory, run the following command:
+Start by creating a new monorepo. A monorepo is a single repository containing multiple distinct projects, with well-defined relationships.
+
+Within your desired directory, run the following command:
-This will set up a NX monorepo within the `dungeon-adventure` directory which you can then open in vscode. It should look like the following:
+This will set up a NX monorepo within the `dungeon-adventure` directory.
+Open the directory in vscode. You will see the following file structure:
- .nx/
@@ -45,29 +48,27 @@ This will set up a NX monorepo within the `dungeon-adventure` directory which yo
- tsconfig.json
-In order to start adding components from the `@aws/nx-plugin` into the monorepo, we need to install it as a dev dependency by running the following command from the root of the `dungeon-adventure` monorepo:
+Before we add components from the `@aws/nx-plugin` into the monorepo, we need to install it as a dev dependency.
+To do this, run the following command in the root of the `dungeon-adventure` monorepo:
-Now we are ready to start creating our different sub-projects using the `@aws/nx-plugin`.
+We are now ready to start creating our different sub-projects using the `@aws/nx-plugin`.
-
+
-### Game API
+### Generate the Game API
-First let's create our Game API. To do this, let's create a tRPC API called `GameApi` by following the below steps:
+We will start with creating our Game API. This API is used for managing the game state.
+To do this, create a tRPC API called `GameApi` using these steps:
-You should see some new files have appeared in your file tree.
+You will see new files appear in your file tree.
-
-
-
+
Below is a list of all files which have been generated by the `ts#trpc-api` generator. We are going to examine some of the key files highlighted in the file tree:
- packages/
@@ -124,7 +125,7 @@ Below is a list of all files which have been generated by the `ts#trpc-api` gene
- vitest.workspace.ts
-Taking a look at a few of the key files:
+Let us look at these key files:
```ts {5,12}
// packages/game-api/backend/src/router.ts
@@ -151,7 +152,8 @@ export const handler = awsLambdaRequestHandler({
export type AppRouter = typeof appRouter;
```
-The router defines the entrypoint for your tRPC API and is the place where you will declare all of your API methods. As you can see above, we have a method called `echo` with it's implementation living in the `./procedures/echo.ts` file.
+The router defines the entry oint for your tRPC API and is the place where you will declare all of your API methods.
+We have a method called `echo` with it's implementation in the `./procedures/echo.ts` file.
```ts {2-5}
// packages/game-api/backend/src/procedures/echo.ts
@@ -167,9 +169,9 @@ export const echo = publicProcedure
.query((opts) => ({ result: opts.input.message }));
```
-This file is the implementation of the `echo` method and as you can see is strongly typed by declaring its input and output data structures. It is importing these definitions from the `:dungeon-adventure/game-api-schema` project which is an [alias](https://www.typescriptlang.org/tsconfig/paths.html) for the schema project.
+This file is the implementation of the `echo` method, which is strongly typed by declaring its input and output data structures. It imports these definitions from the `:dungeon-adventure/game-api-schema` project which is an [alias](https://www.typescriptlang.org/tsconfig/paths.html) for the schema project.
-
+
```ts
// packages/game-api/schema/src/procedures/echo.ts
@@ -188,7 +190,7 @@ export const EchoOutputSchema = z.object({
export type IEchoOutput = z.TypeOf;
```
-All tRPC schema definitions are defined using [Zod](https://zod.dev/) and are exported as typescript types via the `z.TypeOf` syntax.
+All tRPC schema definitions are defined using [Zod](https://zod.dev/), and are exported as typescript types via the `z.TypeOf` syntax.
```ts
// packages/common/constructs/src/app/http-apis/game-api.ts
@@ -216,19 +218,25 @@ export class GameApi extends HttpApi {
}
```
-This is the CDK construct that defines our GameApi. As you can see, it has already configured the handler file path to the generated bundle for our tRPC backend implementation. This means that at `cdk synth` time, bundling does not occur (opposed to using [NodeJsFunction](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html)) as we have already bundled it as part of the backend project's build target.
+This is the CDK construct that defines our GameAPI. It has configured the handler file path to the generated bundle for our tRPC backend implementation, so that at `cdk synth` time, bundling does not occur (opposed to using [NodeJsFunction](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html)), as we have already bundled it as part of the backend project's build target.
-### Story API
+
+
+### Generate the Story API
-Now let's create our Story API. To do this, let's create a Fast API called `StoryApi` by following the below steps:
+Next, let's create our Story API using the FastAPI generator. The Story API is used with streaming responses for story generation, using Amazon Bedrock.
+To do this, create a Fast API called `StoryApi` using these steps:
-You should see some new files have appeared in your file tree.
+You will see new files appear in your file tree.
+
-Below is a list of all files which have been generated by the `py#fast-api` generator. We are going to examine some of the key files highlighted in the file tree:
+This is a list of all files which have been generated by the `py#fast-api` generator. Let us examine some of the key files highlighted in the file tree:
- .venv/ single virtual env for monorepo
- packages/
@@ -283,7 +291,7 @@ export class StoryApi extends HttpApi {
}
```
-This is the CDK construct that defines our StoryApi. As you can see, it has already configured the handler file path to the generated bundle for our Fast API backend implementation. This means that at `cdk synth` time, bundling does not occur (opposed to [PythonFunction](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-lambda-python-alpha.PythonFunction.html)) as we have already bundled it as part of the backend project's build target.
+This is the CDK construct that defines our StoryApi. It configures the handler file path to the generated bundle for our Fast API backend implementation. This means that at `cdk synth` time, bundling does not occur (opposed to [PythonFunction](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-lambda-python-alpha.PythonFunction.html)) as we have already bundled it as part of the backend project's build target.
```diff lang="ts"
// packages/common/types/src/runtime-config.ts
@@ -315,16 +323,17 @@ This is where all your API method will be defined. As you can see here, we have
-### Game UI: Website
+### Add the Game UI website
-Now let's create the UI which will enable you to interact with the game. To do this, let's create a website called `GameUI` by following the below steps:
+To interact with the game, create the UI using CloudScape website generator.
+To do this, create a website called `GameUI` using these steps:
-You should see some new files have appeared in your file tree.
+You will see new files appear in your file tree.
-Below is a list of all files which have been generated by the `ts#cloudscape-website` generator. We are going to examine some of the key files highlighted in the file tree:
+Below is a list of all files which have been generated by the `ts#cloudscape-website` generator. Let us examine some of the key files highlighted in the file tree::
- packages/
- common/
@@ -443,16 +452,16 @@ A component which will be rendered when navigating to the `/welcome` route. `@ta
-### Game UI: Auth
+### Add Game UI authentication
-Now let's configure our Game UI to require authenticated access via Amazon Cognito by following the below steps:
+To configure our Game UI with authenticated access via Amazon Cognito, use these steps:
-You should see some new files have appeared/changed in your file tree.
+You will see new files appear in your file tree.
-Below is a list of all files which have been generated/updated by the `ts#cloudscape-website#auth` generator. We are going to examine some of the key files highlighted in the file tree:
+Below is a list of all files which have been generated/updated by the `ts#cloudscape-website#auth` generator. Let us examine some of the key files highlighted in the file tree:
- packages/
- common/
@@ -510,20 +519,20 @@ root &&
);
```
-The `RuntimeConfigProvider` and `CognitoAuth` components have been added to the `main.tsx` file via an AST transform. This allows the `CognitoAuth` component to authenticate with Amazon Cognito by fetching the `runtime-config.json` which contains the required cognito connection configuration in order to make the backend calls to the correct destination.
+The `RuntimeConfigProvider` and `CognitoAuth` components have been added to the `main.tsx` file via an AST transform. This allows the `CognitoAuth` component to authenticate with Amazon Cognito by fetching the `runtime-config.json` which contains the required cognito connection configuration to make the backend calls to the correct destination.
-### Game UI: Connect to Story API
+### Configure Game UI to connect to the Story API
-Now let's configure our Game UI to connect to our previously created Story API:
+To configure our Game UI to connect to our previously created Story API, use these steps:
-You should see some new files have appeared/changed in your file tree.
+You will see new files appear in your file tree.
-Below is a list of all files which have been generated/updated by the `api-connection` generator. We are going to examine some of the key files highlighted in the file tree:
+Below is a list of all files which have been generated/updated by the `api-connection` generator. Let us examine some of the key files highlighted in the file tree:
- packages/
- game-ui/
@@ -568,7 +577,7 @@ export const useStoryApi = (): StoryApi => {
};
```
-This hook can be used to make authenticated API requests to the `StoryApi`. As you can see in the implementation, it uses the `StoryApi` which is generated at build time and as such you will see an error in your IDE until we build our code. For more details on how the client is generated or how to consume the API, refer to the React to FastAPI guide.
+You can use this hook to make authenticated API requests to the `StoryApi`. It uses the `StoryApi` which is generated at build time, and you will see an error in your IDE until we build our code. For more details on how the client is generated, or how to consume the API, refer to the React to FastAPI guide.
```tsx
// packages/game-ui/src/components/StoryApiProvider.tsx
@@ -607,16 +616,16 @@ The `src/generated/story-api/*.gen.ts` files should never be modified manually a
-### Game UI: Connect to Game API
+### Configure Game UI to connect to the Game API
-Now let's configure our Game UI to connect to our previously created Game API:
+To configure our Game UI to connect to our Game API, use these steps:
You should see some new files have appeared/changed in your file tree.
-Below is a list of all files which have been generated/updated by the `api-connection` generator. We are going to examine some of the key files highlighted in the file tree:
+Below is a list of all files which have been generated/updated by the `api-connection` generator. Let us examine some of the key files highlighted in the file tree:
- packages/
- game-ui/
@@ -641,7 +650,7 @@ import { TrpcApis } from '../components/TrpcClients';
export const useGameApi = () => TrpcApis.GameApi.useTRPC();
```
-This hook uses tRPC's latest [React Query integration](https://trpc.io/blog/introducing-tanstack-react-query-client) allowing user's to interact with `@tanstack/react-query` directly without any additional layers of abstraction. For examples on how to call tRPC APIs, refer to the using the tRPC hook guide.
+This hook uses tRPC's latest [React Query integration](https://trpc.io/blog/introducing-tanstack-react-query-client) allowing users to interact with `@tanstack/react-query` directly without any additional layers of abstraction. For examples on how to call tRPC APIs, refer to the using the tRPC hook guide.
-### Game UI: Infrastructure
+### Create Game UI CDK infrastructure
-Now the final sub-project we need to create is for the CDK infrastructure. To create this, follow the below steps:
+To create the CDK infrastructure as final sub-project, use these steps:
-You should see some new files have appeared/changed in your file tree.
+You should see some new files have appeared/changed in your file tree..
-Below is a list of all files which have been generated/updated by the `ts#infra` generator. We are going to examine some of the key files highlighted in the file tree:
+Below is a list of all files which have been generated/updated by the `ts#infra` generator. Let us examine some of the key files highlighted in the file tree:
- packages/
- common/
@@ -750,9 +759,7 @@ new ApplicationStack(app, 'dungeon-adventure-infra-sandbox', {
app.synth();
```
-This is the entrypoint for your CDK application.
-
-It is configured to use [`cfn-guard`](https://github.com/cdklabs/cdk-validator-cfnguard) to run infrastructure validation based on the configured ruleset. This is instrumented post synthesis.
+This is the entrypoint for your CDK application. It is configured to use [`cfn-guard`](https://github.com/cdklabs/cdk-validator-cfnguard) to run infrastructure validation based on the configured ruleset. This is instrumented post synthesis.
-#### Update our infrastructure
+#### Update CDK infrastructure
-Let's make an update to our `packages/infra/src/stacks/application-stack.ts` to instantiate some of our already generated constructs:
+To instantiate some of our already generated constructs, let us update our `packages/infra/src/stacks/application-stack.ts` :
```diff lang="ts"
+import {
@@ -864,7 +871,7 @@ If for whatever reason you ever wanted to clear your cache (stored in the `.nx`
-You should be prompted with the following:
+You will be prompted with the following:
```bash
NX The workspace is out of sync
@@ -918,6 +925,6 @@ app.synth();
-All built artifacts are now available within the `dist/` folder located at the root of the monorepo. This is a standard practice when using projects generated by the `@aws/nx-plugin` as it does not pollute your file-tree with generated files. In the event you want to clean yor files, you can simply delete the `dist/` folder without having to worry about generated files being littered throughout the file tree.
+All built artifacts are now available within the `dist/` folder located at the root of the monorepo. This is a standard practice when using projects generated by the `@aws/nx-plugin` to not mix your file-tree with generated files. If you want to clean yor files, delete the `dist/` folder without worrying about generated files being littered throughout the file tree.
Congratulations! You’ve created all of the required sub-projects needed to start implementing the core of our Dunegeon Adventure game. 🎉🎉🎉
\ No newline at end of file
diff --git a/docs/src/content/docs/en/get_started/tutorials/dungeon-game/overview.mdx b/docs/src/content/docs/en/get_started/tutorials/dungeon-game/overview.mdx
index fccd2f39..28119c43 100644
--- a/docs/src/content/docs/en/get_started/tutorials/dungeon-game/overview.mdx
+++ b/docs/src/content/docs/en/get_started/tutorials/dungeon-game/overview.mdx
@@ -22,46 +22,47 @@ import gameConversationPng from '@assets/game-conversation.png'
You will build an AI powered dungeon adventure game during this tutorial. This tutorial does not assume any existing knowledge of the `@aws/nx-plugin` or related technologies. The techniques you'll learn in this tutorial are fundamental to building any `@aws/nx-plugin` based application, and fully understanding it will give you a deep understanding of the `@aws/nx-plugin` and a basic understanding of how to use [NX](https://nx.dev/).
-
+
-Users who complete this tutorial can expect to walk away with the knowledge to:
+Users who complete this tutorial will learn how to:
-- use the `@aws/nx-plugin` to create new applications
-- use NX to manage/build their codebase
-- build APIs using both tRPC and FastAPI
-- use Tanstack router to create new pages
-- use Tanstack query to call backend APIs
-- make modifications to generated code to be fit for purpose
-- create and deploy CDK infrastructure
+- use the `@aws/nx-plugin` to create new applications,
+- use NX to manage/build their codebase,
+- build APIs using both tRPC and FastAPI,
+- use a TanStack router to create new pages,
+- use a TanStack query to call backend APIs,
+- make modifications to generated code to be fit for purpose, and
+- create and deploy CDK infrastructure.
## What are you building?
-In this tutorial, you'll build an AI powered dungeon adventure game with `@aws/nx-plugin`.
+In this tutorial, you will build an AI powered dungeon adventure game with `@aws/nx-plugin`.
-You can see what it will look like when you're finished here:
+This is what the final output will look like, after completion of the tutorial.
-### Components of the application
+### Application components
-The AI powered dungeon adventure game will be built using the following component architecture:
+We will build the AI powered dungeon adventure game using the following component architecture.
-- [tRPC](https://trpc.io/) API which uses [ElectroDB](https://electrodb.dev/)/[DynamoDB](https://aws.amazon.com/dynamodb/) for managing the game state
-- Python/[FastAPI](https://fastapi.tiangolo.com/) Lambda function with streaming responses for story generation (powered by [Amazon Bedrock](https://aws.amazon.com/bedrock/))
-- React/Vite frontend website utilising:
- - Amazon Cognito/Identity Pools for secure API calls
- - [Tanstack router](https://tanstack.com/router/latest) which supports type-safe file based routing
- - Generated SDKs for calling the Game and Story APIs (leveraging [Tanstack query](https://tanstack.com/query/latest))
-- [CDK](https://docs.aws.amazon.com/cdk/v2/guide/home.html) infrastructure to deploy the application
+1. The [tRPC](https://trpc.io/) API uses [ElectroDB](https://electrodb.dev/)/[DynamoDB](https://aws.amazon.com/dynamodb/) for managing the game state.
+2. The Python/[FastAPI](https://fastapi.tiangolo.com/) Lambda function with streaming responses for story generation (powered by [Amazon Bedrock](https://aws.amazon.com/bedrock/))
+3. A React/Vite frontend website using:
+ - Amazon Cognito/Identity Pools for secure API calls.
+ - [TanStack router](https://tanstack.com/router/latest) which supports type-safe file based routing.
+ - Generated SDKs for calling the Game and Story APIs (leveraging [TanStack query](https://tanstack.com/query/latest))
+
+A [CDK](https://docs.aws.amazon.com/cdk/v2/guide/home.html) infrastructure to deploy the application components.
## Prerequisites
-The following global dependencies are needed before proceeding:
+Before proceeding, install these global dependencies:
-- Ensure your AWS account has enabled access to the Anthropic Claude 3.5 Sonnet v2 model within Bedrock for your target region via the steps outlined in [this guide](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access-modify.html).
+- Ensure that you have enable access (in your AWS account) to the Anthropic Claude 3.5 Sonnet v2 model within Bedrock for your target region. For instructions on how to complet this, use the steps outlined in the [Add or remove access to Amazon Bedrock foundation models](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access-modify.html) section.
diff --git a/docs/src/content/docs/en/index.mdx b/docs/src/content/docs/en/index.mdx
index ecacbe2f..37dfae54 100644
--- a/docs/src/content/docs/en/index.mdx
+++ b/docs/src/content/docs/en/index.mdx
@@ -1,9 +1,9 @@
---
title: '@aws/nx-plugin'
-description: Quickly bootstrap and build AWS projects easily (with NX plugins)
+description: Bootstrap and build AWS projects easily (with NX plugins)
template: splash
hero:
- tagline: Quickly bootstrap and build AWS projects easily (with NX plugins)
+ tagline: Bootstrap and build AWS projects easily (with NX plugins)
image:
light: ../assets/bulb-black.svg
dark: ../assets/bulb-white.svg
@@ -87,6 +87,7 @@ import websiteGeneratorGif from '@assets/website-generator.gif';
{/* */}
+ ### View an example of how to generate an UI
= 22](https://nodejs.org/en/download) (We recommend using something like [NVM](https://github.com/nvm-sh/nvm) to manage your node versions)
- - verify by running `node --version`
-- [PNPM >= 10](https://pnpm.io/installation#using-npm) (you can also use [Yarn >= 4](https://yarnpkg.com/getting-started/install), [Bun >= 1](https://bun.sh/docs/installation), or [NPM >= 10](https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager) if you prefer)
- - verify by running `pnpm --version`, `yarn --version`, `bun --version` or `npm --version`
-- [UV >= 0.5.29](https://docs.astral.sh/uv/getting-started/installation/)
- 1. install Python 3.12 by running: `uv python install 3.12.0`
- 2. verify with `uv python list --only-installed`
-- [AWS Credentials](https://docs.aws.amazon.com/sdkref/latest/guide/access.html) configured to your target AWS account (where your application will be deployed)
+- Install [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git).
+- Install [Node >= 22](https://nodejs.org/en/download) (We recommend using [NVM](https://github.com/nvm-sh/nvm) to manage your node versions)
+ - To verify your version, run `node --version` in the terminal window.
+- Install [PNPM >= 10](https://pnpm.io/installation#using-npm) (You can also use [Yarn >= 4](https://yarnpkg.com/getting-started/install), [Bun >= 1](https://bun.sh/docs/installation), or [NPM >= 10](https://nodejs.org/en/learn/getting-started/an-introduction-to-the-npm-package-manager))
+ - To verify your version, run `pnpm --version`, `yarn --version`, `bun --version` or `npm --version` in your terminal window.
+- Install [UV >= 0.5.29](https://docs.astral.sh/uv/getting-started/installation/)
+ 1. To install Python 3.1, run `uv python install 3.12.0`.
+ 2. Verify using `uv python list --only-installed`
+- Configure your [AWS Credentials](https://docs.aws.amazon.com/sdkref/latest/guide/access.html) to your target AWS account (where your application will be deployed).
- If you are using [VSCode](https://code.visualstudio.com/), we recommend installing the [Nx Console VSCode Plugin](https://marketplace.visualstudio.com/items?itemName=nrwl.angular-console).
\ No newline at end of file
diff --git a/docs/src/content/docs/es/get_started/concepts.mdx b/docs/src/content/docs/es/get_started/concepts.mdx
index 661daf08..a8985551 100644
--- a/docs/src/content/docs/es/get_started/concepts.mdx
+++ b/docs/src/content/docs/es/get_started/concepts.mdx
@@ -1,6 +1,6 @@
---
title: "Conceptos"
-description: "Conceptos clave."
+description: "Conceptos clave"
---
@@ -11,56 +11,65 @@ import typeSafetyGif from '@assets/type-safety.gif';
import websiteGeneratorGif from '@assets/website-generator.gif';
import generatorsJpg from '@assets/generators.png';
-El `@aws/nx-plugin` es un plugin de [Nx](https://nx.dev/) que proporciona un conjunto de herramientas para simplificar el desarrollo e implementación de aplicaciones full-stack en AWS. Ofrece plantillas preconfiguradas tanto para aplicaciones como para código de Infraestructura como Código (IaC), reduciendo significativamente el tiempo de configuración inicial. El plugin maneja la complejidad de integración con servicios AWS manteniendo flexibilidad para personalizaciones.
+El `@aws/nx-plugin` es un plugin de [Nx](https://nx.dev/) que proporciona un conjunto de herramientas para simplificar el desarrollo y despliegue de aplicaciones full-stack en AWS. Ofrece plantillas preconfiguradas tanto para aplicaciones como para Infraestructura como Código (IaC), reduciendo significativamente el tiempo de configuración inicial. El plugin maneja la complejidad de integrar servicios de AWS mientras mantiene flexibilidad para personalizaciones.
-Los usuarios simplemente seleccionan los componentes deseados de la lista de [Generadores](#generators) disponibles, proveen opciones de configuración y el `@aws/nx-plugin` genera el código inicial requerido. Este kit incluye generadores para crear APIs, sitios web, infraestructura e incluso funcionalidades avanzadas como integrar frontend con backend (¡incluyendo actualizaciones de archivos existentes mediante transformaciones AST!) con clientes type-safe.
+Los usuarios pueden seleccionar componentes específicos de la lista de [generadores](#generators) disponibles, proporcionar opciones de configuración y dejar que el `@aws/nx-plugin` genere el código inicial requerido. Puedes usar generadores específicos para crear APIs, sitios web, infraestructura e integraciones avanzadas como conectar frontends con backends (incluyendo actualizaciones de archivos existentes mediante transformaciones de Árbol de Sintaxis Abstracta (AST)) con clientes type-safe.
## Construido sobre Nx
-[Nx](https://nx.dev) es un framework de construcción inteligente que gestiona proyectos poliglotas complejos mediante dos pilares: un sistema de construcción avanzado y generadores de código.
+[Nx](https://nx.dev) es un framework de construcción inteligente que destaca en la gestión de proyectos políglotas complejos gracias a dos características clave: un sistema de construcción inteligente y generadores de código.
-El sistema de construcción utiliza caché inteligente y análisis de gráficos de dependencias para optimizar la ejecución de tareas. Solo reconstruye lo necesario basado en cambios, reduciendo drásticamente tiempos de compilación. Las tareas se ejecutan en paralelo con un orden óptimo determinado automáticamente según dependencias, haciendo operaciones como testing, linting y builds altamente eficientes en bases de código grandes.
+El sistema de construcción utiliza caché avanzado y análisis de grafos de dependencias para optimizar la ejecución de tareas. Solo reconstruye lo necesario basándose en cambios de código, reduciendo drásticamente los tiempos de compilación. Las tareas pueden ejecutarse en paralelo, con Nx determinando automáticamente el orden óptimo según las dependencias del proyecto. Esto hace operaciones como testing, linting y building altamente eficientes, especialmente en bases de código grandes.
-Los generadores actúan como herramientas de scaffolding automatizado que crean estructuras de código consistentes. Pueden generar desde componentes individuales hasta aplicaciones completas siguiendo plantillas predefinidas. Los equipos pueden personalizar estos generadores para cumplir sus estándares específicos.
+Los generadores actúan como herramientas de scaffolding automatizado que crean estructuras de código consistentes. Pueden generar desde componentes individuales hasta aplicaciones completas, siguiendo plantillas predefinidas. Los equipos pueden personalizar estos generadores para adaptarlos a sus estándares y requisitos específicos.
-Juntas, estas características hacen a Nx particularmente efectivo para gestionar monorepos y mantener prácticas de desarrollo consistentes en equipos, manteniendo alta velocidad de desarrollo.
+Juntas, estas características hacen que Nx sea especialmente efectivo para gestionar monorepos y mantener prácticas de desarrollo consistentes entre equipos, manteniendo alta velocidad de desarrollo.
## Generadores
-Todos los componentes de este plugin se implementan como [Generadores](https://nx.dev/features/generate-code) que automatizan tareas repetitivas y permiten scaffolding consistente en proyectos nuevos y existentes.
+Todos los componentes disponibles en este plugin se implementan como [Generadores](https://nx.dev/features/generate-code) que automatizan tareas repetitivas y permiten generar scaffolding consistente tanto para proyectos nuevos como existentes.
-Los generadores pueden invocarse mediante la [CLI de Nx](https://nx.dev/features/generate-code#invoke-generators) o el [plugin IDE Nx Console](https://nx.dev/getting-started/editor-setup).
+Puedes invocar generadores mediante la [CLI de Nx](https://nx.dev/features/generate-code#invoke-generators) o el [plugin IDE Nx Console](https://nx.dev/getting-started/editor-setup).
## Abierto a modificaciones
-Todo el código generado es tuyo, lo que significa que puedes editarlo libremente. Esto simplifica drásticamente la experiencia de desarrollo: si algo no te gusta del código generado, puedes modificarlo directamente.
+Todo el código generado es tu código, lo que significa que puedes editarlo libremente. Esto simplifica drásticamente la experiencia del desarrollador: si algo no te gusta del código generado, puedes modificarlo directamente.
## Dependencias mínimas
-El `@aws/nx-plugin` mantiene un número mínimo de dependencias. Los requisitos globales dependen únicamente de los generadores que uses.
+El `@aws/nx-plugin` busca minimizar las dependencias globales requeridas, las cuales varían según los generadores que uses.
-Por ejemplo, generadores basados en Typescript solo requieren [Node](https://nodejs.org/en/download). Para proyectos Python, solo se necesita [UV](https://docs.astral.sh/uv/).
+Por ejemplo:
+- Generadores basados en Typescript solo requieren tener [Node](https://nodejs.org/en/download) instalado.
+- Proyectos en Python solo necesitan [UV](https://docs.astral.sh/uv/).
## Política de versión única
-La configuración predeterminada de monorepos usa una [single version policy](https://nx.dev/concepts/decisions/dependency-management#single-version-policy) para proyectos Node y Python.
+La configuración predeterminada del monorepositorio usa una [política de versión única](https://nx.dev/concepts/decisions/dependency-management#single-version-policy) para proyectos Node y Python.
-Esto significa que todos los proyectos usan la misma versión de dependencias por defecto, reduciendo conflictos por incompatibilidades de versiones.
+Esto significa que todos los proyectos usan la misma versión de dependencias por defecto, reduciendo problemas de incompatibilidad entre paquetes.
-En Node: un único lockfile en la raíz con un solo `node_modules`. Las nuevas dependencias se añaden al `package.json` raíz.
+Para proyectos Node:
+- Un único `node_modules` y `package.json` en la raíz.
+- Las nuevas dependencias se añaden al `package.json` raíz.
-En Python: un único `.venv` en la raíz del monorepo. Cada proyecto Python tiene su propio `pyproject.toml`, pero las versiones se gestionan mediante el workspace de uv y se registran en el archivo `uv.lock` raíz.
+Para proyectos Python:
+- Un único `.venv` en la raíz contiene todas las dependencias.
+- Cada proyecto Python tiene su propio `pyproject.toml`, pero las versiones se gestionan desde el workspace de UV y se escriben en el archivo `uv.lock` raíz.
## Seguridad de tipos
-El `@aws/nx-plugin` implementa type-safety para simplificar la experiencia de desarrollo mediante autocompletado en IDEs, eliminando errores en runtime. Todos los componentes incluidos son type-safe por defecto.
+El `@aws/nx-plugin` utiliza type-safety para simplificar la experiencia de desarrollo mediante autocompletado en IDEs, además de eliminar errores que solo ocurrirían en tiempo de ejecución. Todos los componentes incluidos son type-safe por defecto.
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/docs/src/content/docs/es/get_started/quick-start.mdx b/docs/src/content/docs/es/get_started/quick-start.mdx
index 3732fb64..d4d8326e 100644
--- a/docs/src/content/docs/es/get_started/quick-start.mdx
+++ b/docs/src/content/docs/es/get_started/quick-start.mdx
@@ -13,73 +13,74 @@ import InstallCommand from '@components/install-command.astro';
import RunGenerator from '@components/run-generator.astro';
import NxCommands from '@components/nx-commands.astro';
-Esta guía te lleva por los conceptos básicos de instalar y usar `@aws/nx-plugin` para construir proyectos rápidamente en AWS.
+Esta guía te guiará a través de los conceptos básicos para instalar y usar el `@aws/nx-plugin` y construir rápidamente proyectos en AWS.
:::tip
-Para un tutorial más detallado sobre cómo construir una aplicación full-stack, revisa el Tutorial de la Aventura del Calabozo.
+Para un tutorial detallado sobre cómo construir una aplicación full-stack, consulta el Tutorial de Dungeon Adventure.
:::
-## Requisitos Previos
+## Requisitos previos
-Se necesitan las siguientes dependencias globales antes de continuar:
+Antes de continuar, instala estas dependencias globales:
-## Paso 1: Inicializar un Nuevo Espacio de Trabajo Nx
+## Paso 1: Inicializar un nuevo espacio de trabajo Nx
-Ejecuta el siguiente comando para crear un espacio de trabajo Nx con el gestor de paquetes de tu elección:
+Para crear un espacio de trabajo Nx con tu gestor de paquetes preferido, ejecuta el siguiente comando:
-Una vez completado, navega al directorio del proyecto:
+Navega al directorio del proyecto:
```sh
cd my-project
```
-## Paso 2: Agregar el Plugin Nx para AWS
+## Paso 2: Añadir el plugin de Nx para AWS
-Instala el plugin con:
+Instala el plugin usando tu gestor de paquetes.
-## Paso 3: Usar Generadores para Estructurar tu Proyecto
+## Paso 3: Usar generadores para estructurar tu proyecto
-Agregaremos una API tRPC, un Sitio Web React, Autenticación con Cognito e Infraestructura CDK en esta guía rápida. Dependiendo del tipo de proyecto que estés construyendo, puedes elegir cualquier combinación de generadores para inicializar rápidamente tu proyecto. Revisa las __Guías__ en la barra de navegación a la izquierda para ver la lista completa de opciones.
+Para este inicio rápido, añadiremos una API tRPC, un sitio web en React, autenticación con Cognito e infraestructura CDK.
+Dependiendo de tu tipo de proyecto, puedes elegir cualquier combinación de generadores. Para ver todas las opciones, consulta la sección __Guías__ en la barra de navegación izquierda.
-### Agregar una API tRPC
+### Añadir una API tRPC
-Esto creará la API dentro de la carpeta `packages/demo-api`.
+Esto creará la API en la carpeta `packages/demo-api`.
-### Agregar un Sitio Web React
+### Añadir un sitio web con React
-Esto genera un nuevo sitio web React en `packages/demo-website`.
+Genera un nuevo sitio web React en `packages/demo-website`.
-### Agregar Autenticación con Cognito
+### Añadir autenticación con Cognito
-Esto configura la infraestructura necesaria y el código React para agregar Autenticación con Cognito a tu sitio web.
+Configura la infraestructura necesaria y el código React para añadir autenticación Cognito a tu sitio web.
-### Conectar Frontend con Backend
+### Conectar el frontend al backend
-Esto configura los proveedores necesarios para asegurar que tu sitio web pueda consumir tu API tRPC.
+Configura los proveedores necesarios para que tu sitio web pueda consumir la API tRPC.
-### Agregar Infraestructura CDK
+### Añadir infraestructura CDK
-Esto configura una Aplicación CDK que puedes usar para desplegar tu infraestructura en AWS.
+Configura una aplicación CDK que podrás usar para desplegar tu infraestructura en AWS.
-## Paso 4: Definir Recursos en la Nube y Desplegar en AWS
+## Paso 4: Definir recursos en la nube y desplegar en AWS
-Abre `packages/infra/src/stacks/application-stack.ts` y agrega el siguiente código:
+Abre `packages/infra/src/stacks/application-stack.ts` y añade este código:
```typescript
import * as cdk from 'aws-cdk-lib';
@@ -98,35 +99,34 @@ export class ApplicationStack extends cdk.Stack {
}
}
```
+__Nota__: Este es todo el código CDK necesario para desplegar nuestra aplicación full-stack.
-Esto es todo el código CDK que necesitamos escribir para desplegar nuestra aplicación full-stack.
+### Construir y desplegar la infraestructura
-### Construir y Desplegar la Infraestructura
-
-Luego, ejecuta el siguiente comando para construir tu proyecto:
+Para construir tu proyecto, ejecuta:
:::tip
-Si encuentras errores de linting, puedes ejecutar el siguiente comando para corregirlos automáticamente.
+Si encuentras errores de linting, ejecuta este comando para corregirlos automáticamente:
:::
-## Paso 5: Ejecutar el Frontend Localmente
+## Paso 5: Ejecutar el frontend localmente
-1. Obtén el archivo `runtime-config.json`:
+1. Obtén el archivo `runtime-config.json`
-2. Inicia el servidor local del sitio web
+2. Inicia el servidor web local
-Tu sitio web estará disponible en `http://localhost:4200`.
+Puedes previsualizar tu sitio en `http://localhost:4200`.
---
-¡Felicidades! 🎉 ¡Has construido y desplegado exitosamente una aplicación full-stack usando `@aws/nx-plugin`!
\ No newline at end of file
+¡Felicitaciones! 🎉 ¡Has construido y desplegado exitosamente una aplicación full-stack usando `@aws/nx-plugin`!
\ No newline at end of file
diff --git a/docs/src/content/docs/es/get_started/tutorials/dungeon-game/1.mdx b/docs/src/content/docs/es/get_started/tutorials/dungeon-game/1.mdx
index 7788f021..f99b8457 100644
--- a/docs/src/content/docs/es/get_started/tutorials/dungeon-game/1.mdx
+++ b/docs/src/content/docs/es/get_started/tutorials/dungeon-game/1.mdx
@@ -1,6 +1,6 @@
---
title: "Juego de Mazmorra con IA"
-description: "Un tutorial de cómo construir un juego de aventuras de mazmorra con IA usando el @aws/nx-plugin."
+description: "Un tutorial de cómo construir un juego de aventuras de mazmorra con IA utilizando el @aws/nx-plugin."
---
@@ -21,13 +21,16 @@ import nxGraphPng from '@assets/nx-graph.png'
import gameSelectPng from '@assets/game-select.png'
import gameConversationPng from '@assets/game-conversation.png'
-## Módulo 1: Configuración del monorepo
+## Módulo 1: Configurar tu Monorepositorio
-Comenzaremos creando un nuevo monorepo. Desde el directorio deseado, ejecuta el siguiente comando:
+Comienza creando un nuevo monorepositorio. Un monorepositorio es un único repositorio que contiene múltiples proyectos distintos, con relaciones bien definidas.
+
+Dentro del directorio deseado, ejecuta el siguiente comando:
-Esto configurará un monorepo NX en el directorio `dungeon-adventure` que podrás abrir en VSCode. Debería verse así:
+Esto configurará un monorepositorio NX dentro del directorio `dungeon-adventure`.
+Abre el directorio en VSCode. Verás la siguiente estructura de archivos:
- .nx/
@@ -38,7 +41,7 @@ Esto configurará un monorepo NX en el directorio `dungeon-adventure` que podrá
- .npmrc
- .prettierignore
- .prettierrc
-- nx.json configura los valores predeterminados de CLI y monorepo de Nx
+- nx.json configura el CLI de Nx y los valores por defecto del monorepositorio
- package.json todas las dependencias de node se definen aquí
- pnpm-lock.yaml o bun.lock, yarn.lock, package-lock.json según el gestor de paquetes
- pnpm-workspace.yaml si usas pnpm
@@ -47,43 +50,41 @@ Esto configurará un monorepo NX en el directorio `dungeon-adventure` que podrá
- tsconfig.json
-Para empezar a agregar componentes del `@aws/nx-plugin` al monorepo, debemos instalarlo como dependencia de desarrollo ejecutando desde la raíz del monorepo `dungeon-adventure`:
+Antes de agregar componentes del `@aws/nx-plugin` al monorepositorio, debemos instalarlo como dependencia de desarrollo.
+Para esto, ejecuta el siguiente comando en la raíz del monorepositorio `dungeon-adventure`:
-Ahora estamos listos para crear nuestros diferentes subproyectos usando el `@aws/nx-plugin`.
+Ahora estamos listos para comenzar a crear nuestros diferentes subproyectos usando el `@aws/nx-plugin`.
-
+
-### API del Juego
+### Generar la API del Juego
-Primero crearemos nuestra API del Juego. Para esto, crearemos una API tRPC llamada `GameApi` siguiendo estos pasos:
+Comenzaremos creando nuestra API del Juego. Esta API se usa para gestionar el estado del juego.
+Para hacerlo, crea una API tRPC llamada `GameApi` siguiendo estos pasos:
-Deberías ver nuevos archivos en tu árbol de directorios.
-
-
+Verás nuevos archivos aparecer en tu árbol de archivos.
-
-A continuación se muestra la lista de archivos generados por el generador `ts#trpc-api`. Examinaremos algunos archivos clave resaltados en el árbol:
+
+A continuación se muestra una lista de todos los archivos generados por el generador `ts#trpc-api`. Vamos a examinar algunos de los archivos clave resaltados en el árbol:
- packages/
- common/
- constructs/
- src/
- - app/ constructos CDK específicos de la aplicación
+ - app/ constructs CDK específicos de la aplicación
- http-apis/
- - **game-api.ts** constructo CDK para crear tu API tRPC
+ - **game-api.ts** construct CDK para crear tu API tRPC
- index.ts
- ...
- index.ts
- - core/ constructos CDK genéricos
- - http-api.ts constructo base CDK para API HTTP
+ - core/ constructs CDK genéricos
+ - http-api.ts construct base para una API HTTP
- index.ts
- runtime-config.ts
- index.ts
@@ -92,13 +93,13 @@ A continuación se muestra la lista de archivos generados por el generador `ts#t
- types/ tipos compartidos
- src/
- index.ts
- - runtime-config.ts definición de interfaz usada por CDK y sitio web
+ - runtime-config.ts definición de interfaz usada por CDK y el sitio web
- project.json
- ...
- game-api/
- backend/ código de implementación tRPC
- src/
- - client/ cliente vanilla para llamadas máquina a máquina
+ - client/ cliente vanilla típicamente usado para llamadas máquina a máquina
- index.ts
- sigv4.ts
- middleware/ instrumentación powertools
@@ -107,12 +108,12 @@ A continuación se muestra la lista de archivos generados por el generador `ts#t
- logger.ts
- metrics.ts
- tracer.ts
- - procedures/ implementaciones específicas de procedimientos/rutas
+ - procedures/ implementaciones específicas para tus procedimientos/rutas de API
- **echo.ts**
- index.ts
- - init.ts configura contexto y middleware
+ - init.ts configura el contexto y middleware
- local-server.ts usado al ejecutar el servidor tRPC localmente
- - **router.ts** punto de entrada para el manejador lambda que define todos los procedimientos
+ - **router.ts** punto de entrada para tu lambda handler que define todos los procedimientos
- project.json
- ...
- schema/
@@ -126,7 +127,7 @@ A continuación se muestra la lista de archivos generados por el generador `ts#t
- vitest.workspace.ts
-Veamos algunos archivos clave:
+Veamos estos archivos clave:
```ts {5,12}
// packages/game-api/backend/src/router.ts
@@ -153,7 +154,8 @@ export const handler = awsLambdaRequestHandler({
export type AppRouter = typeof appRouter;
```
-El enrutador define el punto de entrada para tu API tRPC y es donde declararás todos tus métodos de API. Como se muestra, tenemos un método `echo` cuya implementación está en `./procedures/echo.ts`.
+El router define el punto de entrada para tu API tRPC y es donde declararás todos tus métodos de API.
+Tenemos un método llamado `echo` con su implementación en el archivo `./procedures/echo.ts`.
```ts {2-5}
// packages/game-api/backend/src/procedures/echo.ts
@@ -169,9 +171,9 @@ export const echo = publicProcedure
.query((opts) => ({ result: opts.input.message }));
```
-Este archivo implementa el método `echo` y está fuertemente tipado mediante esquemas de entrada/salida. Importa estas definiciones del proyecto `:dungeon-adventure/game-api-schema`, que es un [alias](https://www.typescriptlang.org/tsconfig/paths.html) para el proyecto de esquema.
+Este archivo es la implementación del método `echo`, fuertemente tipado al declarar sus estructuras de datos de entrada y salida. Importa estas definiciones del proyecto `:dungeon-adventure/game-api-schema` que es un [alias](https://www.typescriptlang.org/tsconfig/paths.html) para el proyecto de esquema.
-
+
```ts
// packages/game-api/schema/src/procedures/echo.ts
@@ -190,7 +192,7 @@ export const EchoOutputSchema = z.object({
export type IEchoOutput = z.TypeOf;
```
-Todos los esquemas tRPC se definen con [Zod](https://zod.dev/) y se exportan como tipos TypeScript mediante `z.TypeOf`.
+Todas las definiciones de esquema tRPC se definen usando [Zod](https://zod.dev/), y se exportan como tipos TypeScript mediante la sintaxis `z.TypeOf`.
```ts
// packages/common/constructs/src/app/http-apis/game-api.ts
@@ -218,43 +220,49 @@ export class GameApi extends HttpApi {
}
```
-Este constructo CDK define nuestro GameApi. La ruta del handler apunta al bundle generado, evitando rebundling durante `cdk synth` (a diferencia de [NodeJsFunction](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html)).
+Este es el construct CDK que define nuestro GameAPI. Ha configurado la ruta del archivo handler al bundle generado para nuestra implementación backend tRPC, para que en tiempo de `cdk synth` no ocurra bundling (a diferencia de usar [NodeJsFunction](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_lambda_nodejs.NodejsFunction.html)), ya que ya lo hemos empaquetado como parte del target build del proyecto backend.
-### API de Historias
+
+
+### Generar la API de Historia
-Ahora crearemos nuestra API de Historias. Para esto, crearemos una API Fast llamada `StoryApi`:
+A continuación, creemos nuestra API de Historia usando el generador FastAPI. La API de Historia se usa con respuestas en streaming para generación de historias, usando Amazon Bedrock.
+Para hacerlo, crea una API Fast llamada `StoryApi` siguiendo estos pasos:
-Verás nuevos archivos en tu árbol de directorios.
-
-Lista de archivos generados por `py#fast-api`:
+Verás nuevos archivos aparecer en tu árbol de archivos.
+
+
+Esta es una lista de todos los archivos generados por el generador `py#fast-api`. Examinemos algunos archivos clave resaltados en el árbol:
-- .venv/ entorno virtual único para el monorepo
+- .venv/ entorno virtual único para el monorepositorio
- packages/
- common/
- constructs/
- src/
- - app/ constructos CDK específicos
+ - app/ constructs CDK específicos de la aplicación
- http-apis/
- - **story-api.ts** constructo CDK para la API Fast
- - index.ts actualizado para exportar story-api
- - project.json actualizado con dependencia de build en story_api
+ - **story-api.ts** construct CDK para crear tu API Fast
+ - index.ts actualizado para exportar el nuevo story-api
+ - project.json actualizado para agregar una dependencia de build en story_api
- types/ tipos compartidos
- src/
- - **runtime-config.ts** actualizado con StoryApi
+ - **runtime-config.ts** actualizado para agregar StoryApi
- story_api/
- story_api/ módulo Python
- init.py configura powertools, FastAPI y middleware
- - **main.py** punto de entrada lambda con rutas
+ - **main.py** punto de entrada para la lambda que contiene todas las rutas
- tests/
- .python-version
- project.json
- pyproject.toml
- project.json
-- .python-version versión Python fijada
+- .python-version versión Python fijada por uv
- pyproject.toml
- uv.lock
@@ -285,7 +293,7 @@ export class StoryApi extends HttpApi {
}
```
-Constructo CDK para StoryApi. Usa bundle pregenerado, evitando rebundling durante `cdk synth`.
+Este es el construct CDK que define nuestro StoryApi. Configura la ruta del archivo handler al bundle generado para nuestra implementación backend Fast API. Esto significa que en tiempo de `cdk synth` no ocurre bundling (a diferencia de [PythonFunction](https://docs.aws.amazon.com/cdk/api/v2/docs/@aws-cdk_aws-lambda-python-alpha.PythonFunction.html)) ya que ya lo hemos empaquetado como parte del target build del proyecto backend.
```diff lang="ts"
// packages/common/types/src/runtime-config.ts
@@ -299,7 +307,7 @@ export interface IRuntimeConfig {
}
```
-Ejemplo de transformación AST: se añade `StoryApi` a `IRuntimeConfig`, asegurando type safety en frontend.
+Aquí vemos un ejemplo del generador realizando una transformación AST que preserva todo el código existente y realiza una actualización. Aquí puedes ver que `StoryApi` fue agregado a la definición `IRuntimeConfig`, lo que significa que cuando esto sea consumido por nuestro frontend, ¡impondrá seguridad de tipos!
```py
// packages/story_api/story_api/main.py
@@ -313,46 +321,48 @@ def read_root():
return {"Hello": "World"}
```
-Definición de rutas API. Usa [Pydantic](https://docs.pydantic.dev/latest/) para type safety.
+Aquí es donde se definirán todos tus métodos de API. Como puedes ver aquí, tenemos un método `read_root` mapeado a la ruta `GET /`. Puedes usar [Pydantic](https://docs.pydantic.dev/latest/) para declarar las entradas y salidas de tus métodos y garantizar seguridad de tipos.
-### Interfaz del Juego: Sitio web
+### Agregar la interfaz de usuario del juego
-Crearemos la interfaz de usuario. Ejecuta:
+Para interactuar con el juego, crea la UI usando el generador de sitios web CloudScape.
+Para hacerlo, crea un sitio web llamado `GameUI` siguiendo estos pasos:
-Verás nuevos archivos en tu árbol.
-
-Archivos clave generados:
+Verás nuevos archivos aparecer en tu árbol de archivos.
+
+
+A continuación se muestra una lista de todos los archivos generados por el generador `ts#cloudscape-website`. Examinemos algunos archivos clave resaltados en el árbol:
- packages/
- common/
- constructs/
- src/
- - app/
+ - app/ constructs CDK específicos de la aplicación
- static-websites/
- - **game-ui.ts** constructo CDK para Game UI
+ - **game-ui.ts** construct CDK para crear tu Game UI
- core/
- - static-website.ts constructo genérico
+ - static-website.ts construct genérico para sitios estáticos
- game-ui/
- public/
- src/
- components/
- AppLayout/
- - index.ts layout general
- - navitems.ts elementos de navegación
+ - index.ts diseño general de página: encabezado, pie, barra lateral, etc.
+ - navitems.ts elementos de navegación de la barra lateral
- hooks/
- - useAppLayout.tsx configura notificaciones, estilo de página
- - routes/ rutas @tanstack/react-router
- - index.tsx redirige a '/welcome'
- - __root.tsx componente base
+ - useAppLayout.tsx permite configurar dinámicamente notificaciones, estilo de página, etc.
+ - routes/ rutas basadas en archivos de @tanstack/react-router
+ - index.tsx página raíz '/' redirige a '/welcome'
+ - __root.tsx todas las páginas usan este componente como base
- welcome/
- **index.tsx**
- config.ts
- - **main.tsx** entrada React
- - routeTree.gen.ts generado automáticamente
+ - **main.tsx** punto de entrada de React
+ - routeTree.gen.ts este archivo se actualiza automáticamente por @tanstack/react-router
- styles.css
- index.html
- project.json
@@ -361,7 +371,7 @@ Archivos clave generados:
```ts
-// packages/common/constructs/src/app/static-wewebsites/game-ui.ts
+// packages/common/constructs/src/app/static-websites/game-ui.ts
import * as url from 'url';
import { Construct } from 'constructs';
import { StaticWebsite } from '../../core/index.js';
@@ -380,7 +390,7 @@ export class GameUI extends StaticWebsite {
}
```
-Constructo CDK para GameUI. Usa bundle Vite generado.
+Este es el construct CDK que define nuestro GameUI. Como puedes ver, ya ha configurado la ruta al bundle generado para nuestra UI basada en Vite. Esto significa que en tiempo de `build`, el bundling ocurre dentro del target build del proyecto game-ui y su salida se usa aquí.
```tsx
// packages/game-ui/src/main.tsx
@@ -395,6 +405,7 @@ import '@cloudscape-design/global-styles/index.css';
const router = createRouter({ routeTree });
+// Registrar la instancia del router para seguridad de tipos
declare module '@tanstack/react-router' {
interface Register {
router: typeof router;
@@ -412,7 +423,7 @@ root &&
);
```
-Entrada React con [enrutamiento basado en archivos](https://tanstack.com/router/v1/docs/framework/react/routing/file-based-routing).
+Este es el punto de entrada donde se monta React. Como se muestra, inicialmente solo configura un `@tanstack/react-router` en una configuración de [`enrutamiento-basado-en-archivos`](https://tanstack.com/router/v1/docs/framework/react/routing/file-based-routing). Esto significa que, mientras tu servidor de desarrollo esté en ejecución, puedes simplemente crear archivos dentro de la carpeta `routes` y `@tanstack/react-router` creará la configuración boilerplate por ti junto con actualizar el archivo `routeTree.gen.ts`. Este archivo mantiene todas las rutas de manera type-safe, lo que significa que cuando uses ``, la opción `to` solo mostrará rutas válidas. Para más información, consulta la documentación de [`@tanstack/react-router`](https://tanstack.com/router/v1/docs/framework/react/quick-start).
```tsx
// packages/game-ui/src/routes/welcome/index.tsx
@@ -432,54 +443,70 @@ function RouteComponent() {
return (
Welcome}>
- ¡Bienvenido a tu nuevo sitio Cloudscape!
+ ¡Bienvenido a tu nuevo sitio web Cloudscape!
);
}
```
-Componente para la ruta `/welcome`.
+Un componente que se renderizará al navegar a la ruta `/welcome`. `@tanstack/react-router` gestionará la `Route` por ti cuando crees/muevas este archivo (siempre que el servidor de desarrollo esté en ejecución). Esto se mostrará en una sección posterior de este tutorial.
-### Interfaz del Juego: Autenticación
+### Agregar autenticación a la interfaz de usuario
-Habilitamos autenticación con Cognito:
+Para configurar nuestra Game UI con acceso autenticado vía Amazon Cognito, usa estos pasos:
-Cambios en el árbol de archivos.
-
+Verás nuevos archivos aparecer en tu árbol de archivos.
+
+
+A continuación se muestra una lista de todos los archivos generados/actualizados por el generador `ts#cloudscape-website#auth`. Examinemos algunos archivos clave resaltados en el árbol:
- packages/
- common/
- constructs/
- src/
- core/
- - user-identity.ts constructo CDK para pools de identidad
+ - user-identity.ts construct CDK para crear pools de usuarios/identidad
- types/
- src/
- - runtime-config.ts añade cognitoProps
+ - runtime-config.ts actualizado para agregar cognitoProps
- game-ui/
- src/
- components/
- AppLayout/
- - index.tsx añade usuario/logout
+ - index.tsx agrega el usuario logueado/logout al encabezado
- CognitoAuth/
- - index.ts manejo de login
+ - index.ts gestiona el login en Cognito
- RuntimeConfig/
- - index.tsx obtiene runtime-config.json
+ - index.tsx obtiene el `runtime-config.json` y lo provee a los hijos mediante contexto
- hooks/
- useRuntimeConfig.tsx
- - **main.tsx** Actualizado con Cognito
+ - **main.tsx** Actualizado para agregar Cognito
```diff lang="tsx"
// packages/game-ui/src/main.tsx
+import CognitoAuth from './components/CognitoAuth';
+import RuntimeConfigProvider from './components/RuntimeConfig';
-...
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { I18nProvider } from '@cloudscape-design/components/i18n';
+import messages from '@cloudscape-design/components/i18n/messages/all.en';
+import { RouterProvider, createRouter } from '@tanstack/react-router';
+import { routeTree } from './routeTree.gen';
+import '@cloudscape-design/global-styles/index.css';
+const router = createRouter({ routeTree });
+// Registrar la instancia del router para seguridad de tipos
+declare module '@tanstack/react-router' {
+ interface Register {
+ router: typeof router;
+ }
+}
+const root = document.getElementById('root');
root &&
createRoot(root).render(
@@ -494,42 +521,49 @@ root &&
);
```
-Componentes añadidos mediante transformación AST para autenticación.
+Los componentes `RuntimeConfigProvider` y `CognitoAuth` han sido agregados al archivo `main.tsx` mediante una transformación AST. Esto permite que el componente `CognitoAuth` se autentique con Amazon Cognito obteniendo el `runtime-config.json` que contiene la configuración de conexión requerida para realizar llamadas al backend al destino correcto.
-### Interfaz del Juego: Conexión a Story API
+### Configurar Game UI para conectarse a la API de Historia
-Conectamos la UI a Story API:
+Para configurar nuestra Game UI para conectarse a nuestra API de Historia previamente creada, usa estos pasos:
-Cambios en el árbol.
-
+Verás nuevos archivos aparecer en tu árbol de archivos.
+
+
+A continuación se muestra una lista de todos los archivos generados/actualizados por el generador `api-connection`. Examinemos algunos archivos clave resaltados en el árbol:
- packages/
- game-ui/
- src/
- hooks/
- - useSigV4.tsx firma de requests
- - useStoryApiClient.tsx cliente StoryApi
- - useStoryApi.tsx hook con TanStack Query
+ - useSigV4.tsx usado por StoryApi para firmar requests
+ - useStoryApiClient.tsx hook para construir un cliente StoryApi
+ - useStoryApi.tsx hook para interactuar con StoryApi usando TanStack Query
- components/
- - QueryClientProvider.tsx Proveedor TanStack
- - StoryApiProvider.tsx Proveedor hooks
- - main.tsx Inyecta proveedores
- - .gitignore ignora archivos generados
- - project.json targets para generar hooks
+ - QueryClientProvider.tsx proveedor del cliente TanStack Query
+ - StoryApiProvider.tsx Proveedor para el hook TanStack Query de StoryApi
+ - main.tsx Instrumentar QueryClientProvider y StoryApiProvider
+ - .gitignore ignorar archivos cliente generados
+ - project.json actualizado para agregar targets para generar hooks openapi
+ - ...
- story_api/
- scripts/
- generate_open_api.py
- - project.json genera openapi.json
+ - project.json actualizado para emitir un archivo openapi.json
+
```tsx {1,12-15}
// packages/game-ui/src/hooks/useStoryApiClient.tsx
import { StoryApi } from '../generated/story-api/client.gen';
-...
+import { useSigV4 } from './useSigV4';
+import { useRuntimeConfig } from './useRuntimeConfig';
+import { useMemo } from 'react';
+
export const useStoryApi = (): StoryApi => {
const runtimeConfig = useRuntimeConfig();
const apiUrl = runtimeConfig.httpApis.StoryApi;
@@ -545,11 +579,18 @@ export const useStoryApi = (): StoryApi => {
};
```
-Hook para llamadas autenticadas a StoryApi. Cliente generado automáticamente.
+Puedes usar este hook para hacer requests autenticadas a la `StoryApi`. Usa el `StoryApi` que se genera en tiempo de build, y verás un error en tu IDE hasta que compilemos nuestro código. Para más detalles sobre cómo se genera el cliente o cómo consumir la API, consulta la guía de React a FastAPI.
```tsx
// packages/game-ui/src/components/StoryApiProvider.tsx
-...
+import { createContext, FC, PropsWithChildren, useMemo } from 'react';
+import { useStoryApiClient } from '../hooks/useStoryApiClient';
+import { StoryApiOptionsProxy } from '../generated/story-api/options-proxy.gen';
+
+export const StoryApiContext = createContext(
+ undefined,
+);
+
export const StoryApiProvider: FC = ({ children }) => {
const client = useStoryApiClient();
const optionsProxy = useMemo(
@@ -563,24 +604,30 @@ export const StoryApiProvider: FC = ({ children }) => {
);
};
+
+export default StoryApiProvider;
```
-Proveedor para hooks de TanStack Query.
+El componente proveedor anterior usa el hook `useStoryApiClient` e instancia el `StoryApiOptionsProxy`, que se usa para construir opciones para los hooks de TanStack Query. Puedes usar el hook correspondiente `useStoryApi` para acceder a este proxy de opciones, que proporciona una manera de interactuar con tu FastAPI de forma consistente con tu API tRPC.
+
+Dado que `useStoryApiClient` nos provee un iterador asíncrono para nuestra API de streaming, en este tutorial simplemente usaremos el cliente vanilla directamente.
-### Interfaz del Juego: Conexión a Game API
+### Configurar Game UI para conectarse a la API del Juego
-Conectamos UI a Game API:
+Para configurar nuestra Game UI para conectarse a nuestra API del Juego, usa estos pasos:
-Cambios en el árbol.
-
+Deberías ver algunos archivos nuevos haber aparecido/cambiado en tu árbol de archivos.
+
+
+A continuación se muestra una lista de todos los archivos generados/actualizados por el generador `api-connection`. Examinemos algunos archivos clave resaltados en el árbol:
- packages/
- game-ui/
@@ -588,13 +635,14 @@ Cambios en el árbol.
- components/
- TrpcClients/
- index.tsx
- - TrpcApis.tsx APIs tRPC
- - TrpcClientProviders.tsx Proveedores por API
+ - TrpcApis.tsx todas las APIs tRPC configuradas
+ - TrpcClientProviders.tsx crea un proveedor de cliente por API tRPC
- TrpcProvider.tsx
- hooks/
- - **useGameApi.tsx** hooks para GameApi
- - **main.tsx** Inyecta proveedores
+ - **useGameApi.tsx** hooks para llamar a la GameApi
+ - **main.tsx** inyecta los proveedores de clientes trpc
- package.json
+
```tsx
@@ -604,17 +652,36 @@ import { TrpcApis } from '../components/TrpcClients';
export const useGameApi = () => TrpcApis.GameApi.useTRPC();
```
-Hook usando [React Query integration](https://trpc.io/blog/introducing-tanstack-react-query-client).
+Este hook usa la última [integración React Query de tRPC](https://trpc.io/blog/introducing-tanstack-react-query-client) permitiendo a los usuarios interactuar con `@tanstack/react-query` directamente sin capas adicionales de abstracción. Para ejemplos de cómo llamar APIs tRPC, consulta la guía de uso del hook tRPC.
```diff lang="tsx"
// packages/game-ui/src/main.tsx
+import TrpcClientProviders from './components/TrpcClients';
+import QueryClientProvider from './components/QueryClientProvider';
-...
+import CognitoAuth from './components/CognitoAuth';
+import RuntimeConfigProvider from './components/RuntimeConfig';
+import React from 'react';
+import { createRoot } from 'react-dom/client';
+import { I18nProvider } from '@cloudscape-design/components/i18n';
+import messages from '@cloudscape-design/components/i18n/messages/all.en';
+import { RouterProvider, createRouter } from '@tanstack/react-router';
+import { routeTree } from './routeTree.gen';
+import '@cloudscape-design/global-styles/index.css';
+const router = createRouter({ routeTree });
+// Registrar la instancia del router para seguridad de tipos
+declare module '@tanstack/react-router' {
+ interface Register {
+ router: typeof router;
+ }
+}
+const root = document.getElementById('root');
+root &&
+ createRoot(root).render(
+
@@ -626,20 +693,24 @@ Hook usando [React Query integration](https://trpc.io/blog/introducing-tanstack-
+ ,
+ );
```
-Proveedores tRPC añadidos mediante AST.
+El archivo `main.tsx` ha sido actualizado mediante una transformación AST para inyectar los proveedores tRPC.
-### Infraestructura del Juego
+### Crear infraestructura CDK para la interfaz de usuario
-Creamos la infraestructura CDK:
+Para crear la infraestructura CDK como subproyecto final, usa estos pasos:
-Cambios en el árbol.
-
+Deberías ver algunos archivos nuevos haber aparecido/cambiado en tu árbol de archivos.
+
+
+A continuación se muestra una lista de todos los archivos generados/actualizados por el generador `ts#infra`. Examinemos algunos archivos clave resaltados en el árbol:
- packages/
- common/
@@ -653,21 +724,32 @@ Cambios en el árbol.
- infra
- src/
- stacks/
- - **application-stack.ts** recursos CDK
+ - **application-stack.ts** recursos CDK definidos aquí
- index.ts
- - **main.ts** entrada CDK
+ - **main.ts** punto de entrada que define todos los stacks
- cdk.json
- project.json
- ...
+ - package.json
+ - tsconfig.json agregar referencias
+ - tsconfig.base.json agregar alias
+
```ts
// packages/infra/src/main.ts
-...
+import { ApplicationStack } from './stacks/application-stack.js';
+import {
+ App,
+ CfnGuardValidator,
+ RuleSet,
+} from ':dungeon-adventure/common-constructs';
+
const app = new App({
policyValidationBeta1: [new CfnGuardValidator(RuleSet.AWS_PROTOTYPING)],
});
+// Usa esto para desplegar tu propio entorno sandbox (asume tus credenciales CLI)
new ApplicationStack(app, 'dungeon-adventure-infra-sandbox', {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
@@ -675,36 +757,57 @@ new ApplicationStack(app, 'dungeon-adventure-infra-sandbox', {
},
crossRegionReferences: true,
});
+
+app.synth();
```
-Entrada CDK con validación [cfn-guard](https://github.com/cdklabs/cdk-validator-cfnguard).
+Este es el punto de entrada para tu aplicación CDK. Está configurado para usar [`cfn-guard`](https://github.com/cdklabs/cdk-validator-cfnguard) para ejecutar validación de infraestructura basada en el conjunto de reglas configurado. Esto se instrumenta post síntesis.
```ts
// packages/infra/src/stacks/application-stack.ts
-...
+import * as cdk from 'aws-cdk-lib';
+import { Construct } from 'constructs';
+
export class ApplicationStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
- // Código de tu stack aquí
+ // El código que define tu stack va aquí
}
}
```
-Aquí instanciaremos nuestros constructos CDK.
+Aquí es donde instanciamos nuestros constructs CDK para construir nuestro juego de aventuras dungeon.
-#### Actualizar infraestructura
+#### Actualizar infraestructura CDK
-Actualizamos `application-stack.ts`:
+Para instanciar algunos de nuestros constructs ya generados, actualicemos nuestro `packages/infra/src/stacks/application-stack.ts`:
```diff lang="ts"
+import {
@@ -713,33 +816,45 @@ Actualizamos `application-stack.ts`:
+ StoryApi,
+ UserIdentity,
+} from ':dungeon-adventure/common-constructs';
-...
+import * as cdk from 'aws-cdk-lib';
+import { Construct } from 'constructs';
+
+export class ApplicationStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
+- // El código que define tu stack va aquí
+ const userIdentity = new UserIdentity(this, 'UserIdentity');
++
+ const gameApi = new GameApi(this, 'GameApi');
+ const storyApi = new StoryApi(this, 'StoryApi');
+
++ // otorgar a nuestro rol autenticado acceso para invocar nuestras APIs
+ [storyApi, gameApi].forEach((api) =>
+ api.grantInvokeAccess(userIdentity.identityPool.authenticatedRole),
+ );
+
++ // Asegurar que esto se instancie al final para que nuestro runtime-config.json se configure automáticamente
+ new GameUI(this, 'GameUI');
}
+}
+
```
-### Construir el código
+### Construyendo nuestro código
-
+
###### Targets únicos vs múltiples
-`run-many` ejecuta un target en múltiples proyectos (`--all` para todos). Ordena dependencias automáticamente.
+El comando `run-many` ejecutará un target en múltiples subproyectos listados (`--all` los seleccionará todos). Se asegurará que las dependencias se ejecuten en el orden correcto.
+
+También puedes disparar un build (o cualquier otra tarea) para un target de proyecto único ejecutando el target en el proyecto directamente. Por ejemplo, si queremos construir el proyecto `@dungeon-adventure/infra`, puedes ejecutar:
-Para un solo proyecto:
+###### Visualizando tus dependencias
+
+También puedes visualizar tus dependencias vía:
-###### Visualizar dependencias:
@@ -747,45 +862,71 @@ Para un solo proyecto:
###### Caché
-Nx usa [caché](https://nx.dev/concepts/how-caching-works). Para omitirla:
+Nx depende del [caché](https://nx.dev/concepts/how-caching-works) para que puedas reutilizar artefactos de builds previos y acelerar el desarrollo. Se requiere cierta configuración para que esto funcione correctamente y puede haber casos donde quieras realizar un build **sin usar el caché**. Para eso, simplemente agrega el argumento `--skip-nx-cache` a tu comando. Por ejemplo:
+
+Si por alguna razón quisieras borrar tu caché (almacenado en la carpeta `.nx`), puedes ejecutar:
-Limpiar caché:
-Se te preguntará:
+Se te presentará lo siguiente:
```bash
NX The workspace is out of sync
-[@nx/js:typescript-sync]: Faltan referencias en tsconfig.json
+[@nx/js:typescript-sync]: Some TypeScript configuration files are missing project references to the projects they depend on or contain outdated project references.
-? ¿Quieres sincronizar los cambios? …
-Sí, sincronizar y ejecutar tareas
-No, ejecutar sin sincronizar
+This will result in an error in CI.
+
+? Would you like to sync the identified changes to get your workspace up to date? …
+Yes, sync the changes and run the tasks
+No, run the tasks without syncing the changes
```
-Selecciona **Sí** para resolver errores de importación.
+Este mensaje indica que NX ha detectado algunos archivos que pueden actualizarse automáticamente. En este caso, se refiere a los archivos `tsconfig.json` que no tienen referencias de TypeScript configuradas en proyectos dependientes. Selecciona la opción **Yes, sync the changes and run the tasks** para proceder. Deberías notar que todos los errores de importación en tu IDE se resuelven automáticamente, ¡ya que el generador sync agregará las referencias faltantes de TypeScript!
-