diff --git a/docs/api/04-standard-library/cloud/service.md b/docs/api/04-standard-library/cloud/service.md index 72fd7427fb3..b3ee75638b6 100644 --- a/docs/api/04-standard-library/cloud/service.md +++ b/docs/api/04-standard-library/cloud/service.md @@ -119,7 +119,10 @@ Within the context of the simulator, services are just spawned processes ran wit ### AWS (`tf-aws` and `awscdk`) -🚧 Not supported yet (tracking issue: [#1306](https://github.com/winglang/wing/issues/1306)) +Within the context of AWS, services are created using AWS ECS, with a capacity provider of FARGATE. This also requires a VPC and a related resources +such as security groups, subnets, and an internet gateway, etc. If a VPC is not specified in `wing.toml`, a default VPC will be created. + +The inflight closures are packaged up into a docker image and pushed to an AWS ECR repository. ### Azure (`tf-azure`) diff --git a/docs/docs/04-standard-library/aws/api-reference.md b/docs/docs/04-standard-library/aws/api-reference.md deleted file mode 100644 index c6ad1fb16c9..00000000000 --- a/docs/docs/04-standard-library/aws/api-reference.md +++ /dev/null @@ -1,2189 +0,0 @@ ---- -title: API reference -id: api-reference -description: Wing standard library API reference for the aws module -keywords: [Wing sdk, sdk, Wing API Reference] -hide_title: true -sidebar_position: 100 ---- - - -# API Reference - -## Resources - -### BucketRef - -A reference to an external S3 bucket. - -#### Initializers - -```wing -bring aws; - -new aws.BucketRef(bucketName: str); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| bucketName | str | *No description.* | - ---- - -##### `bucketName`Required - -- *Type:* str - ---- - -#### Methods - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| bucketRegion | Get the region of the bucket. | - ---- - -##### `bucketRegion` - -```wing -inflight bucketRegion(): str -``` - -Get the region of the bucket. - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring aws; - -aws.BucketRef.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring aws; - -aws.BucketRef.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| bucketArn | str | The ARN of this bucket. | -| bucketName | str | The Name of this bucket. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `bucketArn`Required - -```wing -bucketArn: str; -``` - -- *Type:* str - -The ARN of this bucket. - ---- - -##### `bucketName`Required - -```wing -bucketName: str; -``` - -- *Type:* str - -The Name of this bucket. - ---- - - -### Domain - -AWS implementation of `cloud.Domain`. - -#### Initializers - -```wing -bring aws; - -new aws.Domain(props: DomainProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | DomainProps | *No description.* | - ---- - -##### `props`Required - -- *Type:* DomainProps - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring aws; - -aws.Domain.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring aws; - -aws.Domain.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| domainName | str | The domain name. | -| acmCertificateArn | str | The AWS Certificate Manager (ACM) certificate arn value. | -| hostedZoneId | str | The hosted zone id value. | -| iamCertificate | str | The IAM certificate identifier value. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `domainName`Required - -```wing -domainName: str; -``` - -- *Type:* str - -The domain name. - ---- - -##### `acmCertificateArn`Optional - -```wing -acmCertificateArn: str; -``` - -- *Type:* str - -The AWS Certificate Manager (ACM) certificate arn value. - ---- - -##### `hostedZoneId`Optional - -```wing -hostedZoneId: str; -``` - -- *Type:* str - -The hosted zone id value. - ---- - -##### `iamCertificate`Optional - -```wing -iamCertificate: str; -``` - -- *Type:* str - -The IAM certificate identifier value. - ---- - - -### FunctionRef - -A reference to an external Lambda function. - -#### Initializers - -```wing -bring aws; - -new aws.FunctionRef(functionArn: str); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| functionArn | str | *No description.* | - ---- - -##### `functionArn`Required - -- *Type:* str - ---- - -#### Methods - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| invoke | Invokes the function with a payload and waits for the result. | -| invokeAsync | Kicks off the execution of the function with a payload and returns immediately while the function is running. | - ---- - -##### `invoke` - -```wing -inflight invoke(payload?: str): str? -``` - -Invokes the function with a payload and waits for the result. - -###### `payload`Optional - -- *Type:* str - -payload to pass to the function. - -If not defined, an empty string will be passed. - ---- - -##### `invokeAsync` - -```wing -inflight invokeAsync(payload?: str): void -``` - -Kicks off the execution of the function with a payload and returns immediately while the function is running. - -###### `payload`Optional - -- *Type:* str - -payload to pass to the function. - -If not defined, an empty string will be passed. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring aws; - -aws.FunctionRef.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring aws; - -aws.FunctionRef.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| functionArn | str | The ARN of this function. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `functionArn`Required - -```wing -functionArn: str; -``` - -- *Type:* str - -The ARN of this function. - ---- - - -### QueueRef - -A reference to an external SQS queue. - -#### Initializers - -```wing -bring aws; - -new aws.QueueRef(queueArn: str); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| queueArn | str | *No description.* | - ---- - -##### `queueArn`Required - -- *Type:* str - ---- - -#### Methods - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| queueUrl | Get the queue URL. | - ---- - -##### `queueUrl` - -```wing -inflight queueUrl(): str -``` - -Get the queue URL. - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring aws; - -aws.QueueRef.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring aws; - -aws.QueueRef.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| queueArn | str | The ARN of this queue. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `queueArn`Required - -```wing -queueArn: str; -``` - -- *Type:* str - -The ARN of this queue. - ---- - - -### SecretRef - -A reference to an existing secret. - -#### Initializers - -```wing -bring aws; - -new aws.SecretRef(secretArn: str); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| secretArn | str | *No description.* | - ---- - -##### `secretArn`Required - -- *Type:* str - ---- - -#### Methods - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| value | Retrieve the value of the secret. | -| valueJson | Retrieve the Json value of the secret. | - ---- - -##### `value` - -```wing -inflight value(options?: GetSecretValueOptions): str -``` - -Retrieve the value of the secret. - -###### `options`Optional - -- *Type:* GetSecretValueOptions - ---- - -##### `valueJson` - -```wing -inflight valueJson(options?: GetSecretValueOptions): Json -``` - -Retrieve the Json value of the secret. - -###### `options`Optional - -- *Type:* GetSecretValueOptions - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring aws; - -aws.SecretRef.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring aws; - -aws.SecretRef.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| secretArn | str | The ARN of the secret. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `secretArn`Required - -```wing -secretArn: str; -``` - -- *Type:* str - -The ARN of the secret. - ---- - - -## Classes - -### Api - -A helper class for working with AWS apis. - -#### Initializers - -```wing -bring aws; - -new aws.Api(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| from | If the api is an AWS RestApi, return a helper interface for working with it. | - ---- - -##### `from` - -```wing -bring aws; - -aws.Api.from(api: Api); -``` - -If the api is an AWS RestApi, return a helper interface for working with it. - -###### `api`Required - -- *Type:* Api - -The cloud.Api. - ---- - - - -### ApiEndpointHandler - -A helper class for working with AWS api endpoint handlers. - -#### Initializers - -```wing -bring aws; - -new aws.ApiEndpointHandler(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| toFunctionHandler | Returns a `cloud.Function` handler for handling requests from a `cloud.Api`. | - ---- - -##### `toFunctionHandler` - -```wing -bring aws; - -aws.ApiEndpointHandler.toFunctionHandler(handler: IApiEndpointHandler, headers?: MutMap); -``` - -Returns a `cloud.Function` handler for handling requests from a `cloud.Api`. - -###### `handler`Required - -- *Type:* IApiEndpointHandler - -The `onRequest` handler. - ---- - -###### `headers`Optional - -- *Type:* MutMap<str> - -HTTP response headers to add to all responses (used by CORS). - ---- - - - -### AwsInflightHost - -Represents an inflight host on AWS. - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| isAwsInflightHost | Returns `true` if `obj` implements `IAwsInflightHost`. | - ---- - -##### `isAwsInflightHost` - -```wing -bring aws; - -aws.AwsInflightHost.isAwsInflightHost(obj: any); -``` - -Returns `true` if `obj` implements `IAwsInflightHost`. - -###### `obj`Required - -- *Type:* any - ---- - - - -### Bucket - -A helper class for working with AWS buckets. - -#### Initializers - -```wing -bring aws; - -new aws.Bucket(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| from | If the bucket is an AWS Bucket, return a helper interface for working with it. | - ---- - -##### `from` - -```wing -bring aws; - -aws.Bucket.from(bucket: Bucket); -``` - -If the bucket is an AWS Bucket, return a helper interface for working with it. - -###### `bucket`Required - -- *Type:* Bucket - -The cloud.Bucket. - ---- - - - -### BucketEventHandler - -Utility class to work with bucket event handlers. - -#### Initializers - -```wing -bring aws; - -new aws.BucketEventHandler(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| toTopicOnMessageHandler | Converts a `cloud.IBucketEventHandler` to a `cloud.ITopicOnMessageHandler`. | - ---- - -##### `toTopicOnMessageHandler` - -```wing -bring aws; - -aws.BucketEventHandler.toTopicOnMessageHandler(handler: IBucketEventHandler, eventType: BucketEventType); -``` - -Converts a `cloud.IBucketEventHandler` to a `cloud.ITopicOnMessageHandler`. - -###### `handler`Required - -- *Type:* IBucketEventHandler - -the handler to convert. - ---- - -###### `eventType`Required - -- *Type:* BucketEventType - -the event type. - ---- - - - -### Counter - -A helper class for working with AWS Counters. - -#### Initializers - -```wing -bring aws; - -new aws.Counter(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| from | If the table is an AWS Counter, return a helper interface for working with it. | - ---- - -##### `from` - -```wing -bring aws; - -aws.Counter.from(counter: Counter); -``` - -If the table is an AWS Counter, return a helper interface for working with it. - -###### `counter`Required - -- *Type:* Counter - -The cloud.Counter. - ---- - - - -### Function - -A helper class for working with AWS functions. - -#### Initializers - -```wing -bring aws; - -new aws.Function(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| context | Returns the current Lambda invocation context, if the host is an AWS Lambda. | -| from | If the inflight host is an AWS Lambda, return a helper interface for working with it. | - ---- - -##### `context` - -```wing -bring aws; - -aws.Function.context(); -``` - -Returns the current Lambda invocation context, if the host is an AWS Lambda. - -> [https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html) - -##### `from` - -```wing -bring aws; - -aws.Function.from(host: IInflightHost); -``` - -If the inflight host is an AWS Lambda, return a helper interface for working with it. - -###### `host`Required - -- *Type:* IInflightHost - -The inflight host. - ---- - - - -### Queue - -A helper class for working with AWS queues. - -#### Initializers - -```wing -bring aws; - -new aws.Queue(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| from | If the queue is an AWS SQS, return a helper interface for working with it. | - ---- - -##### `from` - -```wing -bring aws; - -aws.Queue.from(queue: Queue); -``` - -If the queue is an AWS SQS, return a helper interface for working with it. - -###### `queue`Required - -- *Type:* Queue - -The cloud.Queue. - ---- - - - -### QueueSetConsumerHandler - -Utility class for working with the queue consumer handler. - -#### Initializers - -```wing -bring aws; - -new aws.QueueSetConsumerHandler(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| toFunctionHandler | Converts a queue consumer handler to a function handler. | - ---- - -##### `toFunctionHandler` - -```wing -bring aws; - -aws.QueueSetConsumerHandler.toFunctionHandler(handler: IQueueSetConsumerHandler); -``` - -Converts a queue consumer handler to a function handler. - -###### `handler`Required - -- *Type:* IQueueSetConsumerHandler - -The queue consumer handler. - ---- - - - -### Table - -A helper class for working with AWS tables. - -#### Initializers - -```wing -bring aws; - -new aws.Table(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| from | If the table is an AWS DynamoDB, return a helper interface for working with it. | - ---- - -##### `from` - -```wing -bring aws; - -aws.Table.from(table: Table); -``` - -If the table is an AWS DynamoDB, return a helper interface for working with it. - -###### `table`Required - -- *Type:* Table - -The ex.Table. - ---- - - - -### Topic - -A helper class for working with AWS topics. - -#### Initializers - -```wing -bring aws; - -new aws.Topic(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| from | If the topic is an AWS SNS, return a helper interface for working with it. | - ---- - -##### `from` - -```wing -bring aws; - -aws.Topic.from(topic: Topic); -``` - -If the topic is an AWS SNS, return a helper interface for working with it. - -###### `topic`Required - -- *Type:* Topic - -The cloud.Topic. - ---- - - - -### TopicOnMessageHandler - -A helper class for working with AWS topic on message handlers. - -#### Initializers - -```wing -bring aws; - -new aws.TopicOnMessageHandler(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| toFunctionHandler | Returns a `cloud.Function` handler for handling messages from a `cloud.Topic`. | - ---- - -##### `toFunctionHandler` - -```wing -bring aws; - -aws.TopicOnMessageHandler.toFunctionHandler(handler: ITopicOnMessageHandler); -``` - -Returns a `cloud.Function` handler for handling messages from a `cloud.Topic`. - -###### `handler`Required - -- *Type:* ITopicOnMessageHandler - -The `onMessage` handler. - ---- - - - -### Website - -A helper class for working with AWS buckets. - -#### Initializers - -```wing -bring aws; - -new aws.Website(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| from | If the bucket is an AWS Bucket, return a helper interface for working with it. | - ---- - -##### `from` - -```wing -bring aws; - -aws.Website.from(website: Website); -``` - -If the bucket is an AWS Bucket, return a helper interface for working with it. - -###### `website`Required - -- *Type:* Website - -The cloud.Bucket. - ---- - - - -## Structs - -### AwsWebsiteProps - -Options for AWS `Website`. - -#### Initializer - -```wing -bring aws; - -let AwsWebsiteProps = aws.AwsWebsiteProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| path | str | Local path to the website's static files, relative to the Wing source file or absolute. | -| errorDocument | str | Name of the error document for the website. | -| domain | Domain | The website's custom domain object. | - ---- - -##### `path`Required - -```wing -path: str; -``` - -- *Type:* str - -Local path to the website's static files, relative to the Wing source file or absolute. - ---- - -*Example* - -```wing -"./dist" -``` - - -##### `errorDocument`Optional - -```wing -errorDocument: str; -``` - -- *Type:* str -- *Default:* undefined - -Name of the error document for the website. - ---- - -*Example* - -```wing -"404.html" -``` - - -##### `domain`Optional - -```wing -domain: Domain; -``` - -- *Type:* Domain -- *Default:* undefined - -The website's custom domain object. - ---- - -### NetworkConfig - -Function network configuration used to hold data on subnets and security groups that should be used when a function is deployed within a VPC. - -#### Initializer - -```wing -bring aws; - -let NetworkConfig = aws.NetworkConfig{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| securityGroupIds | MutArray<str> | List of security groups to place function in. | -| subnetIds | MutArray<str> | List of subnets to attach on function. | - ---- - -##### `securityGroupIds`Required - -```wing -securityGroupIds: MutArray; -``` - -- *Type:* MutArray<str> - -List of security groups to place function in. - ---- - -##### `subnetIds`Required - -```wing -subnetIds: MutArray; -``` - -- *Type:* MutArray<str> - -List of subnets to attach on function. - ---- - -### PolicyStatement - -AWS IAM Policy Statement. - -#### Initializer - -```wing -bring aws; - -let PolicyStatement = aws.PolicyStatement{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| actions | MutArray<str> | Actions. | -| effect | Effect | Effect ("Allow" or "Deny"). | -| resources | MutArray<str> | Resources. | - ---- - -##### `actions`Optional - -```wing -actions: MutArray; -``` - -- *Type:* MutArray<str> - -Actions. - ---- - -##### `effect`Optional - -```wing -effect: Effect; -``` - -- *Type:* Effect - -Effect ("Allow" or "Deny"). - ---- - -##### `resources`Optional - -```wing -resources: MutArray; -``` - -- *Type:* MutArray<str> - -Resources. - ---- - -## Protocols - -### IAwsApi - -- *Implemented By:* IAwsApi - -A shared interface for AWS api. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| deploymentId | str | RestApi deployment id. | -| invokeUrl | str | Invoke URL. | -| restApiArn | str | RestApi arn. | -| restApiId | str | RestApi id. | -| restApiName | str | RestApi id. | -| stageName | str | RestApi stage name. | - ---- - -##### `deploymentId`Required - -```wing -deploymentId: str; -``` - -- *Type:* str - -RestApi deployment id. - ---- - -##### `invokeUrl`Required - -```wing -invokeUrl: str; -``` - -- *Type:* str - -Invoke URL. - ---- - -##### `restApiArn`Required - -```wing -restApiArn: str; -``` - -- *Type:* str - -RestApi arn. - ---- - -##### `restApiId`Required - -```wing -restApiId: str; -``` - -- *Type:* str - -RestApi id. - ---- - -##### `restApiName`Required - -```wing -restApiName: str; -``` - -- *Type:* str - -RestApi id. - ---- - -##### `stageName`Required - -```wing -stageName: str; -``` - -- *Type:* str - -RestApi stage name. - ---- - -### IAwsBucket - -- *Implemented By:* IAwsBucket - -A shared interface for AWS buckets. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| bucketArn | str | AWS Bucket arn. | -| bucketName | str | AWS Bucket name. | - ---- - -##### `bucketArn`Required - -```wing -bucketArn: str; -``` - -- *Type:* str - -AWS Bucket arn. - ---- - -##### `bucketName`Required - -```wing -bucketName: str; -``` - -- *Type:* str - -AWS Bucket name. - ---- - -### IAwsCounter - -- *Implemented By:* IAwsCounter - -A shared interface for AWS Counter. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| dynamoTableArn | str | AWS Dynamodb arn. | -| dynamoTableName | str | AWS Dynamodb name. | - ---- - -##### `dynamoTableArn`Required - -```wing -dynamoTableArn: str; -``` - -- *Type:* str - -AWS Dynamodb arn. - ---- - -##### `dynamoTableName`Required - -```wing -dynamoTableName: str; -``` - -- *Type:* str - -AWS Dynamodb name. - ---- - -### IAwsFunction - -- *Extends:* IAwsInflightHost - -- *Implemented By:* IAwsFunction - -A shared interface for AWS functions. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| addLambdaLayer | Add a Lambda layer to the function. | - ---- - -##### `addLambdaLayer` - -```wing -addLambdaLayer(layerArn: str): void -``` - -Add a Lambda layer to the function. - -###### `layerArn`Required - -- *Type:* str - -The ARN of the layer. - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| functionArn | str | AWS Function arn. | -| functionName | str | AWS Function name. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `functionArn`Required - -```wing -functionArn: str; -``` - -- *Type:* str - -AWS Function arn. - ---- - -##### `functionName`Required - -```wing -functionName: str; -``` - -- *Type:* str - -AWS Function name. - ---- - -### IAwsInflightHost - -- *Extends:* IInflightHost - -- *Implemented By:* IAwsFunction, IAwsInflightHost - -Represents an `IInflightHost` on AWS. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| addNetwork | Adds the host to the specified network. | -| addPolicyStatements | Add policy statements to the function's IAM role. | - ---- - -##### `addNetwork` - -```wing -addNetwork(config: NetworkConfig): void -``` - -Adds the host to the specified network. - -###### `config`Required - -- *Type:* NetworkConfig - -The network configuration. - ---- - -##### `addPolicyStatements` - -```wing -addPolicyStatements(...policies: Array): void -``` - -Add policy statements to the function's IAM role. - -###### `policies`Required - -- *Type:* PolicyStatement - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -### IAwsQueue - -- *Implemented By:* IAwsQueue - -A shared interface for AWS queues. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| queueArn | str | AWS Queue arn. | -| queueName | str | AWS Queue name. | -| queueUrl | str | AWS Queue url. | - ---- - -##### `queueArn`Required - -```wing -queueArn: str; -``` - -- *Type:* str - -AWS Queue arn. - ---- - -##### `queueName`Required - -```wing -queueName: str; -``` - -- *Type:* str - -AWS Queue name. - ---- - -##### `queueUrl`Required - -```wing -queueUrl: str; -``` - -- *Type:* str - -AWS Queue url. - ---- - -### IAwsTable - -- *Implemented By:* IAwsTable - -A shared interface for AWS tables. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| dynamoTableArn | str | AWS Table arn. | -| dynamoTableName | str | AWS Table name. | - ---- - -##### `dynamoTableArn`Required - -```wing -dynamoTableArn: str; -``` - -- *Type:* str - -AWS Table arn. - ---- - -##### `dynamoTableName`Required - -```wing -dynamoTableName: str; -``` - -- *Type:* str - -AWS Table name. - ---- - -### IAwsTopic - -- *Implemented By:* IAwsTopic - -A shared interface for AWS topics. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| topicArn | str | AWS Topic arn. | -| topicName | str | AWS Topic name. | - ---- - -##### `topicArn`Required - -```wing -topicArn: str; -``` - -- *Type:* str - -AWS Topic arn. - ---- - -##### `topicName`Required - -```wing -topicName: str; -``` - -- *Type:* str - -AWS Topic name. - ---- - -### IAwsWebsite - -- *Implemented By:* IAwsWebsite - -A shared interface for AWS website. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| bucketArn | str | AWS Bucket arn. | -| bucketName | str | AWS Bucket name. | - ---- - -##### `bucketArn`Required - -```wing -bucketArn: str; -``` - -- *Type:* str - -AWS Bucket arn. - ---- - -##### `bucketName`Required - -```wing -bucketName: str; -``` - -- *Type:* str - -AWS Bucket name. - ---- - -### ILambdaContext - -- *Implemented By:* ILambdaContext - -The AWS Lambda context object. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| remainingTimeInMillis | Returns the number of milliseconds left before the execution times out. | - ---- - -##### `remainingTimeInMillis` - -```wing -remainingTimeInMillis(): num -``` - -Returns the number of milliseconds left before the execution times out. - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| awsRequestId | str | The identifier of the invocation request. | -| functionName | str | The name of the Lambda function. | -| functionVersion | str | The version of the function. | -| invokedFunctionArn | str | The Amazon Resource Name (ARN) that's used to invoke the function. | -| logGroupName | str | The log group for the function. | -| logStreamName | str | The log stream for the function instance. | -| memoryLimitInMB | str | The amount of memory that's allocated for the function. | - ---- - -##### `awsRequestId`Required - -```wing -awsRequestId: str; -``` - -- *Type:* str - -The identifier of the invocation request. - ---- - -##### `functionName`Required - -```wing -functionName: str; -``` - -- *Type:* str - -The name of the Lambda function. - ---- - -##### `functionVersion`Required - -```wing -functionVersion: str; -``` - -- *Type:* str - -The version of the function. - ---- - -##### `invokedFunctionArn`Required - -```wing -invokedFunctionArn: str; -``` - -- *Type:* str - -The Amazon Resource Name (ARN) that's used to invoke the function. - -Indicates if the invoker specified a version number or alias. - ---- - -##### `logGroupName`Required - -```wing -logGroupName: str; -``` - -- *Type:* str - -The log group for the function. - ---- - -##### `logStreamName`Required - -```wing -logStreamName: str; -``` - -- *Type:* str - -The log stream for the function instance. - ---- - -##### `memoryLimitInMB`Required - -```wing -memoryLimitInMB: str; -``` - -- *Type:* str - -The amount of memory that's allocated for the function. - ---- - -## Enums - -### Effect - -The Effect element of an AWS IAM policy statement. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| ALLOW | Allow. | -| DENY | Deny. | - ---- - -##### `ALLOW` - -Allow. - ---- - - -##### `DENY` - -Deny. - ---- - diff --git a/docs/docs/04-standard-library/cloud/api.md b/docs/docs/04-standard-library/cloud/api.md deleted file mode 100644 index 5127273d45e..00000000000 --- a/docs/docs/04-standard-library/cloud/api.md +++ /dev/null @@ -1,1887 +0,0 @@ ---- -title: Api -id: api -description: A built-in resource for creating HTTP endpoints in the cloud. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - APIs, - Endpoints, - HTTP endpoint, - ] -sidebar_position: 1 ---- - -The `cloud.Api` resource represents a collection of HTTP endpoints that can be invoked by clients over the internet. -APIs often serve as the front door for applications to access data, business logic, or functionality from your backend services. - -The `Api` resource models an endpoint as a collection of routes, each mapped to an event handler function. -A route is a combination of a path, like `"/users/:userid"` and a set of HTTP methods, like `GET`, `POST`, or `DELETE`. -When a client invokes a route, the corresponding event handler function executes. - -## Usage - -### REST API - -The following example shows a complete REST API implementation using `cloud.Api`, `ex.Table` & `cloud.Counter` - -```ts playground example -bring cloud; -bring ex; - -let api = new cloud.Api(); -// Used for generating unique id -let counter = new cloud.Counter(); -// our employee database -let db = new ex.Table( - name: "employees", - primaryKey: "id", - columns: { - "name" => ex.ColumnType.STRING - } -); - -api.get("/employees", inflight (request: cloud.ApiRequest): cloud.ApiResponse => { - let result = MutJson []; - let var i = 0; - for employee in db.list() { - result.setAt(i, employee); - i = i + 1; - } - return cloud.ApiResponse { - status: 200, - body: Json.stringify(result) - }; -}); - - -api.get("/employees/:id", inflight (request: cloud.ApiRequest): cloud.ApiResponse => { - let employee = db.get(request.vars.get("id")); - return cloud.ApiResponse { - status: 200, - body: Json.stringify(employee) - }; -}); - -api.post("/employees", inflight (request: cloud.ApiRequest): cloud.ApiResponse => { - if let body = request.body { - let employeeData = Json.parse(body); - let id = "{counter.inc()}"; - db.insert(id, employeeData); - return cloud.ApiResponse { - status: 201, - body: id - }; - } -}); - -api.put("/employees/:id", inflight (request: cloud.ApiRequest): cloud.ApiResponse => { - if let body = request.body { - let employeeData = Json.parse(body); - let id = request.vars.get("id"); - db.update(id, employeeData); - return cloud.ApiResponse { - status: 200, - body: Json.stringify(employeeData) - }; - } -}); - -api.delete("/employees/:id", inflight (request: cloud.ApiRequest): cloud.ApiResponse => { - let id = request.vars.get("id"); - db.delete(id); - return cloud.ApiResponse { - status: 204 - }; -}); -``` - -## Target-specific details - -### Simulator (`sim`) - -The sim implementation of `cloud.Api` uses [nodejs express](https://expressjs.com/). - -### AWS (`tf-aws` and `awscdk`) - -The AWS implementation of `cloud.Api` uses [Amazon API Gateway](https://aws.amazon.com/api-gateway/). - -### Azure (`tf-azure`) - -🚧 Not supported yet (tracking issue: [#625](https://github.com/winglang/wing/issues/625)) - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#624](https://github.com/winglang/wing/issues/624)) -## API Reference - -### Api - -Functionality shared between all `Api` implementations. - -#### Initializers - -```wing -bring cloud; - -new cloud.Api(props?: ApiProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | ApiProps | *No description.* | - ---- - -##### `props`Optional - -- *Type:* ApiProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| connect | Add a inflight handler to the api for CONNECT requests on the given path. | -| delete | Add a inflight handler to the api for DELETE requests on the given path. | -| get | Add a inflight handler to the api for GET requests on the given path. | -| head | Add a inflight handler to the api for HEAD requests on the given path. | -| options | Add a inflight handler to the api for OPTIONS requests on the given path. | -| patch | Add a inflight handler to the api for PATCH requests on the given path. | -| post | Add a inflight handler to the api for POST requests on the given path. | -| put | Add a inflight handler to the api for PUT requests on the given path. | - ---- - -##### `connect` - -```wing -connect(path: str, inflight: IApiEndpointHandler, props?: ApiConnectOptions): void -``` - -Add a inflight handler to the api for CONNECT requests on the given path. - -###### `path`Required - -- *Type:* str - -The path to handle CONNECT requests for. - ---- - -###### `inflight`Required - -- *Type:* IApiEndpointHandler - -The function to handle the request. - ---- - -###### `props`Optional - -- *Type:* ApiConnectOptions - -Options for the route. - ---- - -##### `delete` - -```wing -delete(path: str, inflight: IApiEndpointHandler, props?: ApiDeleteOptions): void -``` - -Add a inflight handler to the api for DELETE requests on the given path. - -###### `path`Required - -- *Type:* str - -The path to handle DELETE requests for. - ---- - -###### `inflight`Required - -- *Type:* IApiEndpointHandler - -The function to handle the request. - ---- - -###### `props`Optional - -- *Type:* ApiDeleteOptions - -Options for the route. - ---- - -##### `get` - -```wing -get(path: str, inflight: IApiEndpointHandler, props?: ApiGetOptions): void -``` - -Add a inflight handler to the api for GET requests on the given path. - -###### `path`Required - -- *Type:* str - -The path to handle GET requests for. - ---- - -###### `inflight`Required - -- *Type:* IApiEndpointHandler - -The function to handle the request. - ---- - -###### `props`Optional - -- *Type:* ApiGetOptions - -Options for the route. - ---- - -##### `head` - -```wing -head(path: str, inflight: IApiEndpointHandler, props?: ApiHeadOptions): void -``` - -Add a inflight handler to the api for HEAD requests on the given path. - -###### `path`Required - -- *Type:* str - -The path to handle HEAD requests for. - ---- - -###### `inflight`Required - -- *Type:* IApiEndpointHandler - -The function to handle the request. - ---- - -###### `props`Optional - -- *Type:* ApiHeadOptions - -Options for the route. - ---- - -##### `options` - -```wing -options(path: str, inflight: IApiEndpointHandler, props?: ApiOptionsOptions): void -``` - -Add a inflight handler to the api for OPTIONS requests on the given path. - -###### `path`Required - -- *Type:* str - -The path to handle OPTIONS requests for. - ---- - -###### `inflight`Required - -- *Type:* IApiEndpointHandler - -The function to handle the request. - ---- - -###### `props`Optional - -- *Type:* ApiOptionsOptions - -Options for the route. - ---- - -##### `patch` - -```wing -patch(path: str, inflight: IApiEndpointHandler, props?: ApiPatchOptions): void -``` - -Add a inflight handler to the api for PATCH requests on the given path. - -###### `path`Required - -- *Type:* str - -The path to handle PATCH requests for. - ---- - -###### `inflight`Required - -- *Type:* IApiEndpointHandler - -The function to handle the request. - ---- - -###### `props`Optional - -- *Type:* ApiPatchOptions - -Options for the route. - ---- - -##### `post` - -```wing -post(path: str, inflight: IApiEndpointHandler, props?: ApiPostOptions): void -``` - -Add a inflight handler to the api for POST requests on the given path. - -###### `path`Required - -- *Type:* str - -The path to handle POST requests for. - ---- - -###### `inflight`Required - -- *Type:* IApiEndpointHandler - -The function to handle the request. - ---- - -###### `props`Optional - -- *Type:* ApiPostOptions - -Options for the route. - ---- - -##### `put` - -```wing -put(path: str, inflight: IApiEndpointHandler, props?: ApiPutOptions): void -``` - -Add a inflight handler to the api for PUT requests on the given path. - -###### `path`Required - -- *Type:* str - -The path to handle PUT requests for. - ---- - -###### `inflight`Required - -- *Type:* IApiEndpointHandler - -The function to handle the request. - ---- - -###### `props`Optional - -- *Type:* ApiPutOptions - -Options for the route. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | -| renderCorsHeaders | Generates an object containing default CORS response headers and OPTIONS response headers. | -| renderOpenApiPath | Converts input path to a valid OpenAPI path (replaces `:` based path params with `{}`). | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Api.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Api.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -##### `renderCorsHeaders` - -```wing -bring cloud; - -cloud.Api.renderCorsHeaders(corsOptions?: ApiCorsOptions); -``` - -Generates an object containing default CORS response headers and OPTIONS response headers. - -###### `corsOptions`Optional - -- *Type:* ApiCorsOptions - -The CORS options to generate the headers from. - ---- - -##### `renderOpenApiPath` - -```wing -bring cloud; - -cloud.Api.renderOpenApiPath(path: str); -``` - -Converts input path to a valid OpenAPI path (replaces `:` based path params with `{}`). - -###### `path`Required - -- *Type:* str - -The path to convert (assumes path is valid). - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| url | str | The base URL of the API endpoint. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `url`Required - -```wing -url: str; -``` - -- *Type:* str - -The base URL of the API endpoint. - ---- - - - -## Structs - -### ApiConnectOptions - -Options for Api patch endpoint. - -#### Initializer - -```wing -bring cloud; - -let ApiConnectOptions = cloud.ApiConnectOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ApiCorsOptions - -Cors Options for `Api`. - -#### Initializer - -```wing -bring cloud; - -let ApiCorsOptions = cloud.ApiCorsOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| allowCredentials | bool | Whether to allow credentials. | -| allowHeaders | MutArray<str> | The list of allowed headers. | -| allowMethods | MutArray<HttpMethod> | The list of allowed methods. | -| allowOrigin | str | The allowed origin. | -| exposeHeaders | MutArray<str> | The list of exposed headers. | -| maxAge | duration | How long the browser should cache preflight request results. | - ---- - -##### `allowCredentials`Optional - -```wing -allowCredentials: bool; -``` - -- *Type:* bool -- *Default:* false - -Whether to allow credentials. - ---- - -##### `allowHeaders`Optional - -```wing -allowHeaders: MutArray; -``` - -- *Type:* MutArray<str> -- *Default:* ["Content-Type", "Authorization"] - -The list of allowed headers. - ---- - -*Example* - -```wing -["Content-Type"] -``` - - -##### `allowMethods`Optional - -```wing -allowMethods: MutArray; -``` - -- *Type:* MutArray<HttpMethod> -- *Default:* [HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.PATCH, HttpMethod.DELETE, HttpMethod.HEAD, HttpMethod.OPTIONS] - -The list of allowed methods. - ---- - -*Example* - -```wing -[HttpMethod.GET, HttpMethod.POST] -``` - - -##### `allowOrigin`Optional - -```wing -allowOrigin: str; -``` - -- *Type:* str -- *Default:* "*" - -The allowed origin. - ---- - -*Example* - -```wing -"https://example.com" -``` - - -##### `exposeHeaders`Optional - -```wing -exposeHeaders: MutArray; -``` - -- *Type:* MutArray<str> -- *Default:* [] - -The list of exposed headers. - ---- - -*Example* - -```wing -["Content-Type"] -``` - - -##### `maxAge`Optional - -```wing -maxAge: duration; -``` - -- *Type:* duration -- *Default:* 300 seconds - -How long the browser should cache preflight request results. - ---- - -### ApiDeleteOptions - -Options for Api put endpoint. - -#### Initializer - -```wing -bring cloud; - -let ApiDeleteOptions = cloud.ApiDeleteOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ApiEndpointOptions - -Base options for Api endpoints. - -#### Initializer - -```wing -bring cloud; - -let ApiEndpointOptions = cloud.ApiEndpointOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ApiGetOptions - -Options for Api get endpoint. - -#### Initializer - -```wing -bring cloud; - -let ApiGetOptions = cloud.ApiGetOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ApiHeadOptions - -Options for Api patch endpoint. - -#### Initializer - -```wing -bring cloud; - -let ApiHeadOptions = cloud.ApiHeadOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ApiOptionsOptions - -Options for Api patch endpoint. - -#### Initializer - -```wing -bring cloud; - -let ApiOptionsOptions = cloud.ApiOptionsOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ApiPatchOptions - -Options for Api patch endpoint. - -#### Initializer - -```wing -bring cloud; - -let ApiPatchOptions = cloud.ApiPatchOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ApiPostOptions - -Options for Api post endpoint. - -#### Initializer - -```wing -bring cloud; - -let ApiPostOptions = cloud.ApiPostOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ApiProps - -Options for `Api`. - -#### Initializer - -```wing -bring cloud; - -let ApiProps = cloud.ApiProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| cors | bool | Options for configuring the API's CORS behavior across all routes. | -| corsOptions | ApiCorsOptions | Options for configuring the API's CORS behavior across all routes. | - ---- - -##### `cors`Optional - -```wing -cors: bool; -``` - -- *Type:* bool -- *Default:* false, CORS configuration is disabled - -Options for configuring the API's CORS behavior across all routes. - -Options can also be overridden on a per-route basis. (not yet implemented) -When enabled this will add CORS headers with default options. -Can be customized by passing `corsOptions` - ---- - -*Example* - -```wing -true -``` - - -##### `corsOptions`Optional - -```wing -corsOptions: ApiCorsOptions; -``` - -- *Type:* ApiCorsOptions -- *Default:* Default CORS options are applied when `cors` is set to `true` allowOrigin: "*", allowMethods: [ HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.HEAD, HttpMethod.OPTIONS, ], allowHeaders: ["Content-Type", "Authorization"], exposeHeaders: [], allowCredentials: false, - -Options for configuring the API's CORS behavior across all routes. - -Options can also be overridden on a per-route basis. (not yet implemented) - ---- - -*Example* - -```wing -{ allowOrigin: "https://example.com" } -``` - - -### ApiPutOptions - -Options for Api put endpoint. - -#### Initializer - -```wing -bring cloud; - -let ApiPutOptions = cloud.ApiPutOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ApiRequest - -Shape of a request to an inflight handler. - -#### Initializer - -```wing -bring cloud; - -let ApiRequest = cloud.ApiRequest{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| method | HttpMethod | The request's HTTP method. | -| path | str | The request's path. | -| query | MutMap<str> | The request's query string values. | -| vars | MutMap<str> | The path variables. | -| body | str | The request's body. | -| headers | MutMap<str> | The request's headers. | - ---- - -##### `method`Required - -```wing -method: HttpMethod; -``` - -- *Type:* HttpMethod - -The request's HTTP method. - ---- - -##### `path`Required - -```wing -path: str; -``` - -- *Type:* str - -The request's path. - ---- - -##### `query`Required - -```wing -query: MutMap; -``` - -- *Type:* MutMap<str> - -The request's query string values. - ---- - -##### `vars`Required - -```wing -vars: MutMap; -``` - -- *Type:* MutMap<str> - -The path variables. - ---- - -##### `body`Optional - -```wing -body: str; -``` - -- *Type:* str - -The request's body. - ---- - -##### `headers`Optional - -```wing -headers: MutMap; -``` - -- *Type:* MutMap<str> - -The request's headers. - ---- - -### ApiResponse - -Shape of a response from a inflight handler. - -#### Initializer - -```wing -bring cloud; - -let ApiResponse = cloud.ApiResponse{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| body | str | The response's body. | -| headers | MutMap<str> | The response's headers. | -| status | num | The response's status code. | - ---- - -##### `body`Optional - -```wing -body: str; -``` - -- *Type:* str -- *Default:* no body - -The response's body. - ---- - -##### `headers`Optional - -```wing -headers: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* {} - -The response's headers. - ---- - -##### `status`Optional - -```wing -status: num; -``` - -- *Type:* num -- *Default:* 200 - -The response's status code. - ---- - -### CorsHeaders - -Type definition for CORS headers which includes default and options headers. - -#### Initializer - -```wing -bring cloud; - -let CorsHeaders = cloud.CorsHeaders{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| defaultResponse | MutMap<str> | Default CORS response headers. | -| optionsResponse | MutMap<str> | CORS options response headers. | - ---- - -##### `defaultResponse`Required - -```wing -defaultResponse: MutMap; -``` - -- *Type:* MutMap<str> - -Default CORS response headers. - ---- - -##### `optionsResponse`Required - -```wing -optionsResponse: MutMap; -``` - -- *Type:* MutMap<str> - -CORS options response headers. - ---- - -## Protocols - -### IApiEndpointHandler - -- *Extends:* IInflight - -- *Implemented By:* IApiEndpointHandler - -**Inflight client:** [@winglang/sdk.cloud.IApiEndpointHandlerClient](#@winglang/sdk.cloud.IApiEndpointHandlerClient) - -A resource with an inflight "handle" method that can be passed to one of the `Api` request preflight methods. - - - -### IApiEndpointHandlerClient - -- *Implemented By:* IApiEndpointHandlerClient - -Inflight client for `IApiEndpointHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Inflight that will be called when a request is made to the endpoint. | - ---- - -##### `handle` - -```wing -inflight handle(request: ApiRequest): ApiResponse? -``` - -Inflight that will be called when a request is made to the endpoint. - -###### `request`Required - -- *Type:* ApiRequest - ---- - - -## Enums - -### HttpMethod - -Allowed HTTP methods for a endpoint. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| GET | Get. | -| HEAD | Head. | -| POST | Post. | -| PUT | Put. | -| DELETE | Delete. | -| CONNECT | Connect. | -| OPTIONS | Options. | -| PATCH | Patch. | - ---- - -##### `GET` - -Get. - ---- - - -##### `HEAD` - -Head. - ---- - - -##### `POST` - -Post. - ---- - - -##### `PUT` - -Put. - ---- - - -##### `DELETE` - -Delete. - ---- - - -##### `CONNECT` - -Connect. - ---- - - -##### `OPTIONS` - -Options. - ---- - - -##### `PATCH` - -Patch. - ---- - diff --git a/docs/docs/04-standard-library/cloud/bucket.md b/docs/docs/04-standard-library/cloud/bucket.md deleted file mode 100644 index 8844346e31e..00000000000 --- a/docs/docs/04-standard-library/cloud/bucket.md +++ /dev/null @@ -1,1224 +0,0 @@ ---- -title: Bucket -id: bucket -description: A built-in resource for handling object storage in the cloud. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - Object storage, - Buckets, - ] -sidebar_position: 1 ---- - -The `cloud.Bucket` resource represents a container for storing data in the cloud. - -Buckets are a common way to store arbitrary files (images, videos, etc.), but can also be used to store structured data like JSON or CSV files. - -Buckets in the cloud use object storage, which is optimized for storing large amounts of data with high availability. -Unlike other kinds of storage like file storage, data is not stored in a hierarchical structure, but rather as a flat list of objects, each associated with a key. - -## Usage - -### Defining a bucket - -```js example -bring cloud; - -let bucket = new cloud.Bucket( - public: true, // optional, defaults to `false` -); -``` - -### Populating objects during deployment - -If you have static data that you want to upload to the bucket each time your app is deployed, you can call the preflight method `addObject`: - -```js example -bring cloud; - -let bucket = new cloud.Bucket(); - -bucket.addObject("my-file.txt", "Hello, world!"); -``` - -### Using a bucket inflight - -```js playground example -bring cloud; - -let bucket = new cloud.Bucket(); - -let bucketFunc = inflight () => { - bucket.put("file.txt", "Hello, world!"); - bucket.putJson("person.json", Json { name: "Alice" }); - - let fileData = bucket.get("file.txt"); - assert(fileData == "Hello, world!"); - - let jsonData = bucket.getJson("person.json"); - assert(jsonData.get("name") == "Alice"); - - let keys = bucket.list(); - assert(keys.at(0) == "file.txt"); - assert(keys.at(1) == "person.json"); - - bucket.delete("file.txt"); -}; - -new cloud.Function(bucketFunc); -``` - -### Run code on bucket events - -You can use the preflight methods `onCreate`, `onUpdate`, and `onDelete` to define code that should run when an object is uploaded, updated, or removed from the bucket. -Use the `onEvent` method for responding to any event. - -Each method creates a new `cloud.Function` resource which will be triggered by the given event type. - -```js playground example -bring cloud; - -let store = new cloud.Bucket(); -let copies = new cloud.Bucket() as "Backup"; - -store.onCreate(inflight (key: str) => { - let data = store.get(key); - if !key.endsWith(".log") { - copies.put(key, data); - } -}); - -store.onDelete(inflight (key: str) => { - copies.delete(key); - log("Deleted {key}"); -}); -``` - -## Target-specific details - -### Simulator (`sim`) - -Under the hood, the simulator uses a temporary local directory to store bucket data. - -Note that bucket data is not persisted between simulator runs. - -### AWS (`tf-aws` and `awscdk`) - -The AWS implementation of `cloud.Bucket` uses [Amazon S3](https://aws.amazon.com/s3/). - -### Azure (`tf-azure`) - -The Azure implementation of `cloud.Bucket` uses [Azure Blob Storage](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blobs-overview). - -### GCP (`tf-gcp`) - -The Google Cloud implementation of `cloud.Bucket` uses [Google Cloud Storage](https://cloud.google.com/storage). -## API Reference - -### Bucket - -A cloud object store. - -#### Initializers - -```wing -bring cloud; - -new cloud.Bucket(props?: BucketProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | BucketProps | *No description.* | - ---- - -##### `props`Optional - -- *Type:* BucketProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| addFile | Add a file to the bucket from system folder. | -| addObject | Add a file to the bucket that is uploaded when the app is deployed. | -| onCreate | Run an inflight whenever a file is uploaded to the bucket. | -| onDelete | Run an inflight whenever a file is deleted from the bucket. | -| onEvent | Run an inflight whenever a file is uploaded, modified, or deleted from the bucket. | -| onUpdate | Run an inflight whenever a file is updated in the bucket. | - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| copy | Copy an object to a new location in the bucket. | -| delete | Delete an existing object using a key from the bucket. | -| exists | Check if an object exists in the bucket. | -| get | Retrieve an object from the bucket. | -| getJson | Retrieve a Json object from the bucket. | -| list | Retrieve existing objects keys from the bucket. | -| metadata | Get the metadata of an object in the bucket. | -| publicUrl | Returns a url to the given file. | -| put | Put an object in the bucket. | -| putJson | Put a Json object in the bucket. | -| rename | Move an object to a new location in the bucket. | -| signedUrl | Returns a signed url to the given file. | -| tryDelete | Delete an object from the bucket if it exists. | -| tryGet | Get an object from the bucket if it exists If the bytes returned are not a valid UTF-8 string, an error is thrown. | -| tryGetJson | Gets an object from the bucket if it exists, parsing it as Json. | - ---- - -##### `addFile` - -```wing -addFile(key: str, path: str, encoding?: str): void -``` - -Add a file to the bucket from system folder. - -###### `key`Required - -- *Type:* str - -The key or name to associate with the file. - ---- - -###### `path`Required - -- *Type:* str - -The path to the file on the local system. - ---- - -###### `encoding`Optional - -- *Type:* str - -The encoding to use when reading the file. - -Defaults to "utf-8". - ---- - -##### `addObject` - -```wing -addObject(key: str, body: str): void -``` - -Add a file to the bucket that is uploaded when the app is deployed. - -TODO: In the future this will support uploading any `Blob` type or -referencing a file from the local filesystem. - -###### `key`Required - -- *Type:* str - ---- - -###### `body`Required - -- *Type:* str - ---- - -##### `onCreate` - -```wing -onCreate(fn: IBucketEventHandler, opts?: BucketOnCreateOptions): void -``` - -Run an inflight whenever a file is uploaded to the bucket. - -###### `fn`Required - -- *Type:* IBucketEventHandler - ---- - -###### `opts`Optional - -- *Type:* BucketOnCreateOptions - ---- - -##### `onDelete` - -```wing -onDelete(fn: IBucketEventHandler, opts?: BucketOnDeleteOptions): void -``` - -Run an inflight whenever a file is deleted from the bucket. - -###### `fn`Required - -- *Type:* IBucketEventHandler - ---- - -###### `opts`Optional - -- *Type:* BucketOnDeleteOptions - ---- - -##### `onEvent` - -```wing -onEvent(fn: IBucketEventHandler, opts?: BucketOnEventOptions): void -``` - -Run an inflight whenever a file is uploaded, modified, or deleted from the bucket. - -###### `fn`Required - -- *Type:* IBucketEventHandler - ---- - -###### `opts`Optional - -- *Type:* BucketOnEventOptions - ---- - -##### `onUpdate` - -```wing -onUpdate(fn: IBucketEventHandler, opts?: BucketOnUpdateOptions): void -``` - -Run an inflight whenever a file is updated in the bucket. - -###### `fn`Required - -- *Type:* IBucketEventHandler - ---- - -###### `opts`Optional - -- *Type:* BucketOnUpdateOptions - ---- - -##### `copy` - -```wing -inflight copy(srcKey: str, dstKey: str): void -``` - -Copy an object to a new location in the bucket. - -If the destination object -already exists, it will be overwritten. - -###### `srcKey`Required - -- *Type:* str - -The key of the source object you wish to copy. - ---- - -###### `dstKey`Required - -- *Type:* str - -The key of the destination object after copying. - ---- - -##### `delete` - -```wing -inflight delete(key: str, opts?: BucketDeleteOptions): void -``` - -Delete an existing object using a key from the bucket. - -###### `key`Required - -- *Type:* str - -Key of the object. - ---- - -###### `opts`Optional - -- *Type:* BucketDeleteOptions - -Options available for delete an item from a bucket. - ---- - -##### `exists` - -```wing -inflight exists(key: str): bool -``` - -Check if an object exists in the bucket. - -###### `key`Required - -- *Type:* str - -Key of the object. - ---- - -##### `get` - -```wing -inflight get(key: str, options?: BucketGetOptions): str -``` - -Retrieve an object from the bucket. - -If the bytes returned are not a valid UTF-8 string, an error is thrown. - -###### `key`Required - -- *Type:* str - -Key of the object. - ---- - -###### `options`Optional - -- *Type:* BucketGetOptions - -Additional get options. - ---- - -##### `getJson` - -```wing -inflight getJson(key: str): Json -``` - -Retrieve a Json object from the bucket. - -###### `key`Required - -- *Type:* str - -Key of the object. - ---- - -##### `list` - -```wing -inflight list(prefix?: str): MutArray -``` - -Retrieve existing objects keys from the bucket. - -###### `prefix`Optional - -- *Type:* str - -Limits the response to keys that begin with the specified prefix. - ---- - -##### `metadata` - -```wing -inflight metadata(key: str): ObjectMetadata -``` - -Get the metadata of an object in the bucket. - -###### `key`Required - -- *Type:* str - -Key of the object. - ---- - -##### `publicUrl` - -```wing -inflight publicUrl(key: str): str -``` - -Returns a url to the given file. - -###### `key`Required - -- *Type:* str - ---- - -##### `put` - -```wing -inflight put(key: str, body: str, options?: BucketPutOptions): void -``` - -Put an object in the bucket. - -###### `key`Required - -- *Type:* str - -Key of the object. - ---- - -###### `body`Required - -- *Type:* str - -Content of the object we want to store into the bucket. - ---- - -###### `options`Optional - -- *Type:* BucketPutOptions - -Additional options. - ---- - -##### `putJson` - -```wing -inflight putJson(key: str, body: Json): void -``` - -Put a Json object in the bucket. - -###### `key`Required - -- *Type:* str - -Key of the object. - ---- - -###### `body`Required - -- *Type:* Json - -Json object that we want to store into the bucket. - ---- - -##### `rename` - -```wing -inflight rename(srcKey: str, dstKey: str): void -``` - -Move an object to a new location in the bucket. - -If the destination object -already exists, it will be overwritten. Returns once the renaming is finished. - -###### `srcKey`Required - -- *Type:* str - -The key of the source object you wish to rename. - ---- - -###### `dstKey`Required - -- *Type:* str - -The key of the destination object after renaming. - ---- - -##### `signedUrl` - -```wing -inflight signedUrl(key: str, options?: BucketSignedUrlOptions): str -``` - -Returns a signed url to the given file. - -###### `key`Required - -- *Type:* str - -The key to access the cloud object. - ---- - -###### `options`Optional - -- *Type:* BucketSignedUrlOptions - -The signedUrlOptions where you can provide the configurations of the signed url. - ---- - -##### `tryDelete` - -```wing -inflight tryDelete(key: str): bool -``` - -Delete an object from the bucket if it exists. - -###### `key`Required - -- *Type:* str - -Key of the object. - ---- - -##### `tryGet` - -```wing -inflight tryGet(key: str, options?: BucketTryGetOptions): str? -``` - -Get an object from the bucket if it exists If the bytes returned are not a valid UTF-8 string, an error is thrown. - -###### `key`Required - -- *Type:* str - -Key of the object. - ---- - -###### `options`Optional - -- *Type:* BucketTryGetOptions - -Additional get options. - ---- - -##### `tryGetJson` - -```wing -inflight tryGetJson(key: str): Json? -``` - -Gets an object from the bucket if it exists, parsing it as Json. - -###### `key`Required - -- *Type:* str - -Key of the object. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Bucket.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Bucket.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - - -## Structs - -### BucketDeleteOptions - -Options for `Bucket.delete()`. - -#### Initializer - -```wing -bring cloud; - -let BucketDeleteOptions = cloud.BucketDeleteOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| mustExist | bool | Check failures on the method and retrieve errors if any. | - ---- - -##### `mustExist`Optional - -```wing -mustExist: bool; -``` - -- *Type:* bool -- *Default:* false - -Check failures on the method and retrieve errors if any. - ---- - -### BucketEvent - -On_event notification payload- will be in use after solving issue: https://github.com/winglang/wing/issues/1927. - -#### Initializer - -```wing -bring cloud; - -let BucketEvent = cloud.BucketEvent{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| key | str | The bucket key that triggered the event. | -| type | BucketEventType | Type of event. | - ---- - -##### `key`Required - -```wing -key: str; -``` - -- *Type:* str - -The bucket key that triggered the event. - ---- - -##### `type`Required - -```wing -type: BucketEventType; -``` - -- *Type:* BucketEventType - -Type of event. - ---- - -### BucketGetOptions - -Options for `Bucket.get()`. - -#### Initializer - -```wing -bring cloud; - -let BucketGetOptions = cloud.BucketGetOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| endByte | num | The ending byte to read up to (including). | -| startByte | num | The starting byte to read from. | - ---- - -##### `endByte`Optional - -```wing -endByte: num; -``` - -- *Type:* num -- *Default:* undefined - -The ending byte to read up to (including). - ---- - -##### `startByte`Optional - -```wing -startByte: num; -``` - -- *Type:* num -- *Default:* undefined - -The starting byte to read from. - ---- - -### BucketOnCreateOptions - -`onCreate` event options. - -#### Initializer - -```wing -bring cloud; - -let BucketOnCreateOptions = cloud.BucketOnCreateOptions{ ... }; -``` - - -### BucketOnDeleteOptions - -`onDelete` event options. - -#### Initializer - -```wing -bring cloud; - -let BucketOnDeleteOptions = cloud.BucketOnDeleteOptions{ ... }; -``` - - -### BucketOnEventOptions - -`onEvent` options. - -#### Initializer - -```wing -bring cloud; - -let BucketOnEventOptions = cloud.BucketOnEventOptions{ ... }; -``` - - -### BucketOnUpdateOptions - -`onUpdate` event options. - -#### Initializer - -```wing -bring cloud; - -let BucketOnUpdateOptions = cloud.BucketOnUpdateOptions{ ... }; -``` - - -### BucketProps - -Options for `Bucket`. - -#### Initializer - -```wing -bring cloud; - -let BucketProps = cloud.BucketProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| public | bool | Whether the bucket's objects should be publicly accessible. | - ---- - -##### `public`Optional - -```wing -public: bool; -``` - -- *Type:* bool -- *Default:* false - -Whether the bucket's objects should be publicly accessible. - ---- - -### BucketPutOptions - -Options for `Bucket.put()`. - -#### Initializer - -```wing -bring cloud; - -let BucketPutOptions = cloud.BucketPutOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| contentType | str | The HTTP Content-Type of the object. | - ---- - -##### `contentType`Required - -```wing -contentType: str; -``` - -- *Type:* str -- *Default:* Determined by file extension or fallback to "application/octet-stream" - -The HTTP Content-Type of the object. - -> [https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) - ---- - -### BucketSignedUrlOptions - -Options for `Bucket.signedUrl()`. - -#### Initializer - -```wing -bring cloud; - -let BucketSignedUrlOptions = cloud.BucketSignedUrlOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| action | BucketSignedUrlAction | The action allowed by the signed URL. | -| duration | duration | The duration for the signed URL to expire. | - ---- - -##### `action`Optional - -```wing -action: BucketSignedUrlAction; -``` - -- *Type:* BucketSignedUrlAction -- *Default:* BucketSignedUrlAction.DOWNLOAD - -The action allowed by the signed URL. - ---- - -##### `duration`Optional - -```wing -duration: duration; -``` - -- *Type:* duration -- *Default:* 15m - -The duration for the signed URL to expire. - ---- - -### BucketTryGetOptions - -Options for `Bucket.tryGet()`. - -#### Initializer - -```wing -bring cloud; - -let BucketTryGetOptions = cloud.BucketTryGetOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| endByte | num | The ending byte to read up to (including). | -| startByte | num | The starting byte to read from. | - ---- - -##### `endByte`Optional - -```wing -endByte: num; -``` - -- *Type:* num -- *Default:* undefined - -The ending byte to read up to (including). - ---- - -##### `startByte`Optional - -```wing -startByte: num; -``` - -- *Type:* num -- *Default:* undefined - -The starting byte to read from. - ---- - -### ObjectMetadata - -Metadata of a bucket object. - -#### Initializer - -```wing -bring cloud; - -let ObjectMetadata = cloud.ObjectMetadata{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| lastModified | datetime | The time the object was last modified. | -| size | num | The size of the object in bytes. | -| contentType | str | The content type of the object, if it is known. | - ---- - -##### `lastModified`Required - -```wing -lastModified: datetime; -``` - -- *Type:* datetime - -The time the object was last modified. - ---- - -##### `size`Required - -```wing -size: num; -``` - -- *Type:* num - -The size of the object in bytes. - ---- - -##### `contentType`Optional - -```wing -contentType: str; -``` - -- *Type:* str - -The content type of the object, if it is known. - ---- - -## Protocols - -### IBucketEventHandler - -- *Extends:* IInflight - -- *Implemented By:* IBucketEventHandler - -**Inflight client:** [@winglang/sdk.cloud.IBucketEventHandlerClient](#@winglang/sdk.cloud.IBucketEventHandlerClient) - -A resource with an inflight "handle" method that can be passed to the bucket events. - - - -### IBucketEventHandlerClient - -- *Implemented By:* IBucketEventHandlerClient - -A resource with an inflight "handle" method that can be passed to the bucket events. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that will be called when an event notification is fired. | - ---- - -##### `handle` - -```wing -inflight handle(key: str, type: BucketEventType): void -``` - -Function that will be called when an event notification is fired. - -###### `key`Required - -- *Type:* str - ---- - -###### `type`Required - -- *Type:* BucketEventType - ---- - - -## Enums - -### BucketEventType - -Bucket events to subscribe to. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| CREATE | Create. | -| DELETE | Delete. | -| UPDATE | Update. | - ---- - -##### `CREATE` - -Create. - ---- - - -##### `DELETE` - -Delete. - ---- - - -##### `UPDATE` - -Update. - ---- - - -### BucketSignedUrlAction - -Specifies the action permitted by a presigned URL for a bucket. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| DOWNLOAD | Represents a HTTP GET request for a presigned URL, allowing read access for an object in the bucket. | -| UPLOAD | Represents a HTTP PUT request for a presigned URL, allowing write access for an object in the bucket. | - ---- - -##### `DOWNLOAD` - -Represents a HTTP GET request for a presigned URL, allowing read access for an object in the bucket. - ---- - - -##### `UPLOAD` - -Represents a HTTP PUT request for a presigned URL, allowing write access for an object in the bucket. - ---- - diff --git a/docs/docs/04-standard-library/cloud/counter.md b/docs/docs/04-standard-library/cloud/counter.md deleted file mode 100644 index 2d5aecf564f..00000000000 --- a/docs/docs/04-standard-library/cloud/counter.md +++ /dev/null @@ -1,347 +0,0 @@ ---- -title: Counter -id: counter -description: A built-in resource for representing an container for numbers in the cloud. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - Counter, - ] -sidebar_position: 1 ---- - -The `cloud.Counter` resource represents a stateful container for one or more numbers in the cloud. - -## Usage - -### Defining a counter - -```js example -bring cloud; - -let counter = new cloud.Counter( - initial: 123, // optional, defaults to 0 -); -``` - -### Using a counter inflight - -```js playground example -bring cloud; - -let counter = new cloud.Counter(); - -let counterFunc = inflight () => { - let prev = counter.inc(); // increment by 1 and return previous value - counter.inc(5); // increment by 5 - counter.dec(); // decrement by 1 - counter.dec(2); // decrement by 2 - - assert(counter.peek() == 3); // check the current value - - counter.set(100); // set to a specific value -}; - -new cloud.Function(counterFunc); -``` - -### Using keys to manage multiple counter values - -```js playground example -bring cloud; - -let counter = new cloud.Counter(initial: 100); - -let counterFunc = inflight () => { - let k1 = "key-1"; - let k2 = "key-2"; - - counter.dec(1, k1); // decrement k1 by 1 - counter.inc(11, k2); // increment k2 by 11 - - assert(counter.peek(k1) == 99); // check the current value of k1 - assert(counter.peek(k2) == 111); // check the current value of k2 -}; - -new cloud.Function(counterFunc); -``` - -## Target-specific details - -### Simulator (`sim`) - -Under the hood, the simulator stores the counter value in memory. - -Note that counter data is not persisted between simulator runs. - -### AWS (`tf-aws` and `awscdk`) - -The AWS implementation of `cloud.Counter` uses [Amazon DynamoDB](https://aws.amazon.com/dynamodb/). - -### Azure (`tf-azure`) - -🚧 Not supported yet (tracking issue: [#629](https://github.com/winglang/wing/issues/629)) - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#628](https://github.com/winglang/wing/issues/628)) -## API Reference - -### Counter - -A distributed atomic counter. - -#### Initializers - -```wing -bring cloud; - -new cloud.Counter(props?: CounterProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | CounterProps | *No description.* | - ---- - -##### `props`Optional - -- *Type:* CounterProps - ---- - -#### Methods - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| dec | Decrement the counter, returning the previous value. | -| inc | Increments the counter atomically by a certain amount and returns the previous value. | -| peek | Get the current value of the counter. | -| set | Set a counter to a given value. | - ---- - -##### `dec` - -```wing -inflight dec(amount?: num, key?: str): num -``` - -Decrement the counter, returning the previous value. - -###### `amount`Optional - -- *Type:* num - -amount to decrement (default is 1). - ---- - -###### `key`Optional - -- *Type:* str - -specify the key to be decremented. - ---- - -##### `inc` - -```wing -inflight inc(amount?: num, key?: str): num -``` - -Increments the counter atomically by a certain amount and returns the previous value. - -###### `amount`Optional - -- *Type:* num - -amount to increment (default is 1). - ---- - -###### `key`Optional - -- *Type:* str - -specify the key to be incremented. - ---- - -##### `peek` - -```wing -inflight peek(key?: str): num -``` - -Get the current value of the counter. - -Using this API may introduce race conditions since the value can change between -the time it is read and the time it is used in your code. - -###### `key`Optional - -- *Type:* str - -specify the key to be retrieved. - ---- - -##### `set` - -```wing -inflight set(value: num, key?: str): void -``` - -Set a counter to a given value. - -###### `value`Required - -- *Type:* num - -new value. - ---- - -###### `key`Optional - -- *Type:* str - -specify the key to be set. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Counter.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Counter.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| initial | num | The initial value of the counter. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `initial`Required - -```wing -initial: num; -``` - -- *Type:* num - -The initial value of the counter. - ---- - - - -## Structs - -### CounterProps - -Options for `Counter`. - -#### Initializer - -```wing -bring cloud; - -let CounterProps = cloud.CounterProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| initial | num | The initial value of the counter. | - ---- - -##### `initial`Optional - -```wing -initial: num; -``` - -- *Type:* num -- *Default:* 0 - -The initial value of the counter. - ---- - - diff --git a/docs/docs/04-standard-library/cloud/domain.md b/docs/docs/04-standard-library/cloud/domain.md deleted file mode 100644 index 251073f5230..00000000000 --- a/docs/docs/04-standard-library/cloud/domain.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: Domain -id: domain -description: A built-in resource for representing a domain in the cloud. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - Domain, - ] -sidebar_position: 1 ---- - -The `cloud.Domain` resource represents a domain configuration in the cloud. - -## Usage - -### Defining a domain - -```js -bring cloud; - -let domain = new cloud.Domain( - domainName: "www.example.com", -); - -new cloud.Website(path: "./site", domain: domain); -``` - -## Target-specific details - -### Simulator (`sim`) - -Under the hood, the simulator stores the domain value in memory. - -Note that domain data is not persisted between simulator runs. - -### AWS (`tf-aws` and `awscdk`) - -The AWS implementation of `cloud.Domain` requires certain platform-specific values such as the `hostedZoneId` and either `iamCertificate` or `acmCertificateArn` to be provided. - -To provide these values, there are two options. You can either pass the values in the command line or you can provide a TOML file with the configurations: - -``` -wing compile -t tf-aws main.w --value root/Default/Default/Domain/acmCertificateArn=arn:aws:acm:us-east-1:111111111111:certificate/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee --value root/Default/Default/Domain/hostedZoneId=Z0111111111111111111F -``` - -Alternatively, create a `wing.toml` file in your project directory: - -```toml -[root.Default.Default.Domain] -hostedZoneId = "Z0XXXXXXXXXXXXXXXXXXF" -acmCertificateArn = "arn:aws:acm:us-east-1:111111111111:certificate/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" -``` - -### Azure (`tf-azure`) - -🚧 Not supported yet - -### GCP (`tf-gcp`) - -🚧 Not supported yet## API Reference - -### Domain - -A cloud Domain. - -#### Initializers - -```wing -bring cloud; - -new cloud.Domain(props: DomainProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | DomainProps | *No description.* | - ---- - -##### `props`Required - -- *Type:* DomainProps - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Domain.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Domain.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| domainName | str | The domain name. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `domainName`Required - -```wing -domainName: str; -``` - -- *Type:* str - -The domain name. - ---- - - - -## Structs - -### DomainProps - -Options for `Domain`. - -#### Initializer - -```wing -bring cloud; - -let DomainProps = cloud.DomainProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| domainName | str | The website's custom domain name. | - ---- - -##### `domainName`Required - -```wing -domainName: str; -``` - -- *Type:* str - -The website's custom domain name. - ---- - -*Example* - -```wing -"example.com" -``` - - - diff --git a/docs/docs/04-standard-library/cloud/endpoint.md b/docs/docs/04-standard-library/cloud/endpoint.md deleted file mode 100644 index c9a3abcc1fb..00000000000 --- a/docs/docs/04-standard-library/cloud/endpoint.md +++ /dev/null @@ -1,321 +0,0 @@ ---- -title: Endpoint -id: endpoint -description: A resource that represents an endpoint. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - Endpoint, - URL, - ] -sidebar_position: 1 ---- - -The `cloud.Endpoint` represents a publicly accessible endpoint and outputs it as part of the compilation target. - -## Usage - -```ts playground example -bring cloud; - -let endpoint = new cloud.Endpoint("https://example.com"); -``` - -## Target-specific details - -### Simulator (`sim`) - -The sim implementation of `cloud.Endpoint` outputs the endpoint URL. - -### AWS (`tf-aws`) - -The TF AWS implementation of `cloud.Endpoint` uses a [Terraform Output](https://developer.hashicorp.com/terraform/language/values/outputs). - -### AWS (`awscdk`) - -The AWS CDK implementation of `cloud.Endpoint` uses a [Cloudformation Output](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html). - -### Azure (`tf-azure`) - -🚧 Not supported yet - -### GCP (`tf-gcp`) - -🚧 Not supported yet -## API Reference - -### Endpoint - -represents a publicly accessible endpoint and outputs it as part of the compilation target. - -#### Initializers - -```wing example -bring cloud; - -new cloud.Endpoint("https://example.com"); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| url | str | *The endpoint URL* | -| props | winglang/sdk.cloud.EndpointProps | *The endpoint Props* | -| - ---- - -##### `url`Required - -- *Type:* str - ---- - -##### `props` - -- *Type:* winglang/sdk.cloud.EndpointProps - ---- - - - -## Structs - -### EndpointProps - -Options for `Endpoint`. - -#### Initializer - -```wing -bring cloud; - -let EndpointProps = cloud.EndpointProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| label | str | The endpoint's label. For UI purposes. | -| browserSupport | bool | Whether the endpoint is supported through browsers. For UI purposes. | - ---- - -##### `label` - -```wing -label: str; -``` - -- *Type:* str - -The endpoint's label. For UI purposes. - ---- - -*Example* - -```wing -"My Dashboard" -``` - ---- - -##### `browserSupport` - -```wing -browserSupport: bool; -``` - -- *Type:* bool - -Whether the endpoint is supported through browsers. For UI purposes. -## API Reference - -### Endpoint - -A cloud Endpoint. - -#### Initializers - -```wing -bring cloud; - -new cloud.Endpoint(url: str, props?: EndpointProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| url | str | *No description.* | -| props | EndpointProps | *No description.* | - ---- - -##### `url`Required - -- *Type:* str - ---- - -##### `props`Optional - -- *Type:* EndpointProps - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Endpoint.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Endpoint.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| url | str | The endpoint url. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `url`Required - -```wing -url: str; -``` - -- *Type:* str - -The endpoint url. - ---- - - - -## Structs - -### EndpointProps - -Options for `Endpoint`. - -#### Initializer - -```wing -bring cloud; - -let EndpointProps = cloud.EndpointProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| browserSupport | bool | Whether the endpoint is supported through browsers. | -| label | str | The endpoint's label. | - ---- - -##### `browserSupport`Optional - -```wing -browserSupport: bool; -``` - -- *Type:* bool -- *Default:* undefined - -Whether the endpoint is supported through browsers. - -For UI purposes. - ---- - -##### `label`Optional - -```wing -label: str; -``` - -- *Type:* str -- *Default:* undefined - -The endpoint's label. - -For UI purposes. - ---- - -*Example* - -```wing -"My Dashboard" -``` - - - diff --git a/docs/docs/04-standard-library/cloud/function.md b/docs/docs/04-standard-library/cloud/function.md deleted file mode 100644 index 889c004d001..00000000000 --- a/docs/docs/04-standard-library/cloud/function.md +++ /dev/null @@ -1,543 +0,0 @@ ---- -title: Function -id: function -description: A built-in resource for creating serverless functions. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - Serverless function, - ] -sidebar_position: 1 ---- - -The `cloud.Function` resource represents a serverless function for performing short, stateless tasks. -Functions are typically used to run business logic in response to events, such as a file being uploaded to a bucket, a message being pushed to a queue, or a timer expiring. - -When a function is invoked on a cloud provider, it is typically executed in a container/host which is provisioned on demand. - -Functions may be invoked more than once, and some cloud providers may automatically retry failed invocations. -For performance reasons, most cloud providers impose a timeout on functions, after which the function is automatically terminated. - -## Usage - -A function can be invoked in two ways: - -* **invoke()** - Executes the function with a payload and waits for the result. -* **invokeAsync()** - Kicks off the execution of the function with a payload and returns immediately while the function is running. - -```ts playground example -bring cloud; -bring util; - -// defining a cloud.Function resource -let countWords = new cloud.Function(inflight (s: str?): str => { - return "{s?.split(" ")?.length ?? 0}"; -}) as "countWords"; - -let longTask = new cloud.Function(inflight () => { - util.sleep(30s); - log("done!"); -}); - -new cloud.Function(inflight () => { - let sentence = "I am a sentence with 7 words"; - // invoking cloud.Function from inflight context - let wordsCount = countWords.invoke(sentence); - log("'{sentence}' has {wordsCount ?? "0"} words"); - - longTask.invokeAsync(""); - log("task started"); -}) as "Invoke Me"; -``` - -## Function container reuse - -Most cloud providers will opportunistically reuse the function's container in additional invocations. -It is possible to leverage this behavior to cache objects across function executions using `inflight new` and inflight fields. - -The following example reads the `bigdata.json` file once and reuses it every time `query()` is called. - -```ts playground example -bring cloud; - -let big = new cloud.Bucket(); - -big.addObject("bigdata.json", Json.stringify({ - "my-key": "my-value" -})); - -class MyDatabase { - inflight bigdata: Json; - inflight new() { - // download big data once - this.bigdata = big.getJson("bigdata.json"); - } - - pub inflight query(key: str): Json { - return this.bigdata.get(key); - } -} - -let db = new MyDatabase(); - -new cloud.Function(inflight () => { - log(Json.stringify(db.query("my-key"))); -}); -``` - -## Target-specific details - -### Simulator (`sim`) - -The sim implementation of `cloud.Function` runs the inflight code as a JavaScript function. - -By default, a maximum of 10 workers can be processing requests sent to a `cloud.Function` concurrently, but this number can be adjusted with the `concurrency` property: - -```ts playground -bring cloud; - -new cloud.Function(inflight () => { - // ... code that shouldn't run concurrently ... -}, concurrency: 1); -``` - -### AWS (`tf-aws` and `awscdk`) - -The AWS implementation of `cloud.Function` uses [AWS Lambda](https://aws.amazon.com/lambda/). - -#### Adding custom IAM permissions - -To add extra IAM permissions to the function, you can use the `aws.Function` class as shown below. - -```ts playground example -bring aws; -bring cloud; - -let f = new cloud.Function(inflight () => { - log("Hello world!"); -}); -if let lambdaFn = aws.Function.from(f) { - lambdaFn.addPolicyStatements( - aws.PolicyStatement { - actions: ["ses:sendEmail"], - effect: aws.Effect.ALLOW, - resources: ["*"], - }, - ); -} -``` - -#### Accessing the Lambda context - -To access the [AWS Lambda context object](https://docs.aws.amazon.com/lambda/latest/dg/nodejs-context.html), you can use the `aws.Function` class as shown below. - -```ts playground example -bring aws; -bring cloud; - -let f = new cloud.Function(inflight () => { - if let ctx = aws.Function.context() { - log(ctx.logGroupName); // prints the log group name - log(ctx.logStreamName); // prints the log stream name - - let remainingTime = ctx.remainingTimeInMillis(); - assert(remainingTime > 0); - } -}); -``` - -The `context()` method returns `nil` when ran on non-AWS targets. - -#### Adding Lambda layers - -To add a [Lambda layer](https://docs.aws.amazon.com/lambda/latest/dg/chapter-layers.html) to the function, you can use the `aws.Function` class as shown below. - -```ts playground example -bring aws; -bring cloud; - -let f = new cloud.Function(inflight () => { - log("Hello world!"); -}); -if let lambdaFn = aws.Function.from(f) { - lambdaFn.addLambdaLayer("arn:aws:lambda:us-west-2:123456789012:layer:my-layer:1"); -} -``` - -In some scenarios, you might want to a Lambda layer to be automatically added to all Lambda function's that use a class's inflight methods. -You can achieve this by using the `onLift` or `onLiftType` hook. - -```ts playground example -bring aws; -bring cloud; - -class Datadog { - pub inflight fetchMetrics() { - // ...implementation... - } - pub onLift(host: std.IInflightHost, ops: Array) { - // Note: the "ops" argument is an array of inflight methods that were used - // so you could conditionally add the layer based on the methods called - if let lambdaFn = aws.Function.from(host) { - lambdaFn.addLambdaLayer("arn:aws:lambda:us-west-2:123456789012:layer:datadog-layer:1"); - } - } -} - -let d = new Datadog(); - -let api = new cloud.Api(); -api.get("/metrics", inflight () => { - d.fetchMetrics(); -}); -``` - -In the previous example, a Lambda function is implicitly created for handling the "/metrics" endpoint, and the `datadog-layer` is automatically added to it. - -### Azure (`tf-azure`) - -The Azure implementation of `cloud.Function` uses [Azure Functions](https://azure.microsoft.com/en-us/products/functions). - -🚧 `invoke` API is not supported yet (tracking issue: [#1371](https://github.com/winglang/wing/issues/1371)) - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#614](https://github.com/winglang/wing/issues/614)) -## API Reference - -### Function - -- *Implements:* IInflightHost - -A function. - -#### Initializers - -```wing -bring cloud; - -new cloud.Function(handler: IFunctionHandler, props?: FunctionProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| handler | IFunctionHandler | *No description.* | -| props | FunctionProps | *No description.* | - ---- - -##### `handler`Required - -- *Type:* IFunctionHandler - ---- - -##### `props`Optional - -- *Type:* FunctionProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| addEnvironment | Add an environment variable to the function. | - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| invoke | Invokes the function with a payload and waits for the result. | -| invokeAsync | Kicks off the execution of the function with a payload and returns immediately while the function is running. | - ---- - -##### `addEnvironment` - -```wing -addEnvironment(name: str, value: str): void -``` - -Add an environment variable to the function. - -###### `name`Required - -- *Type:* str - ---- - -###### `value`Required - -- *Type:* str - ---- - -##### `invoke` - -```wing -inflight invoke(payload?: str): str? -``` - -Invokes the function with a payload and waits for the result. - -###### `payload`Optional - -- *Type:* str - -payload to pass to the function. - -If not defined, an empty string will be passed. - ---- - -##### `invokeAsync` - -```wing -inflight invokeAsync(payload?: str): void -``` - -Kicks off the execution of the function with a payload and returns immediately while the function is running. - -###### `payload`Optional - -- *Type:* str - -payload to pass to the function. - -If not defined, an empty string will be passed. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Function.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Function.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| env | MutMap<str> | Returns the set of environment variables for this function. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `env`Required - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> - -Returns the set of environment variables for this function. - ---- - - - -## Structs - -### FunctionProps - -Options for `Function`. - -#### Initializer - -```wing -bring cloud; - -let FunctionProps = cloud.FunctionProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -## Protocols - -### IFunctionHandler - -- *Extends:* IInflight - -- *Implemented By:* IFunctionHandler - -**Inflight client:** [@winglang/sdk.cloud.IFunctionHandlerClient](#@winglang/sdk.cloud.IFunctionHandlerClient) - -A resource with an inflight "handle" method that can be used to create a `cloud.Function`. - - - -### IFunctionHandlerClient - -- *Implemented By:* IFunctionHandlerClient - -Inflight client for `IFunctionHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Entrypoint function that will be called when the cloud function is invoked. | - ---- - -##### `handle` - -```wing -inflight handle(event?: str): str? -``` - -Entrypoint function that will be called when the cloud function is invoked. - -###### `event`Optional - -- *Type:* str - ---- - - diff --git a/docs/docs/04-standard-library/cloud/on-deploy.md b/docs/docs/04-standard-library/cloud/on-deploy.md deleted file mode 100644 index 5d41d3694bf..00000000000 --- a/docs/docs/04-standard-library/cloud/on-deploy.md +++ /dev/null @@ -1,336 +0,0 @@ ---- -title: OnDeploy -id: on-deploy -description: A resource that runs inflight code during the application's deployment. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - OnDeploy, - Trigger, - Deployment, - ] -sidebar_position: 1 ---- - -The `cloud.OnDeploy` resource runs a block of inflight code each time the application is deployed. - -## Usage - -```ts playground example -bring cloud; - -let bucket = new cloud.Bucket(); - -// each time the application is deployed, all objects in the bucket are deleted -let setup = new cloud.OnDeploy(inflight () => { - for key in bucket.list() { - bucket.delete(key); - } -}); -``` - -To specify that the `cloud.OnDeploy` resource should be run before or after another resource is created or updated, use the `executeBefore` or `executeAfter` properties: - -```ts playground example -bring cloud; - -let counter = new cloud.Counter(); - -let setup2 = new cloud.OnDeploy(inflight () => { - counter.inc(); -}) as "setup2"; -let setup1 = new cloud.OnDeploy(inflight () => { - counter.set(10); -}, executeBefore: [setup2]) as "setup1"; -``` - -## Target-specific details - -### Simulator (`sim`) - -The sim implementation of `cloud.OnDeploy` uses a JavaScript function. - -### AWS (`tf-aws` and `awscdk`) - -The AWS implementation of `cloud.OnDeploy` uses a [Amazon Lambda](https://aws.amazon.com/lambda/) function, which is invoked during the Terraform or CloudFormation deployment. - -### Azure (`tf-azure`) - -🚧 Not supported yet (tracking issue: [#3565](https://github.com/winglang/wing/issues/3565)) - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#3564](https://github.com/winglang/wing/issues/3564)) -## API Reference - -### OnDeploy - -Run code every time the app is deployed. - -#### Initializers - -```wing -bring cloud; - -new cloud.OnDeploy(handler: IOnDeployHandler, props?: OnDeployProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| handler | IOnDeployHandler | *No description.* | -| props | OnDeployProps | *No description.* | - ---- - -##### `handler`Required - -- *Type:* IOnDeployHandler - ---- - -##### `props`Optional - -- *Type:* OnDeployProps - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.OnDeploy.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.OnDeploy.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - - -## Structs - -### OnDeployProps - -Options for `OnDeploy`. - -#### Initializer - -```wing -bring cloud; - -let OnDeployProps = cloud.OnDeployProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | -| executeAfter | MutArray<constructs.Construct> | Execute this trigger only after these resources have been provisioned. | -| executeBefore | MutArray<constructs.Construct> | Adds this trigger as a dependency on other constructs. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -##### `executeAfter`Optional - -```wing -executeAfter: MutArray; -``` - -- *Type:* MutArray<constructs.Construct> -- *Default:* no additional dependencies - -Execute this trigger only after these resources have been provisioned. - ---- - -##### `executeBefore`Optional - -```wing -executeBefore: MutArray; -``` - -- *Type:* MutArray<constructs.Construct> -- *Default:* no additional dependencies - -Adds this trigger as a dependency on other constructs. - ---- - -## Protocols - -### IOnDeployHandler - -- *Extends:* IInflight - -- *Implemented By:* IOnDeployHandler - -**Inflight client:** [@winglang/sdk.cloud.IOnDeployHandlerClient](#@winglang/sdk.cloud.IOnDeployHandlerClient) - -A resource with an inflight "handle" method that can be used by `cloud.OnDeploy`. - - - -### IOnDeployHandlerClient - -- *Implemented By:* IOnDeployHandlerClient - -Inflight client for `IOnDeployHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Entrypoint function that will be called when the app is deployed. | - ---- - -##### `handle` - -```wing -inflight handle(): void -``` - -Entrypoint function that will be called when the app is deployed. - - diff --git a/docs/docs/04-standard-library/cloud/queue.md b/docs/docs/04-standard-library/cloud/queue.md deleted file mode 100644 index 1b5bcbc21b7..00000000000 --- a/docs/docs/04-standard-library/cloud/queue.md +++ /dev/null @@ -1,563 +0,0 @@ ---- -title: Queue -id: queue -description: A built-in resource for creating distributed queues - a data structure for storing messages. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - Queue, - Distributed queue, - Messaging queue, - FIFO queue, - Channel, - ] -sidebar_position: 1 ---- - -The `cloud.Queue` resource represents a data structure for holding a list of messages. -Queues are typically used to decouple producers of data and the consumers of said data in distributed systems. -Queues by default are not FIFO (first in, first out) - so the order of messages is not guaranteed. - -## Usage - -### Setting a Queue Consumer - -```ts playground example -bring cloud; - -let q = new cloud.Queue(); - -q.setConsumer(inflight (m: str) => { - log("message ${m} consumed"); -}); - -new cloud.Function(inflight () => { - q.push("message a"); - q.push("message b"); -}); -``` - -### Using Queue inflight api - -Pushing messages, popping them, and purging. - -```ts playground example -bring cloud; - -let q = new cloud.Queue(); - -new cloud.Function(inflight () => { - q.push("message a"); - q.push("message b", "message c", "message d"); - log("approxSize is ${q.approxSize()}"); - log("popping message ${q.pop()!}"); - log("popping message ${q.pop()!}"); - log("approxSize is ${q.approxSize()}"); - q.purge(); - log("approxSize is ${q.approxSize()}"); -}); -``` - -### Adding a dead-letter queue - -Creating a queue and adding a dead-letter queue with the maximum number of attempts configured - -```ts playground example -bring cloud; - -let dlq = new cloud.Queue() as "dead-letter queue"; -let q = new cloud.Queue( - dlq: { - queue: dlq, - maxDeliveryAttempts: 2 - } -); -``` - -### Referencing an external queue - -If you would like to reference an existing queue from within your application you can use the -`QueueRef` classes in the target-specific namespaces. - -> This is currently only supported for `aws`. - -The following example defines a reference to an Amazon SQS queue with a specific ARN and sends a -message to the queue from the function: - -```js example -bring cloud; -bring aws; - -let outbox = new aws.QueueRef("arn:aws:sqs:us-east-1:111111111111:Outbox"); - -new cloud.Function(inflight () => { - outbox.push("send an email"); -}); -``` - -This works both when running in the simulator (requires AWS credentials on the developer's machine) -and when deployed to AWS. When this is deployed to AWS, the AWS Lambda IAM policy will include the -needed permissions. - -## Target-specific details - -### Simulator (`sim`) - -The sim implementation of `cloud.Queue` uses JavaScript's `Array` - -### AWS (`tf-aws` and `awscdk`) - -The AWS implementation of `cloud.Queue` uses [Amazon Simple Queue Service](https://aws.amazon.com/sqs/). - -### Azure (`tf-azure`) - -🚧 Not supported yet (tracking issue: [#617](https://github.com/winglang/wing/issues/617)) - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#616](https://github.com/winglang/wing/issues/616)) -## API Reference - -### Queue - -A queue. - -#### Initializers - -```wing -bring cloud; - -new cloud.Queue(props?: QueueProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | QueueProps | *No description.* | - ---- - -##### `props`Optional - -- *Type:* QueueProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| setConsumer | Create a function to consume messages from this queue. | - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| approxSize | Retrieve the approximate number of messages in the queue. | -| pop | Pop a message from the queue. | -| purge | Purge all of the messages in the queue. | -| push | Push one or more messages to the queue. | - ---- - -##### `setConsumer` - -```wing -setConsumer(handler: IQueueSetConsumerHandler, props?: QueueSetConsumerOptions): Function -``` - -Create a function to consume messages from this queue. - -###### `handler`Required - -- *Type:* IQueueSetConsumerHandler - ---- - -###### `props`Optional - -- *Type:* QueueSetConsumerOptions - ---- - -##### `approxSize` - -```wing -inflight approxSize(): num -``` - -Retrieve the approximate number of messages in the queue. - -##### `pop` - -```wing -inflight pop(): str? -``` - -Pop a message from the queue. - -##### `purge` - -```wing -inflight purge(): void -``` - -Purge all of the messages in the queue. - -##### `push` - -```wing -inflight push(...messages: Array): void -``` - -Push one or more messages to the queue. - -###### `messages`Required - -- *Type:* str - -Payload to send to the queue. - -Each message must be non-empty. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Queue.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Queue.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - - -## Structs - -### DeadLetterQueueProps - -Dead letter queue options. - -#### Initializer - -```wing -bring cloud; - -let DeadLetterQueueProps = cloud.DeadLetterQueueProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| queue | Queue | Queue to receive messages that failed processing. | -| maxDeliveryAttempts | num | Number of times a message will be processed before being sent to the dead-letter queue. | - ---- - -##### `queue`Required - -```wing -queue: Queue; -``` - -- *Type:* Queue - -Queue to receive messages that failed processing. - ---- - -##### `maxDeliveryAttempts`Optional - -```wing -maxDeliveryAttempts: num; -``` - -- *Type:* num -- *Default:* 1 - -Number of times a message will be processed before being sent to the dead-letter queue. - ---- - -### QueueProps - -Options for `Queue`. - -#### Initializer - -```wing -bring cloud; - -let QueueProps = cloud.QueueProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| dlq | DeadLetterQueueProps | A dead-letter queue. | -| retentionPeriod | duration | How long a queue retains a message. | -| timeout | duration | How long a queue's consumers have to process a message. | - ---- - -##### `dlq`Optional - -```wing -dlq: DeadLetterQueueProps; -``` - -- *Type:* DeadLetterQueueProps -- *Default:* no dead letter queue - -A dead-letter queue. - ---- - -##### `retentionPeriod`Optional - -```wing -retentionPeriod: duration; -``` - -- *Type:* duration -- *Default:* 1h - -How long a queue retains a message. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 30s - -How long a queue's consumers have to process a message. - ---- - -### QueueSetConsumerOptions - -Options for Queue.setConsumer. - -#### Initializer - -```wing -bring cloud; - -let QueueSetConsumerOptions = cloud.QueueSetConsumerOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | -| batchSize | num | The maximum number of messages to send to subscribers at once. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -##### `batchSize`Optional - -```wing -batchSize: num; -``` - -- *Type:* num -- *Default:* 1 - -The maximum number of messages to send to subscribers at once. - ---- - -## Protocols - -### IQueueSetConsumerHandler - -- *Extends:* IInflight - -- *Implemented By:* IQueueSetConsumerHandler - -**Inflight client:** [@winglang/sdk.cloud.IQueueSetConsumerHandlerClient](#@winglang/sdk.cloud.IQueueSetConsumerHandlerClient) - -A resource with an inflight "handle" method that can be passed to `Queue.setConsumer`. - - - -### IQueueSetConsumerHandlerClient - -- *Implemented By:* IQueueSetConsumerHandlerClient - -Inflight client for `IQueueSetConsumerHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that will be called when a message is received from the queue. | - ---- - -##### `handle` - -```wing -inflight handle(message: str): void -``` - -Function that will be called when a message is received from the queue. - -###### `message`Required - -- *Type:* str - ---- - - diff --git a/docs/docs/04-standard-library/cloud/schedule.md b/docs/docs/04-standard-library/cloud/schedule.md deleted file mode 100644 index 7da90e055c4..00000000000 --- a/docs/docs/04-standard-library/cloud/schedule.md +++ /dev/null @@ -1,397 +0,0 @@ ---- -title: Schedule -id: schedule -description: A built-in resource for defining scheduled tasks. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - Schedule, - Cron job, - ] -sidebar_position: 1 ---- - -The `cloud.Schedule` resource is used to trigger events at a regular interval. -Schedules are useful for periodic tasks, such as running backups or sending daily reports. -The timezone used in cron expressions is always UTC. - -## Usage - -### From cron - -```ts playground example -bring cloud; - -let schedule = new cloud.Schedule(cron: "* * * * *"); - -schedule.onTick(inflight () => { - log("schedule: triggered"); -}); -``` - -### From rate - -```ts playground example -bring cloud; - -let schedule = new cloud.Schedule(rate: 1m); - -schedule.onTick(inflight () => { - log("schedule: triggered"); -}); -``` - -### Simulator (`sim`) - -A standard JavaScript `setTimeout` function triggers ticks as callbacks. - -### AWS (`tf-aws` and `awscdk`) - -See [Amazon CloudWatch](https://aws.amazon.com/cloudwatch/). - -### Azure (`tf-azure`) - -🚧 Not supported yet (tracking issue: [#1291](https://github.com/winglang/wing/issues/1291)). - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#1292](https://github.com/winglang/wing/issues/1292)). -## API Reference - -### Schedule - -A schedule. - -#### Initializers - -```wing -bring cloud; - -new cloud.Schedule(props?: ScheduleProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | ScheduleProps | *No description.* | - ---- - -##### `props`Optional - -- *Type:* ScheduleProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| onTick | Create a function that runs when receiving the scheduled event. | - ---- - -##### `onTick` - -```wing -onTick(inflight: IScheduleOnTickHandler, props?: ScheduleOnTickOptions): Function -``` - -Create a function that runs when receiving the scheduled event. - -###### `inflight`Required - -- *Type:* IScheduleOnTickHandler - ---- - -###### `props`Optional - -- *Type:* ScheduleOnTickOptions - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Schedule.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Schedule.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - - -## Structs - -### ScheduleOnTickOptions - -Options for Schedule.onTick. - -#### Initializer - -```wing -bring cloud; - -let ScheduleOnTickOptions = cloud.ScheduleOnTickOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ScheduleProps - -Options for `Schedule`. - -#### Initializer - -```wing -bring cloud; - -let ScheduleProps = cloud.ScheduleProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| cron | str | Trigger events according to a cron schedule using the UNIX cron format. | -| rate | duration | Trigger events at a periodic rate. | - ---- - -##### `cron`Optional - -```wing -cron: str; -``` - -- *Type:* str -- *Default:* undefined - -Trigger events according to a cron schedule using the UNIX cron format. - -Timezone is UTC. -[minute] [hour] [day of month] [month] [day of week] -'*' means all possible values. -'-' means a range of values. -',' means a list of values. -[minute] allows 0-59. -[hour] allows 0-23. -[day of month] allows 1-31. -[month] allows 1-12 or JAN-DEC. -[day of week] allows 0-6 or SUN-SAT. - ---- - -*Example* - -```wing -"* * * * *" -``` - - -##### `rate`Optional - -```wing -rate: duration; -``` - -- *Type:* duration -- *Default:* undefined - -Trigger events at a periodic rate. - ---- - -*Example* - -```wing -1m -``` - - -## Protocols - -### IScheduleOnTickHandler - -- *Extends:* IInflight - -- *Implemented By:* IScheduleOnTickHandler - -**Inflight client:** [@winglang/sdk.cloud.IScheduleOnTickHandlerClient](#@winglang/sdk.cloud.IScheduleOnTickHandlerClient) - -A resource with an inflight "handle" method that can be passed to `Schedule.on_tick`. - - - -### IScheduleOnTickHandlerClient - -- *Implemented By:* IScheduleOnTickHandlerClient - -Inflight client for `IScheduleOnTickHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that will be called when a message is received from the schedule. | - ---- - -##### `handle` - -```wing -inflight handle(): void -``` - -Function that will be called when a message is received from the schedule. - - diff --git a/docs/docs/04-standard-library/cloud/secret.md b/docs/docs/04-standard-library/cloud/secret.md deleted file mode 100644 index 73dafd421eb..00000000000 --- a/docs/docs/04-standard-library/cloud/secret.md +++ /dev/null @@ -1,314 +0,0 @@ ---- -title: Secret -id: secret -description: A built-in resource for securely storing secrets in the cloud. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - secrets, - ] -sidebar_position: 1 ---- - -The `cloud.Secret` class represents a secret value (like an API key, certificate, etc.) that is securely stored in the cloud. - -Secrets are encrypted at rest and in transit, and are only decrypted when they are used in a task. -Storing a secret allows you to use the value in different compute tasks while only having to rotate or revoke it in one place. - -You can use the [`wing secrets`](https://www.winglang.io/docs/tools/cli#store-secrets-wing-secrets) command to store secrets in the target platform. - -## Usage - -### Defining a secret - -```js example -bring cloud; - -let secret = new cloud.Secret( - name: "my-secret", // optional, defaults to a generated name -); -``` - -Before deploying your application, you will be expected to store the secret value in a secure place according to the target-specific instructions below. - -### Retrieving secret values - -```js example -bring cloud; - -let secret = new cloud.Secret( - name: "my-api-key", -); - -new cloud.Function(inflight () => { - let secretValue = secret.value(); // retrieve the secret as a `str` value - let secretValueAsJson = secret.valueJson(); // retrieve the secret as a `Json` value -}); -``` - -## Target-specific details - -### Simulator (`sim`) - -When using a secret in Wing's simulator, a secrets file must be added to your project in a file called: `.env`. -The simulator will look up secrets in this file by their `name`. -Secrets should be saved in a key=value format: - -```json -// .env -my-api-key=1234567890 -secret-key=secret-value -``` - -### AWS (`tf-aws` and `awscdk`) - -AWS implementations of `cloud.Secret` use [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html). -Before deploying your application, you must create a secret in the AWS account with the same `name` as the secret in your Wing application. -You can do this using the AWS CLI: - -```bash -aws secretsmanager create-secret --name my-api-key --secret-string 1234567890 -``` - -It's also possible to create a secret using the AWS console. -See [AWS documentation](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html) for more details. - -### Azure (`tf-azure`) - -🚧 Not supported yet (tracking issue: [#2178](https://github.com/winglang/wing/issues/2178)) - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#2179](https://github.com/winglang/wing/issues/2179)) -## API Reference - -### Secret - -A cloud secret. - -#### Initializers - -```wing -bring cloud; - -new cloud.Secret(props?: SecretProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | SecretProps | *No description.* | - ---- - -##### `props`Optional - -- *Type:* SecretProps - ---- - -#### Methods - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| value | Retrieve the value of the secret. | -| valueJson | Retrieve the Json value of the secret. | - ---- - -##### `value` - -```wing -inflight value(options?: GetSecretValueOptions): str -``` - -Retrieve the value of the secret. - -###### `options`Optional - -- *Type:* GetSecretValueOptions - ---- - -##### `valueJson` - -```wing -inflight valueJson(options?: GetSecretValueOptions): Json -``` - -Retrieve the Json value of the secret. - -###### `options`Optional - -- *Type:* GetSecretValueOptions - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Secret.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Secret.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| name | str | Get secret name. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `name`Optional - -```wing -name: str; -``` - -- *Type:* str - -Get secret name. - ---- - - - -## Structs - -### GetSecretValueOptions - -Options when getting a secret value. - -#### Initializer - -```wing -bring cloud; - -let GetSecretValueOptions = cloud.GetSecretValueOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| cache | bool | Whether to cache the value. | - ---- - -##### `cache`Optional - -```wing -cache: bool; -``` - -- *Type:* bool -- *Default:* true - -Whether to cache the value. - ---- - -### SecretProps - -Options for `Secret`. - -#### Initializer - -```wing -bring cloud; - -let SecretProps = cloud.SecretProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| name | str | The secret's name. | - ---- - -##### `name`Optional - -```wing -name: str; -``` - -- *Type:* str -- *Default:* a new secret is provisioned with a generated name - -The secret's name. - -If no name is provided then a new secret is provisioned in the target. -If a name is provided then the resource will reference an existing -secret in the target. - ---- - - diff --git a/docs/docs/04-standard-library/cloud/service.md b/docs/docs/04-standard-library/cloud/service.md deleted file mode 100644 index b3ee75638b6..00000000000 --- a/docs/docs/04-standard-library/cloud/service.md +++ /dev/null @@ -1,558 +0,0 @@ ---- -title: Service -id: service -description: A built-in resource for publishing messages to subscribers. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - services, - ] -sidebar_position: 1 ---- - -The `cloud.Service` class represents a cloud service that has a start and optional stop lifecycle. - -Services are a common way to define long running code, such as microservices. - -## Usage - -### Creating a service - -When defining a service, the first argument is an inflight closure that represents -the service handler. This handler is responsible to perform any initialization -activity and **return asynchronously** when initialization is complete. - -```js -bring cloud; - -new cloud.Service(inflight () => { - // ... - // kick off any initialization activities asynchronously - // ... - log("Service started..."); -}); -``` - -### Disable auto-start - -By default the service resource will start automatically, however this can be disabled by passing -`autoStart: false` to the constructor. - -```js -bring cloud; - -let handler = inflight () => { - log("service started..."); -}; - -let service = new cloud.Service(handler, autoStart: false); -``` - -### Service cleanup - -Optionally, the service handler inflight closure can return another inflight closure which will be -called when the service is stopped. Using a return closure allows naturally passing context between -the async calls. - -```js -bring cloud; - -new cloud.Service(inflight() => { - let server = startHttpServer(); - log("Service started..."); - return () => { - log("Service stopped..."); - server.close(); - }; -}); -``` - -### Stopping and starting a service - -The inflight methods `start()` and `stop()` are used exactly how they sound, to stop and start the -service. The method `started()` returns a `bool` indicating if the service is currently started. - -Here is an example of using a service that will track how often it is started and stopped using -counters. - -An important aspect to note is that consecutive starts and stops have no affect on a service. For -example, if a `service.start()` is called on a service that is already started, nothing will happen. - -```js -bring cloud; - -let startCounter = new cloud.Counter() as "start counter"; -let stopCounter = new cloud.Counter() as "stop counter"; - -let handler = inflight() => { - let i = startCounter.inc(); - log("Service started for the ${i}th time..."); - return () => { - let i = stopCounter.inc(); - log("Service stopped for the ${i}th time..."); - }; -}; - -let service = new cloud.Service(handler, autoStart: false); - -// Functions to stop and start the service -new cloud.Function(inflight() => { - service.start(); - assert(service.started()); -}) as "start service"; - -new cloud.Function(inflight() => { - service.stop(); - assert(!service.started()); -}) as "stop service"; -``` - -## Target-specific details - -### Simulator (`sim`) - -Within the context of the simulator, services are just spawned processes ran within a node vm. - -### AWS (`tf-aws` and `awscdk`) - -Within the context of AWS, services are created using AWS ECS, with a capacity provider of FARGATE. This also requires a VPC and a related resources -such as security groups, subnets, and an internet gateway, etc. If a VPC is not specified in `wing.toml`, a default VPC will be created. - -The inflight closures are packaged up into a docker image and pushed to an AWS ECR repository. - -### Azure (`tf-azure`) - -🚧 Not supported yet (tracking issue: [#1307](https://github.com/winglang/wing/issues/1307)) - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#1308](https://github.com/winglang/wing/issues/1308)) -## API Reference - -### Service - -- *Implements:* IInflightHost - -A long-running service. - -#### Initializers - -```wing -bring cloud; - -new cloud.Service(handler: IServiceHandler, props?: ServiceProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| handler | IServiceHandler | *No description.* | -| props | ServiceProps | *No description.* | - ---- - -##### `handler`Required - -- *Type:* IServiceHandler - ---- - -##### `props`Optional - -- *Type:* ServiceProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| addEnvironment | Add an environment variable to the function. | - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| start | Start the service. | -| started | Indicates whether the service is started. | -| stop | Stop the service. | - ---- - -##### `addEnvironment` - -```wing -addEnvironment(name: str, value: str): void -``` - -Add an environment variable to the function. - -###### `name`Required - -- *Type:* str - ---- - -###### `value`Required - -- *Type:* str - ---- - -##### `start` - -```wing -inflight start(): void -``` - -Start the service. - -##### `started` - -```wing -inflight started(): bool -``` - -Indicates whether the service is started. - -##### `stop` - -```wing -inflight stop(): void -``` - -Stop the service. - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Service.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Service.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| env | MutMap<str> | Returns the set of environment variables for this function. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `env`Required - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> - -Returns the set of environment variables for this function. - ---- - - - -## Structs - -### ServiceOnStartOptions - -Options for Service.onStart. - -#### Initializer - -```wing -bring cloud; - -let ServiceOnStartOptions = cloud.ServiceOnStartOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### ServiceProps - -Options for `Service`. - -#### Initializer - -```wing -bring cloud; - -let ServiceProps = cloud.ServiceProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| autoStart | bool | Whether the service should start automatically. | -| env | MutMap<str> | Environment variables to pass to the function. | - ---- - -##### `autoStart`Optional - -```wing -autoStart: bool; -``` - -- *Type:* bool -- *Default:* true - -Whether the service should start automatically. - -If `false`, the service will need to be started -manually by calling the inflight `start()` method. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -## Protocols - -### IServiceHandler - -- *Extends:* IInflight - -- *Implemented By:* IServiceHandler - -**Inflight client:** [@winglang/sdk.cloud.IServiceHandlerClient](#@winglang/sdk.cloud.IServiceHandlerClient) - -Executed when a `cloud.Service` is started. - - - -### IServiceHandlerClient - -- *Implemented By:* IServiceHandlerClient - -Inflight client for `IServiceHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Handler to run when the service starts. | - ---- - -##### `handle` - -```wing -inflight handle(): IServiceStopHandler? -``` - -Handler to run when the service starts. - -This is where you implement the initialization logic of -the service, start any activities asynchronously. - -DO NOT BLOCK! This handler should return as quickly as possible. If you need to run a long -running process, start it asynchronously. - -*Example* - -```wing -bring cloud; - -new cloud.Service(inflight () => { - log("starting service..."); - return () => { - log("stoping service..."); - }; -}); -``` - - - -### IServiceStopHandler - -- *Extends:* IInflight - -- *Implemented By:* IServiceStopHandler - -**Inflight client:** [@winglang/sdk.cloud.IServiceStopHandlerClient](#@winglang/sdk.cloud.IServiceStopHandlerClient) - -Executed when a `cloud.Service` is stopped. - - - -### IServiceStopHandlerClient - -- *Implemented By:* IServiceStopHandlerClient - -Inflight client for `IServiceStopHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Handler to run when the service stops. | - ---- - -##### `handle` - -```wing -inflight handle(): void -``` - -Handler to run when the service stops. - -This is where you implement the cleanup logic of -the service, stop any activities asychronously. - - diff --git a/docs/docs/04-standard-library/cloud/topic.md b/docs/docs/04-standard-library/cloud/topic.md deleted file mode 100644 index 11253eba690..00000000000 --- a/docs/docs/04-standard-library/cloud/topic.md +++ /dev/null @@ -1,507 +0,0 @@ ---- -title: Topic -id: topic -description: A built-in resource for publishing messages to subscribers. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - topics, - ] -sidebar_position: 1 ---- - -The `cloud.Topic` class represents a subject of data that is open for subscription. - -Topics are a staple of event-driven architectures, especially those that rely on pub-sub messaging to decouple producers of data and the consumers of said data. - -## Usage - -### Creating a topic - -```js example -bring cloud; - -let topic = new cloud.Topic(); -``` - -### Subscribing to a topic - -```js example -bring cloud; - -let topic = new cloud.Topic(); - -topic.onMessage(inflight (message: str) => { - log("Topic published message: {message}"); -}); -``` - -### Subscribing a Queue to a Topic - -```js example -bring cloud; - -let queue = new cloud.Queue(); -queue.setConsumer(inflight (message: str) => { - log("Topic published message: {message}"); -}); - -let topic = new cloud.Topic(); -topic.subscribeQueue(queue); -``` - -### Publishing to a topic - -The inflight method `publish` sends messages to all of the topic's subscribers. - -```js example -bring cloud; - -let topic = new cloud.Topic(); - -inflight () => { - topic.publish( - "Topics can now publish", - "multiple messages at once" - ); -}; -``` - -### Simple pub-sub example - -Here is an example of combining the preflight and inflight apis for a topic and creating an adorable -simple pub-sub application. - -```js example -bring cloud; - -// First we create a topic -let topic = new cloud.Topic(); - -// Then we define a consumer inflight handler -let consumerHandler = inflight(message: str) => { - log("Doing some work with message: {message}"); -}; - -// Now we can use a preflight method of topic to register the consumer handler -// to be invoked when a message is published to the topic. -topic.onMessage(consumerHandler); - -// Then we define the producer inflight handler -let publisherHandler = inflight () => { - // Here we use the inflight api to publish a message to the topic. - topic.publish("Here are those launch codes you asked for."); -}; - -// Finally we can use multiple resources to invoke our publisher handler -// for simplicity sake we will just use a function. -new cloud.Function(publisherHandler); -``` - -## Target-specific details - -### Simulator (`sim`) - -Within the context of the simulator, topics are implemented by keeping an in-memory list of subscribers and publishing messages to them when `publish` is called. - -### AWS (`tf-aws` and `awscdk`) - -AWS implementations of `cloud.Topic` use [AWS SNS](https://docs.aws.amazon.com/sns/latest/dg/welcome.html). - -### Azure (`tf-azure`) - -🚧 Not supported yet (tracking issue: [#621](https://github.com/winglang/wing/issues/621)) - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#620](https://github.com/winglang/wing/issues/620)) -## API Reference - -### Topic - -A topic. - -#### Initializers - -```wing -bring cloud; - -new cloud.Topic(props?: TopicProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | TopicProps | *No description.* | - ---- - -##### `props`Optional - -- *Type:* TopicProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| onMessage | Run an inflight whenever an message is published to the topic. | -| subscribeQueue | Subscribing queue to the topic. | - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| publish | Publish messages to topic, if multiple messages are passed then they will be published as a batch if supported by the target platform. | - ---- - -##### `onMessage` - -```wing -onMessage(inflight: ITopicOnMessageHandler, props?: TopicOnMessageOptions): Function -``` - -Run an inflight whenever an message is published to the topic. - -###### `inflight`Required - -- *Type:* ITopicOnMessageHandler - ---- - -###### `props`Optional - -- *Type:* TopicOnMessageOptions - ---- - -##### `subscribeQueue` - -```wing -subscribeQueue(queue: Queue, props?: TopicSubscribeQueueOptions): void -``` - -Subscribing queue to the topic. - -###### `queue`Required - -- *Type:* Queue - ---- - -###### `props`Optional - -- *Type:* TopicSubscribeQueueOptions - ---- - -##### `publish` - -```wing -inflight publish(...messages: Array): void -``` - -Publish messages to topic, if multiple messages are passed then they will be published as a batch if supported by the target platform. - -###### `messages`Required - -- *Type:* str - -Payload to publish to Topic. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Topic.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Topic.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - - -## Structs - -### TopicOnMessageOptions - -Options for `Topic.onMessage`. - -#### Initializer - -```wing -bring cloud; - -let TopicOnMessageOptions = cloud.TopicOnMessageOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| concurrency | num | The maximum concurrent invocations that can run at one time. | -| env | MutMap<str> | Environment variables to pass to the function. | -| logRetentionDays | num | Specifies the number of days that function logs will be kept. | -| memory | num | The amount of memory to allocate to the function, in MB. | -| timeout | duration | The maximum amount of time the function can run. | - ---- - -##### `concurrency`Optional - -```wing -concurrency: num; -``` - -- *Type:* num -- *Default:* platform specific limits (100 on the simulator) - -The maximum concurrent invocations that can run at one time. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* No environment variables. - -Environment variables to pass to the function. - ---- - -##### `logRetentionDays`Optional - -```wing -logRetentionDays: num; -``` - -- *Type:* num -- *Default:* 30 - -Specifies the number of days that function logs will be kept. - -Setting negative value means logs will not expire. - ---- - -##### `memory`Optional - -```wing -memory: num; -``` - -- *Type:* num -- *Default:* 1024 - -The amount of memory to allocate to the function, in MB. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The maximum amount of time the function can run. - ---- - -### TopicProps - -Options for `Topic`. - -#### Initializer - -```wing -bring cloud; - -let TopicProps = cloud.TopicProps{ ... }; -``` - - -### TopicSubscribeQueueOptions - -Options for `Topic.subscribeQueue`. - -#### Initializer - -```wing -bring cloud; - -let TopicSubscribeQueueOptions = cloud.TopicSubscribeQueueOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| dlq | DeadLetterQueueProps | A dead-letter queue. | -| retentionPeriod | duration | How long a queue retains a message. | -| timeout | duration | How long a queue's consumers have to process a message. | - ---- - -##### `dlq`Optional - -```wing -dlq: DeadLetterQueueProps; -``` - -- *Type:* DeadLetterQueueProps -- *Default:* no dead letter queue - -A dead-letter queue. - ---- - -##### `retentionPeriod`Optional - -```wing -retentionPeriod: duration; -``` - -- *Type:* duration -- *Default:* 1h - -How long a queue retains a message. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 30s - -How long a queue's consumers have to process a message. - ---- - -## Protocols - -### ITopicOnMessageHandler - -- *Extends:* IInflight - -- *Implemented By:* ITopicOnMessageHandler - -**Inflight client:** [@winglang/sdk.cloud.ITopicOnMessageHandlerClient](#@winglang/sdk.cloud.ITopicOnMessageHandlerClient) - -A resource with an inflight "handle" method that can be passed to `Topic.on_message`. - - - -### ITopicOnMessageHandlerClient - -- *Implemented By:* ITopicOnMessageHandlerClient - -Inflight client for `ITopicOnMessageHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that will be called when a message is received from the topic. | - ---- - -##### `handle` - -```wing -inflight handle(event: str): void -``` - -Function that will be called when a message is received from the topic. - -###### `event`Required - -- *Type:* str - ---- - - diff --git a/docs/docs/04-standard-library/cloud/website.md b/docs/docs/04-standard-library/cloud/website.md deleted file mode 100644 index 0a0ebde366e..00000000000 --- a/docs/docs/04-standard-library/cloud/website.md +++ /dev/null @@ -1,528 +0,0 @@ ---- -title: Website -id: website -description: A built-in resource for creating static websites. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - Schedule, - Cron job, - ] -sidebar_position: 1 ---- - -The `cloud.Website` resource represents a static website that can be hosted in the cloud. -Websites are typically used to serve static content, such as HTML, CSS, and JavaScript files, which are updated whenever the application is redeployed. - -## Usage - -### Website - -```ts -bring cloud; - -let website = new cloud.Website(path: "./public"); -``` - -Under `./public/index.html` - -```html - - - Hello Winglang!!! - -``` - -### Webapp - -An extended Web App example including static Website, API Gateway and a Redis database, can be found in this [example project](https://github.com/winglang/research/tree/main/dogfooding/where-to-eat). - -## Target-specific details - -Review the [Website RFC](https://www.winglang.io/contributing/rfcs/2023-04-16-website-resource) for detailed information. - -### Pass variables to the website -You can pass dynamic variables from the main.w file to the website, and recuperate them by fetching the config.js file. -// inside main.w - -```ts -bring cloud; - -let website = new cloud.Website(path: "./static"); -let api = new cloud.Api(); - -website.addJson("config.json", { api: api.url }); -``` - -inside ./static/index.html - -```html - - - -... - - - -``` - - -### Simulator (`sim`) - -sim implementations of `cloud.Website` is using [nodejs express](https://expressjs.com/). - -### AWS (`tf-aws` and `awscdk`) - -AWS implementations of `cloud.Website` uses [Amazon S3](https://aws.amazon.com/s3/) & [Amazon CloudFront](https://www.amazonaws.cn/en/cloudfront/). - -### Azure (`tf-azure`) - -🚧 Not supported yet (tracking issue: [#1295](https://github.com/winglang/wing/issues/1295)) - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#1296](https://github.com/winglang/wing/issues/1296)) -## API Reference - -### Website - -- *Implements:* IWebsite - -A cloud static website. - -#### Initializers - -```wing -bring cloud; - -new cloud.Website(props: WebsiteProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | WebsiteProps | *No description.* | - ---- - -##### `props`Required - -- *Type:* WebsiteProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| addFile | Add a file to the website during deployment. | -| addJson | Add a JSON file with custom values during the website's deployment. | - ---- - -##### `addFile` - -```wing -addFile(path: str, data: str, options?: AddFileOptions): str -``` - -Add a file to the website during deployment. - -If the path conflicts with file path from the website's static assets, an error will be thrown. - -###### `path`Required - -- *Type:* str - -the file path it will be uploaded as. - ---- - -###### `data`Required - -- *Type:* str - -the data to write to the file. - ---- - -###### `options`Optional - -- *Type:* AddFileOptions - -configure the file's options. - ---- - -##### `addJson` - -```wing -addJson(path: str, data: Json): str -``` - -Add a JSON file with custom values during the website's deployment. - -If the path conflicts with file path from the website's static assets, an error will be thrown. - -###### `path`Required - -- *Type:* str - -the file path it will be uploaded as. - ---- - -###### `data`Required - -- *Type:* Json - -the data to write to the file. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring cloud; - -cloud.Website.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring cloud; - -cloud.Website.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| path | str | Absolute local path to the website's static files. | -| url | str | The website's url. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `path`Required - -```wing -path: str; -``` - -- *Type:* str - -Absolute local path to the website's static files. - ---- - -##### `url`Required - -```wing -url: str; -``` - -- *Type:* str - -The website's url. - ---- - - - -## Structs - -### AddFileOptions - -Options for adding a file with custom value during the website's deployment. - -#### Initializer - -```wing -bring cloud; - -let AddFileOptions = cloud.AddFileOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| contentType | str | File's content type. | - ---- - -##### `contentType`Optional - -```wing -contentType: str; -``` - -- *Type:* str - -File's content type. - ---- - -### WebsiteDomainOptions - -Options for `Website`. - -#### Initializer - -```wing -bring cloud; - -let WebsiteDomainOptions = cloud.WebsiteDomainOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| domain | Domain | The website's custom domain object. | - ---- - -##### `domain`Optional - -```wing -domain: Domain; -``` - -- *Type:* Domain -- *Default:* undefined - -The website's custom domain object. - ---- - -### WebsiteOptions - -Basic options for `Website`. - -#### Initializer - -```wing -bring cloud; - -let WebsiteOptions = cloud.WebsiteOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| path | str | Local path to the website's static files, relative to the Wing source file or absolute. | -| errorDocument | str | Name of the error document for the website. | - ---- - -##### `path`Required - -```wing -path: str; -``` - -- *Type:* str - -Local path to the website's static files, relative to the Wing source file or absolute. - ---- - -*Example* - -```wing -"./dist" -``` - - -##### `errorDocument`Optional - -```wing -errorDocument: str; -``` - -- *Type:* str -- *Default:* undefined - -Name of the error document for the website. - ---- - -*Example* - -```wing -"404.html" -``` - - -### WebsiteProps - -Options for `Website`. - -#### Initializer - -```wing -bring cloud; - -let WebsiteProps = cloud.WebsiteProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| path | str | Local path to the website's static files, relative to the Wing source file or absolute. | -| errorDocument | str | Name of the error document for the website. | -| domain | Domain | The website's custom domain object. | - ---- - -##### `path`Required - -```wing -path: str; -``` - -- *Type:* str - -Local path to the website's static files, relative to the Wing source file or absolute. - ---- - -*Example* - -```wing -"./dist" -``` - - -##### `errorDocument`Optional - -```wing -errorDocument: str; -``` - -- *Type:* str -- *Default:* undefined - -Name of the error document for the website. - ---- - -*Example* - -```wing -"404.html" -``` - - -##### `domain`Optional - -```wing -domain: Domain; -``` - -- *Type:* Domain -- *Default:* undefined - -The website's custom domain object. - ---- - -## Protocols - -### IWebsite - -- *Implemented By:* Website, IWebsite - -Base interface for a website. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| url | str | The website URL. | - ---- - -##### `url`Required - -```wing -url: str; -``` - -- *Type:* str - -The website URL. - ---- - diff --git a/docs/docs/04-standard-library/cloud/workload.md b/docs/docs/04-standard-library/cloud/workload.md deleted file mode 100644 index 2ebf9cc6981..00000000000 --- a/docs/docs/04-standard-library/cloud/workload.md +++ /dev/null @@ -1,378 +0,0 @@ ---- -title: Workload -id: workload -description: A built-in resource for handling containerized workloads -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - Kubernetes, - Containers, - Docker, - EKS, - ECS, - AKS - GKE - ] -sidebar_position: 1 ---- - -The `Workload` resource represents a scalable containerized service deployed and managed by a -container orchestration system such as Kubernetes. - -When running locally within the **Wing Simulator**, either during development or during builds, -workloads are implemented using local docker images. - -When running on the cloud, workloads become [Kubernetes](https://kubernetes.io/) applications, built -and published to an image registry and deployed to a Kubernetes cluster using -[Helm](https://helm.sh/). We currently only support AWS/EKS but support for other platforms are -planned. - -It will also be possible for platforms to implement workloads using any other compatible container -orchestration system such as [Amazon ECS](https://aws.amazon.com/ecs/), [fly.io](https://fly.io) or -[ControlPlane](https://controlplane.com/). - -> :warning: This resource is still experimental. Please ping the team on [Wing -> Discord](https://t.winglang.io/discord) if you encounter any issues or have any questions and let us -> know what you think. See [roadmap](#roadmap) below for more details about our plans. - -## Installation - -For the time being, in order to use this resource you will first first need to install -[@winglibs/containers](https://www.npmjs.com/package/@winglibs/containers) from npm: - -```sh -npm i @winglibs/containers -``` - -You will also need [Docker](https://www.docker.com/) or [OrbStack](https://orbstack.dev/) installed -on your system in order for workloads to work in the Wing Simulator. - -## Usage - -In your code, just `bring containers` and define workloads using the `containers.Workload` class. - -Check out a few examples below or jump to the full [API Reference](#api-reference). - -### Using an image from a registry - -Let's start with a simple example which defines a workload based on the -[hashicorp/http-echo](https://github.com/hashicorp/http-echo) image. It is a simple HTTP server -listening on port 5678 that responds with a message. - -```js -bring containers; - -let hello = new containers.Workload( - name: "hello", - image: "hashicorp/http-echo", - port: 5678, - public: true, - args: ["-text=hello, wingnuts!"], -); -``` - -In order to test this workload, we can use `publicUrl` which resolves to a publicly accessible route -into your container. And if you were wondering: Yes, this also works on the cloud! Every workload -with `public: true` will have a URL that can be used to access it from the web. - -```js -bring http; -bring expect; - -test "message is returned in http body" { - let url = hello.publicUrl ?? "FAIL"; - let body = http.get(url).body ?? "FAIL"; - log(body); - expect.equal(body, "hello, wingnuts!\n"); -} -``` - -### Building an image from source - -Workloads can also be be based on an image defined through a dockerfile within your project. The -image is automatically built during compilation and published to a container registry during -deployment. - -Let's define a workload which based on the docker image built from the dockerfile in the `./backend` -directory: - -```js -bring containers; - -new containers.Workload( - name: "backend", - image: "./backend", - port: 3000, - public: true -); -``` - -Under `./backend`, create: - -`backend/Dockerfile`: - -```dockerfile -FROM node:20.8.0-alpine -EXPOSE 3000 -ADD index.js /app/index.js -ENTRYPOINT [ "node", "/app/index.js" ] -``` - -`backend/index.js`: - -```js -const http = require('http'); - -process.on('SIGINT', () => process.exit(0)); - -const server = http.createServer((req, res) => { - console.log(`request received: ${req.method} ${req.url}`); - res.end('Hello, Wingnuts!'); -}); - -console.log('listening on port 3000'); -server.listen(3000); -``` - -### Defining multiple workloads as microservices - -Using `privateUrl`, it is possible to reach workloads without having to expose them publicly. - -Let's combine the last two examples by deploying the `http-echo` container and ping it from within -our docker image: - -```js -bring containers; - -let echo = new containers.Workload( - name: "echo", - image: "hashicorp/http-echo", - port: 5678, - args: ["-text=hello, wingnuts!"], -) as "echo"; - -let backend = new containers.Workload( - name: "backend", - image: "./backend", - port: 3000, - public: true, - env: { - ECHO_URL: echo.internalUrl - } -) as "backend"; -``` - -In `backend/index.js` file, we can access the internal URL of the `echo` workload -through `process.env.ECHO_URL`. - -Check out the full microservice example -[here](https://github.com/winglang/containers/blob/main/test/microservices.test.w). - -## API Reference - -### `name: str` - -This is a required option and must be a a unique name for the workload within the application. - -In the `tf-aws` target, this name will be used as the name of the Helm chart and the name of all the -resources associated with the workload in your Kubernetes cluster. - -### `image: str` - -This is another required option and can either be the name of a publicly available docker image or a -relative path to a docker build context directory (with a Dockerfile in it). - -### `port: num?` - -* `port: num?` (optional): internal port number listening. This is required to connect to a server - running inside the container. - -### `public: bool?` - -If this option is enabled, this workload will be accessible from the public internet through the URL -returned from `publicUrl`. When disabled, the container can only be accessed by other workloads in -the application via its `privateUrl`. - -When running in `sim`, the container will be accessible through a `localhost` port. - -When running on tf-aws (EKS), an -[Ingress](https://kubernetes.io/docs/concepts/services-networking/ingress/) resource will be defined -for this workload and an ALB (Application Load Balancer) will be allocated. The `publicUrl` of this -workload will contain the fully qualified host name that can be used to access the container from -the public internet. - -By default, containers are only accessible from within the same application through their -`privateUrl`. - -When `public` is enabled, `port` must also be set. - -### `readiness: str?` - -If this is specified, it is the URL path to send HTTP GET requests to in order to determine that the -workload has finished initialization. - -When deployed to Kubernetes, this is implemented using a [readiness -probe](https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-readiness-probes). - -By default, readiness probes are disabled. - -### `replicas: num?` - -Defines the number of container instances needed for this workload. - -When running in the simulator, this option is ignored and there is always a single container. - -When running in Kubernetes, this is implemented by setting `replicas` in the [Deployment -resource](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) that defines this -workload. - -By default this is set to 1 replica. - -### `sources: Array?` - -A list of [glob patterns](https://en.wikipedia.org/wiki/Glob_(programming)) which are used to match -the source files of the container. If any of these files change, the image is rebuilt and -invalidated. This is only relevant if the image is built from source. - -By default, this is all the files under the image directory. - -### `args` and `env` - -* `args: Array?` (optional): arguments to pass to the entrypoint. -* `env: Map?` (optional): environment variables. - -## Target-specific details - -### Simulator (`sim`) - -When executed in the Wing Simulator, the workload is started within a local Docker container. - -### AWS (`tf-aws`) - -Workloads are deployed to a Kubernetes cluster running on [Amazon EKS](https://aws.amazon.com/eks/). - -For each application, a Helm chart is synthesized with a -[Deployment](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/), -[Service](https://kubernetes.io/docs/concepts/services-networking/service/) and if the workload is -public, an [Ingress](https://kubernetes.io/docs/concepts/services-networking/ingress/) as well. - -By default, a new Amazon EKS cluster will be provisioned *for each Wing application*. This might be -okay in a situation where your cluster hosts only a single application, but it is very common to -share a single cluster across multiple applications. - -#### Creating a new EKS cluster - -To share a single EKS cluster across multiple Wing applications, you will first need to create a -cluster in your AWS account. If you already have a cluster, jump to [Deploying into an existing -cluster](#deploying-into-an-existing-eks-cluster) below. - -To create a compatible EKS cluster manually, we recommend to use use the `tfaws.Cluster` resource: - -`eks.main.w`: - -```js -bring containers; -new containers.Cluster("my-wing-cluster"); -``` - -And provision it using Terraform (this operation could take up to 20 minutes...): - -```sh -wing compile -t tf-aws eks.main.w -cd target/eks.main.tfaws -terraform init -terraform apply -``` - -To connect to our new cluster through `kubectl`, use `update-kubeconfig`: - -```sh -aws eks update-kubeconfig --name my-wing-cluster -``` - -Then: - -```sh -$ kubectl get all -NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE -service/kubernetes ClusterIP 172.20.0.1 443/TCP 36m -``` - -#### Deploying into an existing EKS cluster - -To deploy a workload into an the EKS cluster you just created or to an already existing cluster, you -will need to set the following platform values (this can be done using `-v X=Y` or `--values -values.yml`): - -* `eks.cluster_name`: The name of the cluster -* `eks.endpoint`: The URL of the Kubernetes API endpoint of the cluster -* `eks.certificate`: The certificate authority of this cluster. - -You can use the [eks-values.sh](https://github.com/winglang/containers/blob/main/eks-values.sh) -script to obtain the attributes of your EKS cluster. - -Install: - -```sh -$ curl https://raw.githubusercontent.com/winglang/containers/main/eks-values.sh > eks-values.sh -$ chmod +x ./eks-values.sh -``` - -Use: - -```sh -$ ./eks-values.sh CLUSTER-NAME > values.yaml -$ wing compile -t tf-aws --values ./values.yaml main.w -``` - -### Azure (`tf-azure`) - -Not supported yet. - -### GCP (`tf-gcp`) - -Not supported yet. - -## Roadmap - -The following is a non-exhaustive list of capabilities we are looking to add to this resource: - -### Scaling - -- [ ] Constraints -- [ ] Autoscaling - -### Networking - -- [ ] Access `cloud.*` resources from workloads (e.g. put an object in a bucket, poll a queue). -- [ ] Access something like `Redis` from a workload (unify VPCs) -- [ ] Access non-public workloads from `cloud.Function` - -### API - -- [ ] Allow defining workloads using inflights (`cloud.Service`) - -### Runtime - -- [ ] Logs -- [ ] Sidecar containers - -### Endpoints - -- [ ] SSL -- [ ] Custom domains - -### Platforms - -- [ ] ECS -- [ ] GKE -- [ ] AKS -- [ ] fly.io -- [ ] ControlPlane - - - diff --git a/docs/docs/04-standard-library/ex/react-app.md b/docs/docs/04-standard-library/ex/react-app.md deleted file mode 100644 index 954a38305e0..00000000000 --- a/docs/docs/04-standard-library/ex/react-app.md +++ /dev/null @@ -1,441 +0,0 @@ ---- -title: React App -id: react-app -description: A built-in resource for creating deployable websites using the React framework. -keywords: [Website, React, deployment, build] -sidebar_position: 1 ---- - -The `ex.ReactApp` resource represents a website, built using React, that can be both hosted in the cloud or to run on a development hot-reload server in the sim target. - -## Usage - -### Initialization - -Using the default arguments: - -```ts -bring ex; -bring util; - -let website = new ex.ReactApp(projectPath: "./client"); -``` - -or customizing them: - -```ts -bring ex; -bring util; - -let website = new ex.ReactApp( - projectPath: "./client", - useBuildCommand: true // `false` by default. Will run the build command if true, and the start command if not - buildDir: "/dist" // default is "/build" - startCommand: "pnpm start" // default is "npm start" - buildCommand: "pnpm build" // default is "npm build" - localPort: 4000 // default is 3001 - ); -``` - -When `ReactApp` is compiled to the `sim` target, by default it runs the start command (default: `npm start`) inside `projectPath` to serve your app in development mode on a local port. - -If the `useBuildCommand` environment variable is set OR if `ReactApp` is compiled to any other target, it will run the build command (default: `npm build`) inside of the `projectPath` to build the React app for production to `buildDir` and serve the app. - -### Using Wing variables within react code - -`ex.ReactApp` allows you to pass preflight string values from Wing to the React app using `addEnvironment` method: - -```ts -bring cloud; -bring util; -bring ex; - -let api = new cloud.Api(); -let website = new ex.ReactApp(projectPath: "./client"); - -website.addEnvironment("apiUrl", api.url); -website.addEnvironment("another", "some string variable"); - -``` - -Then in the React app use `window.wingEnv`: -(accessible after adding `` to the index file) - -```ts -const { apiUrl } = window.wingEnv; -const users = await fetch(apiUrl + "/users"); -``` - -Currently, we can only pass preflight string variables to the React app environment. - -## Target-specific details - -### Simulator (`sim`) - -sim implementations of `ex.ReactApp` is using either the [Website resource](../cloud/website) (when `useBuildCommand` is `true`) or starts React development server when `false`. - -### AWS (`tf-aws` and `awscdk`) - -AWS implementations of `ex.ReactApp` uses the [Website resource](../cloud/website). - -### Azure (`tf-azure`) - -🚧 Not supported yet (tracking issue: [#4220](https://github.com/winglang/wing/issues/4220)) - -### GCP (`tf-gcp`) - -🚧 Not supported yet (tracking issue: [#4221](https://github.com/winglang/wing/issues/4221)) -# API Reference - -## Resources - -### ReactApp - -A cloud deployable React App. - -#### Initializers - -```wing -bring ex; - -new ex.ReactApp(props: ReactAppProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | ReactAppProps | *No description.* | - ---- - -##### `props`Required - -- *Type:* ReactAppProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| addEnvironment | Adding a key-value pair that can be accessible later via the `window.wingEnv` object in the react code. | - ---- - -##### `addEnvironment` - -```wing -addEnvironment(key: str, value: str): void -``` - -Adding a key-value pair that can be accessible later via the `window.wingEnv` object in the react code. - -###### `key`Required - -- *Type:* str - -the key to add. - ---- - -###### `value`Required - -- *Type:* str - -the value to add. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | - ---- - -##### `onLiftType` - -```wing -bring ex; - -ex.ReactApp.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| url | str | Website's url. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `url`Required - -```wing -url: str; -``` - -- *Type:* str - -Website's url. - ---- - - - -## Structs - -### ReactAppOptions - -Basic options for `ReactApp`. - -#### Initializer - -```wing -bring ex; - -let ReactAppOptions = ex.ReactAppOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| projectPath | str | The path to the React app root folder- can be absolute or relative to the wing folder. | -| buildCommand | str | A command for building the React app. | -| buildDir | str | The path to the React app build folder- relative to the `projectPath`. | -| localPort | num | A port to start a local build of the React app on. | -| startCommand | str | A command for starting React app locally. | -| useBuildCommand | bool | In sim, if `true` - will use the start command, and if `false` - the build command. | - ---- - -##### `projectPath`Required - -```wing -projectPath: str; -``` - -- *Type:* str - -The path to the React app root folder- can be absolute or relative to the wing folder. - ---- - -##### `buildCommand`Optional - -```wing -buildCommand: str; -``` - -- *Type:* str -- *Default:* "npm run build" - -A command for building the React app. - ---- - -##### `buildDir`Optional - -```wing -buildDir: str; -``` - -- *Type:* str -- *Default:* "/build" - -The path to the React app build folder- relative to the `projectPath`. - ---- - -##### `localPort`Optional - -```wing -localPort: num; -``` - -- *Type:* num -- *Default:* 3001 - -A port to start a local build of the React app on. - ---- - -##### `startCommand`Optional - -```wing -startCommand: str; -``` - -- *Type:* str -- *Default:* "npm run start" - -A command for starting React app locally. - ---- - -##### `useBuildCommand`Optional - -```wing -useBuildCommand: bool; -``` - -- *Type:* bool -- *Default:* false - -In sim, if `true` - will use the start command, and if `false` - the build command. - ---- - -### ReactAppProps - -Options for `ReactApp`. - -#### Initializer - -```wing -bring ex; - -let ReactAppProps = ex.ReactAppProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| domain | Domain | The website's custom domain object. | -| projectPath | str | The path to the React app root folder- can be absolute or relative to the wing folder. | -| buildCommand | str | A command for building the React app. | -| buildDir | str | The path to the React app build folder- relative to the `projectPath`. | -| localPort | num | A port to start a local build of the React app on. | -| startCommand | str | A command for starting React app locally. | -| useBuildCommand | bool | In sim, if `true` - will use the start command, and if `false` - the build command. | - ---- - -##### `domain`Optional - -```wing -domain: Domain; -``` - -- *Type:* Domain -- *Default:* undefined - -The website's custom domain object. - ---- - -##### `projectPath`Required - -```wing -projectPath: str; -``` - -- *Type:* str - -The path to the React app root folder- can be absolute or relative to the wing folder. - ---- - -##### `buildCommand`Optional - -```wing -buildCommand: str; -``` - -- *Type:* str -- *Default:* "npm run build" - -A command for building the React app. - ---- - -##### `buildDir`Optional - -```wing -buildDir: str; -``` - -- *Type:* str -- *Default:* "/build" - -The path to the React app build folder- relative to the `projectPath`. - ---- - -##### `localPort`Optional - -```wing -localPort: num; -``` - -- *Type:* num -- *Default:* 3001 - -A port to start a local build of the React app on. - ---- - -##### `startCommand`Optional - -```wing -startCommand: str; -``` - -- *Type:* str -- *Default:* "npm run start" - -A command for starting React app locally. - ---- - -##### `useBuildCommand`Optional - -```wing -useBuildCommand: bool; -``` - -- *Type:* bool -- *Default:* false - -In sim, if `true` - will use the start command, and if `false` - the build command. - ---- - - diff --git a/docs/docs/04-standard-library/ex/redis.md b/docs/docs/04-standard-library/ex/redis.md deleted file mode 100644 index 6c69132ab9c..00000000000 --- a/docs/docs/04-standard-library/ex/redis.md +++ /dev/null @@ -1,458 +0,0 @@ ---- -title: Redis -id: redis -description: A cloud redis db. -keywords: [Redis, DB, database, store, cache] -sidebar_position: 1 ---- -# API Reference - -## Resources - -### Redis - -A cloud redis db. - -#### Initializers - -```wing -bring ex; - -new ex.Redis(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - -#### Methods - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| del | Removes the specified key. | -| get | Get value at given key. | -| hget | Returns the value associated with field in the hash stored at key. | -| hset | Sets the specified field to respective value in the hash stored at key. | -| sadd | Add the specified members to the set stored at key. | -| set | Set key value pair. | -| smembers | Returns all the members of the set value stored at key. | -| url | Get url of redis server. | - ---- - -##### `del` - -```wing -inflight del(key: str): num -``` - -Removes the specified key. - -###### `key`Required - -- *Type:* str - -the key. - ---- - -##### `get` - -```wing -inflight get(key: str): str? -``` - -Get value at given key. - -###### `key`Required - -- *Type:* str - -the key to get. - ---- - -##### `hget` - -```wing -inflight hget(key: str, field: str): str? -``` - -Returns the value associated with field in the hash stored at key. - -###### `key`Required - -- *Type:* str - -the key. - ---- - -###### `field`Required - -- *Type:* str - -the field at given key. - ---- - -##### `hset` - -```wing -inflight hset(key: str, field: str, value: str): num -``` - -Sets the specified field to respective value in the hash stored at key. - -###### `key`Required - -- *Type:* str - -key to set. - ---- - -###### `field`Required - -- *Type:* str - -field in key to set. - ---- - -###### `value`Required - -- *Type:* str - -value to set at field in key. - ---- - -##### `sadd` - -```wing -inflight sadd(key: str, value: str): num -``` - -Add the specified members to the set stored at key. - -###### `key`Required - -- *Type:* str - -the key. - ---- - -###### `value`Required - -- *Type:* str - -the value to add to the set at given key. - ---- - -##### `set` - -```wing -inflight set(key: str, value: str): void -``` - -Set key value pair. - -###### `key`Required - -- *Type:* str - -the key to set. - ---- - -###### `value`Required - -- *Type:* str - -the value to store at given key. - ---- - -##### `smembers` - -```wing -inflight smembers(key: str): MutArray -``` - -Returns all the members of the set value stored at key. - -###### `key`Required - -- *Type:* str - -the key. - ---- - -##### `url` - -```wing -inflight url(): str -``` - -Get url of redis server. - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring ex; - -ex.Redis.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring ex; - -ex.Redis.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - -## Classes - -### RedisClientBase - -- *Implements:* IRedisClient - -Base class for `Redis` Client. - -#### Initializers - -```wing -bring ex; - -new ex.RedisClientBase(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| del | Removes the specified key. | -| get | Get value at given key. | -| hget | Returns the value associated with field in the hash stored at key. | -| hset | Sets the specified field to respective value in the hash stored at key. | -| sadd | Add the specified members to the set stored at key. | -| set | Set key value pair. | -| smembers | Returns all the members of the set value stored at key. | -| url | Get url of redis server. | - ---- - -##### `del` - -```wing -del(key: str): num -``` - -Removes the specified key. - -###### `key`Required - -- *Type:* str - ---- - -##### `get` - -```wing -get(key: str): str? -``` - -Get value at given key. - -###### `key`Required - -- *Type:* str - ---- - -##### `hget` - -```wing -hget(key: str, field: str): str? -``` - -Returns the value associated with field in the hash stored at key. - -###### `key`Required - -- *Type:* str - ---- - -###### `field`Required - -- *Type:* str - ---- - -##### `hset` - -```wing -hset(key: str, field: str, value: str): num -``` - -Sets the specified field to respective value in the hash stored at key. - -###### `key`Required - -- *Type:* str - ---- - -###### `field`Required - -- *Type:* str - ---- - -###### `value`Required - -- *Type:* str - ---- - -##### `sadd` - -```wing -sadd(key: str, value: str): num -``` - -Add the specified members to the set stored at key. - -###### `key`Required - -- *Type:* str - ---- - -###### `value`Required - -- *Type:* str - ---- - -##### `set` - -```wing -set(key: str, value: str): void -``` - -Set key value pair. - -###### `key`Required - -- *Type:* str - ---- - -###### `value`Required - -- *Type:* str - ---- - -##### `smembers` - -```wing -smembers(key: str): MutArray -``` - -Returns all the members of the set value stored at key. - -###### `key`Required - -- *Type:* str - ---- - -##### `url` - -```wing -url(): str -``` - -Get url of redis server. - - - - - - diff --git a/docs/docs/04-standard-library/ex/table.md b/docs/docs/04-standard-library/ex/table.md deleted file mode 100644 index 2b93ebe153d..00000000000 --- a/docs/docs/04-standard-library/ex/table.md +++ /dev/null @@ -1,454 +0,0 @@ ---- -title: Table -id: table -description: A NoSQL database table that can be used to store and query data. -keywords: [dynamoDB, NoSQL, store, DB, database, cache] -sidebar_position: 1 ---- -# API Reference - -## Resources - -### Table - -A NoSQL database table that can be used to store and query data. - -#### Initializers - -```wing -bring ex; - -new ex.Table(props: TableProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | TableProps | *No description.* | - ---- - -##### `props`Required - -- *Type:* TableProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| addRow | Add a row to the table that is created when the app is deployed. | - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| delete | Delete a row from the table, by primary key. | -| get | Get a row from the table, by primary key. | -| insert | Insert a row into the table. | -| list | List all rows in the table. | -| tryGet | Get a row from the table if exists, by primary key. | -| update | Update a row in the table. | -| upsert | Insert a row into the table if it doesn't exist, otherwise update it. | - ---- - -##### `addRow` - -```wing -addRow(key: str, row: Json): void -``` - -Add a row to the table that is created when the app is deployed. - -###### `key`Required - -- *Type:* str - ---- - -###### `row`Required - -- *Type:* Json - ---- - -##### `delete` - -```wing -inflight delete(key: str): void -``` - -Delete a row from the table, by primary key. - -###### `key`Required - -- *Type:* str - -primary key to delete the row. - ---- - -##### `get` - -```wing -inflight get(key: str): Json -``` - -Get a row from the table, by primary key. - -###### `key`Required - -- *Type:* str - -primary key to search. - ---- - -##### `insert` - -```wing -inflight insert(key: str, row: Json): void -``` - -Insert a row into the table. - -###### `key`Required - -- *Type:* str - -primary key to insert the row. - ---- - -###### `row`Required - -- *Type:* Json - -data to be inserted. - ---- - -##### `list` - -```wing -inflight list(): MutArray -``` - -List all rows in the table. - -##### `tryGet` - -```wing -inflight tryGet(key: str): Json? -``` - -Get a row from the table if exists, by primary key. - -###### `key`Required - -- *Type:* str - -primary key to search. - ---- - -##### `update` - -```wing -inflight update(key: str, row: Json): void -``` - -Update a row in the table. - -###### `key`Required - -- *Type:* str - -primary key to update the row. - ---- - -###### `row`Required - -- *Type:* Json - -data to be updated. - ---- - -##### `upsert` - -```wing -inflight upsert(key: str, row: Json): void -``` - -Insert a row into the table if it doesn't exist, otherwise update it. - -###### `key`Required - -- *Type:* str - -primary key to upsert the row. - ---- - -###### `row`Required - -- *Type:* Json - -data to be upserted. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring ex; - -ex.Table.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring ex; - -ex.Table.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| columns | MutMap<ColumnType> | Table columns. | -| name | str | Table name. | -| primaryKey | str | Table primary key name. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `columns`Required - -```wing -columns: MutMap; -``` - -- *Type:* MutMap<ColumnType> - -Table columns. - ---- - -##### `name`Required - -```wing -name: str; -``` - -- *Type:* str - -Table name. - ---- - -##### `primaryKey`Required - -```wing -primaryKey: str; -``` - -- *Type:* str - -Table primary key name. - ---- - - - -## Structs - -### TableProps - -Properties for `Table`. - -#### Initializer - -```wing -bring ex; - -let TableProps = ex.TableProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| columns | MutMap<ColumnType> | The table's columns. | -| initialRows | MutMap<Json> | The table's initial rows. | -| name | str | The table's name. | -| primaryKey | str | The table's primary key. | - ---- - -##### `columns`Optional - -```wing -columns: MutMap; -``` - -- *Type:* MutMap<ColumnType> -- *Default:* undefined - -The table's columns. - ---- - -##### `initialRows`Optional - -```wing -initialRows: MutMap; -``` - -- *Type:* MutMap<Json> -- *Default:* undefined - -The table's initial rows. - ---- - -##### `name`Optional - -```wing -name: str; -``` - -- *Type:* str -- *Default:* undefined - -The table's name. - ---- - -##### `primaryKey`Optional - -```wing -primaryKey: str; -``` - -- *Type:* str -- *Default:* undefined - -The table's primary key. - -No two rows can have the same value for the -primary key. - ---- - - -## Enums - -### ColumnType - -Table column types. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| STRING | String type. | -| NUMBER | Number type. | -| BOOLEAN | Bool type. | -| DATE | Date type. | -| JSON | Json type. | - ---- - -##### `STRING` - -String type. - ---- - - -##### `NUMBER` - -Number type. - ---- - - -##### `BOOLEAN` - -Bool type. - ---- - - -##### `DATE` - -Date type. - ---- - - -##### `JSON` - -Json type. - ---- - diff --git a/docs/docs/04-standard-library/expect/api-reference.md b/docs/docs/04-standard-library/expect/api-reference.md deleted file mode 100644 index 2dc3972033f..00000000000 --- a/docs/docs/04-standard-library/expect/api-reference.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: API reference -id: api-reference -description: Wing standard library API reference for the expect module -keywords: [Wing sdk, sdk, Wing API Reference] -hide_title: true -sidebar_position: 100 ---- - - -# API Reference - - -## Classes - -### Expect - -The Util class provides methods for making assertions in tests, such as comparing two strings for equality with rich error messages. - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| doesNotMatch | Checks if a string does not match a regular expression pattern. | -| equal | Compares two values for equality. | -| fail | Marks a test as failed. | -| match | Checks if a string matches a regular expression pattern. | -| nil | Checks if a value is nil. | -| notEqual | Compares two values for inequality. | -| notNil | Checks if a value is not nil. | -| ok | Asserts that a condition is truthy. | - ---- - -##### `doesNotMatch` - -```wing -bring expect; - -inflight expect.doesNotMatch(actual: str, expected: str); -``` - -Checks if a string does not match a regular expression pattern. - -###### `actual`Required - -- *Type:* str - -The string to test. - ---- - -###### `expected`Required - -- *Type:* str - -The regular expression pattern to check against. - ---- - -##### `equal` - -```wing -bring expect; - -inflight expect.equal(actual: any, expected: any); -``` - -Compares two values for equality. - -###### `actual`Required - -- *Type:* any - -The value to test. - ---- - -###### `expected`Required - -- *Type:* any - -The expected value. - ---- - -##### `fail` - -```wing -bring expect; - -inflight expect.fail(message?: str); -``` - -Marks a test as failed. - -###### `message`Optional - -- *Type:* str - -An optional message to include with the failure. - ---- - -##### `match` - -```wing -bring expect; - -inflight expect.match(actual: str, expected: str); -``` - -Checks if a string matches a regular expression pattern. - -###### `actual`Required - -- *Type:* str - -The string to test. - ---- - -###### `expected`Required - -- *Type:* str - -The regular expression pattern to match against. - ---- - -##### `nil` - -```wing -bring expect; - -inflight expect.nil(actual: any); -``` - -Checks if a value is nil. - -###### `actual`Required - -- *Type:* any - -The value to test. - ---- - -##### `notEqual` - -```wing -bring expect; - -inflight expect.notEqual(actual: any, expected: any); -``` - -Compares two values for inequality. - -###### `actual`Required - -- *Type:* any - -The value to test. - ---- - -###### `expected`Required - -- *Type:* any - -The expected value. - ---- - -##### `notNil` - -```wing -bring expect; - -inflight expect.notNil(actual: any); -``` - -Checks if a value is not nil. - -###### `actual`Required - -- *Type:* any - -The value to test. - ---- - -##### `ok` - -```wing -bring expect; - -inflight expect.ok(condition: bool, message?: str); -``` - -Asserts that a condition is truthy. - -###### `condition`Required - -- *Type:* bool - -The condition to test. - ---- - -###### `message`Optional - -- *Type:* str - -An optional message to include if the condition is falsy. - ---- - - - - - diff --git a/docs/docs/04-standard-library/fs/api-reference.md b/docs/docs/04-standard-library/fs/api-reference.md deleted file mode 100644 index d1f9e903155..00000000000 --- a/docs/docs/04-standard-library/fs/api-reference.md +++ /dev/null @@ -1,1254 +0,0 @@ ---- -title: API reference -id: api-reference -description: Wing standard library API reference for the fs module -keywords: [Wing sdk, sdk, Wing API Reference] -hide_title: true -sidebar_position: 100 ---- - - -# API Reference - - -## Classes - -### Fs - -The fs class is used for interacting with the file system. - -All file paths must be POSIX file paths (/ instead of \), -and will be normalized to the target platform if running on Windows. - -#### Initializers - -```wing -bring fs; - -new fs.Util(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| absolute | The right-most parameter is considered {to}. Other parameters are considered an array of {from}. | -| appendFile | Appends new data to the end of an existing file. | -| basename | Retrieve the final segment of a given file path. | -| dirname | Retrieve the name of the directory from a given file path. | -| exists | Check if the path exists. | -| extension | Extracts the extension (without the leading dot) from the path, if possible. | -| glob | Match files using the patterns the shell uses. | -| isDir | Checks if the given path is a directory and exists. | -| join | Join all arguments together and normalize the resulting path. | -| md5 | Calculate an MD5 content hash of all the files that match a glob pattern. | -| metadata | Gets the stats of the given path. | -| mkdir | Create a directory. | -| mkdtemp | Create a temporary directory. | -| readdir | Read the contents of the directory. | -| readFile | Read the entire contents of a file. | -| readJson | Read the contents of the file and convert it to JSON. | -| readYaml | Convert all YAML objects from a single file into JSON objects. | -| relative | Solve the relative path from {from} to {to} based on the current working directory. | -| remove | Remove files and directories (modeled on the standard POSIX `rm`utility). | -| setPermissions | Set the permissions of the file, directory, etc. | -| symlink | Creates a symbolic link. | -| symlinkMetadata | Gets the stats of the given path without following symbolic links. | -| tryReaddir | If the path exists, read the contents of the directory; | -| tryReadFile | If the file exists and can be read successfully, read the entire contents; | -| tryReadJson | Retrieve the contents of the file and convert it to JSON if the file exists and can be parsed successfully, otherwise, return `undefined`. | -| tryReadYaml | Convert all YAML objects from a single file into JSON objects if the file exists and can be parsed successfully, `undefined` otherwise. | -| writeFile | Writes data to a file, replacing the file if it already exists. | -| writeJson | Writes JSON to a file, replacing the file if it already exists. | -| writeYaml | Writes multiple YAML objects to a file, replacing the file if it already exists. | - ---- - -##### `absolute` - -```wing -bring fs; - -fs.absolute(...paths: Array); -``` - -The right-most parameter is considered {to}. Other parameters are considered an array of {from}. - -Starting from leftmost {from} parameter, resolves {to} to an absolute path. - -If {to} isn't already absolute, {from} arguments are prepended in right to left order, -until an absolute path is found. If after using all {from} paths still no absolute path is found, -the current working directory is used as well. The resulting path is normalized, -and trailing slashes are removed unless the path gets resolved to the root directory. - -###### `paths`Required - -- *Type:* str - -A sequence of paths or path segments. - ---- - -##### `appendFile` - -```wing -bring fs; - -fs.appendFile(filepath: str, data: str, options?: WriteFileOptions); -``` - -Appends new data to the end of an existing file. - -###### `filepath`Required - -- *Type:* str - -The file path that needs to be appended. - ---- - -###### `data`Required - -- *Type:* str - -The text to be appended to the file. - ---- - -###### `options`Optional - -- *Type:* WriteFileOptions - -The `encoding` can be set to specify the character encoding. - -And the `flag` can be set to specify the attributes. -If a flag is not provided, it defaults to `"w"`. - ---- - -##### `basename` - -```wing -bring fs; - -fs.basename(path: str); -``` - -Retrieve the final segment of a given file path. - -###### `path`Required - -- *Type:* str - -The path to evaluate. - ---- - -##### `dirname` - -```wing -bring fs; - -fs.dirname(path: str); -``` - -Retrieve the name of the directory from a given file path. - -###### `path`Required - -- *Type:* str - -The path to evaluate. - ---- - -##### `exists` - -```wing -bring fs; - -fs.exists(path: str); -``` - -Check if the path exists. - -###### `path`Required - -- *Type:* str - -The path to evaluate. - ---- - -##### `extension` - -```wing -bring fs; - -fs.extension(path: str); -``` - -Extracts the extension (without the leading dot) from the path, if possible. - -###### `path`Required - -- *Type:* str - -The path to get extension for. - ---- - -##### `glob` - -```wing -bring fs; - -fs.glob(pattern: str, options?: GlobOptions); -``` - -Match files using the patterns the shell uses. - -Built with the great `glob` package, based on https://www.npmjs.com/package/glob - -###### `pattern`Required - -- *Type:* str - -The pattern to match. - ---- - -###### `options`Optional - -- *Type:* GlobOptions - -Glob options. - ---- - -##### `isDir` - -```wing -bring fs; - -fs.isDir(path: str); -``` - -Checks if the given path is a directory and exists. - -###### `path`Required - -- *Type:* str - -The path to check. - ---- - -##### `join` - -```wing -bring fs; - -fs.join(...paths: Array); -``` - -Join all arguments together and normalize the resulting path. - -###### `paths`Required - -- *Type:* str - -The array of path need to join. - ---- - -##### `md5` - -```wing -bring fs; - -fs.md5(dir: str, globPattern?: str); -``` - -Calculate an MD5 content hash of all the files that match a glob pattern. - -###### `dir`Required - -- *Type:* str - -The root directory. - ---- - -###### `globPattern`Optional - -- *Type:* str - -The glob pattern to match (defaults to all files and subdirectories). - ---- - -##### `metadata` - -```wing -bring fs; - -fs.metadata(path: str); -``` - -Gets the stats of the given path. - -###### `path`Required - -- *Type:* str - -The path to get stats for. - ---- - -##### `mkdir` - -```wing -bring fs; - -fs.mkdir(dirpath: str, opts?: MkdirOptions); -``` - -Create a directory. - -###### `dirpath`Required - -- *Type:* str - -The path to the directory you want to create. - ---- - -###### `opts`Optional - -- *Type:* MkdirOptions - ---- - -##### `mkdtemp` - -```wing -bring fs; - -fs.mkdtemp(prefix?: str); -``` - -Create a temporary directory. - -Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - -###### `prefix`Optional - -- *Type:* str - -The prefix for the directory to be created, default `wingtemp`. - ---- - -##### `readdir` - -```wing -bring fs; - -fs.readdir(dirpath: str); -``` - -Read the contents of the directory. - -###### `dirpath`Required - -- *Type:* str - -The path to evaluate. - ---- - -##### `readFile` - -```wing -bring fs; - -fs.readFile(filepath: str, options?: ReadFileOptions); -``` - -Read the entire contents of a file. - -###### `filepath`Required - -- *Type:* str - -The path of the file to be read. - ---- - -###### `options`Optional - -- *Type:* ReadFileOptions - -The `encoding` can be set to specify the character encoding. - -And the `flag` can be set to specify the attributes. -If a flag is not provided, it defaults to `"r"`. - ---- - -##### `readJson` - -```wing -bring fs; - -fs.readJson(filepath: str); -``` - -Read the contents of the file and convert it to JSON. - -###### `filepath`Required - -- *Type:* str - -The file path of the JSON file. - ---- - -##### `readYaml` - -```wing -bring fs; - -fs.readYaml(filepath: str); -``` - -Convert all YAML objects from a single file into JSON objects. - -###### `filepath`Required - -- *Type:* str - -The file path of the YAML file. - ---- - -##### `relative` - -```wing -bring fs; - -fs.relative(from: str, to: str); -``` - -Solve the relative path from {from} to {to} based on the current working directory. - -At times we have two absolute paths, and we need to derive the relative path from one to the other. - -###### `from`Required - -- *Type:* str - ---- - -###### `to`Required - -- *Type:* str - ---- - -##### `remove` - -```wing -bring fs; - -fs.remove(path: str, opts?: RemoveOptions); -``` - -Remove files and directories (modeled on the standard POSIX `rm`utility). - -Returns `undefined`. - -###### `path`Required - -- *Type:* str - -The path to the file or directory you want to remove. - ---- - -###### `opts`Optional - -- *Type:* RemoveOptions - ---- - -##### `setPermissions` - -```wing -bring fs; - -fs.setPermissions(path: str, permissions: str); -``` - -Set the permissions of the file, directory, etc. - -Expects a permission string like `"755"` or `"644"`. - -###### `path`Required - -- *Type:* str - -The path of the file or directory. - ---- - -###### `permissions`Required - -- *Type:* str - -The mode to set as a string. - ---- - -##### `symlink` - -```wing -bring fs; - -fs.symlink(target: str, path: str, type?: SymlinkType); -``` - -Creates a symbolic link. - -###### `target`Required - -- *Type:* str - -The path to the target file or directory. - ---- - -###### `path`Required - -- *Type:* str - -The path to the symbolic link to be created. - ---- - -###### `type`Optional - -- *Type:* SymlinkType - -The type of the target. - -It can be `FILE`, `DIRECTORY`, or `JUNCTION` (Windows only). -Defaults to `FILE` if not specified. - ---- - -##### `symlinkMetadata` - -```wing -bring fs; - -fs.symlinkMetadata(path: str); -``` - -Gets the stats of the given path without following symbolic links. - -###### `path`Required - -- *Type:* str - -The path to get stats for. - ---- - -##### `tryReaddir` - -```wing -bring fs; - -fs.tryReaddir(dirpath: str); -``` - -If the path exists, read the contents of the directory; - -otherwise, return `undefined`. - -###### `dirpath`Required - -- *Type:* str - -The path to evaluate. - ---- - -##### `tryReadFile` - -```wing -bring fs; - -fs.tryReadFile(filepath: str, options?: ReadFileOptions); -``` - -If the file exists and can be read successfully, read the entire contents; - -otherwise, return `undefined`. - -###### `filepath`Required - -- *Type:* str - -The path of the file to be read. - ---- - -###### `options`Optional - -- *Type:* ReadFileOptions - -The `encoding` can be set to specify the character encoding, or the `flag` can be set to specify the attributes. - ---- - -##### `tryReadJson` - -```wing -bring fs; - -fs.tryReadJson(filepath: str); -``` - -Retrieve the contents of the file and convert it to JSON if the file exists and can be parsed successfully, otherwise, return `undefined`. - -###### `filepath`Required - -- *Type:* str - -The file path of the JSON file. - ---- - -##### `tryReadYaml` - -```wing -bring fs; - -fs.tryReadYaml(filepath: str); -``` - -Convert all YAML objects from a single file into JSON objects if the file exists and can be parsed successfully, `undefined` otherwise. - -###### `filepath`Required - -- *Type:* str - -The file path of the YAML file. - ---- - -##### `writeFile` - -```wing -bring fs; - -fs.writeFile(filepath: str, data: str, options?: WriteFileOptions); -``` - -Writes data to a file, replacing the file if it already exists. - -###### `filepath`Required - -- *Type:* str - -The file path that needs to be written. - ---- - -###### `data`Required - -- *Type:* str - -The data to write. - ---- - -###### `options`Optional - -- *Type:* WriteFileOptions - -The `encoding` can be set to specify the character encoding. - -And the `flag` can be set to specify the attributes. -If a flag is not provided, it defaults to `"w"`. - ---- - -##### `writeJson` - -```wing -bring fs; - -fs.writeJson(filepath: str, obj: Json); -``` - -Writes JSON to a file, replacing the file if it already exists. - -###### `filepath`Required - -- *Type:* str - -The file path that needs to be written. - ---- - -###### `obj`Required - -- *Type:* Json - -The JSON object to be dumped. - ---- - -##### `writeYaml` - -```wing -bring fs; - -fs.writeYaml(filepath: str, ...objs: Array); -``` - -Writes multiple YAML objects to a file, replacing the file if it already exists. - -###### `filepath`Required - -- *Type:* str - -The file path that needs to be written. - ---- - -###### `objs`Required - -- *Type:* Json - -The YANL objects to be dumped. - ---- - - - -## Structs - -### GlobOptions - -Options for `glob`, based on https://www.npmjs.com/package/glob. - -#### Initializer - -```wing -bring fs; - -let GlobOptions = fs.GlobOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| absolute | bool | Set to `true` to always receive absolute paths for matched files. | -| cwd | str | The current working directory in which to search. | -| dot | bool | Include `.dot` files in normal matches and globstar matches. Note that an explicit dot in a portion of the pattern will always match dot files. | -| follow | bool | Follow symlinked directories when expanding `**` patterns. | -| ignore | MutArray<str> | An array of glob patterns to exclude from matches. | -| maxDepth | num | Specify a number to limit the depth of the directory traversal to this many levels below the cwd. | -| nodir | bool | Do not match directories, only files. | - ---- - -##### `absolute`Optional - -```wing -absolute: bool; -``` - -- *Type:* bool -- *Default:* false - -Set to `true` to always receive absolute paths for matched files. - -Set to `false` to always -receive relative paths for matched files. - ---- - -##### `cwd`Optional - -```wing -cwd: str; -``` - -- *Type:* str -- *Default:* process.cwd() - -The current working directory in which to search. - ---- - -##### `dot`Optional - -```wing -dot: bool; -``` - -- *Type:* bool -- *Default:* false - -Include `.dot` files in normal matches and globstar matches. Note that an explicit dot in a portion of the pattern will always match dot files. - ---- - -##### `follow`Optional - -```wing -follow: bool; -``` - -- *Type:* bool -- *Default:* false - -Follow symlinked directories when expanding `**` patterns. - -This can result in a lot of -duplicate references in the presence of cyclic links, and make performance quite bad. - ---- - -##### `ignore`Optional - -```wing -ignore: MutArray; -``` - -- *Type:* MutArray<str> -- *Default:* [] - -An array of glob patterns to exclude from matches. - -To ignore all children within a directory, -as well as the entry itself, append '/**' to the ignore pattern. - ---- - -##### `maxDepth`Optional - -```wing -maxDepth: num; -``` - -- *Type:* num -- *Default:* no limit - -Specify a number to limit the depth of the directory traversal to this many levels below the cwd. - ---- - -##### `nodir`Optional - -```wing -nodir: bool; -``` - -- *Type:* bool -- *Default:* false - -Do not match directories, only files. - -(Note: to match only directories, put a `/` at the end of -the pattern.) - ---- - -### Metadata - -Metadata of a file system object. - -#### Initializer - -```wing -bring fs; - -let Metadata = fs.Metadata{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| accessed | datetime | The date and time the file was last accessed. | -| created | datetime | The date and time the file was created. | -| fileType | FileType | The type of file. | -| modified | datetime | The date and time the file was last modified. | -| permissions | str | The permissions of the file. | -| size | num | The size of the file in bytes. | - ---- - -##### `accessed`Required - -```wing -accessed: datetime; -``` - -- *Type:* datetime - -The date and time the file was last accessed. - ---- - -##### `created`Required - -```wing -created: datetime; -``` - -- *Type:* datetime - -The date and time the file was created. - ---- - -##### `fileType`Required - -```wing -fileType: FileType; -``` - -- *Type:* FileType - -The type of file. - ---- - -##### `modified`Required - -```wing -modified: datetime; -``` - -- *Type:* datetime - -The date and time the file was last modified. - ---- - -##### `permissions`Required - -```wing -permissions: str; -``` - -- *Type:* str - -The permissions of the file. - ---- - -##### `size`Required - -```wing -size: num; -``` - -- *Type:* num - -The size of the file in bytes. - ---- - -### MkdirOptions - -Custom settings for creating directory. - -#### Initializer - -```wing -bring fs; - -let MkdirOptions = fs.MkdirOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| mode | str | A file mode. | -| recursive | bool | Indicates whether parent folders should be created. | - ---- - -##### `mode`Optional - -```wing -mode: str; -``` - -- *Type:* str -- *Default:* "0777" - -A file mode. - -The string will be parsed as an octal integer. - ---- - -##### `recursive`Optional - -```wing -recursive: bool; -``` - -- *Type:* bool -- *Default:* true - -Indicates whether parent folders should be created. - -If a folder was created, the path to the first created folder will be returned. - ---- - -### ReadFileOptions - -Custom settings for reading from a file. - -#### Initializer - -```wing -bring fs; - -let ReadFileOptions = fs.ReadFileOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| encoding | str | The character encoding utilized for file reading. | -| flag | str | The `flag` can be set to specify the attributes. | - ---- - -##### `encoding`Optional - -```wing -encoding: str; -``` - -- *Type:* str -- *Default:* "utf-8" - -The character encoding utilized for file reading. - ---- - -##### `flag`Optional - -```wing -flag: str; -``` - -- *Type:* str -- *Default:* "r". - -The `flag` can be set to specify the attributes. - ---- - -### RemoveOptions - -Custom settings for removing files and directories. - -#### Initializer - -```wing -bring fs; - -let RemoveOptions = fs.RemoveOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| force | bool | When `true`, exceptions will be ignored if `path` does not exist. | -| recursive | bool | If `true`, perform a recursive directory removal. | - ---- - -##### `force`Optional - -```wing -force: bool; -``` - -- *Type:* bool -- *Default:* true - -When `true`, exceptions will be ignored if `path` does not exist. - ---- - -##### `recursive`Optional - -```wing -recursive: bool; -``` - -- *Type:* bool -- *Default:* true - -If `true`, perform a recursive directory removal. - -In -recursive mode, operations are retried on failure. - ---- - -### WriteFileOptions - -Custom settings for writing to a file. - -#### Initializer - -```wing -bring fs; - -let WriteFileOptions = fs.WriteFileOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| encoding | str | The character encoding utilized for file writing. | -| flag | str | The `flag` can be set to specify the attributes. | - ---- - -##### `encoding`Optional - -```wing -encoding: str; -``` - -- *Type:* str -- *Default:* "utf-8" - -The character encoding utilized for file writing. - ---- - -##### `flag`Optional - -```wing -flag: str; -``` - -- *Type:* str -- *Default:* "w". - -The `flag` can be set to specify the attributes. - ---- - - -## Enums - -### FileType - -Represents the type of a file system object. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| FILE | Represents a regular file. | -| DIRECTORY | Represents a directory. | -| SYMLINK | Represents a symbolic link. | -| OTHER | Represents any type of file system object that is not `FILE`, `DIRECTORY` or `SYMLINK`. | - ---- - -##### `FILE` - -Represents a regular file. - ---- - - -##### `DIRECTORY` - -Represents a directory. - ---- - - -##### `SYMLINK` - -Represents a symbolic link. - ---- - - -##### `OTHER` - -Represents any type of file system object that is not `FILE`, `DIRECTORY` or `SYMLINK`. - -This includes sockets, FIFOs (named pipes), block devices, and character devices. - ---- - - -### SymlinkType - -Represents the type of the target for creating symbolic links. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| FILE | Symbolic link that points to a file. | -| DIRECTORY | Symbolic link that points to a directory. | -| JUNCTION | Windows-specific: Symbolic link that points to a directory junction. | - ---- - -##### `FILE` - -Symbolic link that points to a file. - ---- - - -##### `DIRECTORY` - -Symbolic link that points to a directory. - ---- - - -##### `JUNCTION` - -Windows-specific: Symbolic link that points to a directory junction. - ---- - diff --git a/docs/docs/04-standard-library/http/api-reference.md b/docs/docs/04-standard-library/http/api-reference.md deleted file mode 100644 index e80f4ba23ed..00000000000 --- a/docs/docs/04-standard-library/http/api-reference.md +++ /dev/null @@ -1,924 +0,0 @@ ---- -title: API reference -id: api-reference -description: Wing standard library API reference for the http module -keywords: [Wing sdk, sdk, Wing API Reference] -hide_title: true -sidebar_position: 100 ---- - - -# API Reference - - -## Classes - -### Http - -The Http class is used for calling different HTTP methods and requesting and sending information online, as well as testing public accessible resources. - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| connect | Executes a CONNECT request to a specified URL and provides a formatted response. | -| delete | Executes a DELETE request to a specified URL and provides a formatted response. | -| fetch | Executes a HTTP request to a specified URL and provides a formatted response. | -| formatUrl | Serializes an URL Struct to a String. | -| get | Executes a GET request to a specified URL and provides a formatted response. | -| parseUrl | Parses the input URL String using WHATWG URL API and returns an URL Struct. | -| patch | Executes a PATCH request to a specified URL and provides a formatted response. | -| post | Executes a POST request to a specified URL and provides a formatted response. | -| put | Executes a PUT request to a specified URL and provides a formatted response. | -| trace | Executes a TRACE request to a specified URL and provides a formatted response. | - ---- - -##### `connect` - -```wing -bring http; - -inflight http.connect(url: str, options?: RequestOptions); -``` - -Executes a CONNECT request to a specified URL and provides a formatted response. - -###### `url`Required - -- *Type:* str - -The target URL for the CONNECT request. - ---- - -###### `options`Optional - -- *Type:* RequestOptions - -Optional parameters for customizing the CONNECT request. - ---- - -##### `delete` - -```wing -bring http; - -inflight http.delete(url: str, options?: RequestOptions); -``` - -Executes a DELETE request to a specified URL and provides a formatted response. - -###### `url`Required - -- *Type:* str - -The target URL for the DELETE request. - ---- - -###### `options`Optional - -- *Type:* RequestOptions - -Optional parameters for customizing the DELETE request. - ---- - -##### `fetch` - -```wing -bring http; - -inflight http.fetch(url: str, options?: RequestOptions); -``` - -Executes a HTTP request to a specified URL and provides a formatted response. - -This method allows various HTTP methods based on the provided options. - -###### `url`Required - -- *Type:* str - -The target URL for the request. - ---- - -###### `options`Optional - -- *Type:* RequestOptions - -Optional parameters for customizing the HTTP request. - ---- - -##### `formatUrl` - -```wing -bring http; - -inflight http.formatUrl(url: Url, options?: FormatUrlOptions); -``` - -Serializes an URL Struct to a String. - -###### `url`Required - -- *Type:* Url - -The URL Struct to be formatted. - ---- - -###### `options`Optional - -- *Type:* FormatUrlOptions - ---- - -##### `get` - -```wing -bring http; - -inflight http.get(url: str, options?: RequestOptions); -``` - -Executes a GET request to a specified URL and provides a formatted response. - -###### `url`Required - -- *Type:* str - -The target URL for the GET request. - ---- - -###### `options`Optional - -- *Type:* RequestOptions - -Optional parameters for customizing the GET request. - ---- - -##### `parseUrl` - -```wing -bring http; - -inflight http.parseUrl(urlString: str); -``` - -Parses the input URL String using WHATWG URL API and returns an URL Struct. - -###### `urlString`Required - -- *Type:* str - -The URL String to be parsed. - ---- - -##### `patch` - -```wing -bring http; - -inflight http.patch(url: str, options?: RequestOptions); -``` - -Executes a PATCH request to a specified URL and provides a formatted response. - -###### `url`Required - -- *Type:* str - -The target URL for the PATCH request. - ---- - -###### `options`Optional - -- *Type:* RequestOptions - -Optional parameters for customizing the PATCH request. - ---- - -##### `post` - -```wing -bring http; - -inflight http.post(url: str, options?: RequestOptions); -``` - -Executes a POST request to a specified URL and provides a formatted response. - -###### `url`Required - -- *Type:* str - -The target URL for the POST request. - ---- - -###### `options`Optional - -- *Type:* RequestOptions - -Optional parameters for customizing the POST request. - ---- - -##### `put` - -```wing -bring http; - -inflight http.put(url: str, options?: RequestOptions); -``` - -Executes a PUT request to a specified URL and provides a formatted response. - -###### `url`Required - -- *Type:* str - -The target URL for the PUT request. - ---- - -###### `options`Optional - -- *Type:* RequestOptions - -ptional parameters for customizing the PUT request. - ---- - -##### `trace` - -```wing -bring http; - -inflight http.trace(url: str, options?: RequestOptions); -``` - -Executes a TRACE request to a specified URL and provides a formatted response. - -###### `url`Required - -- *Type:* str - -The target URL for the TRACE request. - ---- - -###### `options`Optional - -- *Type:* RequestOptions - -Optional parameters for customizing the TRACE request. - ---- - - - -## Structs - -### FormatUrlOptions - -Options for serializing a WHATWG URL to a String. - -#### Initializer - -```wing -bring http; - -let FormatUrlOptions = http.FormatUrlOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| auth | bool | Whether the formatted URL should include the username and password. | -| fragment | bool | Whether the formatted URL should include the fragment identifier. | -| search | bool | Whether the formatted URL should include the search query. | -| unicode | bool | Whether the formatted URL should represent Unicode characters for the host component. | - ---- - -##### `auth`Optional - -```wing -auth: bool; -``` - -- *Type:* bool - -Whether the formatted URL should include the username and password. - ---- - -##### `fragment`Optional - -```wing -fragment: bool; -``` - -- *Type:* bool - -Whether the formatted URL should include the fragment identifier. - ---- - -##### `search`Optional - -```wing -search: bool; -``` - -- *Type:* bool - -Whether the formatted URL should include the search query. - ---- - -##### `unicode`Optional - -```wing -unicode: bool; -``` - -- *Type:* bool - -Whether the formatted URL should represent Unicode characters for the host component. - ---- - -### RequestOptions - -An object containing any custom settings that you want to apply to the request. - -#### Initializer - -```wing -bring http; - -let RequestOptions = http.RequestOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| body | str | Any body that you want to add to your request. | -| cache | RequestCache | The cache mode you want to use for the request. | -| headers | MutMap<str> | Any headers you want to add to your request. | -| method | HttpMethod | The request method, e.g., GET, POST. The default is GET. | -| redirect | RequestRedirect | An enum specifying the redirect mode to use: follow, error or manual. | -| referrer | str | A string specifying "no-referrer", client, or a URL. | -| timeout | duration | Timeout for terminating a pending request. | - ---- - -##### `body`Optional - -```wing -body: str; -``` - -- *Type:* str - -Any body that you want to add to your request. - -Note that a request using the GET or HEAD method cannot have a body. - ---- - -##### `cache`Optional - -```wing -cache: RequestCache; -``` - -- *Type:* RequestCache -- *Default:* RequestCache.DEFAULT - -The cache mode you want to use for the request. - ---- - -##### `headers`Optional - -```wing -headers: MutMap; -``` - -- *Type:* MutMap<str> - -Any headers you want to add to your request. - ---- - -##### `method`Optional - -```wing -method: HttpMethod; -``` - -- *Type:* HttpMethod -- *Default:* GET - -The request method, e.g., GET, POST. The default is GET. - ---- - -##### `redirect`Optional - -```wing -redirect: RequestRedirect; -``` - -- *Type:* RequestRedirect -- *Default:* RequestRedirect.FOLLOW - -An enum specifying the redirect mode to use: follow, error or manual. - -The default is follow. - ---- - -##### `referrer`Optional - -```wing -referrer: str; -``` - -- *Type:* str -- *Default:* about:client - -A string specifying "no-referrer", client, or a URL. - -The default is "about:client". - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* no timeout - -Timeout for terminating a pending request. - -None if undefined. - ---- - -### Response - -The response to a HTTP request. - -#### Initializer - -```wing -bring http; - -let Response = http.Response{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| body | str | A string representation of the body contents. | -| headers | MutMap<str> | The map of header information associated with the response. | -| ok | bool | A boolean indicating whether the response was successful (status in the range 200 – 299) or not. | -| status | num | The status code of the response. | -| url | str | The URL of the response. | - ---- - -##### `body`Required - -```wing -body: str; -``` - -- *Type:* str - -A string representation of the body contents. - ---- - -##### `headers`Required - -```wing -headers: MutMap; -``` - -- *Type:* MutMap<str> - -The map of header information associated with the response. - ---- - -##### `ok`Required - -```wing -ok: bool; -``` - -- *Type:* bool - -A boolean indicating whether the response was successful (status in the range 200 – 299) or not. - ---- - -##### `status`Required - -```wing -status: num; -``` - -- *Type:* num - -The status code of the response. - -(This will be 200 for a success). - ---- - -##### `url`Required - -```wing -url: str; -``` - -- *Type:* str - -The URL of the response. - ---- - -### Url - -An URL following WHATWG URL Standard. - -#### Initializer - -```wing -bring http; - -let Url = http.Url{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| hash | str | The URL's fragment. | -| host | str | The URL's host. | -| hostname | str | The URL's hostname. | -| href | str | The entire URL. | -| origin | str | The URL's origin. | -| password | str | The URL’s password. | -| pathname | str | The URL's pathname. | -| port | str | The URL's port. | -| protocol | str | The URL's protocol. | -| search | str | The URL's search. | -| username | str | The URL's username. | - ---- - -##### `hash`Required - -```wing -hash: str; -``` - -- *Type:* str - -The URL's fragment. - ---- - -##### `host`Required - -```wing -host: str; -``` - -- *Type:* str - -The URL's host. - ---- - -##### `hostname`Required - -```wing -hostname: str; -``` - -- *Type:* str - -The URL's hostname. - ---- - -##### `href`Required - -```wing -href: str; -``` - -- *Type:* str - -The entire URL. - ---- - -##### `origin`Required - -```wing -origin: str; -``` - -- *Type:* str - -The URL's origin. - ---- - -##### `password`Required - -```wing -password: str; -``` - -- *Type:* str - -The URL’s password. - ---- - -##### `pathname`Required - -```wing -pathname: str; -``` - -- *Type:* str - -The URL's pathname. - ---- - -##### `port`Required - -```wing -port: str; -``` - -- *Type:* str - -The URL's port. - ---- - -##### `protocol`Required - -```wing -protocol: str; -``` - -- *Type:* str - -The URL's protocol. - ---- - -##### `search`Required - -```wing -search: str; -``` - -- *Type:* str - -The URL's search. - ---- - -##### `username`Required - -```wing -username: str; -``` - -- *Type:* str - -The URL's username. - ---- - - -## Enums - -### HttpMethod - -The request's method. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| GET | GET. | -| PUT | PUT. | -| DELETE | DELETE. | -| PATCH | PATCH. | -| POST | POST. | -| OPTIONS | OPTIONS. | -| HEAD | HEAD. | -| CONNECT | CONNECT. | -| TRACE | TRACE. | - ---- - -##### `GET` - -GET. - ---- - - -##### `PUT` - -PUT. - ---- - - -##### `DELETE` - -DELETE. - ---- - - -##### `PATCH` - -PATCH. - ---- - - -##### `POST` - -POST. - ---- - - -##### `OPTIONS` - -OPTIONS. - ---- - - -##### `HEAD` - -HEAD. - ---- - - -##### `CONNECT` - -CONNECT. - ---- - - -##### `TRACE` - -TRACE. - ---- - - -### RequestCache - -The cache mode of the request. - -It controls how a request will interact with the system's HTTP cache. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| DEFAULT | The runtime environment looks for a matching request in its HTTP cache. | -| NO_STORE | The runtime environment fetches the resource from the remote server without first looking in the cache, and will not update the cache with the downloaded resource. | -| RELOAD | The runtime environment fetches the resource from the remote server without first looking in the cache, but then will update the cache with the downloaded resource. | -| NO_CACHE | The runtime environment looks for a matching request in its HTTP cache. | -| FORCE_CACHE | The runtime environment looks for a matching request in its HTTP cache. | - ---- - -##### `DEFAULT` - -The runtime environment looks for a matching request in its HTTP cache. - -* If there is a match and it is fresh, it will be returned from the cache. -* If there is a match but it is stale, the runtime environment will make a conditional request to the remote server. -* If the server indicates that the resource has not changed, it will be returned from the cache. -* Otherwise the resource will be downloaded from the server and the cache will be updated. -* If there is no match, the runtime environment will make a normal request, and will update the cache with the downloaded resource. - ---- - - -##### `NO_STORE` - -The runtime environment fetches the resource from the remote server without first looking in the cache, and will not update the cache with the downloaded resource. - ---- - - -##### `RELOAD` - -The runtime environment fetches the resource from the remote server without first looking in the cache, but then will update the cache with the downloaded resource. - ---- - - -##### `NO_CACHE` - -The runtime environment looks for a matching request in its HTTP cache. - -* If there is a match, fresh or stale, the runtime environment will make a conditional request to the remote server. -* If the server indicates that the resource has not changed, it will be returned from the cache. Otherwise the resource will be downloaded from the server and the cache will be updated. -* If there is no match, the runtime environment will make a normal request, and will update the cache with the downloaded resource. - ---- - - -##### `FORCE_CACHE` - -The runtime environment looks for a matching request in its HTTP cache. - -* If there is a match, fresh or stale, it will be returned from the cache. -* If there is no match, the runtime environment will make a normal request, and will update the cache with the downloaded resource. - ---- - - -### RequestRedirect - -The redirect read-only property that contains the mode for how redirects are handled. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| MANUAL | Do not follow redirects automatically. | -| FOLLOW | Follow all redirects incurred when fetching a resource. | -| ERROR | Return a network error when a request is met with a redirect. | - ---- - -##### `MANUAL` - -Do not follow redirects automatically. - -The `Location` response header includes the redirect -target. - ---- - - -##### `FOLLOW` - -Follow all redirects incurred when fetching a resource. - ---- - - -##### `ERROR` - -Return a network error when a request is met with a redirect. - ---- - diff --git a/docs/docs/04-standard-library/math/api-reference.md b/docs/docs/04-standard-library/math/api-reference.md deleted file mode 100644 index d0bbd66381b..00000000000 --- a/docs/docs/04-standard-library/math/api-reference.md +++ /dev/null @@ -1,874 +0,0 @@ ---- -title: API reference -id: api-reference -description: Wing standard library API reference for the math module -keywords: [Wing sdk, sdk, Wing API Reference] -hide_title: true -sidebar_position: 100 ---- - - -# API Reference - - -## Classes - -### Math - -Utility class for mathematical operations. - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| abs | Returns the absolute value of a number. | -| acos | Returns the inverse cosine (in radians) of a number. | -| acot | Calculates the inverse cotangent (acot) of a number. | -| acsc | Calculates the inverse cosecant (acsc) of a number. | -| arithmeticMean | Calculates the mean value of an array of numbers. | -| asec | Calculates the inverse secant (asec) of a number. | -| asin | Returns the inverse sine (in radians) of a number. | -| atan | Returns the inverse tangent (in radians) of a number. | -| atan2 | Returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for Math.atan2(y, x). | -| ceil | Returns the smallest integer greater than or equal to a given number. | -| combinations | Calculates the number of combinations for choosing r items from a total of n items. | -| cos | Returns the cosine of a number in radians. | -| cot | Calculates the cotangent of an angle (in radians). | -| csc | Calculates the cosecant of an angle (in radians). | -| degreesToRadians | Convert degrees to radians. | -| factorial | Calculates the factorial of a given number. | -| fibonacci | Calculates the nth Fibonacci number. | -| floor | Returns the largest integer less than or equal to a given number. | -| geometricMean | Calculates the geometric mean of an array of numbers. | -| harmonicMean | Calculates the harmonic mean of an array of numbers. | -| hypot | Calculate the length of the vector from the origin to the point given by the coordinates. | -| isPrime | Checks if a number is prime. | -| log | Returns the natural logarithm (base e) of a number. | -| log10 | Returns the base-10 logarithm of a number. | -| log2 | Returns the base-2 logarithm of a number. | -| max | Returns the maximum value from an array of numbers. | -| median | Calculates the median value of an array of numbers. | -| min | Returns the minimum value from an array of numbers. | -| mode | Calculates the mode values of an array of numbers. | -| radiansToDegrees | Convert radians to degrees. | -| random | Generates a pseudo-random number between 0 and max (default of 1). | -| round | Rounds the given number to the nearest integer. | -| sec | Calculates the secant of an angle (in radians). | -| sign | Returns 1 or -1, indicating the sign of the number passed as an argument, 0 for 0. | -| sin | Returns the sine of a number in radians. | -| sqrt | Returns the square root of a number. | -| tan | Returns the tangent of a number in radians. | -| toRadix | Convert a value to a new number base. | - ---- - -##### `abs` - -```wing -bring math; - -math.abs(value: num); -``` - -Returns the absolute value of a number. - -###### `value`Required - -- *Type:* num - -The input number. - ---- - -##### `acos` - -```wing -bring math; - -math.acos(value: num); -``` - -Returns the inverse cosine (in radians) of a number. - -###### `value`Required - -- *Type:* num - -A number between -1 and 1, inclusive, representing the angle's cosine value. - ---- - -##### `acot` - -```wing -bring math; - -math.acot(value: num); -``` - -Calculates the inverse cotangent (acot) of a number. - -###### `value`Required - -- *Type:* num - -A number representing the cotangent value. - ---- - -##### `acsc` - -```wing -bring math; - -math.acsc(value: num); -``` - -Calculates the inverse cosecant (acsc) of a number. - -###### `value`Required - -- *Type:* num - -A number equal or greater than |1|, representing the cosecant value. - ---- - -##### `arithmeticMean` - -```wing -bring math; - -math.arithmeticMean(arr: MutArray); -``` - -Calculates the mean value of an array of numbers. - -###### `arr`Required - -- *Type:* MutArray<num> - -The array of numbers. - ---- - -##### `asec` - -```wing -bring math; - -math.asec(value: num); -``` - -Calculates the inverse secant (asec) of a number. - -###### `value`Required - -- *Type:* num - -A number equal or greater than |1|, representing the secant value. - ---- - -##### `asin` - -```wing -bring math; - -math.asin(value: num); -``` - -Returns the inverse sine (in radians) of a number. - -###### `value`Required - -- *Type:* num - -A number between -1 and 1, inclusive, representing the angle's sine value. - ---- - -##### `atan` - -```wing -bring math; - -math.atan(value: num); -``` - -Returns the inverse tangent (in radians) of a number. - -###### `value`Required - -- *Type:* num - -A number. - ---- - -##### `atan2` - -```wing -bring math; - -math.atan2(y: num, x: num); -``` - -Returns the angle in the plane (in radians) between the positive x-axis and the ray from (0, 0) to the point (x, y), for Math.atan2(y, x). - -###### `y`Required - -- *Type:* num - -The y coordinate of the point. - ---- - -###### `x`Required - -- *Type:* num - -The x coordinate of the point. - ---- - -##### `ceil` - -```wing -bring math; - -math.ceil(value: num); -``` - -Returns the smallest integer greater than or equal to a given number. - -###### `value`Required - -- *Type:* num - -The input number. - ---- - -##### `combinations` - -```wing -bring math; - -math.combinations(n: num, r: num); -``` - -Calculates the number of combinations for choosing r items from a total of n items. - -###### `n`Required - -- *Type:* num - -The total number of items. - ---- - -###### `r`Required - -- *Type:* num - -The number of items to be chosen. - ---- - -##### `cos` - -```wing -bring math; - -math.cos(value: num); -``` - -Returns the cosine of a number in radians. - -###### `value`Required - -- *Type:* num - -A number representing an angle in radians. - ---- - -##### `cot` - -```wing -bring math; - -math.cot(value: num); -``` - -Calculates the cotangent of an angle (in radians). - -###### `value`Required - -- *Type:* num - -The angle in radians. - ---- - -##### `csc` - -```wing -bring math; - -math.csc(value: num); -``` - -Calculates the cosecant of an angle (in radians). - -###### `value`Required - -- *Type:* num - -The angle in radians. - ---- - -##### `degreesToRadians` - -```wing -bring math; - -math.degreesToRadians(degrees: num); -``` - -Convert degrees to radians. - -###### `degrees`Required - -- *Type:* num - -Degree value. - ---- - -##### `factorial` - -```wing -bring math; - -math.factorial(n: num); -``` - -Calculates the factorial of a given number. - -###### `n`Required - -- *Type:* num - -The number to calculate the factorial for. - ---- - -##### `fibonacci` - -```wing -bring math; - -math.fibonacci(n: num); -``` - -Calculates the nth Fibonacci number. - -###### `n`Required - -- *Type:* num - -The position of the Fibonacci number to calculate. - ---- - -##### `floor` - -```wing -bring math; - -math.floor(value: num); -``` - -Returns the largest integer less than or equal to a given number. - -###### `value`Required - -- *Type:* num - -The input number. - ---- - -##### `geometricMean` - -```wing -bring math; - -math.geometricMean(arr: MutArray); -``` - -Calculates the geometric mean of an array of numbers. - -###### `arr`Required - -- *Type:* MutArray<num> - -The array of numbers. - ---- - -##### `harmonicMean` - -```wing -bring math; - -math.harmonicMean(arr: MutArray); -``` - -Calculates the harmonic mean of an array of numbers. - -###### `arr`Required - -- *Type:* MutArray<num> - -The array of numbers. - ---- - -##### `hypot` - -```wing -bring math; - -math.hypot(coordinates: MutArray); -``` - -Calculate the length of the vector from the origin to the point given by the coordinates. - -###### `coordinates`Required - -- *Type:* MutArray<num> - -Array of coordinates. - ---- - -##### `isPrime` - -```wing -bring math; - -math.isPrime(n: num); -``` - -Checks if a number is prime. - -###### `n`Required - -- *Type:* num - -The number to check for primality. - ---- - -##### `log` - -```wing -bring math; - -math.log(value: num); -``` - -Returns the natural logarithm (base e) of a number. - -###### `value`Required - -- *Type:* num - -The input number. - ---- - -##### `log10` - -```wing -bring math; - -math.log10(value: num); -``` - -Returns the base-10 logarithm of a number. - -###### `value`Required - -- *Type:* num - -The input number. - ---- - -##### `log2` - -```wing -bring math; - -math.log2(value: num); -``` - -Returns the base-2 logarithm of a number. - -###### `value`Required - -- *Type:* num - -The input number. - ---- - -##### `max` - -```wing -bring math; - -math.max(arr: MutArray); -``` - -Returns the maximum value from an array of numbers. - -###### `arr`Required - -- *Type:* MutArray<num> - -The array of numbers. - ---- - -##### `median` - -```wing -bring math; - -math.median(arr: MutArray); -``` - -Calculates the median value of an array of numbers. - -###### `arr`Required - -- *Type:* MutArray<num> - -The array of numbers. - ---- - -##### `min` - -```wing -bring math; - -math.min(arr: MutArray); -``` - -Returns the minimum value from an array of numbers. - -###### `arr`Required - -- *Type:* MutArray<num> - -The array of numbers. - ---- - -##### `mode` - -```wing -bring math; - -math.mode(arr: MutArray); -``` - -Calculates the mode values of an array of numbers. - -###### `arr`Required - -- *Type:* MutArray<num> - -The array of numbers. - ---- - -##### `radiansToDegrees` - -```wing -bring math; - -math.radiansToDegrees(radians: num); -``` - -Convert radians to degrees. - -###### `radians`Required - -- *Type:* num - -Radians value. - ---- - -##### `random` - -```wing -bring math; - -math.random(max?: num); -``` - -Generates a pseudo-random number between 0 and max (default of 1). - -###### `max`Optional - -- *Type:* num - -The maximum value of the random number. - ---- - -##### `round` - -```wing -bring math; - -math.round(value: num, options?: RoundingOptions); -``` - -Rounds the given number to the nearest integer. - -###### `value`Required - -- *Type:* num - -The number to be rounded. - ---- - -###### `options`Optional - -- *Type:* RoundingOptions - ---- - -##### `sec` - -```wing -bring math; - -math.sec(value: num); -``` - -Calculates the secant of an angle (in radians). - -###### `value`Required - -- *Type:* num - -The angle in radians. - ---- - -##### `sign` - -```wing -bring math; - -math.sign(value: num); -``` - -Returns 1 or -1, indicating the sign of the number passed as an argument, 0 for 0. - -###### `value`Required - -- *Type:* num - -The input number. - ---- - -##### `sin` - -```wing -bring math; - -math.sin(value: num); -``` - -Returns the sine of a number in radians. - -###### `value`Required - -- *Type:* num - -A number representing an angle in radians. - ---- - -##### `sqrt` - -```wing -bring math; - -math.sqrt(value: num); -``` - -Returns the square root of a number. - -###### `value`Required - -- *Type:* num - -A number greater than or equal to 0. - ---- - -##### `tan` - -```wing -bring math; - -math.tan(value: num); -``` - -Returns the tangent of a number in radians. - -###### `value`Required - -- *Type:* num - -A number representing an angle in radians. - ---- - -##### `toRadix` - -```wing -bring math; - -math.toRadix(value: num, base: num); -``` - -Convert a value to a new number base. - -###### `value`Required - -- *Type:* num - -The number to be converted. - ---- - -###### `base`Required - -- *Type:* num - -The base of the new value. - ---- - - -#### Constants - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| E | num | Euler's number, a mathematical constant approximately equal to 2.71828. | -| INF | num | Positive infinity constant. | -| PI | num | The mathematical constant representing the ratio of a circle's circumference to its diameter. | -| TAU | num | The mathematical constant representing the ratio of a circle's circumference to the radius. | - ---- - -##### `E`Required - -```wing -E: num; -``` - -- *Type:* num - -Euler's number, a mathematical constant approximately equal to 2.71828. - ---- - -##### `INF`Required - -```wing -INF: num; -``` - -- *Type:* num - -Positive infinity constant. - ---- - -##### `PI`Required - -```wing -PI: num; -``` - -- *Type:* num - -The mathematical constant representing the ratio of a circle's circumference to its diameter. - ---- - -##### `TAU`Required - -```wing -TAU: num; -``` - -- *Type:* num - -The mathematical constant representing the ratio of a circle's circumference to the radius. - ---- - -## Structs - -### RoundingOptions - -Options for rounding a number. - -#### Initializer - -```wing -bring math; - -let RoundingOptions = math.RoundingOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| decimalPlaces | num | The number of decimal places to round to. | - ---- - -##### `decimalPlaces`Optional - -```wing -decimalPlaces: num; -``` - -- *Type:* num - -The number of decimal places to round to. - ---- - - diff --git a/docs/docs/04-standard-library/sim/api-reference.md b/docs/docs/04-standard-library/sim/api-reference.md deleted file mode 100644 index 058af73e049..00000000000 --- a/docs/docs/04-standard-library/sim/api-reference.md +++ /dev/null @@ -1,1166 +0,0 @@ ---- -title: API reference -id: api-reference -description: Wing standard library API reference for the sim module -keywords: [Wing sdk, sdk, Wing API Reference] -hide_title: true -sidebar_position: 100 ---- - - -# API Reference - -## Resources - -### Container - -- *Implements:* ISimulatorResource - -Represents a container running in the Wing Simulator. - -#### Initializers - -```wing -bring sim; - -new sim.Container(props: ContainerProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | ContainerProps | *No description.* | - ---- - -##### `props`Required - -- *Type:* ContainerProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| toSimulator | Convert this resource to a resource schema for the simulator. | - ---- - -##### `toSimulator` - -```wing -toSimulator(): ToSimulatorOutput -``` - -Convert this resource to a resource schema for the simulator. - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring sim; - -sim.Container.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring sim; - -sim.Container.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| hostPort | str | A token that resolves to the host port of this container. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `hostPort`Optional - -```wing -hostPort: str; -``` - -- *Type:* str - -A token that resolves to the host port of this container. - ---- - - -### Policy - -- *Implements:* ISimulatorResource - -Implementation of `sim.Policy`. - -#### Initializers - -```wing -bring sim; - -new sim.Policy(props: PolicyProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | PolicyProps | *No description.* | - ---- - -##### `props`Required - -- *Type:* PolicyProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| addStatement | Adds a statement to the policy. | -| toSimulator | Convert this resource to a resource schema for the simulator. | - ---- - -##### `addStatement` - -```wing -addStatement(resource: IResource, op: str): void -``` - -Adds a statement to the policy. - -###### `resource`Required - -- *Type:* IResource - ---- - -###### `op`Required - -- *Type:* str - ---- - -##### `toSimulator` - -```wing -toSimulator(): ToSimulatorOutput -``` - -Convert this resource to a resource schema for the simulator. - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring sim; - -sim.Policy.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring sim; - -sim.Policy.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - -### Resource - -- *Implements:* IResource, ISimulatorResource, IInflightHost, ISimulatorInflightHost - -A backend for a simulated resource. - -#### Initializers - -```wing -bring sim; - -new sim.Resource(factory: IResourceFactory); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| factory | IResourceFactory | *No description.* | - ---- - -##### `factory`Required - -- *Type:* IResourceFactory - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| addEnvironment | Add an environment variable to make available to the inflight code. | -| addPermission | Add a simulated permission to this inflight host. | -| createToken | Obtain a token that can be used to reference an attribute of this resource that is only resolved once the resource is started in the simulator. | -| toSimulator | Convert this resource to a resource schema for the simulator. | - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| call | Call a method on the resource. | - ---- - -##### `addEnvironment` - -```wing -addEnvironment(name: str, value: str): void -``` - -Add an environment variable to make available to the inflight code. - -###### `name`Required - -- *Type:* str - ---- - -###### `value`Required - -- *Type:* str - ---- - -##### `addPermission` - -```wing -addPermission(resource: IResource, op: str): void -``` - -Add a simulated permission to this inflight host. - -###### `resource`Required - -- *Type:* IResource - ---- - -###### `op`Required - -- *Type:* str - ---- - -##### `createToken` - -```wing -createToken(name: str): str -``` - -Obtain a token that can be used to reference an attribute of this resource that is only resolved once the resource is started in the simulator. - -If the token is used in inflight code or in the configuration of a simulated -resource (e.g. as an environment variable), the relevant resource will -automatically take a dependency on the resource the token belongs to. - -###### `name`Required - -- *Type:* str - -The name of the token. - ---- - -##### `toSimulator` - -```wing -toSimulator(): ToSimulatorOutput -``` - -Convert this resource to a resource schema for the simulator. - -##### `call` - -```wing -inflight call(method: str, args?: MutArray): Json -``` - -Call a method on the resource. - -###### `method`Required - -- *Type:* str - ---- - -###### `args`Optional - -- *Type:* MutArray<Json> - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring sim; - -sim.Resource.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring sim; - -sim.Resource.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - -### State - -- *Implements:* ISimulatorResource - -Key/value in-memory state for the simulator. - -Use the preflight method `token(key)` to obtain a token that can be used to reference the value -of the state at runtime. - -During deployment (i.e. `cloud.OnDeploy` or `cloud.Service` startup), you must call the inflight -method `set(key, value)` to set the runtime value. The value will be available at runtime through -the inflight method `get(key)` (or resolved as a token). - -See tests for examples. - -#### Initializers - -```wing -bring sim; - -new sim.State(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| token | Returns a token that can be used to retrieve the value of the state after the simulation has run. | -| toSimulator | Convert this resource to a resource schema for the simulator. | - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| get | Gets the runtime state of this object. | -| set | Sets the state of runtime a runtime object. | -| tryGet | Checks if runtime state exists for this object and returns it's value. | - ---- - -##### `token` - -```wing -token(key: str): str -``` - -Returns a token that can be used to retrieve the value of the state after the simulation has run. - -###### `key`Required - -- *Type:* str - -The object key retrieved through the inflight `state.get()`. - ---- - -##### `toSimulator` - -```wing -toSimulator(): ToSimulatorOutput -``` - -Convert this resource to a resource schema for the simulator. - -##### `get` - -```wing -inflight get(key: str): Json -``` - -Gets the runtime state of this object. - -Throws if there is no value for the given key. - -###### `key`Required - -- *Type:* str - -The object's key. - ---- - -##### `set` - -```wing -inflight set(key: str, value: Json): void -``` - -Sets the state of runtime a runtime object. - -###### `key`Required - -- *Type:* str - -The object's key. - ---- - -###### `value`Required - -- *Type:* Json - -The object's value. - ---- - -##### `tryGet` - -```wing -inflight tryGet(key: str): Json? -``` - -Checks if runtime state exists for this object and returns it's value. - -If no value exists, -returns `nil`. - -###### `key`Required - -- *Type:* str - -The object's key. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring sim; - -sim.State.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring sim; - -sim.State.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - - -## Structs - -### ContainerProps - -Initialization properties for `sim.Container`. - -#### Initializer - -```wing -bring sim; - -let ContainerProps = sim.ContainerProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| image | str | A name of a public Docker image to pull and run or a path to a local directory with a `Dockerfile`. | -| name | str | A name for the container. | -| args | MutArray<str> | Container arguments. | -| containerPort | num | Internal container port to expose. | -| entrypoint | str | Container entrypoint. | -| env | MutMap<str> | Environment variables to set in the container. | -| network | str | Docker network to use for the container - such as 'host', 'bridge', etc. | -| sourceHash | str | An explicit source hash that represents the container source. | -| sourcePattern | str | A glob of local files to consider as input sources for the container, relative to the build context directory. | -| volumes | MutArray<str> | Volume mount points. | - ---- - -##### `image`Required - -```wing -image: str; -``` - -- *Type:* str - -A name of a public Docker image to pull and run or a path to a local directory with a `Dockerfile`. - ---- - -##### `name`Required - -```wing -name: str; -``` - -- *Type:* str - -A name for the container. - ---- - -##### `args`Optional - -```wing -args: MutArray; -``` - -- *Type:* MutArray<str> -- *Default:* [] - -Container arguments. - ---- - -##### `containerPort`Optional - -```wing -containerPort: num; -``` - -- *Type:* num -- *Default:* no port exposed - -Internal container port to expose. - ---- - -##### `entrypoint`Optional - -```wing -entrypoint: str; -``` - -- *Type:* str -- *Default:* default image entrypoint - -Container entrypoint. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* {} - -Environment variables to set in the container. - ---- - -##### `network`Optional - -```wing -network: str; -``` - -- *Type:* str -- *Default:* default docker network - -Docker network to use for the container - such as 'host', 'bridge', etc. - -> [https://docs.docker.com/network.](https://docs.docker.com/network.) - ---- - -*Example* - -```wing -'host' -``` - - -##### `sourceHash`Optional - -```wing -sourceHash: str; -``` - -- *Type:* str -- *Default:* calculated based on the source files - -An explicit source hash that represents the container source. - -if not set, and `sourcePattern` -is set, the hash will be calculated based on the content of the source files. - ---- - -##### `sourcePattern`Optional - -```wing -sourcePattern: str; -``` - -- *Type:* str -- *Default:* all files - -A glob of local files to consider as input sources for the container, relative to the build context directory. - ---- - -##### `volumes`Optional - -```wing -volumes: MutArray; -``` - -- *Type:* MutArray<str> -- *Default:* [] - -Volume mount points. - ---- - -*Example* - -```wing -['/host:/container'] -``` - - -### PolicyProps - -Options for `sim.Policy`. - -#### Initializer - -```wing -bring sim; - -let PolicyProps = sim.PolicyProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| principal | IResource | The resource to which the policy is attached. | - ---- - -##### `principal`Required - -```wing -principal: IResource; -``` - -- *Type:* IResource - -The resource to which the policy is attached. - ---- - -## Protocols - -### IResource - -- *Implemented By:* IResource - -Contract that a resource backend must implement. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| onStop | Runs when the resource is stopped. | - ---- - -##### `onStop` - -```wing -onStop(): void -``` - -Runs when the resource is stopped. - - -### IResourceContext - -- *Implemented By:* IResourceContext - -Context for implementing a simulator resource. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| log | Log a message at the current point in time. | -| resolveToken | Resolves a token value. | -| statedir | The directory for the resource's state. | - ---- - -##### `log` - -```wing -inflight log(message: str, level?: LogLevel): void -``` - -Log a message at the current point in time. - -Defaults to `info` level. - -###### `message`Required - -- *Type:* str - -The message to log. - ---- - -###### `level`Optional - -- *Type:* LogLevel - -The severity of the message. - ---- - -##### `resolveToken` - -```wing -inflight resolveToken(name: str, value: str): void -``` - -Resolves a token value. - -All tokens must be resolved during the -constructor of the resource. - -###### `name`Required - -- *Type:* str - -The name of the token. - ---- - -###### `value`Required - -- *Type:* str - -The value of the token. - ---- - -##### `statedir` - -```wing -statedir(): str -``` - -The directory for the resource's state. - - -### IResourceFactory - -- *Extends:* IInflight - -- *Implemented By:* IResourceFactory - -**Inflight client:** [@winglang/sdk.sim.IResourceFactoryClient](#@winglang/sdk.sim.IResourceFactoryClient) - -A resource with an inflight "handle" method that can be passed to the `sim.Resource` constructor. - - - -### IResourceFactoryClient - -- *Implemented By:* IResourceFactoryClient - -A resource with an inflight "handle" method that can be passed to the `sim.Resource` constructor. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that will be called to initialize the simulator resource. | - ---- - -##### `handle` - -```wing -inflight handle(context: IResourceContext): IResource? -``` - -Function that will be called to initialize the simulator resource. - -To implement a shutdown sequence, return an object that implements the `IResource` inflight interface with an `onStop()` method. - -###### `context`Required - -- *Type:* IResourceContext - ---- - - -### ISimulatorInflightHost - -- *Extends:* IInflightHost - -- *Implemented By:* Resource, ISimulatorInflightHost - -Interfaces shared by all preflight classes that host inflight code. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| addPermission | Add a simulated permission to this inflight host. | - ---- - -##### `addPermission` - -```wing -addPermission(resource: IResource, op: str): void -``` - -Add a simulated permission to this inflight host. - -###### `resource`Required - -- *Type:* IResource - -The resource to add. - ---- - -###### `op`Required - -- *Type:* str - -The action to add. - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -### ISimulatorResource - -- *Extends:* IResource - -- *Implemented By:* Container, Policy, Resource, State, ISimulatorResource - -Interfaces shared by all preflight classes targeting the simulator. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| toSimulator | Convert this resource to a resource schema for the simulator. | - ---- - -##### `toSimulator` - -```wing -toSimulator(): ToSimulatorOutput -``` - -Convert this resource to a resource schema for the simulator. - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - diff --git a/docs/docs/04-standard-library/sim/container.md b/docs/docs/04-standard-library/sim/container.md deleted file mode 100644 index 086e22c58ab..00000000000 --- a/docs/docs/04-standard-library/sim/container.md +++ /dev/null @@ -1,394 +0,0 @@ ---- -title: Container -id: container -description: Runs a container in the Wing Simulator -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - docker, - container, - docker compose, - simulator - ] ---- - -The `sim.Container` resource allows running containers in the Wing Simulator: - -```js -bring sim; -bring http; - -let c = new sim.Container( - name: "http-echo", - image: "hashicorp/http-echo", - containerPort: 5678, - args: ["-text=bang"], -); - -test "send request" { - http.get("http://localhost:{c.hostPort}"); -} -``` - -There is also support for building containers from a local directory with a `Dockerfile`: - -```js -new sim.Container( - name: "my-service", - image: "./my-service", - containerPort: 8080, -); -``` - -### Retaining state - -When the Wing Console is closed, all containers are stopped and removed. -To retain the state of a container across console restarts, you can mount an anonymous volume: - -```js -new sim.Container( - name: "my-service", - image: "./my-service", - containerPort: 8080, - volumes: ["/var/data"], -); -``` - -Wing will automatically name each unnamed volume in `volumes`, and reuse the named -volumes across console restarts. - -## API - -* `name` - a name for the container. -* `image` - a name of a public Docker image to pull and run or a path to a local directory with a - `Dockerfile`. -* `containerPort` - a TCP port to expose from the container (optional). -* `env` - environment variables to set in the container. -* `args` - container entrypoint arguments -* `sourcePattern` - a glob pattern to use to match the files for calculating the source hash when - determining if a rebuild is needed. By default this is all the files in the docker build context - directory (and below). -* `sourceHash` - An explicit source hash that represents the container source. if not set, and - `sourcePattern` is set, the hash will be calculated based on the content of the source files. - -# API Reference - -## Resources - -### Container - -- *Implements:* ISimulatorResource - -Represents a container running in the Wing Simulator. - -#### Initializers - -```wing -bring sim; - -new sim.Container(props: ContainerProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | ContainerProps | *No description.* | - ---- - -##### `props`Required - -- *Type:* ContainerProps - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| toSimulator | Convert this resource to a resource schema for the simulator. | - ---- - -##### `toSimulator` - -```wing -toSimulator(): ToSimulatorOutput -``` - -Convert this resource to a resource schema for the simulator. - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring sim; - -sim.Container.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring sim; - -sim.Container.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| hostPort | str | A token that resolves to the host port of this container. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `hostPort`Optional - -```wing -hostPort: str; -``` - -- *Type:* str - -A token that resolves to the host port of this container. - ---- - - - -## Structs - -### ContainerProps - -Initialization properties for `sim.Container`. - -#### Initializer - -```wing -bring sim; - -let ContainerProps = sim.ContainerProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| image | str | A name of a public Docker image to pull and run or a path to a local directory with a `Dockerfile`. | -| name | str | A name for the container. | -| args | MutArray<str> | Container arguments. | -| containerPort | num | Internal container port to expose. | -| entrypoint | str | Container entrypoint. | -| env | MutMap<str> | Environment variables to set in the container. | -| network | str | Docker network to use for the container - such as 'host', 'bridge', etc. | -| sourceHash | str | An explicit source hash that represents the container source. | -| sourcePattern | str | A glob of local files to consider as input sources for the container, relative to the build context directory. | -| volumes | MutArray<str> | Volume mount points. | - ---- - -##### `image`Required - -```wing -image: str; -``` - -- *Type:* str - -A name of a public Docker image to pull and run or a path to a local directory with a `Dockerfile`. - ---- - -##### `name`Required - -```wing -name: str; -``` - -- *Type:* str - -A name for the container. - ---- - -##### `args`Optional - -```wing -args: MutArray; -``` - -- *Type:* MutArray<str> -- *Default:* [] - -Container arguments. - ---- - -##### `containerPort`Optional - -```wing -containerPort: num; -``` - -- *Type:* num -- *Default:* no port exposed - -Internal container port to expose. - ---- - -##### `entrypoint`Optional - -```wing -entrypoint: str; -``` - -- *Type:* str -- *Default:* default image entrypoint - -Container entrypoint. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* {} - -Environment variables to set in the container. - ---- - -##### `network`Optional - -```wing -network: str; -``` - -- *Type:* str -- *Default:* default docker network - -Docker network to use for the container - such as 'host', 'bridge', etc. - -> [https://docs.docker.com/network.](https://docs.docker.com/network.) - ---- - -*Example* - -```wing -'host' -``` - - -##### `sourceHash`Optional - -```wing -sourceHash: str; -``` - -- *Type:* str -- *Default:* calculated based on the source files - -An explicit source hash that represents the container source. - -if not set, and `sourcePattern` -is set, the hash will be calculated based on the content of the source files. - ---- - -##### `sourcePattern`Optional - -```wing -sourcePattern: str; -``` - -- *Type:* str -- *Default:* all files - -A glob of local files to consider as input sources for the container, relative to the build context directory. - ---- - -##### `volumes`Optional - -```wing -volumes: MutArray; -``` - -- *Type:* MutArray<str> -- *Default:* [] - -Volume mount points. - ---- - -*Example* - -```wing -['/host:/container'] -``` - - - diff --git a/docs/docs/04-standard-library/sim/resource.md b/docs/docs/04-standard-library/sim/resource.md deleted file mode 100644 index b891461b412..00000000000 --- a/docs/docs/04-standard-library/sim/resource.md +++ /dev/null @@ -1,657 +0,0 @@ ---- -title: Resource -id: resource -description: Model a simulated resource with a lifecycle. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - Resource, - Simulator - ] ---- - -The `sim.Resource` class models a simulated resource with a lifecycle. -It's can be used to represent any cloud service where API calls are made over HTTP -to interact with the service at runtime. - -## Usage - -As an example, suppose we want to simulate a service that stores a number, like the one in `cloud.Counter`, which has two methods: `inc` and `peek`. - -First, we'll define an inflight class that represents the service's backend: - -```js -bring sim; - -// a resource backend must implement IResource -inflight class CounterBackend impl sim.IResource { - var counter: num; - - new(ctx: sim.IResourceContext) { - // startup code - this.counter = 0; - } - - pub onStop() { - // shutdown code - } - - pub inc(n: num?): num { - let p = this.counter; - this.counter += (n ?? 1); - return p; - } - - pub peek(): num { - return this.counter; - } -} -``` - -Each `CounterBackend` object that's created will have its own state. -It will be initialized by the simulator with its constructor (the `new()` method), and shut down using its `onStop` method. - -From the perspective of `CounterBackend`, its `inc` and `peek` methods are always called serially, even if requests are made concurrently from other resources. - -Next, we have to define a preflight class which represents the service's frontend: - -```js -class Counter { - backend: sim.Resource; - - new() { - // this is a "backend factory". it returns an inflight class that implements the - // resource. - let factory = inflight (ctx): sim.IResource => { - return new CounterBackend(ctx); - }; - - this.backend = new sim.Resource(factory); - } - - pub inflight inc(n: num?): num { - let response = this.backend.call("inc", [Json (n ?? 1)]); - return num.fromJson(response); - } - - pub inflight peek(): num { - let response = this.backend.call("peek"); - return num.fromJson(response); - } -} -``` - -The `Counter` class is a simple wrapper around the `CounterBackend` class. It provides a way to interact with the resource using the `inc` and `peek` methods. - -`sim.Resource` has an inflight method named `call` that takes the name of a method to call and an array of arguments, and returns the serialized response from the resource. -The arguments are serialized and sent to the resource over HTTP, which will process the request and returns a serialized response. - -> Note: Since the `call` method makes networked requests, it's important that the resource implementation provided by the inflight class responds in a timely manner. -> If the resource takes over 30 seconds to respond, `call` will throw an error, and the simulator will terminate the resource. - -The `Counter` class can be used like this: - -```js -let c = new Counter(); - -new cloud.Function(inflight () => { - log("counter is {c.peek()}"); - c.inc(); - log("counter is now {c.peek()}"); -}); -``` - -### Serializability - -Methods that are called on a `sim.Resource` instance must be serializable, meaning -all of their arguments and return values must be serializable. - -The following types are serializable: - -- `num` -- `str` -- `bool` -- `Json` -- `Array` -- `Map` -- `T?` where `T` is a serializable type -- enums -- structs that contain only serializable types - -The `call` function on `sim.Resource` only supports arguments that are valid `Json` values. -To convert a value to `Json`, use the `Json` constructor: - -```js -let x: num = 5; -let y: str = "a"; -this.backend.call("myMethod", Json [x, y]); -``` - -Return values can be converted back from `Json` using an appropriate `fromJson` method. - -```js -let response = this.backend.call("myMethod"); -let result: num = num.fromJson(response); -``` - -> Note: some types are missing `fromJson` methods. To work around this, you may use `unsafeCast()` to cast the value into the desired type. -> -> ```js -> let response = this.backend.call("myOtherMethod"); -> let result: MyEnum = unsafeCast(response); -> ``` - -### Late-bound Tokens - -Consider a use case where there is an attribute of a simulated service that only gets resolved during initialization (e.g. the exposed port of a container). -In order to create such resources, we need a way to obtain a lazy token that gets resolved during simulator initialization. - -Use the preflight method `resource.createToken(key)` to obtain a token that can be used to reference the value of the attribute at runtime. - -During resource simulation, you must call `ctx.resolveToken(key, value)` during a resource's constructor method to set the runtime value. - -```js playground -inflight class MyResourceBackend impl sim.IResource { - new(ctx: sim.IResourceContext) { - ctx.resolveToken("startTime", "2023-10-16T20:47:39.511Z"); - } - - pub onStop() {} -} - -class MyResource { - backend: sim.Resource; - pub startTime: str; - - new() { - this.backend = new sim.Resource(inflight () => { - return new MyResourceBackend(); - }); - this.startTime = this.backend.createToken("startTime"); - } -} - -let r = new MyResource(); - -new cloud.Function(inflight () => { - let time = util.env("START_TIME"); - log("start time is {time}"); -}, env: { - START_TIME: r.startTime, // lazy token can be used in preflight configuration -}); - -// ...or you can use it directly inflight, where the value is automatically resolved - -new cloud.Function(inflight () => { - log("start time is {r.startTime}"); -}); -``` -# API Reference - -## Resources - -### Resource - -- *Implements:* IResource, ISimulatorResource, IInflightHost, ISimulatorInflightHost - -A backend for a simulated resource. - -#### Initializers - -```wing -bring sim; - -new sim.Resource(factory: IResourceFactory); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| factory | IResourceFactory | *No description.* | - ---- - -##### `factory`Required - -- *Type:* IResourceFactory - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| addEnvironment | Add an environment variable to make available to the inflight code. | -| addPermission | Add a simulated permission to this inflight host. | -| createToken | Obtain a token that can be used to reference an attribute of this resource that is only resolved once the resource is started in the simulator. | -| toSimulator | Convert this resource to a resource schema for the simulator. | - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| call | Call a method on the resource. | - ---- - -##### `addEnvironment` - -```wing -addEnvironment(name: str, value: str): void -``` - -Add an environment variable to make available to the inflight code. - -###### `name`Required - -- *Type:* str - ---- - -###### `value`Required - -- *Type:* str - ---- - -##### `addPermission` - -```wing -addPermission(resource: IResource, op: str): void -``` - -Add a simulated permission to this inflight host. - -###### `resource`Required - -- *Type:* IResource - ---- - -###### `op`Required - -- *Type:* str - ---- - -##### `createToken` - -```wing -createToken(name: str): str -``` - -Obtain a token that can be used to reference an attribute of this resource that is only resolved once the resource is started in the simulator. - -If the token is used in inflight code or in the configuration of a simulated -resource (e.g. as an environment variable), the relevant resource will -automatically take a dependency on the resource the token belongs to. - -###### `name`Required - -- *Type:* str - -The name of the token. - ---- - -##### `toSimulator` - -```wing -toSimulator(): ToSimulatorOutput -``` - -Convert this resource to a resource schema for the simulator. - -##### `call` - -```wing -inflight call(method: str, args?: MutArray): Json -``` - -Call a method on the resource. - -###### `method`Required - -- *Type:* str - ---- - -###### `args`Optional - -- *Type:* MutArray<Json> - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring sim; - -sim.Resource.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring sim; - -sim.Resource.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - - - -## Protocols - -### IResource - -- *Implemented By:* IResource - -Contract that a resource backend must implement. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| onStop | Runs when the resource is stopped. | - ---- - -##### `onStop` - -```wing -onStop(): void -``` - -Runs when the resource is stopped. - - -### IResourceContext - -- *Implemented By:* IResourceContext - -Context for implementing a simulator resource. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| log | Log a message at the current point in time. | -| resolveToken | Resolves a token value. | -| statedir | The directory for the resource's state. | - ---- - -##### `log` - -```wing -inflight log(message: str, level?: LogLevel): void -``` - -Log a message at the current point in time. - -Defaults to `info` level. - -###### `message`Required - -- *Type:* str - -The message to log. - ---- - -###### `level`Optional - -- *Type:* LogLevel - -The severity of the message. - ---- - -##### `resolveToken` - -```wing -inflight resolveToken(name: str, value: str): void -``` - -Resolves a token value. - -All tokens must be resolved during the -constructor of the resource. - -###### `name`Required - -- *Type:* str - -The name of the token. - ---- - -###### `value`Required - -- *Type:* str - -The value of the token. - ---- - -##### `statedir` - -```wing -statedir(): str -``` - -The directory for the resource's state. - - -### IResourceFactory - -- *Extends:* IInflight - -- *Implemented By:* IResourceFactory - -**Inflight client:** [@winglang/sdk.sim.IResourceFactoryClient](#@winglang/sdk.sim.IResourceFactoryClient) - -A resource with an inflight "handle" method that can be passed to the `sim.Resource` constructor. - - - -### IResourceFactoryClient - -- *Implemented By:* IResourceFactoryClient - -A resource with an inflight "handle" method that can be passed to the `sim.Resource` constructor. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that will be called to initialize the simulator resource. | - ---- - -##### `handle` - -```wing -inflight handle(context: IResourceContext): IResource? -``` - -Function that will be called to initialize the simulator resource. - -To implement a shutdown sequence, return an object that implements the `IResource` inflight interface with an `onStop()` method. - -###### `context`Required - -- *Type:* IResourceContext - ---- - - -### ISimulatorInflightHost - -- *Extends:* IInflightHost - -- *Implemented By:* Resource, ISimulatorInflightHost - -Interfaces shared by all preflight classes that host inflight code. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| addPermission | Add a simulated permission to this inflight host. | - ---- - -##### `addPermission` - -```wing -addPermission(resource: IResource, op: str): void -``` - -Add a simulated permission to this inflight host. - -###### `resource`Required - -- *Type:* IResource - -The resource to add. - ---- - -###### `op`Required - -- *Type:* str - -The action to add. - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -### ISimulatorResource - -- *Extends:* IResource - -- *Implemented By:* Container, Policy, Resource, State, ISimulatorResource - -Interfaces shared by all preflight classes targeting the simulator. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| toSimulator | Convert this resource to a resource schema for the simulator. | - ---- - -##### `toSimulator` - -```wing -toSimulator(): ToSimulatorOutput -``` - -Convert this resource to a resource schema for the simulator. - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - diff --git a/docs/docs/04-standard-library/sim/state.md b/docs/docs/04-standard-library/sim/state.md deleted file mode 100644 index 9d21fdd00e8..00000000000 --- a/docs/docs/04-standard-library/sim/state.md +++ /dev/null @@ -1,283 +0,0 @@ ---- -title: State -id: state -description: Key/value in-memory state for the simulator. -keywords: - [ - Wing reference, - Wing language, - language, - Wing standard library, - Wing programming language, - In-memory state, - State, - Simulator - ] ---- - -The `sim.State` is a simple key/value in-memory store for the simulator with support for lazy -tokens. - -Consider a use case where there is an attribute of a simulated service that only gets resolved during initialization (e.g. the exposed port of a container). In order to create such resources, we need a way to obtain a lazy token that gets resolved during simulator initialization. It just so happens that we already have a mechanism like this, but it was not exposed as a public API. - -Use the preflight method `state.token(key)` to obtain a token that can be used to reference the -value of the state at runtime. - -During simulator app initialization (i.e. `cloud.OnDeploy` or `cloud.Service` startup), you must -call the inflight method `state.set(key, value)` to set the runtime value. The value will be -available at runtime through the inflight method `state.get(key)`, or via a resolved token. - -## Usage - -Let's say I want to create a simulated service that has property called `startTime` which returns -the time the service was started. This information is also known when the service is actually -initialized. - -```js -bring cloud; -bring sim; - -class MyService { - startTime: str; - - new() { - let state = new sim.State(); - - new cloud.Service(inflight () => { - state.set("start", std.Datetime.utcNow().toIso()); - }); - - this.startTime = state.token("start"); - } -} -``` - -In this example, the `startTime` property will resolve to a *simulator token* (something like -`${root/MyService/State#attrs.start)}`) which can be referenced ("lifted") into inflight context -naturally: - -```js -let s = new MyService(); - -new cloud.Function(inflight () => { - log("service start time is {s}"); -}); -``` - -This creates an implicit dependency between the `cloud.Function` and `MyService` such that only when -the state `start` is set, the `cloud.Function` will be initialized with the actual value. -# API Reference - -## Resources - -### State - -- *Implements:* ISimulatorResource - -Key/value in-memory state for the simulator. - -Use the preflight method `token(key)` to obtain a token that can be used to reference the value -of the state at runtime. - -During deployment (i.e. `cloud.OnDeploy` or `cloud.Service` startup), you must call the inflight -method `set(key, value)` to set the runtime value. The value will be available at runtime through -the inflight method `get(key)` (or resolved as a token). - -See tests for examples. - -#### Initializers - -```wing -bring sim; - -new sim.State(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - -#### Methods - -##### Preflight Methods - -| **Name** | **Description** | -| --- | --- | -| token | Returns a token that can be used to retrieve the value of the state after the simulation has run. | -| toSimulator | Convert this resource to a resource schema for the simulator. | - -##### Inflight Methods - -| **Name** | **Description** | -| --- | --- | -| get | Gets the runtime state of this object. | -| set | Sets the state of runtime a runtime object. | -| tryGet | Checks if runtime state exists for this object and returns it's value. | - ---- - -##### `token` - -```wing -token(key: str): str -``` - -Returns a token that can be used to retrieve the value of the state after the simulation has run. - -###### `key`Required - -- *Type:* str - -The object key retrieved through the inflight `state.get()`. - ---- - -##### `toSimulator` - -```wing -toSimulator(): ToSimulatorOutput -``` - -Convert this resource to a resource schema for the simulator. - -##### `get` - -```wing -inflight get(key: str): Json -``` - -Gets the runtime state of this object. - -Throws if there is no value for the given key. - -###### `key`Required - -- *Type:* str - -The object's key. - ---- - -##### `set` - -```wing -inflight set(key: str, value: Json): void -``` - -Sets the state of runtime a runtime object. - -###### `key`Required - -- *Type:* str - -The object's key. - ---- - -###### `value`Required - -- *Type:* Json - -The object's value. - ---- - -##### `tryGet` - -```wing -inflight tryGet(key: str): Json? -``` - -Checks if runtime state exists for this object and returns it's value. - -If no value exists, -returns `nil`. - -###### `key`Required - -- *Type:* str - -The object's key. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | - ---- - -##### `onLiftType` - -```wing -bring sim; - -sim.State.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring sim; - -sim.State.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - - - - diff --git a/docs/docs/04-standard-library/std/README.md b/docs/docs/04-standard-library/std/README.md deleted file mode 100644 index da8b4831e25..00000000000 --- a/docs/docs/04-standard-library/std/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Wing Globals - -This directory contains types available in the global scope of Wing. \ No newline at end of file diff --git a/docs/docs/04-standard-library/std/array.md b/docs/docs/04-standard-library/std/array.md deleted file mode 100644 index bfb6a1a2375..00000000000 --- a/docs/docs/04-standard-library/std/array.md +++ /dev/null @@ -1,479 +0,0 @@ ---- -title: array -id: array ---- - -# API Reference - - -## Classes - -### Array - -Immutable Array. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| at | Get the value at the given index. | -| concat | Merge arr to the end of this array. | -| contains | Checks if this array includes searchElement. | -| copyMut | Create a mutable shallow copy of this array. | -| indexOf | Returns the index of the first occurrence of searchElement found. | -| join | Returns a new string containing the concatenated values in this array, separated by commas or a specified separator string. | -| lastIndexOf | Returns the index of the last occurrence of searchElement found. | -| slice | Returns a shallow copy of a portion of the array. | -| tryAt | Get the value at the given index, returning nil if the index is out of bounds. | - ---- - -##### `at` - -```wing -at(index: num): -``` - -Get the value at the given index. - -###### `index`Required - -- *Type:* num - -index of the value to get. - ---- - -##### `concat` - -```wing -concat(arr: Array): Array -``` - -Merge arr to the end of this array. - -###### `arr`Required - -- *Type:* Array - -array to merge. - ---- - -##### `contains` - -```wing -contains(searchElement: ): bool -``` - -Checks if this array includes searchElement. - -###### `searchElement`Required - -- *Type:* <T> - -to search for. - ---- - -##### `copyMut` - -```wing -copyMut(): MutArray -``` - -Create a mutable shallow copy of this array. - -##### `indexOf` - -```wing -indexOf(searchElement: ): num -``` - -Returns the index of the first occurrence of searchElement found. - -###### `searchElement`Required - -- *Type:* <T> - -to search for. - ---- - -##### `join` - -```wing -join(separator?: str): str -``` - -Returns a new string containing the concatenated values in this array, separated by commas or a specified separator string. - -If the array has only -one item, then that item will be returned without using the separator. - -###### `separator`Optional - -- *Type:* str - ---- - -##### `lastIndexOf` - -```wing -lastIndexOf(searchElement: ): num -``` - -Returns the index of the last occurrence of searchElement found. - -###### `searchElement`Required - -- *Type:* <T> - -to search for. - ---- - -##### `slice` - -```wing -slice(start?: num, end?: num): Array -``` - -Returns a shallow copy of a portion of the array. - -###### `start`Optional - -- *Type:* num - -the beginning index of the slice, inclusive. - ---- - -###### `end`Optional - -- *Type:* num - -the ending index of the slice, exclusive. - ---- - -##### `tryAt` - -```wing -tryAt(index: num): ? -``` - -Get the value at the given index, returning nil if the index is out of bounds. - -###### `index`Required - -- *Type:* num - -index of the value to get. - ---- - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| length | num | The length of the array. | - ---- - -##### `length`Required - -```wing -length: num; -``` - -- *Type:* num - -The length of the array. - ---- - - -### MutArray - -Mutable Array. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| at | Get the value at the given index. | -| concat | Merge arr to the end of this array. | -| contains | Checks if this array includes searchElement. | -| copy | Create an immutable shallow copy of this array. | -| indexOf | Returns the index of the first occurrence of searchElement found. | -| insert | Inserts a new value at the given index of an array. | -| join | Returns a new string containing the concatenated values in this array, separated by commas or a specified separator string. | -| lastIndexOf | Returns the index of the last occurrence of searchElement found. | -| pop | Remove value from end of array. | -| popAt | Removes value from the given index of an array. | -| push | Add values to end of array. | -| removeFirst | Removes first occurrence of a given value in an array. | -| set | Sets a new value at the given index of an array. | -| slice | Returns a shallow copy of a portion of the array. | - ---- - -##### `at` - -```wing -at(index: num): -``` - -Get the value at the given index. - -###### `index`Required - -- *Type:* num - -index of the value to get. - ---- - -##### `concat` - -```wing -concat(arr: MutArray): MutArray -``` - -Merge arr to the end of this array. - -###### `arr`Required - -- *Type:* MutArray - -array to merge. - ---- - -##### `contains` - -```wing -contains(searchElement: ): bool -``` - -Checks if this array includes searchElement. - -###### `searchElement`Required - -- *Type:* <T> - -to search for. - ---- - -##### `copy` - -```wing -copy(): Array -``` - -Create an immutable shallow copy of this array. - -##### `indexOf` - -```wing -indexOf(searchElement: ): num -``` - -Returns the index of the first occurrence of searchElement found. - -###### `searchElement`Required - -- *Type:* <T> - -to search for. - ---- - -##### `insert` - -```wing -insert(index: num, value: ): void -``` - -Inserts a new value at the given index of an array. - -###### `index`Required - -- *Type:* num - -the index to insert the value at. - ---- - -###### `value`Required - -- *Type:* <T> - -the value to insert at the given index. - ---- - -##### `join` - -```wing -join(separator?: str): str -``` - -Returns a new string containing the concatenated values in this array, separated by commas or a specified separator string. - -If the array has only -one item, then that item will be returned without using the separator. - -###### `separator`Optional - -- *Type:* str - ---- - -##### `lastIndexOf` - -```wing -lastIndexOf(searchElement: ): num -``` - -Returns the index of the last occurrence of searchElement found. - -###### `searchElement`Required - -- *Type:* <T> - -to search for. - ---- - -##### `pop` - -```wing -pop(): -``` - -Remove value from end of array. - -##### `popAt` - -```wing -popAt(index: num): -``` - -Removes value from the given index of an array. - -###### `index`Required - -- *Type:* num - -the index to remove the value at. - ---- - -##### `push` - -```wing -push(...values: Array<>): void -``` - -Add values to end of array. - -###### `values`Required - -- *Type:* <T> - -values to add. - ---- - -##### `removeFirst` - -```wing -removeFirst(value: ): bool -``` - -Removes first occurrence of a given value in an array. - -###### `value`Required - -- *Type:* <T> - -the value to remove. - ---- - -##### `set` - -```wing -set(index: num, value: ): void -``` - -Sets a new value at the given index of an array. - -###### `index`Required - -- *Type:* num - -the index to set the value at. - ---- - -###### `value`Required - -- *Type:* <T> - -the value to set at the given index. - ---- - -##### `slice` - -```wing -slice(start?: num, end?: num): MutArray -``` - -Returns a shallow copy of a portion of the array. - -###### `start`Optional - -- *Type:* num - -the beginning index of the slice, inclusive. - ---- - -###### `end`Optional - -- *Type:* num - -the ending index of the slice, exclusive. - ---- - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| length | num | The length of the array. | - ---- - -##### `length`Required - -```wing -length: num; -``` - -- *Type:* num - -The length of the array. - ---- - - - - diff --git a/docs/docs/04-standard-library/std/bool.md b/docs/docs/04-standard-library/std/bool.md deleted file mode 100644 index 4f1639ce733..00000000000 --- a/docs/docs/04-standard-library/std/bool.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: bool -id: bool ---- - -# API Reference - - -## Classes - -### Boolean - -Boolean. - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| fromJson | Parse a boolean from Json. | - ---- - -##### `fromJson` - -```wing -bool.fromJson(json: Json, options?: JsonValidationOptions); -``` - -Parse a boolean from Json. - -###### `json`Required - -- *Type:* Json - -to parse boolean from. - ---- - -###### `options`Optional - -- *Type:* JsonValidationOptions - ---- - - - - - diff --git a/docs/docs/04-standard-library/std/datetime.md b/docs/docs/04-standard-library/std/datetime.md deleted file mode 100644 index 56c353326e7..00000000000 --- a/docs/docs/04-standard-library/std/datetime.md +++ /dev/null @@ -1,392 +0,0 @@ ---- -title: datetime -id: datetime ---- - -# API Reference - - -## Classes - -### Datetime - -- *Implements:* ILiftable - -Represents a local or UTC date object. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| toIso | Returns ISO-8601 string. | -| toUtc | Returns a Datetime represents the same date in utc. | - ---- - -##### `toIso` - -```wing -toIso(): str -``` - -Returns ISO-8601 string. - -##### `toUtc` - -```wing -toUtc(): datetime -``` - -Returns a Datetime represents the same date in utc. - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| fromComponents | Create a Datetime from Datetime components. | -| fromDate | Create a Datetime from a JavaScript Date object. | -| fromIso | Create a Datetime from an ISO-8601 string. | -| systemNow | Create a Datetime from local system timezone. | -| utcNow | Create a Datetime from UTC timezone. | - ---- - -##### `fromComponents` - -```wing -datetime.fromComponents(c: DatetimeComponents); -``` - -Create a Datetime from Datetime components. - -###### `c`Required - -- *Type:* DatetimeComponents - -DatetimeComponents. - ---- - -##### `fromDate` - -```wing -datetime.fromDate(date: datetime); -``` - -Create a Datetime from a JavaScript Date object. - -###### `date`Required - -- *Type:* datetime - -The JavaScript Date object. - ---- - -##### `fromIso` - -```wing -datetime.fromIso(iso: str); -``` - -Create a Datetime from an ISO-8601 string. - -###### `iso`Required - -- *Type:* str - -ISO-8601 string. - ---- - -##### `systemNow` - -```wing -datetime.systemNow(); -``` - -Create a Datetime from local system timezone. - -##### `utcNow` - -```wing -datetime.utcNow(); -``` - -Create a Datetime from UTC timezone. - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| dayOfMonth | num | Returns the day of month in the local machine time or in utc (1 - 31). | -| dayOfWeek | num | Returns the day in month of the local machine time or in utc (0 - 6). | -| hours | num | Returns the hour of the local machine time or in utc. | -| min | num | Returns the minute of the local machine time or in utc. | -| month | num | Returns the month of the local machine time or in utc (0 - 11). | -| ms | num | Returns the milliseconds of the local machine time or in utc *. | -| sec | num | Returns the seconds of the local machine time or in utc. | -| timestamp | num | Return a timestamp of non-leap year seconds since epoch. | -| timestampMs | num | Return a timestamp of non-leap year milliseconds since epoch. | -| timezone | num | Returns the offset in minutes from UTC. | -| year | num | Returns the year of the local machine time or in utc. | - ---- - -##### `dayOfMonth`Required - -```wing -dayOfMonth: num; -``` - -- *Type:* num - -Returns the day of month in the local machine time or in utc (1 - 31). - ---- - -##### `dayOfWeek`Required - -```wing -dayOfWeek: num; -``` - -- *Type:* num - -Returns the day in month of the local machine time or in utc (0 - 6). - ---- - -##### `hours`Required - -```wing -hours: num; -``` - -- *Type:* num - -Returns the hour of the local machine time or in utc. - ---- - -##### `min`Required - -```wing -min: num; -``` - -- *Type:* num - -Returns the minute of the local machine time or in utc. - ---- - -##### `month`Required - -```wing -month: num; -``` - -- *Type:* num - -Returns the month of the local machine time or in utc (0 - 11). - ---- - -##### `ms`Required - -```wing -ms: num; -``` - -- *Type:* num - -Returns the milliseconds of the local machine time or in utc *. - ---- - -##### `sec`Required - -```wing -sec: num; -``` - -- *Type:* num - -Returns the seconds of the local machine time or in utc. - ---- - -##### `timestamp`Required - -```wing -timestamp: num; -``` - -- *Type:* num - -Return a timestamp of non-leap year seconds since epoch. - ---- - -##### `timestampMs`Required - -```wing -timestampMs: num; -``` - -- *Type:* num - -Return a timestamp of non-leap year milliseconds since epoch. - ---- - -##### `timezone`Required - -```wing -timezone: num; -``` - -- *Type:* num - -Returns the offset in minutes from UTC. - ---- - -##### `year`Required - -```wing -year: num; -``` - -- *Type:* num - -Returns the year of the local machine time or in utc. - ---- - - -## Structs - -### DatetimeComponents - -Interface that is used for setting Datetime date. - -#### Initializer - -```wing -let DatetimeComponents = DatetimeComponents{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| day | num | Day. | -| hour | num | Hours. | -| min | num | Minutes. | -| month | num | Month. | -| ms | num | Milliseconds. | -| sec | num | Seconds. | -| tz | num | Timezone offset in minutes from UTC. | -| year | num | Year. | - ---- - -##### `day`Required - -```wing -day: num; -``` - -- *Type:* num - -Day. - ---- - -##### `hour`Required - -```wing -hour: num; -``` - -- *Type:* num - -Hours. - ---- - -##### `min`Required - -```wing -min: num; -``` - -- *Type:* num - -Minutes. - ---- - -##### `month`Required - -```wing -month: num; -``` - -- *Type:* num - -Month. - ---- - -##### `ms`Required - -```wing -ms: num; -``` - -- *Type:* num - -Milliseconds. - ---- - -##### `sec`Required - -```wing -sec: num; -``` - -- *Type:* num - -Seconds. - ---- - -##### `tz`Required - -```wing -tz: num; -``` - -- *Type:* num - -Timezone offset in minutes from UTC. - ---- - -##### `year`Required - -```wing -year: num; -``` - -- *Type:* num - -Year. - ---- - - diff --git a/docs/docs/04-standard-library/std/duration.md b/docs/docs/04-standard-library/std/duration.md deleted file mode 100644 index 0c2807e5cfc..00000000000 --- a/docs/docs/04-standard-library/std/duration.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: duration -id: duration ---- - -# API Reference - - -## Classes - -### Duration - -- *Implements:* ILiftable - -Represents a length of time. - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| fromDays | Create a Duration representing an amount of days. | -| fromHours | Create a Duration representing an amount of hours. | -| fromMilliseconds | Create a Duration representing an amount of milliseconds. | -| fromMinutes | Create a Duration representing an amount of minutes. | -| fromMonths | Create a Duration representing an amount of months. | -| fromSeconds | Create a Duration representing an amount of seconds. | -| fromYears | Create a Duration representing an amount of years. | - ---- - -##### `fromDays` - -```wing -duration.fromDays(amount: num); -``` - -Create a Duration representing an amount of days. - -###### `amount`Required - -- *Type:* num - -the amount of Days the `Duration` will represent. - ---- - -##### `fromHours` - -```wing -duration.fromHours(amount: num); -``` - -Create a Duration representing an amount of hours. - -###### `amount`Required - -- *Type:* num - -the amount of Hours the `Duration` will represent. - ---- - -##### `fromMilliseconds` - -```wing -duration.fromMilliseconds(amount: num); -``` - -Create a Duration representing an amount of milliseconds. - -###### `amount`Required - -- *Type:* num - -the amount of Milliseconds the `Duration` will represent. - ---- - -##### `fromMinutes` - -```wing -duration.fromMinutes(amount: num); -``` - -Create a Duration representing an amount of minutes. - -###### `amount`Required - -- *Type:* num - -the amount of Minutes the `Duration` will represent. - ---- - -##### `fromMonths` - -```wing -duration.fromMonths(amount: num); -``` - -Create a Duration representing an amount of months. - -###### `amount`Required - -- *Type:* num - -the amount of Months the `Duration` will represent. - ---- - -##### `fromSeconds` - -```wing -duration.fromSeconds(amount: num); -``` - -Create a Duration representing an amount of seconds. - -###### `amount`Required - -- *Type:* num - -the amount of Seconds the `Duration` will represent. - ---- - -##### `fromYears` - -```wing -duration.fromYears(amount: num); -``` - -Create a Duration representing an amount of years. - -###### `amount`Required - -- *Type:* num - -the amount of Years the `Duration` will represent. - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| days | num | Return the total number of days in this Duration. | -| hours | num | Return the total number of hours in this Duration. | -| milliseconds | num | Return the total number of milliseconds in this Duration. | -| minutes | num | Return the total number of minutes in this Duration. | -| months | num | Return the total number of months in this Duration. | -| seconds | num | Return the total number of seconds in this Duration. | -| years | num | Return the total number of years in this Duration. | - ---- - -##### `days`Required - -```wing -days: num; -``` - -- *Type:* num - -Return the total number of days in this Duration. - ---- - -##### `hours`Required - -```wing -hours: num; -``` - -- *Type:* num - -Return the total number of hours in this Duration. - ---- - -##### `milliseconds`Required - -```wing -milliseconds: num; -``` - -- *Type:* num - -Return the total number of milliseconds in this Duration. - ---- - -##### `minutes`Required - -```wing -minutes: num; -``` - -- *Type:* num - -Return the total number of minutes in this Duration. - ---- - -##### `months`Required - -```wing -months: num; -``` - -- *Type:* num - -Return the total number of months in this Duration. - ---- - -##### `seconds`Required - -```wing -seconds: num; -``` - -- *Type:* num - -Return the total number of seconds in this Duration. - ---- - -##### `years`Required - -```wing -years: num; -``` - -- *Type:* num - -Return the total number of years in this Duration. - ---- - - - - diff --git a/docs/docs/04-standard-library/std/json.md b/docs/docs/04-standard-library/std/json.md deleted file mode 100644 index 72436d5dc3f..00000000000 --- a/docs/docs/04-standard-library/std/json.md +++ /dev/null @@ -1,724 +0,0 @@ ---- -title: json -id: json ---- - -# API Reference - - -## Classes - -### Json - -Immutable Json. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| asBool | Convert Json element to boolean if possible. | -| asNum | Convert Json element to number if possible. | -| asStr | Convert Json element to string if possible. | -| get | Returns the value associated with the specified Json key. | -| getAt | Returns a specified element at a given index from Json Array. | -| has | Checks if a Json object has a given key. | -| tryAsBool | Convert Json element to boolean if possible. | -| tryAsNum | Convert Json element to number if possible. | -| tryAsStr | Convert Json element to string if possible. | -| tryGet | Optionally returns an specified element from the Json. | -| tryGetAt | Optionally returns a specified element at a given index from Json Array. | - ---- - -##### `asBool` - -```wing -asBool(): bool -``` - -Convert Json element to boolean if possible. - -##### `asNum` - -```wing -asNum(): num -``` - -Convert Json element to number if possible. - -##### `asStr` - -```wing -asStr(): str -``` - -Convert Json element to string if possible. - -##### `get` - -```wing -get(key: str): Json -``` - -Returns the value associated with the specified Json key. - -###### `key`Required - -- *Type:* str - -The key of the Json property. - ---- - -##### `getAt` - -```wing -getAt(index: num): Json -``` - -Returns a specified element at a given index from Json Array. - -###### `index`Required - -- *Type:* num - -The index of the element in the Json Array to return. - ---- - -##### `has` - -```wing -has(key: str): bool -``` - -Checks if a Json object has a given key. - -###### `key`Required - -- *Type:* str - -The key to check. - ---- - -##### `tryAsBool` - -```wing -tryAsBool(): bool? -``` - -Convert Json element to boolean if possible. - -##### `tryAsNum` - -```wing -tryAsNum(): num? -``` - -Convert Json element to number if possible. - -##### `tryAsStr` - -```wing -tryAsStr(): str? -``` - -Convert Json element to string if possible. - -##### `tryGet` - -```wing -tryGet(key: str): Json? -``` - -Optionally returns an specified element from the Json. - -###### `key`Required - -- *Type:* str - -The key of the element to return. - ---- - -##### `tryGetAt` - -```wing -tryGetAt(index: num): Json? -``` - -Optionally returns a specified element at a given index from Json Array. - -###### `index`Required - -- *Type:* num - -The index of the element in the Json Array to return. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| deepCopy | Creates an immutable deep copy of the Json. | -| deepCopyMut | Creates a mutable deep copy of the Json. | -| delete | Deletes a key in a given Json. | -| entries | Returns the entries from the Json. | -| keys | Returns the keys from the Json. | -| parse | Parse a string into a Json. | -| stringify | Formats Json as string. | -| tryParse | Try to parse a string into a Json. | -| values | Returns the values from the Json. | - ---- - -##### `deepCopy` - -```wing -Json.deepCopy(json: MutJson); -``` - -Creates an immutable deep copy of the Json. - -###### `json`Required - -- *Type:* MutJson - -to copy. - ---- - -##### `deepCopyMut` - -```wing -Json.deepCopyMut(json: Json); -``` - -Creates a mutable deep copy of the Json. - -###### `json`Required - -- *Type:* Json - -to copy. - ---- - -##### `delete` - -```wing -Json.delete(json: MutJson, key: str); -``` - -Deletes a key in a given Json. - -###### `json`Required - -- *Type:* MutJson - -to delete key from. - ---- - -###### `key`Required - -- *Type:* str - -the key to delete. - ---- - -##### `entries` - -```wing -Json.entries(json: Json); -``` - -Returns the entries from the Json. - -###### `json`Required - -- *Type:* Json - -map to get the entries from. - ---- - -##### `keys` - -```wing -Json.keys(json: any); -``` - -Returns the keys from the Json. - -###### `json`Required - -- *Type:* any - -map to get the keys from. - ---- - -##### `parse` - -```wing -Json.parse(str: str); -``` - -Parse a string into a Json. - -###### `str`Required - -- *Type:* str - -to parse as Json. - ---- - -##### `stringify` - -```wing -Json.stringify(json: any, options?: JsonStringifyOptions); -``` - -Formats Json as string. - -###### `json`Required - -- *Type:* any - -to format as string. - ---- - -###### `options`Optional - -- *Type:* JsonStringifyOptions - ---- - -##### `tryParse` - -```wing -Json.tryParse(str?: str); -``` - -Try to parse a string into a Json. - -###### `str`Optional - -- *Type:* str - -to parse as Json. - ---- - -##### `values` - -```wing -Json.values(json: Json); -``` - -Returns the values from the Json. - -###### `json`Required - -- *Type:* Json - -map to get the values from. - ---- - - - -### JsonSchema - -Struct Schema. - -#### Initializers - -```wing -new JsonSchema(schema: Json); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| schema | Json | *No description.* | - ---- - -##### `schema`Required - -- *Type:* Json - ---- - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| asStr | Retrieve the json schema as a string. | -| validate | Attempt to validate a json object against the schema. | - ---- - -##### `asStr` - -```wing -asStr(): str -``` - -Retrieve the json schema as a string. - -##### `validate` - -```wing -validate(obj: Json, options?: JsonValidationOptions): void -``` - -Attempt to validate a json object against the schema. - -###### `obj`Required - -- *Type:* Json - -the Json object to validate. - ---- - -###### `options`Optional - -- *Type:* JsonValidationOptions - ---- - - - - -### MutJson - -Mutable Json. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| asBool | Convert Json element to boolean if possible. | -| asNum | Convert Json element to number if possible. | -| asStr | Convert Json element to string if possible. | -| delete | Removes the specified element from a map. | -| get | Returns the value associated with the specified Json key. | -| getAt | Returns a specified element at a given index from MutJson Array. | -| has | Checks if a Json object has a given key. | -| set | Adds or updates an element in MutJson with a specific key and value. | -| setAt | Set element in MutJson Array with a specific key and value. | -| tryAsBool | Convert Json element to boolean if possible. | -| tryAsNum | Convert Json element to number if possible. | -| tryAsStr | Convert Json element to string if possible. | -| tryGet | Optionally returns an specified element from the Json. | -| tryGetAt | Optionally returns a specified element at a given index from Json Array. | - ---- - -##### `asBool` - -```wing -asBool(): bool -``` - -Convert Json element to boolean if possible. - -##### `asNum` - -```wing -asNum(): num -``` - -Convert Json element to number if possible. - -##### `asStr` - -```wing -asStr(): str -``` - -Convert Json element to string if possible. - -##### `delete` - -```wing -delete(key: str): bool -``` - -Removes the specified element from a map. - -###### `key`Required - -- *Type:* str - -The key. - ---- - -##### `get` - -```wing -get(key: str): MutJson -``` - -Returns the value associated with the specified Json key. - -###### `key`Required - -- *Type:* str - -The key of the Json property. - ---- - -##### `getAt` - -```wing -getAt(index: num): MutJson -``` - -Returns a specified element at a given index from MutJson Array. - -###### `index`Required - -- *Type:* num - -The index of the element in the MutJson Array to return. - ---- - -##### `has` - -```wing -has(key: str): bool -``` - -Checks if a Json object has a given key. - -###### `key`Required - -- *Type:* str - -The key to check. - ---- - -##### `set` - -```wing -set(key: str, value: MutJson): void -``` - -Adds or updates an element in MutJson with a specific key and value. - -###### `key`Required - -- *Type:* str - -The key of the element to add. - ---- - -###### `value`Required - -- *Type:* MutJson - -The value of the element to add. - ---- - -##### `setAt` - -```wing -setAt(index: num, value: MutJson): void -``` - -Set element in MutJson Array with a specific key and value. - -###### `index`Required - -- *Type:* num - ---- - -###### `value`Required - -- *Type:* MutJson - -The value of the element to set. - ---- - -##### `tryAsBool` - -```wing -tryAsBool(): bool? -``` - -Convert Json element to boolean if possible. - -##### `tryAsNum` - -```wing -tryAsNum(): num? -``` - -Convert Json element to number if possible. - -##### `tryAsStr` - -```wing -tryAsStr(): str? -``` - -Convert Json element to string if possible. - -##### `tryGet` - -```wing -tryGet(key: str): MutJson? -``` - -Optionally returns an specified element from the Json. - -###### `key`Required - -- *Type:* str - -The key of the element to return. - ---- - -##### `tryGetAt` - -```wing -tryGetAt(index: num): MutJson? -``` - -Optionally returns a specified element at a given index from Json Array. - -###### `index`Required - -- *Type:* num - -The index of the element in the Json Array to return. - ---- - - - - -## Structs - -### JsonEntry - -Json entry representation. - -#### Initializer - -```wing -let JsonEntry = JsonEntry{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| key | str | The entry key. | -| value | Json | The entry value. | - ---- - -##### `key`Required - -```wing -key: str; -``` - -- *Type:* str - -The entry key. - ---- - -##### `value`Required - -```wing -value: Json; -``` - -- *Type:* Json - -The entry value. - ---- - -### JsonStringifyOptions - -Options for stringify() method. - -#### Initializer - -```wing -let JsonStringifyOptions = JsonStringifyOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| indent | num | Indentation spaces number. | - ---- - -##### `indent`Required - -```wing -indent: num; -``` - -- *Type:* num - -Indentation spaces number. - ---- - -### JsonValidationOptions - -Options for validating Json. - -#### Initializer - -```wing -let JsonValidationOptions = JsonValidationOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| unsafe | bool | Unsafe mode to skip validation (may lead to runtime errors). | - ---- - -##### `unsafe`Optional - -```wing -unsafe: bool; -``` - -- *Type:* bool - -Unsafe mode to skip validation (may lead to runtime errors). - ---- - - diff --git a/docs/docs/04-standard-library/std/json_schema.md b/docs/docs/04-standard-library/std/json_schema.md deleted file mode 100644 index 87d228043ea..00000000000 --- a/docs/docs/04-standard-library/std/json_schema.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: jsonSchema -id: jsonSchema ---- - -# API Reference - - -## Classes - -### JsonSchema - -Struct Schema. - -#### Initializers - -```wing -new JsonSchema(schema: Json); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| schema | Json | *No description.* | - ---- - -##### `schema`Required - -- *Type:* Json - ---- - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| asStr | Retrieve the json schema as a string. | -| validate | Attempt to validate a json object against the schema. | - ---- - -##### `asStr` - -```wing -asStr(): str -``` - -Retrieve the json schema as a string. - -##### `validate` - -```wing -validate(obj: Json, options?: JsonValidationOptions): void -``` - -Attempt to validate a json object against the schema. - -###### `obj`Required - -- *Type:* Json - -the Json object to validate. - ---- - -###### `options`Optional - -- *Type:* JsonValidationOptions - ---- - - - - - - diff --git a/docs/docs/04-standard-library/std/map.md b/docs/docs/04-standard-library/std/map.md deleted file mode 100644 index e23e3d49c23..00000000000 --- a/docs/docs/04-standard-library/std/map.md +++ /dev/null @@ -1,339 +0,0 @@ ---- -title: map -id: map ---- - -# API Reference - - -## Classes - -### Map - -Immutable Map. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| copyMut | Create a mutable shallow copy of this map. | -| entries | Returns the entries from the map. | -| get | Returns a specified element from the map. | -| has | Returns a boolean indicating whether an element with the specified key exists or not. | -| keys | Returns the keys of this map. | -| size | Returns the number of elements in the map. | -| tryGet | Optionally returns a specified element from the map. | -| values | Returns the values of this map. | - ---- - -##### `copyMut` - -```wing -copyMut(): MutMap -``` - -Create a mutable shallow copy of this map. - -##### `entries` - -```wing -entries(): MutArray -``` - -Returns the entries from the map. - -##### `get` - -```wing -get(key: str): -``` - -Returns a specified element from the map. - -If the value that is associated to the provided key is an object, then you will get a reference -to that object and any change made to that object will effectively modify it inside the map. - -###### `key`Required - -- *Type:* str - -The key of the element to return. - ---- - -##### `has` - -```wing -has(key: str): bool -``` - -Returns a boolean indicating whether an element with the specified key exists or not. - -###### `key`Required - -- *Type:* str - -The key of the element to test for presence. - ---- - -##### `keys` - -```wing -keys(): MutArray -``` - -Returns the keys of this map. - -##### `size` - -```wing -size(): num -``` - -Returns the number of elements in the map. - -TODO: For now this has to be a method rather than a getter as macros only work on methods https://github.com/winglang/wing/issues/1658 - -##### `tryGet` - -```wing -tryGet(key: str): ? -``` - -Optionally returns a specified element from the map. - -###### `key`Required - -- *Type:* str - -The key of the element to return. - ---- - -##### `values` - -```wing -values(): Array -``` - -Returns the values of this map. - - - - -### MutMap - -Mutable Map. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| clear | Removes all elements. | -| copy | Create an immutable shallow copy of this map. | -| delete | Removes the specified element from a map. | -| entries | Returns the entries from the map. | -| get | Returns a specified element from the map. | -| has | Returns a boolean indicating whether an element with the specified key exists or not. | -| keys | Returns the keys of this map. | -| set | Adds or updates an entry in a Map object with a specified key and a value. | -| size | Returns the number of elements in the map. | -| tryGet | Optionally returns a specified element from the map. | -| values | Returns the values of this map. | - ---- - -##### `clear` - -```wing -clear(): void -``` - -Removes all elements. - -##### `copy` - -```wing -copy(): Map -``` - -Create an immutable shallow copy of this map. - -##### `delete` - -```wing -delete(key: str): bool -``` - -Removes the specified element from a map. - -###### `key`Required - -- *Type:* str - -The key. - ---- - -##### `entries` - -```wing -entries(): MutArray -``` - -Returns the entries from the map. - -##### `get` - -```wing -get(key: str): -``` - -Returns a specified element from the map. - -If the value that is associated to the provided key is an object, then you will get a reference -to that object and any change made to that object will effectively modify it inside the map. - -###### `key`Required - -- *Type:* str - -The key of the element to return. - ---- - -##### `has` - -```wing -has(key: str): bool -``` - -Returns a boolean indicating whether an element with the specified key exists or not. - -###### `key`Required - -- *Type:* str - -The key of the element to test for presence. - ---- - -##### `keys` - -```wing -keys(): MutArray -``` - -Returns the keys of this map. - -##### `set` - -```wing -set(key: str, value: ): void -``` - -Adds or updates an entry in a Map object with a specified key and a value. - -TODO: revisit this macro after we support indexed args https://github.com/winglang/wing/issues/1659 - -###### `key`Required - -- *Type:* str - -The key of the element to add. - ---- - -###### `value`Required - -- *Type:* <T> - -The value of the element to add. - ---- - -##### `size` - -```wing -size(): num -``` - -Returns the number of elements in the map. - -TODO: For now this has to be a method rather than a getter as macros only work on methods https://github.com/winglang/wing/issues/1658 - -##### `tryGet` - -```wing -tryGet(key: str): ? -``` - -Optionally returns a specified element from the map. - -###### `key`Required - -- *Type:* str - -The key of the element to return. - ---- - -##### `values` - -```wing -values(): Array -``` - -Returns the values of this map. - - - - -## Structs - -### ArrayEntry - -Array entry representation. - -#### Initializer - -```wing -let ArrayEntry = ArrayEntry{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| key | str | The entry key. | -| value | <T> | The entry value. | - ---- - -##### `key`Required - -```wing -key: str; -``` - -- *Type:* str - -The entry key. - ---- - -##### `value`Required - -```wing -value: ; -``` - -- *Type:* <T> - -The entry value. - ---- - - diff --git a/docs/docs/04-standard-library/std/node.md b/docs/docs/04-standard-library/std/node.md deleted file mode 100644 index f6c4f60df8a..00000000000 --- a/docs/docs/04-standard-library/std/node.md +++ /dev/null @@ -1,770 +0,0 @@ ---- -title: node -id: node ---- - -# API Reference - - -## Classes - -### Node - -The internal node of a construct. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| addConnection | Adds a connection between two constructs. | -| addDependency | Add an ordering dependency on another construct. | -| addMetadata | Adds a metadata entry to this construct. | -| addValidation | Adds a validation to this construct. | -| findAll | Return this construct and all of its children in the given order. | -| findChild | Return a direct child by id. | -| getContext | Retrieves a value from tree context if present. Otherwise, would throw an error. | -| lock | Locks this construct from allowing more children to be added. | -| setContext | This can be used to set contextual values. | -| tryFindChild | Return a direct child by id, or undefined. | -| tryGetContext | Retrieves a value from tree context. | -| tryRemoveChild | Remove the child with the given name, if present. | -| validate | Validates this construct. | - ---- - -##### `addConnection` - -```wing -addConnection(props: AddConnectionProps): void -``` - -Adds a connection between two constructs. - -A connection is a piece of -metadata describing how one construct is related to another construct. - -###### `props`Required - -- *Type:* AddConnectionProps - ---- - -##### `addDependency` - -```wing -addDependency(...deps: Array): void -``` - -Add an ordering dependency on another construct. - -An `IDependable` - -###### `deps`Required - -- *Type:* constructs.IDependable - ---- - -##### `addMetadata` - -```wing -addMetadata(type: str, data: any, options?: MetadataOptions): void -``` - -Adds a metadata entry to this construct. - -Entries are arbitrary values and will also include a stack trace to allow tracing back to -the code location for when the entry was added. It can be used, for example, to include source -mapping in CloudFormation templates to improve diagnostics. - -###### `type`Required - -- *Type:* str - -a string denoting the type of metadata. - ---- - -###### `data`Required - -- *Type:* any - -the value of the metadata (can be a Token). - -If null/undefined, metadata will not be added. - ---- - -###### `options`Optional - -- *Type:* constructs.MetadataOptions - -options. - ---- - -##### `addValidation` - -```wing -addValidation(validation: IValidation): void -``` - -Adds a validation to this construct. - -When `node.validate()` is called, the `validate()` method will be called on -all validations and all errors will be returned. - -###### `validation`Required - -- *Type:* constructs.IValidation - -The validation object. - ---- - -##### `findAll` - -```wing -findAll(order?: ConstructOrder): MutArray -``` - -Return this construct and all of its children in the given order. - -###### `order`Optional - -- *Type:* constructs.ConstructOrder - ---- - -##### `findChild` - -```wing -findChild(): IConstruct -``` - -Return a direct child by id. - -Throws an error if the child is not found. - -##### `getContext` - -```wing -getContext(key: str): any -``` - -Retrieves a value from tree context if present. Otherwise, would throw an error. - -Context is usually initialized at the root, but can be overridden at any point in the tree. - -###### `key`Required - -- *Type:* str - -The context key. - ---- - -##### `lock` - -```wing -lock(): void -``` - -Locks this construct from allowing more children to be added. - -After this -call, no more children can be added to this construct or to any children. - -##### `setContext` - -```wing -setContext(key: str, value: any): void -``` - -This can be used to set contextual values. - -Context must be set before any children are added, since children may consult context info during construction. -If the key already exists, it will be overridden. - -###### `key`Required - -- *Type:* str - -The context key. - ---- - -###### `value`Required - -- *Type:* any - -The context value. - ---- - -##### `tryFindChild` - -```wing -tryFindChild(): IConstruct? -``` - -Return a direct child by id, or undefined. - -##### `tryGetContext` - -```wing -tryGetContext(key: str): any -``` - -Retrieves a value from tree context. - -Context is usually initialized at the root, but can be overridden at any point in the tree. - -###### `key`Required - -- *Type:* str - -The context key. - ---- - -##### `tryRemoveChild` - -```wing -tryRemoveChild(childName: str): bool -``` - -Remove the child with the given name, if present. - -###### `childName`Required - -- *Type:* str - ---- - -##### `validate` - -```wing -validate(): MutArray -``` - -Validates this construct. - -Invokes the `validate()` method on all validations added through -`addValidation()`. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| addr | str | Returns an opaque tree-unique address for this construct. | -| app | IApp | Returns the root of the construct tree (the `cloud.App` object). | -| children | MutArray<constructs.IConstruct> | All direct children of this construct. | -| dependencies | MutArray<constructs.IConstruct> | Return all dependencies registered on this node (non-recursive). | -| id | str | The id of this construct within the current scope. | -| locked | bool | Returns true if this construct or the scopes in which it is defined are locked. | -| metadata | MutArray<constructs.MetadataEntry> | An immutable array of metadata objects associated with this construct. | -| path | str | The full, absolute path of this construct in the tree. | -| root | constructs.IConstruct | Returns the root of the construct tree (the `cloud.App` object). | -| scopes | MutArray<constructs.IConstruct> | All parent scopes of this construct. | -| scope | constructs.IConstruct | Returns the scope in which this construct is defined. | -| color | str | The color of the construct for display purposes. | -| defaultChild | constructs.IConstruct | Returns the child construct that has the id `Default` or `Resource"`. | -| description | str | Description of the construct for display purposes. | -| expanded | bool | Whether the node is expanded or collapsed by default in the UI. | -| hidden | bool | Whether the construct should be hidden by default in tree visualizations. | -| icon | str | The icon of the construct for display purposes. | -| sourceModule | str | The source file or library where the construct was defined. | -| title | str | Title of the construct for display purposes. | - ---- - -##### `addr`Required - -```wing -addr: str; -``` - -- *Type:* str - -Returns an opaque tree-unique address for this construct. - -Addresses are 42 characters hexadecimal strings. They begin with "c8" -followed by 40 lowercase hexadecimal characters (0-9a-f). - -Addresses are calculated using a SHA-1 of the components of the construct -path. - -To enable refactorings of construct trees, constructs with the ID `Default` -will be excluded from the calculation. In those cases constructs in the -same tree may have the same addreess. - ---- - -*Example* - -```wing -c83a2846e506bcc5f10682b564084bca2d275709ee -``` - - -##### `app`Required - -```wing -app: IApp; -``` - -- *Type:* IApp - -Returns the root of the construct tree (the `cloud.App` object). - -Similar to `root`. - ---- - -##### `children`Required - -```wing -children: MutArray; -``` - -- *Type:* MutArray<constructs.IConstruct> - -All direct children of this construct. - ---- - -##### `dependencies`Required - -```wing -dependencies: MutArray; -``` - -- *Type:* MutArray<constructs.IConstruct> - -Return all dependencies registered on this node (non-recursive). - ---- - -##### `id`Required - -```wing -id: str; -``` - -- *Type:* str - -The id of this construct within the current scope. - -This is a a scope-unique id. To obtain an app-unique id for this construct, use `addr`. - ---- - -##### `locked`Required - -```wing -locked: bool; -``` - -- *Type:* bool - -Returns true if this construct or the scopes in which it is defined are locked. - ---- - -##### `metadata`Required - -```wing -metadata: MutArray; -``` - -- *Type:* MutArray<constructs.MetadataEntry> - -An immutable array of metadata objects associated with this construct. - -This can be used, for example, to implement support for deprecation notices, source mapping, etc. - ---- - -##### `path`Required - -```wing -path: str; -``` - -- *Type:* str - -The full, absolute path of this construct in the tree. - -Components are separated by '/'. - ---- - -##### `root`Required - -```wing -root: IConstruct; -``` - -- *Type:* constructs.IConstruct - -Returns the root of the construct tree (the `cloud.App` object). - -Similar to `app`. - ---- - -##### `scopes`Required - -```wing -scopes: MutArray; -``` - -- *Type:* MutArray<constructs.IConstruct> - -All parent scopes of this construct. - ---- - -##### `scope`Optional - -```wing -scope: IConstruct; -``` - -- *Type:* constructs.IConstruct - -Returns the scope in which this construct is defined. - -The value is `undefined` at the root of the construct scope tree. - ---- - -##### `color`Optional - -```wing -color: str; -``` - -- *Type:* str - -The color of the construct for display purposes. - -Supported colors are: -- orange -- sky -- emerald -- lime -- pink -- amber -- cyan -- purple -- red -- violet -- slate - ---- - -##### `defaultChild`Optional - -```wing -defaultChild: IConstruct; -``` - -- *Type:* constructs.IConstruct - -Returns the child construct that has the id `Default` or `Resource"`. - -This is usually the construct that provides the bulk of the underlying functionality. -Useful for modifications of the underlying construct that are not available at the higher levels. -Override the defaultChild property. - -This should only be used in the cases where the correct -default child is not named 'Resource' or 'Default' as it -should be. - -If you set this to undefined, the default behavior of finding -the child named 'Resource' or 'Default' will be used. - ---- - -##### `description`Optional - -```wing -description: str; -``` - -- *Type:* str - -Description of the construct for display purposes. - ---- - -##### `expanded`Optional - -```wing -expanded: bool; -``` - -- *Type:* bool -- *Default:* false - -Whether the node is expanded or collapsed by default in the UI. - -By default, nodes are collapsed. Set this to `true` if you want the node to be expanded by default. - ---- - -##### `hidden`Optional - -```wing -hidden: bool; -``` - -- *Type:* bool - -Whether the construct should be hidden by default in tree visualizations. - ---- - -##### `icon`Optional - -```wing -icon: str; -``` - -- *Type:* str - -The icon of the construct for display purposes. - -Supported icons are from Heroicons: -- https://heroicons.com/ -e.g. -- "academic-cap" - ---- - -##### `sourceModule`Optional - -```wing -sourceModule: str; -``` - -- *Type:* str - -The source file or library where the construct was defined. - ---- - -##### `title`Optional - -```wing -title: str; -``` - -- *Type:* str - -Title of the construct for display purposes. - ---- - - -## Structs - -### AddConnectionProps - -Props for `Node.addConnection`. - -#### Initializer - -```wing -let AddConnectionProps = AddConnectionProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| name | str | A name for the connection. | -| target | constructs.IConstruct | The target of the connection. | -| source | constructs.IConstruct | The source of the connection. | -| sourceOp | str | An operation that the source construct supports. | -| targetOp | str | An operation that the target construct supports. | - ---- - -##### `name`Required - -```wing -name: str; -``` - -- *Type:* str - -A name for the connection. - ---- - -##### `target`Required - -```wing -target: IConstruct; -``` - -- *Type:* constructs.IConstruct - -The target of the connection. - ---- - -##### `source`Optional - -```wing -source: IConstruct; -``` - -- *Type:* constructs.IConstruct -- *Default:* this - -The source of the connection. - ---- - -##### `sourceOp`Optional - -```wing -sourceOp: str; -``` - -- *Type:* str -- *Default:* no operation - -An operation that the source construct supports. - ---- - -##### `targetOp`Optional - -```wing -targetOp: str; -``` - -- *Type:* str -- *Default:* no operation - -An operation that the target construct supports. - ---- - -## Protocols - -### IApp - -- *Extends:* constructs.IConstruct - -- *Implemented By:* App, IApp - -Represents a Wing application. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| makeId | Generate a unique ID for the given scope and prefix. | - ---- - -##### `makeId` - -```wing -makeId(prefix?: str): str -``` - -Generate a unique ID for the given scope and prefix. - -The newly generated ID is -guaranteed to be unique within the given scope. -It will have the form '{prefix}{n}', where '{prefix}' is the given prefix and '{n}' is an -ascending sequence of integers starting from '0'. - -###### `prefix`Optional - -- *Type:* str - -prepended to the unique identifier. - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | -| entrypointDir | str | The directory of the entrypoint of the current program. | -| isTestEnvironment | bool | `true` if this is a testing environment. | -| parameters | ParameterRegistrar | The application's parameter registrar. | -| workdir | str | The `.wing` directory into which you can emit artifacts during preflight. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - -##### `entrypointDir`Required - -```wing -entrypointDir: str; -``` - -- *Type:* str - -The directory of the entrypoint of the current program. - ---- - -##### `isTestEnvironment`Required - -```wing -isTestEnvironment: bool; -``` - -- *Type:* bool - -`true` if this is a testing environment. - ---- - -##### `parameters`Required - -```wing -parameters: ParameterRegistrar; -``` - -- *Type:* ParameterRegistrar - -The application's parameter registrar. - ---- - -##### `workdir`Required - -```wing -workdir: str; -``` - -- *Type:* str - -The `.wing` directory into which you can emit artifacts during preflight. - ---- - diff --git a/docs/docs/04-standard-library/std/number.md b/docs/docs/04-standard-library/std/number.md deleted file mode 100644 index 4d9ea120fb8..00000000000 --- a/docs/docs/04-standard-library/std/number.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: number -id: number ---- - -# API Reference - - -## Classes - -### Number - -Number. - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| fromJson | Parse a number from Json. | -| fromStr | Parse a number from string. | - ---- - -##### `fromJson` - -```wing -num.fromJson(json: Json, options?: JsonValidationOptions); -``` - -Parse a number from Json. - -###### `json`Required - -- *Type:* Json - -to parse number from. - ---- - -###### `options`Optional - -- *Type:* JsonValidationOptions - ---- - -##### `fromStr` - -```wing -num.fromStr(str: str); -``` - -Parse a number from string. - -###### `str`Required - -- *Type:* str - -to parse number from. - ---- - - - - - diff --git a/docs/docs/04-standard-library/std/regex.md b/docs/docs/04-standard-library/std/regex.md deleted file mode 100644 index 48584bbb245..00000000000 --- a/docs/docs/04-standard-library/std/regex.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: regex -id: regex ---- - -# API Reference - - -## Classes - -### Regex - -- *Implements:* ILiftable - -Represents a compiled regular expression pattern. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| find | Finds the first occurrence of the pattern within the text. | -| findAll | Finds all non-overlapping occurrences of the pattern within the text. | -| findAllIndex | Finds the start and end index of all matches within the text. | -| findIndex | Finds the start and end index of the first match within the text. | -| findSubmatch | Finds the first match and its submatches. | -| findSubmatchIndex | Finds the start and end index of the match and all submatches. | -| replaceAll | Replaces all occurrences of the match with a replacement string. | -| test | Checks if the regular expression matches the provided text. | - ---- - -##### `find` - -```wing -find(text: str): str? -``` - -Finds the first occurrence of the pattern within the text. - -###### `text`Required - -- *Type:* str - -The text to search within. - ---- - -##### `findAll` - -```wing -findAll(text: str): MutArray -``` - -Finds all non-overlapping occurrences of the pattern within the text. - -Returns an empty array if no matches are found. - -###### `text`Required - -- *Type:* str - -The text to search within. - ---- - -##### `findAllIndex` - -```wing -findAllIndex(text: str): MutArray> -``` - -Finds the start and end index of all matches within the text. - -Indices are zero-based. - -###### `text`Required - -- *Type:* str - -The text to search within. - ---- - -##### `findIndex` - -```wing -findIndex(text: str): MutArray? -``` - -Finds the start and end index of the first match within the text. - -###### `text`Required - -- *Type:* str - -The text to search within. - ---- - -##### `findSubmatch` - -```wing -findSubmatch(text: str): MutArray? -``` - -Finds the first match and its submatches. - -###### `text`Required - -- *Type:* str - -The text to search within. - ---- - -##### `findSubmatchIndex` - -```wing -findSubmatchIndex(text: str): MutArray>? -``` - -Finds the start and end index of the match and all submatches. - -###### `text`Required - -- *Type:* str - -The text to search within. - ---- - -##### `replaceAll` - -```wing -replaceAll(text: str, replacement: str): str -``` - -Replaces all occurrences of the match with a replacement string. - -###### `text`Required - -- *Type:* str - -The text to search and replace within. - ---- - -###### `replacement`Required - -- *Type:* str - -The replacement string. - ---- - -##### `test` - -```wing -test(text: str): bool -``` - -Checks if the regular expression matches the provided text. - -###### `text`Required - -- *Type:* str - -The text to check against. - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| compile | Compiles the provided regex pattern into a `Regex` object. | - ---- - -##### `compile` - -```wing -regex.compile(pattern: str); -``` - -Compiles the provided regex pattern into a `Regex` object. - -###### `pattern`Required - -- *Type:* str - -The regex pattern to compile. - ---- - - - - - diff --git a/docs/docs/04-standard-library/std/set.md b/docs/docs/04-standard-library/std/set.md deleted file mode 100644 index 540128db000..00000000000 --- a/docs/docs/04-standard-library/std/set.md +++ /dev/null @@ -1,191 +0,0 @@ ---- -title: set -id: set ---- - -# API Reference - - -## Classes - -### MutSet - -Mutable Set. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| add | Add value to set. | -| clear | The clear() method removes all elements from a set. | -| copy | Create an immutable shallow copy of this set. | -| delete | Removes a specified value from a set, if it is in the set. | -| has | Returns a boolean indicating whether an element with the specified value exists in the set. | -| toArray | Create an immutable array shallow copy of this set. | - ---- - -##### `add` - -```wing -add(value: ): MutSet -``` - -Add value to set. - -###### `value`Required - -- *Type:* <T> - -value to add. - ---- - -##### `clear` - -```wing -clear(): void -``` - -The clear() method removes all elements from a set. - -##### `copy` - -```wing -copy(): Set -``` - -Create an immutable shallow copy of this set. - -##### `delete` - -```wing -delete(value: ): bool -``` - -Removes a specified value from a set, if it is in the set. - -###### `value`Required - -- *Type:* <T> - -The value to remove from the set. - ---- - -##### `has` - -```wing -has(value: ): bool -``` - -Returns a boolean indicating whether an element with the specified value exists in the set. - -###### `value`Required - -- *Type:* <T> - -The value to test for presence in the Set object. - ---- - -##### `toArray` - -```wing -toArray(): Array -``` - -Create an immutable array shallow copy of this set. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| size | num | The length of the set. | - ---- - -##### `size`Required - -```wing -size: num; -``` - -- *Type:* num - -The length of the set. - ---- - - -### Set - -Immutable Set. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| copyMut | Create a mutable shallow copy of this set. | -| has | Returns a boolean indicating whether an element with the specified value exists in the set. | -| toArray | Create an immutable array shallow copy of this set. | - ---- - -##### `copyMut` - -```wing -copyMut(): MutSet -``` - -Create a mutable shallow copy of this set. - -##### `has` - -```wing -has(value: ): bool -``` - -Returns a boolean indicating whether an element with the specified value exists in the set. - -###### `value`Required - -- *Type:* <T> - -The value to test for presence in the Set object. - ---- - -##### `toArray` - -```wing -toArray(): Array -``` - -Create an immutable array shallow copy of this set. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| size | num | The length of the set. | - ---- - -##### `size`Required - -```wing -size: num; -``` - -- *Type:* num - -The length of the set. - ---- - - - - diff --git a/docs/docs/04-standard-library/std/string.md b/docs/docs/04-standard-library/std/string.md deleted file mode 100644 index 63d7c79498e..00000000000 --- a/docs/docs/04-standard-library/std/string.md +++ /dev/null @@ -1,295 +0,0 @@ ---- -title: string -id: string ---- - -# API Reference - - -## Classes - -### String - -String. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| at | Returns the character at the specified index. | -| concat | Combines the text of two (or more) strings and returns a new string. | -| contains | Checks if string includes substring. | -| endsWith | Does this string end with the given searchString? | -| indexOf | Returns the index of the first occurrence of searchString found. | -| lowercase | Returns this string in lower case. | -| replace | Replaces the first occurence of a substring within a string. | -| replaceAll | Replaces all occurrences of a substring within a string. | -| split | Splits string by separator. | -| startsWith | Does this string start with the given searchString? | -| substring | Returns a string between indexStart, indexEnd. | -| trim | Removes white spaces from start and end of this string. | -| uppercase | Returns this string in upper case. | - ---- - -##### `at` - -```wing -at(index: num): str -``` - -Returns the character at the specified index. - -###### `index`Required - -- *Type:* num - -position of the character. - ---- - -##### `concat` - -```wing -concat(strN: str): str -``` - -Combines the text of two (or more) strings and returns a new string. - -###### `strN`Required - -- *Type:* str - -one or more strings to concatenate to this string. - ---- - -##### `contains` - -```wing -contains(searchString: str): bool -``` - -Checks if string includes substring. - -###### `searchString`Required - -- *Type:* str - -substring to search for. - ---- - -##### `endsWith` - -```wing -endsWith(searchString: str): bool -``` - -Does this string end with the given searchString? - -###### `searchString`Required - -- *Type:* str - -substring to search for. - ---- - -##### `indexOf` - -```wing -indexOf(searchString: str): num -``` - -Returns the index of the first occurrence of searchString found. - -###### `searchString`Required - -- *Type:* str - -substring to search for. - ---- - -##### `lowercase` - -```wing -lowercase(): str -``` - -Returns this string in lower case. - -##### `replace` - -```wing -replace(searchString: str, replaceString: str): str -``` - -Replaces the first occurence of a substring within a string. - -###### `searchString`Required - -- *Type:* str - -The substring to search for. - ---- - -###### `replaceString`Required - -- *Type:* str - -The replacement substring. - ---- - -##### `replaceAll` - -```wing -replaceAll(searchString: str, replaceString: str): str -``` - -Replaces all occurrences of a substring within a string. - -###### `searchString`Required - -- *Type:* str - -The substring to search for. - ---- - -###### `replaceString`Required - -- *Type:* str - -The replacement substring. - ---- - -##### `split` - -```wing -split(separator: str): MutArray -``` - -Splits string by separator. - -###### `separator`Required - -- *Type:* str - -separator to split by. - ---- - -##### `startsWith` - -```wing -startsWith(searchString: str): bool -``` - -Does this string start with the given searchString? - -###### `searchString`Required - -- *Type:* str - -substring to search for. - ---- - -##### `substring` - -```wing -substring(indexStart: num, indexEnd?: num): str -``` - -Returns a string between indexStart, indexEnd. - -###### `indexStart`Required - -- *Type:* num - -index of the character we slice at. - ---- - -###### `indexEnd`Optional - -- *Type:* num - -optional - index of the character we end slicing at. - ---- - -##### `trim` - -```wing -trim(): str -``` - -Removes white spaces from start and end of this string. - -##### `uppercase` - -```wing -uppercase(): str -``` - -Returns this string in upper case. - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| fromJson | Parse string from Json. | - ---- - -##### `fromJson` - -```wing -str.fromJson(json: Json, options?: JsonValidationOptions); -``` - -Parse string from Json. - -###### `json`Required - -- *Type:* Json - -to create string from. - ---- - -###### `options`Optional - -- *Type:* JsonValidationOptions - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| length | num | The length of the string. | - ---- - -##### `length`Required - -```wing -length: num; -``` - -- *Type:* num - -The length of the string. - ---- - - - - diff --git a/docs/docs/04-standard-library/std/struct.md b/docs/docs/04-standard-library/std/struct.md deleted file mode 100644 index af463247e27..00000000000 --- a/docs/docs/04-standard-library/std/struct.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: struct -id: struct ---- - -# API Reference - - -## Classes - -### Struct - -Shared behavior for all structs. - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| fromJson | Converts a Json to a Struct. | -| parseJson | Parse a Json string into a Struct. | -| schema | Retrieve the schema for this struct. | -| tryFromJson | Converts a Json to a Struct, returning nil if the Json is not valid. | -| tryParseJson | Parse a Json string into a Struct, returning nil if the Json is not valid. | - ---- - -##### `fromJson` - -```wing -Struct.fromJson(json: Json, options?: JsonValidationOptions); -``` - -Converts a Json to a Struct. - -###### `json`Required - -- *Type:* Json - ---- - -###### `options`Optional - -- *Type:* JsonValidationOptions - ---- - -##### `parseJson` - -```wing -Struct.parseJson(json: str); -``` - -Parse a Json string into a Struct. - -###### `json`Required - -- *Type:* str - ---- - -##### `schema` - -```wing -Struct.schema(); -``` - -Retrieve the schema for this struct. - -##### `tryFromJson` - -```wing -Struct.tryFromJson(json: Json); -``` - -Converts a Json to a Struct, returning nil if the Json is not valid. - -###### `json`Required - -- *Type:* Json - ---- - -##### `tryParseJson` - -```wing -Struct.tryParseJson(json?: str); -``` - -Parse a Json string into a Struct, returning nil if the Json is not valid. - -###### `json`Optional - -- *Type:* str - ---- - - - - - diff --git a/docs/docs/04-standard-library/ui/api-reference.md b/docs/docs/04-standard-library/ui/api-reference.md deleted file mode 100644 index ff880ac2107..00000000000 --- a/docs/docs/04-standard-library/ui/api-reference.md +++ /dev/null @@ -1,1420 +0,0 @@ ---- -title: API reference -id: api-reference -description: Wing standard library API reference for the ui module -keywords: [Wing sdk, sdk, Wing API Reference] -hide_title: true -sidebar_position: 100 ---- - - -# API Reference - -## Resources - -### Button - -A button can be used to perform an action. - -#### Initializers - -```wing -bring ui; - -new ui.Button(label: str, handler: IButtonHandler); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| label | str | *No description.* | -| handler | IButtonHandler | *No description.* | - ---- - -##### `label`Required - -- *Type:* str - ---- - -##### `handler`Required - -- *Type:* IButtonHandler - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | -| isVisualComponent | Returns whether the given construct is a visual component. | - ---- - -##### `onLiftType` - -```wing -bring ui; - -ui.Button.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring ui; - -ui.Button.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -##### `isVisualComponent` - -```wing -bring ui; - -ui.Button.isVisualComponent(c: IConstruct); -``` - -Returns whether the given construct is a visual component. - -###### `c`Required - -- *Type:* constructs.IConstruct - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - -### Field - -A field can be used to display a value. - -#### Initializers - -```wing -bring ui; - -new ui.Field(label: str, handler: IFieldHandler, props?: FieldProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| label | str | *No description.* | -| handler | IFieldHandler | *No description.* | -| props | FieldProps | *No description.* | - ---- - -##### `label`Required - -- *Type:* str - ---- - -##### `handler`Required - -- *Type:* IFieldHandler - ---- - -##### `props`Optional - -- *Type:* FieldProps - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | -| isVisualComponent | Returns whether the given construct is a visual component. | - ---- - -##### `onLiftType` - -```wing -bring ui; - -ui.Field.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring ui; - -ui.Field.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -##### `isVisualComponent` - -```wing -bring ui; - -ui.Field.isVisualComponent(c: IConstruct); -``` - -Returns whether the given construct is a visual component. - -###### `c`Required - -- *Type:* constructs.IConstruct - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - -### FileBrowser - -A file browser can be used to browse files. - -#### Initializers - -```wing -bring ui; - -new ui.FileBrowser(label: str, handlers: FileBrowserHandlers); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| label | str | *No description.* | -| handlers | FileBrowserHandlers | *No description.* | - ---- - -##### `label`Required - -- *Type:* str - ---- - -##### `handlers`Required - -- *Type:* FileBrowserHandlers - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | -| isVisualComponent | Returns whether the given construct is a visual component. | - ---- - -##### `onLiftType` - -```wing -bring ui; - -ui.FileBrowser.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring ui; - -ui.FileBrowser.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -##### `isVisualComponent` - -```wing -bring ui; - -ui.FileBrowser.isVisualComponent(c: IConstruct); -``` - -Returns whether the given construct is a visual component. - -###### `c`Required - -- *Type:* constructs.IConstruct - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - -### HttpClient - -An HttpClient can be used to make HTTP requests. - -#### Initializers - -```wing -bring ui; - -new ui.HttpClient(label: str, getUrlHandler: IHttpClientGetUrlHandler, getApiSpecHandler: IHttpClientGetApiSpecHandler); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| label | str | *No description.* | -| getUrlHandler | IHttpClientGetUrlHandler | *No description.* | -| getApiSpecHandler | IHttpClientGetApiSpecHandler | *No description.* | - ---- - -##### `label`Required - -- *Type:* str - ---- - -##### `getUrlHandler`Required - -- *Type:* IHttpClientGetUrlHandler - ---- - -##### `getApiSpecHandler`Required - -- *Type:* IHttpClientGetApiSpecHandler - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | -| isVisualComponent | Returns whether the given construct is a visual component. | - ---- - -##### `onLiftType` - -```wing -bring ui; - -ui.HttpClient.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring ui; - -ui.HttpClient.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -##### `isVisualComponent` - -```wing -bring ui; - -ui.HttpClient.isVisualComponent(c: IConstruct); -``` - -Returns whether the given construct is a visual component. - -###### `c`Required - -- *Type:* constructs.IConstruct - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - -### Section - -A section can be used to group other visual components. - -#### Initializers - -```wing -bring ui; - -new ui.Section(props?: SectionProps); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| props | SectionProps | *No description.* | - ---- - -##### `props`Optional - -- *Type:* SectionProps - ---- - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| add | Adds a visual component to the section. | -| addButton | Adds a button to the section. | -| addField | Adds a field to the section. | - ---- - -##### `add` - -```wing -add(...components: Array): void -``` - -Adds a visual component to the section. - -The components -will be rendered in the order they were added. - -###### `components`Required - -- *Type:* VisualComponent - ---- - -##### `addButton` - -```wing -addButton(label: str, handler: IButtonHandler): void -``` - -Adds a button to the section. - -Shorthand for `add(new ui.Button(...))`. - -###### `label`Required - -- *Type:* str - ---- - -###### `handler`Required - -- *Type:* IButtonHandler - ---- - -##### `addField` - -```wing -addField(label: str, handler: IFieldHandler, props?: FieldProps): void -``` - -Adds a field to the section. - -Shorthand for `add(new ui.Field(...))`. - -###### `label`Required - -- *Type:* str - ---- - -###### `handler`Required - -- *Type:* IFieldHandler - ---- - -###### `props`Optional - -- *Type:* FieldProps - ---- - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | -| isVisualComponent | Returns whether the given construct is a visual component. | - ---- - -##### `onLiftType` - -```wing -bring ui; - -ui.Section.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring ui; - -ui.Section.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -##### `isVisualComponent` - -```wing -bring ui; - -ui.Section.isVisualComponent(c: IConstruct); -``` - -Returns whether the given construct is a visual component. - -###### `c`Required - -- *Type:* constructs.IConstruct - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - -### ValueField - -A value field can be used to display a string value. - -#### Initializers - -```wing -bring ui; - -new ui.ValueField(label: str, value: str); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| label | str | *No description.* | -| value | str | *No description.* | - ---- - -##### `label`Required - -- *Type:* str - ---- - -##### `value`Required - -- *Type:* str - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | -| isVisualComponent | Returns whether the given construct is a visual component. | - ---- - -##### `onLiftType` - -```wing -bring ui; - -ui.ValueField.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring ui; - -ui.ValueField.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -##### `isVisualComponent` - -```wing -bring ui; - -ui.ValueField.isVisualComponent(c: IConstruct); -``` - -Returns whether the given construct is a visual component. - -###### `c`Required - -- *Type:* constructs.IConstruct - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - -### VisualComponent - -A visual component is used to customize the view of other classes in the Wing Console. - -This is a base class for all other visual components. - -#### Initializers - -```wing -bring ui; - -new ui.VisualComponent(); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | - ---- - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| onLiftType | A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. | -| toInflight | Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. | -| isVisualComponent | Returns whether the given construct is a visual component. | - ---- - -##### `onLiftType` - -```wing -bring ui; - -ui.VisualComponent.onLiftType(host: IInflightHost, ops: MutArray); -``` - -A hook called by the Wing compiler once for each inflight host that needs to use this type inflight. - -The list of requested inflight methods -needed by the inflight host are given by `ops`. - -This method is commonly used for adding permissions, environment variables, or -other capabilities to the inflight host. - -###### `host`Required - -- *Type:* IInflightHost - ---- - -###### `ops`Required - -- *Type:* MutArray<str> - ---- - -##### `toInflight` - -```wing -bring ui; - -ui.VisualComponent.toInflight(obj: IResource); -``` - -Generates an asynchronous JavaScript statement which can be used to create an inflight client for a resource. - -NOTE: This statement must be executed within an async context. - -###### `obj`Required - -- *Type:* IResource - ---- - -##### `isVisualComponent` - -```wing -bring ui; - -ui.VisualComponent.isVisualComponent(c: IConstruct); -``` - -Returns whether the given construct is a visual component. - -###### `c`Required - -- *Type:* constructs.IConstruct - ---- - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| node | constructs.Node | The tree node. | - ---- - -##### `node`Required - -```wing -node: Node; -``` - -- *Type:* constructs.Node - -The tree node. - ---- - - - -## Structs - -### FieldProps - -Props for `Field`. - -#### Initializer - -```wing -bring ui; - -let FieldProps = ui.FieldProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| link | bool | Indicates that this field is a link. | -| refreshRate | duration | How often the field should be refreshed. | - ---- - -##### `link`Optional - -```wing -link: bool; -``` - -- *Type:* bool -- *Default:* false - -Indicates that this field is a link. - ---- - -##### `refreshRate`Optional - -```wing -refreshRate: duration; -``` - -- *Type:* duration -- *Default:* no automatic refresh - -How often the field should be refreshed. - ---- - -### FileBrowserHandlers - -File browser handlers. - -#### Initializer - -```wing -bring ui; - -let FileBrowserHandlers = ui.FileBrowserHandlers{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| delete | IFileBrowserDeleteHandler | Handler for deleting a file. | -| get | IFileBrowserGetHandler | Handler for getting a file. | -| list | IFileBrowserListHandler | Handler for listing files. | -| put | IFileBrowserPutHandler | Handler for putting a file. | - ---- - -##### `delete`Required - -```wing -delete: IFileBrowserDeleteHandler; -``` - -- *Type:* IFileBrowserDeleteHandler - -Handler for deleting a file. - ---- - -##### `get`Required - -```wing -get: IFileBrowserGetHandler; -``` - -- *Type:* IFileBrowserGetHandler - -Handler for getting a file. - ---- - -##### `list`Required - -```wing -list: IFileBrowserListHandler; -``` - -- *Type:* IFileBrowserListHandler - -Handler for listing files. - ---- - -##### `put`Required - -```wing -put: IFileBrowserPutHandler; -``` - -- *Type:* IFileBrowserPutHandler - -Handler for putting a file. - ---- - -### SectionProps - -Props for `Section`. - -#### Initializer - -```wing -bring ui; - -let SectionProps = ui.SectionProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| label | str | The label of the section. | - ---- - -##### `label`Optional - -```wing -label: str; -``` - -- *Type:* str -- *Default:* no label - -The label of the section. - ---- - -## Protocols - -### IButtonHandler - -- *Extends:* IInflight - -- *Implemented By:* IButtonHandler - -**Inflight client:** [@winglang/sdk.ui.IButtonHandlerClient](#@winglang/sdk.ui.IButtonHandlerClient) - -A resource with an inflight "handle" method that can be passed to `Button`. - - - -### IButtonHandlerClient - -- *Implemented By:* IButtonHandlerClient - -Inflight client for `IButtonHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that peforms an action. | - ---- - -##### `handle` - -```wing -inflight handle(): void -``` - -Function that peforms an action. - - -### IFieldHandler - -- *Extends:* IInflight - -- *Implemented By:* IFieldHandler - -**Inflight client:** [@winglang/sdk.ui.IFieldHandlerClient](#@winglang/sdk.ui.IFieldHandlerClient) - -A resource with an inflight "handle" method that can be passed to `addField`. - - - -### IFieldHandlerClient - -- *Implemented By:* IFieldHandlerClient - -Inflight client for `IFieldHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that returns a string to display. | - ---- - -##### `handle` - -```wing -inflight handle(): str -``` - -Function that returns a string to display. - - -### IFileBrowserDeleteHandler - -- *Extends:* IInflight - -- *Implemented By:* IFileBrowserDeleteHandler - -**Inflight client:** [@winglang/sdk.ui.IFileBrowserDeleteHandlerClient](#@winglang/sdk.ui.IFileBrowserDeleteHandlerClient) - -A resource with an inflight "handle" method that can be passed to `IFileBrowser`. - - - -### IFileBrowserDeleteHandlerClient - -- *Implemented By:* IFileBrowserDeleteHandlerClient - -Inflight client for `IFileBrowserDeleteHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that performs an action. | - ---- - -##### `handle` - -```wing -inflight handle(fileName: str): void -``` - -Function that performs an action. - -###### `fileName`Required - -- *Type:* str - ---- - - -### IFileBrowserGetHandler - -- *Extends:* IInflight - -- *Implemented By:* IFileBrowserGetHandler - -**Inflight client:** [@winglang/sdk.ui.IFileBrowserGetHandlerClient](#@winglang/sdk.ui.IFileBrowserGetHandlerClient) - -A resource with an inflight "handle" method that can be passed to `IFileBrowser`. - - - -### IFileBrowserGetHandlerClient - -- *Implemented By:* IFileBrowserGetHandlerClient - -Inflight client for `IFileBrowserGetHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that performs an action. | - ---- - -##### `handle` - -```wing -inflight handle(fileName: str): str -``` - -Function that performs an action. - -###### `fileName`Required - -- *Type:* str - ---- - - -### IFileBrowserListHandler - -- *Extends:* IInflight - -- *Implemented By:* IFileBrowserListHandler - -**Inflight client:** [@winglang/sdk.ui.IFileBrowserListHandlerClient](#@winglang/sdk.ui.IFileBrowserListHandlerClient) - -A resource with an inflight "handle" method that can be passed to `IFileBrowser`. - - - -### IFileBrowserListHandlerClient - -- *Implemented By:* IFileBrowserListHandlerClient - -Inflight client for `IFileBrowserListHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that performs an action. | - ---- - -##### `handle` - -```wing -inflight handle(): MutArray -``` - -Function that performs an action. - - -### IFileBrowserPutHandler - -- *Extends:* IInflight - -- *Implemented By:* IFileBrowserPutHandler - -**Inflight client:** [@winglang/sdk.ui.IFileBrowserPutHandlerClient](#@winglang/sdk.ui.IFileBrowserPutHandlerClient) - -A resource with an inflight "handle" method that can be passed to `IFileBrowser`. - - - -### IFileBrowserPutHandlerClient - -- *Implemented By:* IFileBrowserPutHandlerClient - -Inflight client for `IFileBrowserVoidHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that performs an action. | - ---- - -##### `handle` - -```wing -inflight handle(fileName: str, fileContent: str): void -``` - -Function that performs an action. - -###### `fileName`Required - -- *Type:* str - ---- - -###### `fileContent`Required - -- *Type:* str - ---- - - -### IHttpClientGetApiSpecHandler - -- *Extends:* IInflight - -- *Implemented By:* IHttpClientGetApiSpecHandler - -**Inflight client:** [@winglang/sdk.ui.IHttpClientGetApiSpecHandlerClient](#@winglang/sdk.ui.IHttpClientGetApiSpecHandlerClient) - -A resource with an inflight "handle" method that can be passed to `IHttpClient`. - - - -### IHttpClientGetApiSpecHandlerClient - -- *Implemented By:* IHttpClientGetApiSpecHandlerClient - -Inflight client for `IHttpClientGetApiSpecHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that returns the OpenAPI spec. | - ---- - -##### `handle` - -```wing -inflight handle(): str -``` - -Function that returns the OpenAPI spec. - - -### IHttpClientGetUrlHandler - -- *Extends:* IInflight - -- *Implemented By:* IHttpClientGetUrlHandler - -**Inflight client:** [@winglang/sdk.ui.IHttpClientGetUrlHandlerClient](#@winglang/sdk.ui.IHttpClientGetUrlHandlerClient) - -A resource with an inflight "handle" method that can be passed to `IHttpClient`. - - - -### IHttpClientGetUrlHandlerClient - -- *Implemented By:* IHttpClientGetUrlHandlerClient - -Inflight client for `IHttpClientGetUrlHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | Function that returns the URL to make a request to. | - ---- - -##### `handle` - -```wing -inflight handle(): str -``` - -Function that returns the URL to make a request to. - - diff --git a/docs/docs/04-standard-library/util/api-reference.md b/docs/docs/04-standard-library/util/api-reference.md deleted file mode 100644 index ee63f0ad45b..00000000000 --- a/docs/docs/04-standard-library/util/api-reference.md +++ /dev/null @@ -1,1066 +0,0 @@ ---- -title: API reference -id: api-reference -description: Wing standard library API reference for the util module -keywords: [Wing sdk, sdk, Wing API Reference] -hide_title: true -sidebar_position: 100 ---- - - -# API Reference - - -## Classes - -### ChildProcess - -Handle to a running child process. - -#### Initializers - -```wing -bring util; - -new util.ChildProcess(program: str, args: MutArray, opts?: SpawnOptions); -``` - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| program | str | *No description.* | -| args | MutArray<str> | *No description.* | -| opts | SpawnOptions | *No description.* | - ---- - -##### `program`Required - -- *Type:* str - ---- - -##### `args`Required - -- *Type:* MutArray<str> - ---- - -##### `opts`Optional - -- *Type:* SpawnOptions - ---- - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| kill | Kill the process. | -| wait | Wait for the process to finish and return its output. | - ---- - -##### `kill` - -```wing -kill(signal?: num): void -``` - -Kill the process. - -###### `signal`Optional - -- *Type:* num - -the signal to send to the process (defaults to SIGTERM). - ---- - -##### `wait` - -```wing -wait(): Output -``` - -Wait for the process to finish and return its output. - -Calling this method multiple times will return the same output. - - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| pid | num | The child's OS-assigned process ID. | - ---- - -##### `pid`Optional - -```wing -pid: num; -``` - -- *Type:* num - -The child's OS-assigned process ID. - ---- - - -### Util - -Utility functions. - - -#### Static Functions - -| **Name** | **Description** | -| --- | --- | -| base64Decode | Converts a string from base64 to UTF-8. | -| base64Encode | Converts a string from UTF-8 to base64. | -| env | Returns the value of an environment variable. | -| exec | Execute a program with the given arguments, wait for it to finish, and return its outputs. | -| nanoid | Generates a unique ID using the nanoid library. | -| os | Returns a string identifying the operating system platform. | -| setEnv | Sets the given name and value as an environment variable. | -| sha256 | Computes the SHA256 hash of the given data. | -| shell | Executes a command in the shell and returns its standard output. | -| sleep | Suspends execution for a given duration. | -| spawn | Execute a program with the given arguments, and return a `ChildProcess` object that can be used to interact with the process while it is running. | -| tryEnv | Returns the value of an environment variable. | -| ulid | Generates universally unique lexicographically sortable identifier. | -| uuidv4 | Generates a version 4 UUID. | -| waitUntil | Run a predicate repeatedly, waiting until it returns true or until the timeout elapses. | - ---- - -##### `base64Decode` - -```wing -bring util; - -util.base64Decode(stringToDecode: str, url?: bool); -``` - -Converts a string from base64 to UTF-8. - -###### `stringToDecode`Required - -- *Type:* str - -base64 string to decode. - ---- - -###### `url`Optional - -- *Type:* bool - -If `true`, the source is expected to be a URL-safe base64 string. - ---- - -##### `base64Encode` - -```wing -bring util; - -util.base64Encode(stringToEncode: str, url?: bool); -``` - -Converts a string from UTF-8 to base64. - -###### `stringToEncode`Required - -- *Type:* str - -The name of the UTF-8 string to encode. - ---- - -###### `url`Optional - -- *Type:* bool - -If `true`, a URL-safe base64 string is returned. - ---- - -##### `env` - -```wing -bring util; - -util.env(name: str); -``` - -Returns the value of an environment variable. - -Throws if not found or empty. - -###### `name`Required - -- *Type:* str - -The name of the environment variable. - ---- - -##### `exec` - -```wing -bring util; - -util.exec(program: str, args: MutArray, opts?: ExecOptions); -``` - -Execute a program with the given arguments, wait for it to finish, and return its outputs. - -###### `program`Required - -- *Type:* str - -The program to execute. - ---- - -###### `args`Required - -- *Type:* MutArray<str> - -An array of arguments to pass to the program. - ---- - -###### `opts`Optional - -- *Type:* ExecOptions - -`ExecOptions`, such as the working directory and environment variables. - ---- - -##### `nanoid` - -```wing -bring util; - -util.nanoid(options?: NanoidOptions); -``` - -Generates a unique ID using the nanoid library. - -# - -> [https://github.com/ai/nanoid](https://github.com/ai/nanoid) - -###### `options`Optional - -- *Type:* NanoidOptions - -Optional options object for generating the ID. - ---- - -##### `os` - -```wing -bring util; - -util.os(); -``` - -Returns a string identifying the operating system platform. - -*Example* - -```wing -"linux", "darwin", "win32" -``` - - -##### `setEnv` - -```wing -bring util; - -util.setEnv(name: str, value: str); -``` - -Sets the given name and value as an environment variable. - -###### `name`Required - -- *Type:* str - -The name of the environment variable. - ---- - -###### `value`Required - -- *Type:* str - -The value of the environment variable. - ---- - -##### `sha256` - -```wing -bring util; - -util.sha256(data: str); -``` - -Computes the SHA256 hash of the given data. - -###### `data`Required - -- *Type:* str - -The string to be hashed. - ---- - -##### `shell` - -```wing -bring util; - -util.shell(command: str, opts?: ShellOptions); -``` - -Executes a command in the shell and returns its standard output. - -###### `command`Required - -- *Type:* str - -The command string to execute in the shell. - ---- - -###### `opts`Optional - -- *Type:* ShellOptions - -`ShellOptions`, such as the working directory and environment variables. - ---- - -##### `sleep` - -```wing -bring util; - -util.sleep(delay: duration); -``` - -Suspends execution for a given duration. - -###### `delay`Required - -- *Type:* duration - -The time to suspend execution. - ---- - -##### `spawn` - -```wing -bring util; - -util.spawn(program: str, args: MutArray, opts?: SpawnOptions); -``` - -Execute a program with the given arguments, and return a `ChildProcess` object that can be used to interact with the process while it is running. - -###### `program`Required - -- *Type:* str - -The program to execute. - ---- - -###### `args`Required - -- *Type:* MutArray<str> - -An array of arguments to pass to the program. - ---- - -###### `opts`Optional - -- *Type:* SpawnOptions - -Spawn options including working directory, environment variables, and stdio configurations. - ---- - -##### `tryEnv` - -```wing -bring util; - -util.tryEnv(name: str); -``` - -Returns the value of an environment variable. - -Returns `nil` if not found or empty. - -###### `name`Required - -- *Type:* str - -The name of the environment variable. - ---- - -##### `ulid` - -```wing -bring util; - -util.ulid(options?: UlidOptions); -``` - -Generates universally unique lexicographically sortable identifier. - -# - -> [https://github.com/ulid/javascript](https://github.com/ulid/javascript) - -###### `options`Optional - -- *Type:* UlidOptions - -Optional options object for generating the ID. - ---- - -##### `uuidv4` - -```wing -bring util; - -util.uuidv4(); -``` - -Generates a version 4 UUID. - -##### `waitUntil` - -```wing -bring util; - -util.waitUntil(predicate: IPredicateHandler, props?: WaitUntilProps); -``` - -Run a predicate repeatedly, waiting until it returns true or until the timeout elapses. - -If the timeout elapses, the function throws an error. - -Alternatively, you can pass `throws: false` to suppress the error, and instead return a boolean -indicating whether the predicate returned true within the timeout. - -###### `predicate`Required - -- *Type:* IPredicateHandler - -The function that will be evaluated. - ---- - -###### `props`Optional - -- *Type:* WaitUntilProps - -Timeout and interval values, default to one 1m timeout and 0.1sec interval. - ---- - - - -## Structs - -### CommandOptions - -Base command options. - -#### Initializer - -```wing -bring util; - -let CommandOptions = util.CommandOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| cwd | str | Path to a directory to run the command in. | -| env | MutMap<str> | Environment variables. | -| inheritEnv | bool | Whether to inherit environment variables from the host's environment. | - ---- - -##### `cwd`Optional - -```wing -cwd: str; -``` - -- *Type:* str -- *Default:* the default working directory of the host - -Path to a directory to run the command in. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* no environment variables - -Environment variables. - ---- - -##### `inheritEnv`Optional - -```wing -inheritEnv: bool; -``` - -- *Type:* bool -- *Default:* false - -Whether to inherit environment variables from the host's environment. - ---- - -### ExecOptions - -Additional options for `util.exec()`. - -#### Initializer - -```wing -bring util; - -let ExecOptions = util.ExecOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| cwd | str | Path to a directory to run the command in. | -| env | MutMap<str> | Environment variables. | -| inheritEnv | bool | Whether to inherit environment variables from the host's environment. | - ---- - -##### `cwd`Optional - -```wing -cwd: str; -``` - -- *Type:* str -- *Default:* the default working directory of the host - -Path to a directory to run the command in. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* no environment variables - -Environment variables. - ---- - -##### `inheritEnv`Optional - -```wing -inheritEnv: bool; -``` - -- *Type:* bool -- *Default:* false - -Whether to inherit environment variables from the host's environment. - ---- - -### NanoidOptions - -Options to generating a unique ID. - -#### Initializer - -```wing -bring util; - -let NanoidOptions = util.NanoidOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| alphabet | str | Characters that make up the alphabet to generate the ID, limited to 256 characters or fewer. | -| size | num | Size of ID. | - ---- - -##### `alphabet`Optional - -```wing -alphabet: str; -``` - -- *Type:* str - -Characters that make up the alphabet to generate the ID, limited to 256 characters or fewer. - ---- - -##### `size`Optional - -```wing -size: num; -``` - -- *Type:* num -- *Default:* 21 - -Size of ID. - ---- - -### Output - -Output of a finished process. - -#### Initializer - -```wing -bring util; - -let Output = util.Output{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| status | num | A process's exit status. | -| stderr | str | The standard error of a finished process. | -| stdout | str | The standard output of a finished process. | - ---- - -##### `status`Required - -```wing -status: num; -``` - -- *Type:* num - -A process's exit status. - ---- - -##### `stderr`Required - -```wing -stderr: str; -``` - -- *Type:* str - -The standard error of a finished process. - ---- - -##### `stdout`Required - -```wing -stdout: str; -``` - -- *Type:* str - -The standard output of a finished process. - ---- - -### ShellOptions - -Additional options for `util.shell()`. - -#### Initializer - -```wing -bring util; - -let ShellOptions = util.ShellOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| cwd | str | Path to a directory to run the command in. | -| env | MutMap<str> | Environment variables. | -| inheritEnv | bool | Whether to inherit environment variables from the host's environment. | -| throw | bool | Whether to throw an error on command execution failure. | - ---- - -##### `cwd`Optional - -```wing -cwd: str; -``` - -- *Type:* str -- *Default:* the default working directory of the host - -Path to a directory to run the command in. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* no environment variables - -Environment variables. - ---- - -##### `inheritEnv`Optional - -```wing -inheritEnv: bool; -``` - -- *Type:* bool -- *Default:* false - -Whether to inherit environment variables from the host's environment. - ---- - -##### `throw`Optional - -```wing -throw: bool; -``` - -- *Type:* bool -- *Default:* true - -Whether to throw an error on command execution failure. - ---- - -### SpawnOptions - -Additional options for `util.spawn()`. - -#### Initializer - -```wing -bring util; - -let SpawnOptions = util.SpawnOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| cwd | str | Path to a directory to run the command in. | -| env | MutMap<str> | Environment variables. | -| inheritEnv | bool | Whether to inherit environment variables from the host's environment. | -| stderr | Stdio | Configuration for the process's standard error stream. | -| stdin | Stdio | Configuration for the process's standard input stream. | -| stdout | Stdio | Configuration for the process's standard output stream. | - ---- - -##### `cwd`Optional - -```wing -cwd: str; -``` - -- *Type:* str -- *Default:* the default working directory of the host - -Path to a directory to run the command in. - ---- - -##### `env`Optional - -```wing -env: MutMap; -``` - -- *Type:* MutMap<str> -- *Default:* no environment variables - -Environment variables. - ---- - -##### `inheritEnv`Optional - -```wing -inheritEnv: bool; -``` - -- *Type:* bool -- *Default:* false - -Whether to inherit environment variables from the host's environment. - ---- - -##### `stderr`Optional - -```wing -stderr: Stdio; -``` - -- *Type:* Stdio -- *Default:* Stdio.INHERIT - -Configuration for the process's standard error stream. - ---- - -##### `stdin`Optional - -```wing -stdin: Stdio; -``` - -- *Type:* Stdio -- *Default:* Stdio.INHERIT - -Configuration for the process's standard input stream. - ---- - -##### `stdout`Optional - -```wing -stdout: Stdio; -``` - -- *Type:* Stdio -- *Default:* Stdio.INHERIT - -Configuration for the process's standard output stream. - ---- - -### UlidOptions - -Options to generate universally unique lexicographically sortable identifiers. - -#### Initializer - -```wing -bring util; - -let UlidOptions = util.UlidOptions{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| seed | num | You can also input a seed time which will consistently give you the same string for the time component. | - ---- - -##### `seed`Optional - -```wing -seed: num; -``` - -- *Type:* num -- *Default:* Date.now() - -You can also input a seed time which will consistently give you the same string for the time component. - -This is useful for migrating to ulid. - ---- - -### WaitUntilProps - -Properties for `util.waitUntil`. - -#### Initializer - -```wing -bring util; - -let WaitUntilProps = util.WaitUntilProps{ ... }; -``` - -#### Properties - -| **Name** | **Type** | **Description** | -| --- | --- | --- | -| interval | duration | Interval between predicate retries. | -| throws | bool | Whether to throw an error if the timeout elapses. | -| timeout | duration | The timeout for keep trying predicate. | - ---- - -##### `interval`Optional - -```wing -interval: duration; -``` - -- *Type:* duration -- *Default:* 0.1s - -Interval between predicate retries. - ---- - -##### `throws`Optional - -```wing -throws: bool; -``` - -- *Type:* bool -- *Default:* true - -Whether to throw an error if the timeout elapses. - ---- - -##### `timeout`Optional - -```wing -timeout: duration; -``` - -- *Type:* duration -- *Default:* 1m - -The timeout for keep trying predicate. - ---- - -## Protocols - -### IPredicateHandler - -- *Extends:* IInflight - -- *Implemented By:* IPredicateHandler - -**Inflight client:** [@winglang/sdk.util.IPredicateHandlerClient](#@winglang/sdk.util.IPredicateHandlerClient) - -A predicate with an inflight "handle" method that can be passed to `util.busyWait`. - - - -### IPredicateHandlerClient - -- *Implemented By:* IPredicateHandlerClient - -Inflight client for `IPredicateHandler`. - -#### Methods - -| **Name** | **Description** | -| --- | --- | -| handle | The Predicate function that is called. | - ---- - -##### `handle` - -```wing -inflight handle(): bool -``` - -The Predicate function that is called. - - -## Enums - -### Stdio - -Describes what to do with a standard I/O stream for a child process. - -#### Members - -| **Name** | **Description** | -| --- | --- | -| INHERIT | The child inherits from the corresponding parent descriptor. | -| PIPED | A new pipe should be arranged to connect the parent and child processes. | -| NULL | This stream will be ignored. | - ---- - -##### `INHERIT` - -The child inherits from the corresponding parent descriptor. - ---- - - -##### `PIPED` - -A new pipe should be arranged to connect the parent and child processes. - ---- - - -##### `NULL` - -This stream will be ignored. - -This is the equivalent of attaching the stream to /dev/null. - ---- - diff --git a/libs/wingsdk/scripts/docgen.mts b/libs/wingsdk/scripts/docgen.mts index ed55c71c5ec..2cd4fe03cb8 100644 --- a/libs/wingsdk/scripts/docgen.mts +++ b/libs/wingsdk/scripts/docgen.mts @@ -11,7 +11,7 @@ let docCounter = 0; const ANSI_LINE_CLEAR = "\x1b[1A\x1b[2K"; const rootDir = fileURLToPath(new URL("../", import.meta.url)); -const docsDir = join(rootDir, "..", "..", "docs", "docs"); +const docsDir = join(rootDir, "..", "..", "docs", "api"); const WING_LANGUAGE = Language.fromString("wing"); const SDK_DOCS = await Documentation.forProject(rootDir);