hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
listlengths
5
5
{ "id": 4, "code_window": [ " return acc;\n", " }, []);\n", "\n", " // Append one value column per data set\n", " data.forEach((_, i) => {\n", " // Value (A), Value (B),...\n", " const text = `Value #${String.fromCharCode(65 + i)}`;\n", " columnNames[text] = columns.length;\n", " columns.push({ text });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // Value #A, Value #B,...\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "replace", "edit_start_line_idx": 157 }
Release v1.10.18 (2017-07-27) === ### Service Client Updates * `service/ec2`: Updates service API and documentation * The CreateDefaultVPC API enables you to create a new default VPC . You no longer need to contact AWS support, if your default VPC has been deleted. * `service/kinesisanalytics`: Updates service API and documentation * Added additional exception types and clarified documentation. Release v1.10.17 (2017-07-27) === ### Service Client Updates * `service/dynamodb`: Updates service documentation and examples * Corrected a typo. * `service/ec2`: Updates service API and documentation * Amazon EC2 Elastic GPUs allow you to easily attach low-cost graphics acceleration to current generation EC2 instances. With Amazon EC2 Elastic GPUs, you can configure the right amount of graphics acceleration to your particular workload without being constrained by fixed hardware configurations and limited GPU selection. * `service/monitoring`: Updates service documentation * This release adds high resolution features to CloudWatch, with support for Custom Metrics down to 1 second and Alarms down to 10 seconds. Release v1.10.16 (2017-07-26) === ### Service Client Updates * `service/clouddirectory`: Updates service API and documentation * Cloud Directory adds support for additional batch operations. * `service/cloudformation`: Updates service API and documentation * AWS CloudFormation StackSets enables you to manage stacks across multiple accounts and regions. ### SDK Enhancements * `aws/signer/v4`: Optimize V4 signer's header duplicate space stripping. [#1417](https://github.com/aws/aws-sdk-go/pull/1417) Release v1.10.15 (2017-07-24) === ### Service Client Updates * `service/appstream`: Updates service API, documentation, and waiters * Amazon AppStream 2.0 image builders and fleets can now access applications and network resources that rely on Microsoft Active Directory (AD) for authentication and permissions. This new feature allows you to join your streaming instances to your AD, so you can use your existing AD user management tools. * `service/ec2`: Updates service API and documentation * Spot Fleet tagging capability allows customers to automatically tag instances launched by Spot Fleet. You can use this feature to label or distinguish instances created by distinct Spot Fleets. Tagging your EC2 instances also enables you to see instance cost allocation by tag in your AWS bill. ### SDK Bugs * `aws/signer/v4`: Fix out of bounds panic in stripExcessSpaces [#1412](https://github.com/aws/aws-sdk-go/pull/1412) * Fixes the out of bands panic in stripExcessSpaces caused by an incorrect calculation of the stripToIdx value. Simplified to code also. * Fixes [#1411](https://github.com/aws/aws-sdk-go/issues/1411) Release v1.10.14 (2017-07-20) === ### Service Client Updates * `service/elasticmapreduce`: Updates service API and documentation * Amazon EMR now includes the ability to use a custom Amazon Linux AMI and adjustable root volume size when launching a cluster. Release v1.10.13 (2017-07-19) === ### Service Client Updates * `service/budgets`: Updates service API and documentation * Update budget Management API's to list/create/update RI_UTILIZATION type budget. Update budget Management API's to support DAILY timeUnit for RI_UTILIZATION type budget. ### SDK Enhancements * `service/s3`: Use interfaces assertions instead of ValuesAtPath for S3 field lookups. [#1401](https://github.com/aws/aws-sdk-go/pull/1401) * Improves the performance across the board for all S3 API calls by removing the usage of `ValuesAtPath` being used for every S3 API call. ### SDK Bugs * `aws/request`: waiter test bug * waiters_test.go file would sometimes fail due to travis hiccups. This occurs because a test would sometimes fail the cancel check and succeed the timeout. However, the timeout check should never occur in that test. This fix introduces a new field that dictates how waiters will sleep. Release v1.10.12 (2017-07-17) === ### Service Client Updates * `service/cognito-idp`: Updates service API and documentation * `service/lambda`: Updates service API and documentation * Lambda@Edge lets you run code closer to your end users without provisioning or managing servers. With Lambda@Edge, your code runs in AWS edge locations, allowing you to respond to your end users at the lowest latency. Your code is triggered by Amazon CloudFront events, such as requests to and from origin servers and viewers, and it is ready to execute at every AWS edge location whenever a request for content is received. You just upload your Node.js code to AWS Lambda and Lambda takes care of everything required to run and scale your code with high availability. You only pay for the compute time you consume - there is no charge when your code is not running. Release v1.10.11 (2017-07-14) === ### Service Client Updates * `service/discovery`: Updates service API and documentation * Adding feature to the Export API for Discovery Service to allow filters for the export task to allow export based on per agent id. * `service/ec2`: Updates service API * New EC2 GPU Graphics instance * `service/marketplacecommerceanalytics`: Updates service documentation * Update to Documentation Model For New Report Cadence / Reformat of Docs Release v1.10.10 (2017-07-13) === ### Service Client Updates * `service/apigateway`: Updates service API and documentation * Adds support for management of gateway responses. * `service/ec2`: Updates service API and documentation * X-ENI (or Cross-Account ENI) is a new feature that allows the attachment or association of Elastic Network Interfaces (ENI) between VPCs in different AWS accounts located in the same availability zone. With this new capability, service providers and partners can deliver managed solutions in a variety of new architectural patterns where the provider and consumer of the service are in different AWS accounts. * `service/lex-models`: Updates service documentation Release v1.10.9 (2017-07-12) === ### Service Client Updates * `service/autoscaling`: Updates service API and documentation * Auto Scaling now supports a new type of scaling policy called target tracking scaling policies that you can use to set up dynamic scaling for your application. * `service/swf`: Updates service API, documentation, paginators, and examples * Added support for attaching control data to Lambda tasks. Control data lets you attach arbitrary strings to your decisions and history events. Release v1.10.8 (2017-07-06) === ### Service Client Updates * `service/ds`: Updates service API, documentation, and paginators * You can now improve the resilience and performance of your Microsoft AD directory by deploying additional domain controllers. Added UpdateNumberofDomainControllers API that allows you to update the number of domain controllers you want for your directory, and DescribeDomainControllers API that allows you to describe the detailed information of each domain controller of your directory. Also added the 'DesiredNumberOfDomainControllers' field to the DescribeDirectories API output for Microsoft AD. * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/kinesis`: Updates service API and documentation * You can now encrypt your data at rest within an Amazon Kinesis Stream using server-side encryption. Server-side encryption via AWS KMS makes it easy for customers to meet strict data management requirements by encrypting their data at rest within the Amazon Kinesis Streams, a fully managed real-time data processing service. * `service/kms`: Updates service API and documentation * This release of AWS Key Management Service introduces the ability to determine whether a key is AWS managed or customer managed. * `service/ssm`: Updates service API and documentation * Amazon EC2 Systems Manager now expands Patching support to Amazon Linux, Red Hat and Ubuntu in addition to the already supported Windows Server. Release v1.10.7 (2017-07-05) === ### Service Client Updates * `service/monitoring`: Updates service API and documentation * We are excited to announce the availability of APIs and CloudFormation support for CloudWatch Dashboards. You can use the new dashboard APIs or CloudFormation templates to dynamically build and maintain dashboards to monitor your infrastructure and applications. There are four new dashboard APIs - PutDashboard, GetDashboard, DeleteDashboards, and ListDashboards APIs. PutDashboard is used to create a new dashboard or modify an existing one whereas GetDashboard is the API to get the details of a specific dashboard. ListDashboards and DeleteDashboards are used to get the names or delete multiple dashboards respectively. Getting started with dashboard APIs is similar to any other AWS APIs. The APIs can be accessed through AWS SDK or through CLI tools. * `service/route53`: Updates service API and documentation * Bug fix for InvalidChangeBatch exception. ### SDK Enhancements * `service/s3/s3manager`: adding cleanup function to batch objects [#1375](https://github.com/aws/aws-sdk-go/issues/1375) * This enhancement will add an After field that will be called after each iteration of the batch operation. Release v1.10.6 (2017-06-30) === ### Service Client Updates * `service/marketplacecommerceanalytics`: Updates service documentation * Documentation updates for AWS Marketplace Commerce Analytics. * `service/s3`: Updates service API and documentation * API Update for S3: Adding Object Tagging Header to MultipartUpload Initialization Release v1.10.5 (2017-06-29) === ### Service Client Updates * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/events`: Updates service API and documentation * CloudWatch Events now allows different AWS accounts to share events with each other through a new resource called event bus. Event buses accept events from AWS services, other AWS accounts and PutEvents API calls. Currently all AWS accounts have one default event bus. To send events to another account, customers simply write rules to match the events of interest and attach an event bus in the receiving account as the target to the rule. The PutTargets API has been updated to allow adding cross account event buses as targets. In addition, we have released two new APIs - PutPermission and RemovePermission - that enables customers to add/remove permissions to their default event bus. * `service/gamelift`: Updates service API and documentation * Allow developers to download GameLift fleet creation logs to assist with debugging. * `service/ssm`: Updates service API and documentation * Adding Resource Data Sync support to SSM Inventory. New APIs: * CreateResourceDataSync - creates a new resource data sync configuration, * ListResourceDataSync - lists existing resource data sync configurations, * DeleteResourceDataSync - deletes an existing resource data sync configuration. Release v1.10.4 (2017-06-27) === ### Service Client Updates * `service/servicecatalog`: Updates service API, documentation, and paginators * Proper tagging of resources is critical to post-launch operations such as billing, cost allocation, and resource management. By using Service Catalog's TagOption Library, administrators can define a library of re-usable TagOptions that conform to company standards, and associate these with Service Catalog portfolios and products. Learn how to move your current tags to the new library, create new TagOptions, and view and associate your library items with portfolios and products. Understand how to ensure that the right tags are created on products launched through Service Catalog and how to provide users with defined selectable tags. ### SDK Bugs * `aws/signer/v4`: checking length on `stripExcessSpaces` [#1372](https://github.com/aws/aws-sdk-go/issues/1372) * Fixes a bug where `stripExcessSpaces` did not check length against the slice. * Fixes: [#1371](https://github.com/aws/aws-sdk-go/issues/1371) Release v1.10.3 (2017-06-23) === ### Service Client Updates * `service/lambda`: Updates service API and documentation * The Lambda Invoke API will now throw new exception InvalidRuntimeException (status code 502) for invokes with deprecated runtimes. Release v1.10.2 (2017-06-22) === ### Service Client Updates * `service/codepipeline`: Updates service API, documentation, and paginators * A new API, ListPipelineExecutions, enables you to retrieve summary information about the most recent executions in a pipeline, including pipeline execution ID, status, start time, and last updated time. You can request information for a maximum of 100 executions. Pipeline execution data is available for the most recent 12 months of activity. * `service/dms`: Updates service API and documentation * Added tagging for DMS certificates. * `service/elasticloadbalancing`: Updates service waiters * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/lightsail`: Updates service API and documentation * This release adds a new nextPageToken property to the result of the GetOperationsForResource API. Developers can now get the next set of items in a list by making subsequent calls to GetOperationsForResource API with the token from the previous call. This release also deprecates the nextPageCount property, which previously returned null (use the nextPageToken property instead). This release also deprecates the customImageName property on the CreateInstancesRequest class, which was previously ignored by the API. * `service/route53`: Updates service API and documentation * This release reintroduces the HealthCheckInUse exception. Release v1.10.1 (2017-06-21) === ### Service Client Updates * `service/dax`: Adds new service * Amazon DynamoDB Accelerator (DAX) is a fully managed, highly available, in-memory cache for DynamoDB that delivers up to a 10x performance improvement - from milliseconds to microseconds - even at millions of requests per second. DAX does all the heavy lifting required to add in-memory acceleration to your DynamoDB tables, without requiring developers to manage cache invalidation, data population, or cluster management. * `service/route53`: Updates service API and documentation * Amazon Route 53 now supports multivalue answers in response to DNS queries, which lets you route traffic approximately randomly to multiple resources, such as web servers. Create one multivalue answer record for each resource and, optionally, associate an Amazon Route 53 health check with each record, and Amazon Route 53 responds to DNS queries with up to eight healthy records. * `service/ssm`: Updates service API, documentation, and paginators * Adding hierarchy support to the SSM Parameter Store API. Added support tor tagging. New APIs: GetParameter - retrieves one parameter, DeleteParameters - deletes multiple parameters (max number 10), GetParametersByPath - retrieves parameters located in the hierarchy. Updated APIs: PutParameter - added ability to enforce parameter value by applying regex (AllowedPattern), DescribeParameters - modified to support Tag filtering. * `service/waf`: Updates service API and documentation * You can now create, edit, update, and delete a new type of WAF rule with a rate tracking component. * `service/waf-regional`: Updates service API and documentation Release v1.10.0 (2017-06-20) === ### Service Client Updates * `service/workdocs`: Updates service API and documentation * This release provides a new API to retrieve the activities performed by WorkDocs users. ### SDK Features * `aws/credentials/plugincreds`: Add support for Go plugin for credentials [#1320](https://github.com/aws/aws-sdk-go/pull/1320) * Adds support for using plugins to retrieve credentials for API requests. This change adds a new package plugincreds under aws/credentials. See the `example/aws/credentials/plugincreds` folder in the SDK for example usage. Release v1.9.00 (2017-06-19) === ### Service Client Updates * `service/organizations`: Updates service API and documentation * Improvements to Exception Modeling ### SDK Features * `service/s3/s3manager`: Adds batch operations to s3manager [#1333](https://github.com/aws/aws-sdk-go/pull/1333) * Allows for batch upload, download, and delete of objects. Also adds the interface pattern to allow for easy traversal of objects. E.G `DownloadWithIterator`, `UploadWithIterator`, and `BatchDelete`. `BatchDelete` also contains a utility iterator using the `ListObjects` API to easily delete a list of objects. Release v1.8.44 (2017-06-16) === ### Service Client Updates * `service/xray`: Updates service API, documentation, and paginators * Add a response time histogram to the services in response of GetServiceGraph API. Release v1.8.43 (2017-06-15) === ### Service Client Updates * `service/ec2`: Updates service API and documentation * Adds API to describe Amazon FPGA Images (AFIs) available to customers, which includes public AFIs, private AFIs that you own, and AFIs owned by other AWS accounts for which you have load permissions. * `service/ecs`: Updates service API and documentation * Added support for cpu, memory, and memory reservation container overrides on the RunTask and StartTask APIs. * `service/iot`: Updates service API and documentation * Revert the last release: remove CertificatePem from DescribeCertificate API. * `service/servicecatalog`: Updates service API, documentation, and paginators * Added ProvisioningArtifactSummaries to DescribeProductAsAdmin's output to show the provisioning artifacts belong to the product. Allow filtering by SourceProductId in SearchProductsAsAdmin for AWS Marketplace products. Added a verbose option to DescribeProvisioningArtifact to display the CloudFormation template used to create the provisioning artifact.Added DescribeProvisionedProduct API. Changed the type of ProvisionedProduct's Status to be distinct from Record's Status. New ProvisionedProduct's Status are AVAILABLE, UNDER_CHANGE, TAINTED, ERROR. Changed Record's Status set of values to CREATED, IN_PROGRESS, IN_PROGRESS_IN_ERROR, SUCCEEDED, FAILED. ### SDK Bugs * `private/model/api`: Fix RESTXML support for XML Namespace [#1343](https://github.com/aws/aws-sdk-go/pull/1343) * Fixes a bug with the SDK's generation of services using the REST XML protocol not annotating shape references with the XML Namespace attribute. * Fixes [#1334](https://github.com/aws/aws-sdk-go/pull/1334) Release v1.8.42 (2017-06-14) === ### Service Client Updates * `service/applicationautoscaling`: Updates service API and documentation * `service/clouddirectory`: Updates service documentation * Documentation update for Cloud Directory Release v1.8.41 (2017-06-13) === ### Service Client Updates * `service/configservice`: Updates service API Release v1.8.40 (2017-06-13) === ### Service Client Updates * `service/rds`: Updates service API and documentation * API Update for RDS: this update enables copy-on-write, a new Aurora MySQL Compatible Edition feature that allows users to restore their database, and support copy of TDE enabled snapshot cross region. ### SDK Bugs * `aws/request`: Fix NewErrParamMinLen to use correct ParamMinLenErrCode [#1336](https://github.com/aws/aws-sdk-go/issues/1336) * Fixes the `NewErrParamMinLen` function returning the wrong error code. `ParamMinLenErrCode` should be returned not `ParamMinValueErrCode`. * Fixes [#1335](https://github.com/aws/aws-sdk-go/issues/1335) Release v1.8.39 (2017-06-09) === ### Service Client Updates * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/opsworks`: Updates service API and documentation * Tagging Support for AWS OpsWorks Stacks Release v1.8.38 (2017-06-08) === ### Service Client Updates * `service/iot`: Updates service API and documentation * In addition to using certificate ID, AWS IoT customers can now obtain the description of a certificate with the certificate PEM. * `service/pinpoint`: Updates service API and documentation * Starting today Amazon Pinpoint adds SMS Text and Email Messaging support in addition to Mobile Push Notifications, providing developers, product managers and marketers with multi-channel messaging capabilities to drive user engagement in their applications. Pinpoint also enables backend services and applications to message users directly and provides advanced user and app analytics to understand user behavior and messaging performance. * `service/rekognition`: Updates service API and documentation * API Update for AmazonRekognition: Adding RecognizeCelebrities API Release v1.8.37 (2017-06-07) === ### Service Client Updates * `service/codebuild`: Updates service API and documentation * Add support to APIs for privileged containers. This change would allow performing privileged operations like starting the Docker daemon inside builds possible in custom docker images. * `service/greengrass`: Adds new service * AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud. Release v1.8.36 (2017-06-06) === ### Service Client Updates * `service/acm`: Updates service documentation * Documentation update for AWS Certificate Manager. * `service/cloudfront`: Updates service documentation * Doc update to fix incorrect prefix in S3OriginConfig * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/iot`: Updates service API * Update client side validation for SalesForce action. Release v1.8.35 (2017-06-05) === ### Service Client Updates * `service/appstream`: Updates service API and documentation * AppStream 2.0 Custom Security Groups allows you to easily control what network resources your streaming instances and images have access to. You can assign up to 5 security groups per Fleet to control the inbound and outbound network access to your streaming instances to specific IP ranges, network protocols, or ports. * `service/iot`: Updates service API, documentation, paginators, and examples * Added Salesforce action to IoT Rules Engine. Release v1.8.34 (2017-06-02) === ### Service Client Updates * `service/kinesisanalytics`: Updates service API, documentation, and paginators * Kinesis Analytics publishes error messages CloudWatch logs in case of application misconfigurations * `service/workdocs`: Updates service API and documentation * This release includes new APIs to manage tags and custom metadata on resources and also new APIs to add and retrieve comments at the document level. Release v1.8.33 (2017-06-01) === ### Service Client Updates * `service/codedeploy`: Updates service API and documentation * AWS CodeDeploy has improved how it manages connections to GitHub accounts and repositories. You can now create and store up to 25 connections to GitHub accounts in order to associate AWS CodeDeploy applications with GitHub repositories. Each connection can support multiple repositories. You can create connections to up to 25 different GitHub accounts, or create more than one connection to a single account. The ListGitHubAccountTokenNames command has been introduced to retrieve the names of stored connections to GitHub accounts that you have created. The name of the connection to GitHub used for an AWS CodeDeploy application is also included in the ApplicationInfo structure. Two new fields, lastAttemptedDeployment and lastSuccessfulDeployment, have been added to DeploymentGroupInfo to improve the handling of deployment group information in the AWS CodeDeploy console. Information about these latest deployments can also be retrieved using the GetDeploymentGroup and BatchGetDeployment group requests. Also includes a region update (us-gov-west-1). * `service/cognitoidentityprovider`: Updates service API, documentation, and paginators * `service/elbv2`: Updates service API and documentation * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/lexmodelbuildingservice`: Updates service documentation and examples ### SDK Enhancements * `aws/defaults`: Exports shared credentials and config default filenames used by the SDK. [#1308](https://github.com/aws/aws-sdk-go/pull/1308) * Adds SharedCredentialsFilename and SharedConfigFilename functions to defaults package. ### SDK Bugs * `aws/credentials`: Fixes shared credential provider's default filename on Windows. [#1308](https://github.com/aws/aws-sdk-go/pull/1308) * The shared credentials provider would attempt to use the wrong filename on Windows if the `HOME` environment variable was defined. * `service/s3/s3manager`: service/s3/s3manager: Fix Downloader ignoring Range get parameter [#1311](https://github.com/aws/aws-sdk-go/pull/1311) * Fixes the S3 Download Manager ignoring the GetObjectInput's Range parameter. If this parameter is provided it will force the downloader to fallback to a single GetObject request disabling concurrency and automatic part size gets. * Fixes [#1296](https://github.com/aws/aws-sdk-go/issues/1296) Release v1.8.32 (2017-05-31) === ### Service Client Updates * `service/rds`: Updates service API and documentation * Amazon RDS customers can now easily and quickly stop and start their DB instances. Release v1.8.31 (2017-05-30) === ### Service Client Updates * `service/clouddirectory`: Updates service API, documentation, and paginators * Cloud Directory has launched support for Typed Links, enabling customers to create object-to-object relationships that are not hierarchical in nature. Typed Links enable customers to quickly query for data along these relationships. Customers can also enforce referential integrity using Typed Links, ensuring data in use is not inadvertently deleted. * `service/s3`: Updates service paginators and examples * New example snippets for Amazon S3. Release v1.8.30 (2017-05-25) === ### Service Client Updates * `service/appstream`: Updates service API and documentation * Support added for persistent user storage, backed by S3. * `service/rekognition`: Updates service API and documentation * Updated the CompareFaces API response to include orientation information, unmatched faces, landmarks, pose, and quality of the compared faces. Release v1.8.29 (2017-05-24) === ### Service Client Updates * `service/iam`: Updates service API * The unique ID and access key lengths were extended from 32 to 128 * `service/storagegateway`: Updates service API and documentation * Two Storage Gateway data types, Tape and TapeArchive, each have a new response element, TapeUsedInBytes. This element helps you manage your virtual tapes. By using TapeUsedInBytes, you can see the amount of data written to each virtual tape. * `service/sts`: Updates service API, documentation, and paginators * The unique ID and access key lengths were extended from 32 to 128. Release v1.8.28 (2017-05-23) === ### Service Client Updates * `service/databasemigrationservice`: Updates service API, documentation, paginators, and examples * This release adds support for using Amazon S3 and Amazon DynamoDB as targets for database migration, and using MongoDB as a source for database migration. For more information, see the AWS Database Migration Service documentation. Release v1.8.27 (2017-05-22) === ### Service Client Updates * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/resourcegroupstaggingapi`: Updates service API, documentation, and paginators * You can now specify the number of resources returned per page in GetResources operation, as an optional parameter, to easily manage the list of resources returned by your queries. ### SDK Bugs * `aws/request`: Add support for PUT temporary redirects (307) [#1283](https://github.com/aws/aws-sdk-go/issues/1283) * Adds support for Go 1.8's GetBody function allowing the SDK's http request using PUT and POST methods to be redirected with temporary redirects with 307 status code. * Fixes: [#1267](https://github.com/aws/aws-sdk-go/issues/1267) * `aws/request`: Add handling for retrying temporary errors during unmarshal [#1289](https://github.com/aws/aws-sdk-go/issues/1289) * Adds support for retrying temporary errors that occur during unmarshaling of a request's response body. * Fixes: [#1275](https://github.com/aws/aws-sdk-go/issues/1275) Release v1.8.26 (2017-05-18) === ### Service Client Updates * `service/athena`: Adds new service * This release adds support for Amazon Athena. Amazon Athena is an interactive query service that makes it easy to analyze data in Amazon S3 using standard SQL. Athena is serverless, so there is no infrastructure to manage, and you pay only for the queries that you run. * `service/lightsail`: Updates service API, documentation, and paginators * This release adds new APIs that make it easier to set network port configurations on Lightsail instances. Developers can now make a single request to both open and close public ports on an instance using the PutInstancePublicPorts operation. ### SDK Bugs * `aws/request`: Fix logging from reporting wrong retry request errors #1281 * Fixes the SDK's retry request logging to report the the actual error that occurred, not a stubbed Unknown error message. * Fixes the SDK's response logger to not output the response log multiple times per retry. Release v1.8.25 (2017-05-17) === ### Service Client Updates * `service/autoscaling`: Updates service documentation, paginators, and examples * Various Auto Scaling documentation updates * `service/cloudwatchevents`: Updates service documentation * Various CloudWatch Events documentation updates. * `service/cloudwatchlogs`: Updates service documentation and paginators * Various CloudWatch Logs documentation updates. * `service/polly`: Updates service API * Amazon Polly adds new German voice "Vicki" Release v1.8.24 (2017-05-16) === ### Service Client Updates * `service/codedeploy`: Updates service API and documentation * This release introduces the previousRevision field in the responses to the GetDeployment and BatchGetDeployments actions. previousRevision provides information about the application revision that was deployed to the deployment group before the most recent successful deployment. Also, the fileExistsBehavior parameter has been added for CreateDeployment action requests. In the past, if the AWS CodeDeploy agent detected files in a target location that weren't part of the application revision from the most recent successful deployment, it would fail the current deployment by default. This new parameter provides options for how the agent handles these files: fail the deployment, retain the content, or overwrite the content. * `service/gamelift`: Updates service API and documentation * Allow developers to specify how metrics are grouped in CloudWatch for their GameLift fleets. Developers can also specify how many concurrent game sessions activate on a per-instance basis. * `service/inspector`: Updates service API, documentation, paginators, and examples * Adds ability to produce an assessment report that includes detailed and comprehensive results of a specified assessment run. * `service/kms`: Updates service documentation * Update documentation for KMS. Release v1.8.23 (2017-05-15) === ### Service Client Updates * `service/ssm`: Updates service API and documentation * UpdateAssociation API now supports updating document name and targets of an association. GetAutomationExecution API can return FailureDetails as an optional field to the StepExecution Object, which contains failure type, failure stage as well as other failure related information for a failed step. ### SDK Enhancements * `aws/session`: SDK should be able to load multiple custom shared config files. [#1258](https://github.com/aws/aws-sdk-go/issues/1258) * This change adds a `SharedConfigFiles` field to the `session.Options` type that allows you to specify the files, and their order, the SDK will use for loading shared configuration and credentials from when the `Session` is created. Use the `NewSessionWithOptions` Session constructor to specify these options. You'll also most likely want to enable support for the shared configuration file's additional attributes by setting `session.Option`'s `SharedConfigState` to `session.SharedConfigEnabled`. Release v1.8.22 (2017-05-11) === ### Service Client Updates * `service/elb`: Updates service API, documentation, and paginators * `service/elbv2`: Updates service API and documentation * `service/lexmodelbuildingservice`: Updates service API and documentation * `service/organizations`: Updates service API, documentation, paginators, and examples * AWS Organizations APIs that return an Account object now include the email address associated with the account’s root user. Release v1.8.21 (2017-05-09) === ### Service Client Updates * `service/codestar`: Updates service documentation * Updated documentation for AWS CodeStar. * `service/workspaces`: Updates service API, documentation, and paginators * Doc-only Update for WorkSpaces Release v1.8.20 (2017-05-04) === ### Service Client Updates * `service/ecs`: Updates service API, documentation, and paginators * Exposes container instance registration time in ECS:DescribeContainerInstances. * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/marketplaceentitlementservice`: Adds new service * `service/lambda`: Updates service API and documentation * Support for UpdateFunctionCode DryRun option Release v1.8.19 (2017-04-28) === ### Service Client Updates * `service/cloudformation`: Updates service waiters and paginators * Adding back the removed waiters and paginators. Release v1.8.18 (2017-04-28) === ### Service Client Updates * `service/cloudformation`: Updates service API, documentation, waiters, paginators, and examples * API update for CloudFormation: New optional parameter ClientRequestToken which can be used as an idempotency token to safely retry certain operations as well as tagging StackEvents. * `service/rds`: Updates service API, documentation, and examples * The DescribeDBClusterSnapshots API now returns a SourceDBClusterSnapshotArn field which identifies the source DB cluster snapshot of a copied snapshot. * `service/rekognition`: Updates service API * Fix for missing file type check * `service/snowball`: Updates service API, documentation, and paginators * The Snowball API has a new exception that can be thrown for list operation requests. * `service/sqs`: Updates service API, documentation, and paginators * Adding server-side encryption (SSE) support to SQS by integrating with AWS KMS; adding new queue attributes to SQS CreateQueue, SetQueueAttributes and GetQueueAttributes APIs to support SSE. Release v1.8.17 (2017-04-26) === ### Service Client Updates * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/rds`: Updates service API and documentation * With Amazon Relational Database Service (Amazon RDS) running MySQL or Amazon Aurora, you can now authenticate to your DB instance using IAM database authentication. Release v1.8.16 (2017-04-21) === ### Service Client Updates * `service/appstream`: Updates service API, documentation, and paginators * The new feature named "Default Internet Access" will enable Internet access from AppStream 2.0 instances - image builders and fleet instances. Admins will check a flag either through AWS management console for AppStream 2.0 or through API while creating an image builder or while creating/updating a fleet. * `service/kinesis`: Updates service API, documentation, waiters, and paginators * Adds a new waiter, StreamNotExists, to Kinesis. ### SDK Enhancements * `aws/endpoints`: Add utilities improving endpoints lookup (#1218) * Adds several utilities to the endpoints packages to make looking up partitions, regions, and services easier. * Fixes #994 ### SDK Bugs * `private/protocol/xml/xmlutil`: Fix unmarshaling dropping errors (#1219) * The XML unmarshaler would drop any serialization or body read error that occurred on the floor effectively hiding any errors that would occur. * Fixes #1205 Release v1.8.15 (2017-04-20) === ### Service Client Updates * `service/devicefarm`: Updates service API and documentation * API Update for AWS Device Farm: Support for Deals and Promotions * `service/directconnect`: Updates service documentation * Documentation updates for AWS Direct Connect. * `service/elbv2`: Updates service waiters * `service/kms`: Updates service documentation and examples * Doc-only update for Key Management Service (KMS): Update docs for GrantConstraints and GenerateRandom * `service/route53`: Updates service documentation * Release notes: SDK documentation now includes examples for ChangeResourceRecordSets for all types of resource record set, such as weighted, alias, and failover. * `service/route53domains`: Updates service API, documentation, and paginators * Adding examples and other documentation updates. ### SDK Enhancements * `service/s3`: Add utilities to make getting a bucket's region easier (#1207) * Adds two features which make it easier to get a bucket's region, `s3.NormalizeBucketLocation` and `s3manager.GetBucketRegion`. ### SDK Bugs * `service/s3`: Fix HeadObject's incorrect documented error codes (#1213) * The HeadObject's model incorrectly states that the operation can return the NoSuchKey error code. * Fixes #1208 Release v1.8.14 (2017-04-19) === ### Service Client Updates * `service/apigateway`: Updates service API and documentation * Add support for "embed" property. * `service/codestar`: Adds new service * AWS CodeStar is a cloud-based service for creating, managing, and working with software development projects on AWS. An AWS CodeStar project creates and integrates AWS services for your project development toolchain. AWS CodeStar also manages the permissions required for project users. * `service/ec2`: Updates service API and documentation * Adds support for creating an Amazon FPGA Image (AFI) from a specified design checkpoint (DCP). * `service/iam`: Updates service API and documentation * This changes introduces a new IAM role type, Service Linked Role, which works like a normal role but must be managed via services' control. * `service/lambda`: Updates service API and documentation * Lambda integration with CloudDebugger service to enable customers to enable tracing for the Lambda functions and send trace information to the CloudDebugger service. * `service/lexmodelbuildingservice`: Adds new service * `service/polly`: Updates service API, documentation, and paginators * API Update for Amazon Polly: Add support for speech marks * `service/rekognition`: Updates service API and documentation * Given an image, the API detects explicit or suggestive adult content in the image and returns a list of corresponding labels with confidence scores, as well as a taxonomy (parent-child relation) for each label. Release v1.8.13 (2017-04-18) === ### Service Client Updates * `service/lambda`: Updates service API and documentation * You can use tags to group and filter your Lambda functions, making it easier to analyze them for billing allocation purposes. For more information, see Tagging Lambda Functions. You can now write or upgrade your Lambda functions using Python version 3.6. For more information, see Programming Model for Authoring Lambda Functions in Python. Note: Features will be rolled out in the US regions on 4/19. ### SDK Enhancements * `aws/request`: add support for appengine's custom standard library (#1190) * Remove syscall error checking on appengine platforms. Release v1.8.12 (2017-04-11) === ### Service Client Updates * `service/apigateway`: Updates service API and documentation * API Gateway request validators * `service/batch`: Updates service API and documentation * API Update for AWS Batch: Customer provided AMI for MANAGED Compute Environment * `service/gamelift`: Updates service API and documentation * Allows developers to utilize an improved workflow when calling our Queues API and introduces a new feature that allows developers to specify a maximum allowable latency per Queue. * `service/opsworks`: Updates service API, documentation, and paginators * Cloudwatch Logs agent configuration can now be attached to OpsWorks Layers using CreateLayer and UpdateLayer. OpsWorks will then automatically install and manage the CloudWatch Logs agent on the instances part of the OpsWorks Layer. ### SDK Bugs * `aws/client`: Fix clients polluting handler list (#1197) * Fixes the clients potentially polluting the passed in handler list with the client's customizations. This change ensures every client always works with a clean copy of the request handlers and it cannot pollute the handlers back upstream. * Fixes #1184 * `aws/request`: Fix waiter error match condition (#1195) * Fixes the waiters's matching overwriting the request's err, effectively ignoring the error condition. This broke waiters with the FailureWaiterState matcher state. Release v1.8.11 (2017-04-07) === ### Service Client Updates * `service/redshift`: Updates service API, documentation, and paginators * This update adds the GetClusterCredentials API which is used to get temporary login credentials to the cluster. AccountWithRestoreAccess now has a new member AccountAlias, this is the identifier of the AWS support account authorized to restore the specified snapshot. This is added to support the feature where the customer can share their snapshot with the Amazon Redshift Support Account without having to manually specify the AWS Redshift Service account ID on the AWS Console/API. Release v1.8.10 (2017-04-06) === ### Service Client Updates * `service/elbv2`: Updates service documentation Release v1.8.9 (2017-04-05) === ### Service Client Updates * `service/elasticache`: Updates service API, documentation, paginators, and examples * ElastiCache added support for testing the Elasticache Multi-AZ feature with Automatic Failover. Release v1.8.8 (2017-04-04) === ### Service Client Updates * `service/cloudwatch`: Updates service API, documentation, and paginators * Amazon Web Services announced the immediate availability of two additional alarm configuration rules for Amazon CloudWatch Alarms. The first rule is for configuring missing data treatment. Customers have the options to treat missing data as alarm threshold breached, alarm threshold not breached, maintain alarm state and the current default treatment. The second rule is for alarms based on percentiles metrics that can trigger unnecassarily if the percentile is calculated from a small number of samples. The new rule can treat percentiles with low sample counts as same as missing data. If the first rule is enabled, the same treatment will be applied when an alarm encounters a percentile with low sample counts. Release v1.8.7 (2017-04-03) === ### Service Client Updates * `service/lexruntimeservice`: Updates service API and documentation * Adds support to PostContent for speech input ### SDK Enhancements * `aws/request`: Improve handler copy, push back, push front performance (#1171) * Minor optimization to the handler list's handling of copying and pushing request handlers to the handler list. * Update codegen header to use Go std wording (#1172) * Go recently accepted the proposal for standard generated file header wording in, https://golang.org/s/generatedcode. ### SDK Bugs * `service/dynamodb`: Fix DynamoDB using custom retryer (#1170) * Fixes (#1139) the DynamoDB service client clobbering any custom retryer that was passed into the service client or Session's config. Release v1.8.6 (2017-04-01) === ### Service Client Updates * `service/clouddirectory`: Updates service API and documentation * ListObjectAttributes now supports filtering by facet. * `aws/endpoints`: Updated Regions and Endpoints metadata. Release v1.8.5 (2017-03-30) === ### Service Client Updates * `service/cloudformation`: Updates service waiters and paginators * Adding paginators for ListExports and ListImports * `service/cloudfront`: Adds new service * Amazon CloudFront now supports user configurable HTTP Read and Keep-Alive Idle Timeouts for your Custom Origin Servers * `service/configservice`: Updates service documentation * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/resourcegroupstaggingapi`: Adds new service * `service/storagegateway`: Updates service API and documentation * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. Once a file share is created, any changes made externally to the S3 bucket will not be reflected by the gateway. Using the cache refresh feature in this update, the customer can trigger an on-demand scan of the keys in their S3 bucket and refresh the file namespace cached on the gateway. It takes as an input the fileShare ARN and refreshes the cache for only that file share. Additionally there is new functionality on file gateway that allows you configure what squash options they would like on their file share, this allows a customer to configure their gateway to not squash root permissions. This can be done by setting options in NfsOptions for CreateNfsFileShare and UpdateNfsFileShare APIs. Release v1.8.4 (2017-03-28) === ### Service Client Updates * `service/batch`: Updates service API, documentation, and paginators * Customers can now provide a retryStrategy as part of the RegisterJobDefinition and SubmitJob API calls. The retryStrategy object has a number value for attempts. This is the number of non successful executions before a job is considered FAILED. In addition, the JobDetail object now has an attempts field and shows all execution attempts. * `service/ec2`: Updates service API and documentation * Customers can now tag their Amazon EC2 Instances and Amazon EBS Volumes at the time of their creation. You can do this from the EC2 Instance launch wizard or through the RunInstances or CreateVolume APIs. By tagging resources at the time of creation, you can eliminate the need to run custom tagging scripts after resource creation. In addition, you can now set resource-level permissions on the CreateVolume, CreateTags, DeleteTags, and the RunInstances APIs. This allows you to implement stronger security policies by giving you more granular control over which users and groups have access to these APIs. You can also enforce the use of tagging and control what tag keys and values are set on your resources. When you combine tag usage and resource-level IAM policies together, you can ensure your instances and volumes are properly secured upon creation and achieve more accurate cost allocation reporting. These new features are provided at no additional cost. ### SDK Enhancements * `aws/request`: Add retry support for RequestTimeoutException (#1158) * Adds support for retrying RequestTimeoutException error code that is returned by some services. ### SDK Bugs * `private/model/api`: Fix Waiter and Paginators panic on nil param inputs (#1157) * Corrects the code generation for Paginators and waiters that caused a panic if nil input parameters were used with the operations. Release v1.8.3 (2017-03-27) === ## Service Client Updates * `service/ssm`: Updates service API, documentation, and paginators * Updated validation rules for SendCommand and RegisterTaskWithMaintenanceWindow APIs. Release v1.8.2 (2017-03-24) === Service Client Updates --- * `service/applicationautoscaling`: Updates service API, documentation, and paginators * Application AutoScaling is launching support for a new target resource (AppStream 2.0 Fleets) as a scalable target. * `service/cloudtrail`: Updates service API and documentation * Doc-only Update for CloudTrail: Add required parameters for GetEventSelectors and PutEventSelectors Release v1.8.1 (2017-03-23) === Service Client Updates --- * `service/applicationdiscoveryservice`: Updates service API, documentation, and paginators * Adds export configuration options to the AWS Discovery Service API. * `service/elbv2`: Updates waiters * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/lambda`: Updates service API and paginators * Adds support for new runtime Node.js v6.10 for AWS Lambda service Release v1.8.0 (2017-03-22) === Service Client Updates --- * `service/codebuild`: Updates service documentation * `service/directconnect`: Updates service API * Deprecated DescribeConnectionLoa, DescribeInterconnectLoa, AllocateConnectionOnInterconnect and DescribeConnectionsOnInterconnect operations in favor of DescribeLoa, DescribeLoa, AllocateHostedConnection and DescribeHostedConnections respectively. * `service/marketplacecommerceanalytics`: Updates service API, documentation, and paginators * This update adds a new data set, us_sales_and_use_tax_records, which enables AWS Marketplace sellers to programmatically access to their U.S. Sales and Use Tax report data. * `service/pinpoint`: Updates service API and documentation * Amazon Pinpoint User Segmentation * Added ability to segment endpoints by user attributes in addition to endpoint attributes. Amazon Pinpoint Event Stream Preview * Added functionality to publish raw app analytics and campaign events data as events streams to Kinesis and Kinesis Firehose * The feature provides developers with increased flexibility of exporting raw events to S3, Redshift, Elasticsearch using a Kinesis Firehose stream or enable real time event processing use cases using a Kinesis stream * `service/rekognition`: Updates service documentation. SDK Features --- * `aws/request`: Add support for context.Context to SDK API operation requests (#1132) * Adds support for context.Context to the SDK by adding `WithContext` methods for each API operation, Paginators and Waiters. e.g `PutObjectWithContext`. This change also adds the ability to provide request functional options to the method calls instead of requiring you to use the `Request` API operation method (e.g `PutObjectRequest`). * Adds a `Complete` Request handler list that will be called ever time a request is completed. This includes both success and failure. Complete will only be called once per API operation request. * `private/waiter` package moved from the private group to `aws/request/waiter` and made publicly available. * Adds Context support to all API operations, Waiters(WaitUntil) and Paginators(Pages) methods. * Adds Context support for s3manager and s3crypto clients. SDK Enhancements --- * `aws/signer/v4`: Adds support for unsigned payload signer config (#1130) * Adds configuration option to the v4.Signer to specify the request's body should not be signed. This will only correclty function on services that support unsigned payload. e.g. S3, Glacier. SDK Bug Fixes --- * `service/s3`: Fix S3 HostID to be available in S3 request error message (#1131) * Adds a new type s3.RequestFailure which exposes the S3 HostID value from a S3 API operation response. This is helpful when you have an error with S3, and need to contact support. Both RequestID and HostID are needed. * `private/model/api`: Do not return a link if uid is empty (#1133) * Fixes SDK's doc generation to not generate API reference doc links if the SDK us unable to create a valid link. * `aws/request`: Optimization to handler list copy to prevent multiple alloc calls. (#1134) Release v1.7.9 (2017-03-13) === Service Client Updates --- * `service/devicefarm`: Updates service API, documentation, paginators, and examples * Network shaping allows users to simulate network connections and conditions while testing their Android, iOS, and web apps with AWS Device Farm. * `service/cloudwatchevents`: Updates service API, documentation, and examples SDK Enhancement === * `aws/session`: Add support for side loaded CA bundles (#1117) * Adds supports for side loading Certificate Authority bundle files to the SDK using AWS_CA_BUNDLE environment variable or CustomCABundle session option. * `service/s3/s3crypto`: Add support for AES/CBC/PKCS5Padding (#1124) SDK Bug === * `service/rds`: Fixing issue when not providing `SourceRegion` on cross region operations (#1127) * `service/rds`: Enables cross region for `CopyDBClusterSnapshot` and `CreateDBCluster` (#1128) Release v1.7.8 (2017-03-10) === Service Client Updates --- * `service/codedeploy`: Updates service paginators * Add paginators for Codedeploy * `service/emr`: Updates service API, documentation, and paginators * This release includes support for instance fleets in Amazon EMR. Release v1.7.7 (2017-03-09) === Service Client Updates --- * `service/apigateway`: Updates service API, documentation, and paginators * API Gateway has added support for ACM certificates on custom domain names. Both Amazon-issued certificates and uploaded third-part certificates are supported. * `service/clouddirectory`: Updates service API, documentation, and paginators * Introduces a new Cloud Directory API that enables you to retrieve all available parent paths for any type of object (a node, leaf node, policy node, and index node) in a hierarchy. Release v1.7.6 (2017-03-09) === Service Client Updates --- * `service/organizations`: Updates service documentation and examples * Doc-only Update for Organizations: Add SDK Code Snippets * `service/workdocs`: Adds new service * The Administrative SDKs for Amazon WorkDocs provides full administrator level access to WorkDocs site resources, allowing developers to integrate their applications to manage WorkDocs users, content and permissions programmatically Release v1.7.5 (2017-03-08) === Service Client Updates --- * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/rds`: Updates service API and documentation * Add support to using encrypted clusters as cross-region replication masters. Update CopyDBClusterSnapshot API to support encrypted cross region copy of Aurora cluster snapshots. Release v1.7.4 (2017-03-06) === Service Client Updates --- * `service/budgets`: Updates service API and paginators * When creating or editing a budget via the AWS Budgets API you can define notifications that are sent to subscribers when the actual or forecasted value for cost or usage exceeds the notificationThreshold associated with the budget notification object. Starting today, the maximum allowed value for the notificationThreshold was raised from 100 to 300. This change was made to give you more flexibility when setting budget notifications. * `service/cloudtrail`: Updates service documentation and paginators * Doc-only update for AWSCloudTrail: Updated links/descriptions * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/opsworkscm`: Updates service API, documentation, and paginators * OpsWorks for Chef Automate has added a new field "AssociatePublicIpAddress" to the CreateServer request, "CloudFormationStackArn" to the Server model and "TERMINATED" server state. Release v1.7.3 (2017-02-28) === Service Client Updates --- * `service/mturk`: Renaming service * service/mechanicalturkrequesterservice was renamed to service/mturk. Be sure to change any references of the old client to the new. Release v1.7.2 (2017-02-28) === Service Client Updates --- * `service/dynamodb`: Updates service API and documentation * Release notes: Time to Live (TTL) is a feature that allows you to define when items in a table expire and can be purged from the database, so that you don't have to track expired data and delete it manually. With TTL enabled on a DynamoDB table, you can set a timestamp for deletion on a per-item basis, allowing you to limit storage usage to only those records that are relevant. * `service/iam`: Updates service API, documentation, and paginators * This release adds support for AWS Organizations service control policies (SCPs) to SimulatePrincipalPolicy operation. If there are SCPs associated with the simulated user's account, their effect on the result is captured in the OrganizationDecisionDetail element in the EvaluationResult. * `service/mechanicalturkrequesterservice`: Adds new service * Amazon Mechanical Turk is a web service that provides an on-demand, scalable, human workforce to complete jobs that humans can do better than computers, for example, recognizing objects in photos. * `service/organizations`: Adds new service * AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources. * `service/dynamodbstreams`: Updates service API, documentation, and paginators * `service/waf`: Updates service API, documentation, and paginators * Aws WAF - For GetSampledRequests action, changed max number of samples from 100 to 500. * `service/wafregional`: Updates service API, documentation, and paginators Release v1.7.1 (2017-02-24) === Service Client Updates --- * `service/elasticsearchservice`: Updates service API, documentation, paginators, and examples * Added three new API calls to existing Amazon Elasticsearch service to expose Amazon Elasticsearch imposed limits to customers. Release v1.7.0 (2017-02-23) === Service Client Updates --- * `service/ec2`: Updates service API * New EC2 I3 instance type SDK Bug --- * `service/s3/s3manager`: Adding support for SSE (#1097) * Fixes SSE fields not being applied to a part during multi part upload. SDK Feature --- * `aws/session`: Add support for AssumeRoles with MFA (#1088) * Adds support for assuming IAM roles with MFA enabled. A TokenProvider func was added to stscreds.AssumeRoleProvider that will be called each time the role's credentials need to be refreshed. A basic token provider that sources the MFA token from stdin as stscreds.StdinTokenProvider. * `aws/session`: Update SDK examples and docs to use session.Must (#1099) * Updates the SDK's example and docs to use session.Must where possible to highlight its usage as apposed to session error checking that is most cases errors will be terminal to the application anyways. Release v1.6.27 (2017-02-22) === Service Client Updates --- * `service/clouddirectory`: Updates service documentation * ListObjectAttributes documentation updated based on forum feedback * `service/elasticbeanstalk`: Updates service API, documentation, and paginators * Elastic Beanstalk adds support for creating and managing custom platform. * `service/gamelift`: Updates service API, documentation, and paginators * Allow developers to configure global queues for creating GameSessions. Allow PlayerData on PlayerSessions to store player-specific data. * `service/route53`: Updates service API, documentation, and examples * Added support for operations CreateVPCAssociationAuthorization and DeleteVPCAssociationAuthorization to throw a ConcurrentModification error when a conflicting modification occurs in parallel to the authorizations in place for a given hosted zone. Release v1.6.26 (2017-02-21) === Service Client Updates --- * `service/ec2`: Updates service API and documentation * Added the billingProduct parameter to the RegisterImage API. Release v1.6.25 (2017-02-17) === Service Client Updates --- * `service/directconnect`: Updates service API, documentation, and paginators * This update will introduce the ability for Direct Connect customers to take advantage of Link Aggregation (LAG). This allows you to bundle many individual physical interfaces into a single logical interface, referred to as a LAG. This makes administration much simpler as the majority of configuration is done on the LAG while you are free to add or remove physical interfaces from the bundle as bandwidth demand increases or decreases. A concrete example of the simplification added by LAG is that customers need only a single BGP session as opposed to one session per physical connection. Release v1.6.24 (2017-02-16) === Service Client Updates --- * `service/cognitoidentity`: Updates service API, documentation, and paginators * Allow createIdentityPool and updateIdentityPool API to set server side token check value on identity pool * `service/configservice`: Updates service API and documentation * AWS Config now supports a new test mode for the PutEvaluations API. Set the TestMode parameter to true in your custom rule to verify whether your AWS Lambda function will deliver evaluation results to AWS Config. No updates occur to your existing evaluations, and evaluation results are not sent to AWS Config. Release v1.6.23 (2017-02-15) === Service Client Updates --- * `service/kms`: Updates service API, documentation, paginators, and examples * his release of AWS Key Management Service introduces the ability to tag keys. Tagging keys can help you organize your keys and track your KMS costs in the cost allocation report. This release also increases the maximum length of a key ID to accommodate ARNs that include a long key alias. Release v1.6.22 (2017-02-14) === Service Client Updates --- * `service/ec2`: Updates service API, documentation, and paginators * Adds support for the new Modify Volumes apis. Release v1.6.21 (2017-02-11) === Service Client Updates --- * `service/storagegateway`: Updates service API, documentation, and paginators * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. This is done by creating Nfs file shares using existing APIs CreateNfsFileShare. Using the feature in this update, the customer can restrict the clients that have read/write access to the gateway by specifying the list of clients as a list of IP addresses or CIDR blocks. This list can be specified using the API CreateNfsFileShare while creating new file shares, or UpdateNfsFileShare while update existing file shares. To find out the list of clients that have access, the existing API DescribeNfsFileShare will now output the list of clients that have access. Release v1.6.20 (2017-02-09) === Service Client Updates --- * `service/ec2`: Updates service API and documentation * This feature allows customers to associate an IAM profile to running instances that do not have any. * `service/rekognition`: Updates service API and documentation * DetectFaces and IndexFaces operations now return an estimate of the age of the face as an age range. SDK Features --- * `aws/endpoints`: Add option to resolve unknown endpoints (#1074) Release v1.6.19 (2017-02-08) === Service Client Updates --- * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/glacier`: Updates service examples * Doc Update * `service/lexruntimeservice`: Adds new service * Preview release SDK Bug Fixes --- * `private/protocol/json`: Fixes json to throw an error if a float number is (+/-)Inf and NaN (#1068) * `private/model/api`: Fix documentation error listing (#1067) SDK Features --- * `private/model`: Add service response error code generation (#1061) Release v1.6.18 (2017-01-27) === Service Client Updates --- * `service/clouddirectory`: Adds new service * Amazon Cloud Directory is a highly scalable, high performance, multi-tenant directory service in the cloud. Its web-based directories make it easy for you to organize and manage application resources such as users, groups, locations, devices, policies, and the rich relationships between them. * `service/codedeploy`: Updates service API, documentation, and paginators * This release of AWS CodeDeploy introduces support for blue/green deployments. In a blue/green deployment, the current set of instances in a deployment group is replaced by new instances that have the latest application revision installed on them. After traffic is rerouted behind a load balancer to the replacement instances, the original instances can be terminated automatically or kept running for other uses. * `service/ec2`: Updates service API and documentation * Adds instance health check functionality to replace unhealthy EC2 Spot fleet instances with fresh ones. * `service/rds`: Updates service API and documentation * Snapshot Engine Version Upgrade Release v1.6.17 (2017-01-25) === Service Client Updates --- * `service/elbv2`: Updates service API, documentation, and paginators * Application Load Balancers now support native Internet Protocol version 6 (IPv6) in an Amazon Virtual Private Cloud (VPC). With this ability, clients can now connect to the Application Load Balancer in a dual-stack mode via either IPv4 or IPv6. * `service/rds`: Updates service API and documentation * Cross Region Read Replica Copying (CreateDBInstanceReadReplica) Release v1.6.16 (2017-01-24) === Service Client Updates --- * `service/codebuild`: Updates service documentation and paginators * Documentation updates * `service/codecommit`: Updates service API, documentation, and paginators * AWS CodeCommit now includes the option to view the differences between a commit and its parent commit from within the console. You can view the differences inline (Unified view) or side by side (Split view). To view information about the differences between a commit and something other than its parent, you can use the AWS CLI and the get-differences and get-blob commands, or you can use the GetDifferences and GetBlob APIs. * `service/ecs`: Updates service API and documentation * Amazon ECS now supports a state for container instances that can be used to drain a container instance in preparation for maintenance or cluster scale down. Release v1.6.15 (2017-01-20) === Service Client Updates --- * `service/acm`: Updates service API, documentation, and paginators * Update for AWS Certificate Manager: Updated response elements for DescribeCertificate API in support of managed renewal * `service/health`: Updates service documentation Release v1.6.14 (2017-01-19) === Service Client Updates --- * `service/ec2`: Updates service API, documentation, and paginators * Amazon EC2 Spot instances now support dedicated tenancy, providing the ability to run Spot instances single-tenant manner on physically isolated hardware within a VPC to satisfy security, privacy, or other compliance requirements. Dedicated Spot instances can be requested using RequestSpotInstances and RequestSpotFleet. Release v1.6.13 (2017-01-18) === Service Client Updates --- * `service/rds`: Updates service API, documentation, and paginators Release v1.6.12 (2017-01-17) === Service Client Updates --- * `service/dynamodb`: Updates service API, documentation, and paginators * Tagging Support for Amazon DynamoDB Tables and Indexes * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/glacier`: Updates service API, paginators, and examples * Doc-only Update for Glacier: Added code snippets * `service/polly`: Updates service documentation and examples * Doc-only update for Amazon Polly -- added snippets * `service/rekognition`: Updates service documentation and paginators * Added code samples to Rekognition reference topics. * `service/route53`: Updates service API and paginators * Add ca-central-1 and eu-west-2 enum values to CloudWatchRegion enum Release v1.6.11 (2017-01-16) === Service Client Updates --- * `service/configservice`: Updates service API, documentation, and paginators * `service/costandusagereportservice`: Adds new service * The AWS Cost and Usage Report Service API allows you to enable and disable the Cost & Usage report, as well as modify the report name, the data granularity, and the delivery preferences. * `service/dynamodb`: Updates service API, documentation, and examples * Snippets for the DynamoDB API. * `service/elasticache`: Updates service API, documentation, and examples * Adds new code examples. * `aws/endpoints`: Updated Regions and Endpoints metadata. Release v1.6.10 (2017-01-04) === Service Client Updates --- * `service/configservice`: Updates service API and documentation * AWSConfig is planning to add support for OversizedConfigurationItemChangeNotification message type in putConfigRule. After this release customers can use/write rules based on OversizedConfigurationItemChangeNotification mesage type. * `service/efs`: Updates service API, documentation, and examples * Doc-only Update for EFS: Added code snippets * `service/iam`: Updates service documentation and examples * `service/lambda`: Updates service documentation and examples * Doc only updates for Lambda: Added code snippets * `service/marketplacecommerceanalytics`: Updates service API and documentation * Added support for data set disbursed_amount_by_instance_hours, with historical data available starting 2012-09-04. New data is published to this data set every 30 days. * `service/rds`: Updates service documentation * Updated documentation for CopyDBSnapshot. * `service/rekognition`: Updates service documentation and examples * Doc-only Update for Rekognition: Added code snippets * `service/snowball`: Updates service examples * `service/dynamodbstreams`: Updates service API and examples * Doc-only Update for DynamoDB Streams: Added code snippets SDK Feature --- * `private/model/api`: Increasing the readability of code generated files. (#1024) Release v1.6.9 (2016-12-30) === Service Client Updates --- * `service/codedeploy`: Updates service API and documentation * CodeDeploy will support Iam Session Arns in addition to Iam User Arns for on premise host authentication. * `service/ecs`: Updates service API and documentation * Amazon EC2 Container Service (ECS) now supports the ability to customize the placement of tasks on container instances. * `aws/endpoints`: Updated Regions and Endpoints metadata. Release v1.6.8 (2016-12-22) === Service Client Updates --- * `service/apigateway`: Updates service API and documentation * Amazon API Gateway is adding support for generating SDKs in more languages. This update introduces two new operations used to dynamically discover these SDK types and what configuration each type accepts. * `service/directoryservice`: Updates service documentation * Added code snippets for the DS SDKs * `service/elasticbeanstalk`: Updates service API and documentation * `service/iam`: Updates service API and documentation * Adds service-specific credentials to IAM service to make it easier to onboard CodeCommit customers. These are username/password credentials that work with a single service. * `service/kms`: Updates service API, documentation, and examples * Update docs and add SDK examples Release v1.6.7 (2016-12-22) === Service Client Updates --- * `service/ecr`: Updates service API and documentation * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/rds`: Updates service API and documentation * Cross Region Encrypted Snapshot Copying (CopyDBSnapshot) Release v1.6.6 (2016-12-20) === Service Client Updates --- * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/firehose`: Updates service API, documentation, and examples * Processing feature enables users to process and modify records before Amazon Firehose delivers them to destinations. * `service/route53`: Updates service API and documentation * Enum updates for eu-west-2 and ca-central-1 * `service/storagegateway`: Updates service API, documentation, and examples * File gateway is a new mode in the AWS Storage Gateway that support a file interface into S3, alongside the current block-based volume and VTL storage. File gateway combines a service and virtual software appliance, enabling you to store and retrieve objects in Amazon S3 using industry standard file protocols such as NFS. The software appliance, or gateway, is deployed into your on-premises environment as a virtual machine (VM) running on VMware ESXi. The gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. Release v1.6.5 (2016-12-19) === Service Client Updates --- * `service/cloudformation`: Updates service documentation * Minor doc update for CloudFormation. * `service/cloudtrail`: Updates service paginators * `service/cognitoidentity`: Updates service API and documentation * We are adding Groups to Cognito user pools. Developers can perform CRUD operations on groups, add and remove users from groups, list users in groups, etc. We are adding fine-grained role-based access control for Cognito identity pools. Developers can configure an identity pool to get the IAM role from an authenticated user's token, or they can configure rules that will map a user to a different role * `service/applicationdiscoveryservice`: Updates service API and documentation * Adds new APIs to group discovered servers into Applications with get summary and neighbors. Includes additional filters for ListConfigurations and DescribeAgents API. * `service/inspector`: Updates service API, documentation, and examples * Doc-only Update for Inspector: Adding SDK code snippets for Inspector * `service/sqs`: Updates service documentation SDK Bug Fixes --- * `aws/request`: Add PriorRequestNotComplete to throttle retry codes (#1011) * Fixes: Not retrying when PriorRequestNotComplete #1009 SDK Feature --- * `private/model/api`: Adds crosslinking to service documentation (#1010) Release v1.6.4 (2016-12-15) === Service Client Updates --- * `service/cognitoidentityprovider`: Updates service API and documentation * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/ssm`: Updates service API and documentation * This will provide customers with access to the Patch Baseline and Patch Compliance APIs. SDK Bug Fixes --- * `service/route53`: Fix URL path cleaning for Route53 API requests (#1006) * Fixes: SerializationError when using Route53 ChangeResourceRecordSets #1005 * `aws/request`: Add PriorRequestNotComplete to throttle retry codes (#1002) * Fixes: Not retrying when PriorRequestNotComplete #1001 Release v1.6.3 (2016-12-14) === Service Client Updates --- * `service/batch`: Adds new service * AWS Batch is a batch computing service that lets customers define queues and compute environments and then submit work as batch jobs. * `service/databasemigrationservice`: Updates service API and documentation * Adds support for SSL enabled Oracle endpoints and task modification. * `service/elasticbeanstalk`: Updates service documentation * `aws/endpoints`: Updated Regions and Endpoints metadata. * `service/cloudwatchlogs`: Updates service API and documentation * Add support for associating LogGroups with AWSTagris tags * `service/marketplacecommerceanalytics`: Updates service API and documentation * Add new enum to DataSetType: sales_compensation_billed_revenue * `service/rds`: Updates service documentation * Doc-only Update for RDS: New versions available in CreateDBInstance * `service/sts`: Updates service documentation * Adding Code Snippet Examples for SDKs for STS SDK Bug Fixes --- * `aws/request`: Fix retrying timeout requests (#981) * Fixes: Requests Retrying is broken if the error was caused due to a client timeout #947 * `aws/request`: Fix for Go 1.8 request incorrectly sent with body (#991) * Fixes: service/route53: ListHostedZones hangs and then fails with go1.8 #984 * private/protocol/rest: Use RawPath instead of Opaque (#993) * Fixes: HTTP2 request failing with REST protocol services, e.g AWS X-Ray * private/model/api: Generate REST-JSON JSONVersion correctly (#998) * Fixes: REST-JSON protocol service code missing JSONVersion metadata. Release v1.6.2 (2016-12-08) === Service Client Updates --- * `service/cloudfront`: Add lambda function associations to cache behaviors * `service/codepipeline`: This is a doc-only update request to incorporate some recent minor revisions to the doc content. * `service/rds`: Updates service API and documentation * `service/wafregional`: With this new feature, customers can use AWS WAF directly on Application Load Balancers in a VPC within available regions to protect their websites and web services from malicious attacks such as SQL injection, Cross Site Scripting, bad bots, etc. Release v1.6.1 (2016-12-07) === Service Client Updates --- * `service/config`: Updates service API * `service/s3`: Updates service API * `service/sqs`: Updates service API and documentation Release v1.6.0 (2016-12-06) === Service Client Updates --- * `service/config`: Updates service API and documentation * `service/ec2`: Updates service API * `service/sts`: Updates service API, documentation, and examples SDK Bug Fixes --- * private/protocol/xml/xmlutil: Fix SDK XML unmarshaler #975 * Fixes GetBucketACL Grantee required type always nil. #916 SDK Feature --- * aws/endpoints: Add endpoint metadata to SDK #961 * Adds Region and Endpoint metadata to the SDK. This allows you to enumerate regions and endpoint metadata based on a defined model embedded in the SDK. Release v1.5.13 (2016-12-01) === Service Client Updates --- * `service/apigateway`: Updates service API and documentation * `service/appstream`: Adds new service * `service/codebuild`: Adds new service * `service/directconnect`: Updates service API and documentation * `service/ec2`: Adds new service * `service/elasticbeanstalk`: Updates service API and documentation * `service/health`: Adds new service * `service/lambda`: Updates service API and documentation * `service/opsworkscm`: Adds new service * `service/pinpoint`: Adds new service * `service/shield`: Adds new service * `service/ssm`: Updates service API and documentation * `service/states`: Adds new service * `service/xray`: Adds new service Release v1.5.12 (2016-11-30) === Service Client Updates --- * `service/lightsail`: Adds new service * `service/polly`: Adds new service * `service/rekognition`: Adds new service * `service/snowball`: Updates service API and documentation Release v1.5.11 (2016-11-29) === Service Client Updates --- `service/s3`: Updates service API and documentation Release v1.5.10 (2016-11-22) === Service Client Updates --- * `service/cloudformation`: Updates service API and documentation * `service/glacier`: Updates service API, documentation, and examples * `service/route53`: Updates service API and documentation * `service/s3`: Updates service API and documentation SDK Bug Fixes --- * `private/protocol/xml/xmlutil`: Fixes xml marshaler to unmarshal properly into tagged fields [#916](https://github.com/aws/aws-sdk-go/issues/916) Release v1.5.9 (2016-11-22) === Service Client Updates --- * `service/cloudtrail`: Updates service API and documentation * `service/ecs`: Updates service API and documentation Release v1.5.8 (2016-11-18) === Service Client Updates --- * `service/application-autoscaling`: Updates service API and documentation * `service/elasticmapreduce`: Updates service API and documentation * `service/elastictranscoder`: Updates service API, documentation, and examples * `service/gamelift`: Updates service API and documentation * `service/lambda`: Updates service API and documentation Release v1.5.7 (2016-11-18) === Service Client Updates --- * `service/apigateway`: Updates service API and documentation * `service/meteringmarketplace`: Updates service API and documentation * `service/monitoring`: Updates service API and documentation * `service/sqs`: Updates service API, documentation, and examples Release v1.5.6 (2016-11-16) === Service Client Updates --- `service/route53`: Updates service API and documentation `service/servicecatalog`: Updates service API and documentation Release v1.5.5 (2016-11-15) === Service Client Updates --- * `service/ds`: Updates service API and documentation * `service/elasticache`: Updates service API and documentation * `service/kinesis`: Updates service API and documentation Release v1.5.4 (2016-11-15) === Service Client Updates --- * `service/cognito-idp`: Updates service API and documentation Release v1.5.3 (2016-11-11) === Service Client Updates --- * `service/cloudformation`: Updates service documentation and examples * `service/logs`: Updates service API and documentation Release v1.5.2 (2016-11-03) === Service Client Updates --- * `service/directconnect`: Updates service API and documentation Release v1.5.1 (2016-11-02) === Service Client Updates --- * `service/email`: Updates service API and documentation Release v1.5.0 (2016-11-01) === Service Client Updates --- * `service/cloudformation`: Updates service API and documentation * `service/ecr`: Updates service paginators SDK Feature Updates --- * `private/model/api`: Add generated setters for API parameters (#918) * Adds setters to the SDK's API parameter types, and are a convenience method that reduce the need to use `aws.String` and like utility. Release v1.4.22 (2016-10-25) === Service Client Updates --- * `service/elasticloadbalancingv2`: Updates service documentation. * `service/autoscaling`: Updates service documentation. Release v1.4.21 (2016-10-24) === Service Client Updates --- * `service/sms`: AWS Server Migration Service (SMS) is an agentless service which makes it easier and faster for you to migrate thousands of on-premises workloads to AWS. AWS SMS allows you to automate, schedule, and track incremental replications of live server volumes, making it easier for you to coordinate large-scale server migrations. * `service/ecs`: Updates documentation. SDK Feature Updates --- * `private/models/api`: Improve code generation of documentation. Release v1.4.20 (2016-10-20) === Service Client Updates --- * `service/budgets`: Adds new service, AWS Budgets. * `service/waf`: Updates service documentation. Release v1.4.19 (2016-10-18) === Service Client Updates --- * `service/cloudfront`: Updates service API and documentation. * Ability to use Amazon CloudFront to deliver your content both via IPv6 and IPv4 using HTTP/HTTPS. * `service/configservice`: Update service API and documentation. * `service/iot`: Updates service API and documentation. * `service/kinesisanalytics`: Updates service API and documentation. * Whenever Amazon Kinesis Analytics is not able to detect schema for the given streaming source on DiscoverInputSchema API, we would return the raw records that was sampled to detect the schema. * `service/rds`: Updates service API and documentation. * Amazon Aurora integrates with other AWS services to allow you to extend your Aurora DB cluster to utilize other capabilities in the AWS cloud. Permission to access other AWS services is granted by creating an IAM role with the necessary permissions, and then associating the role with your DB cluster. SDK Feature Updates --- * `service/dynamodb/dynamodbattribute`: Add UnmarshalListOfMaps #897 * Adds support for unmarshaling a list of maps. This is useful for unmarshaling the DynamoDB AttributeValue list of maps returned by APIs like Query and Scan. Release v1.4.18 (2016-10-17) === Service Model Updates --- * `service/route53`: Updates service API and documentation. Release v1.4.17 === Service Model Updates --- * `service/acm`: Update service API, and documentation. * This change allows users to import third-party SSL/TLS certificates into ACM. * `service/elasticbeanstalk`: Update service API, documentation, and pagination. * Elastic Beanstalk DescribeApplicationVersions API is being updated to support pagination. * `service/gamelift`: Update service API, and documentation. * New APIs to protect game developer resource (builds, alias, fleets, instances, game sessions and player sessions) against abuse. SDK Features --- * `service/s3`: Add support for accelerate with dualstack [#887](https://github.com/aws/aws-sdk-go/issues/887) Release v1.4.16 (2016-10-13) === Service Model Updates --- * `service/ecr`: Update Amazon EC2 Container Registry service model * DescribeImages is a new api used to expose image metadata which today includes image size and image creation timestamp. * `service/elasticache`: Update Amazon ElastiCache service model * Elasticache is launching a new major engine release of Redis, 3.2 (providing stability updates and new command sets over 2.8), as well as ElasticSupport for enabling Redis Cluster in 3.2, which provides support for multiple node groups to horizontally scale data, as well as superior engine failover capabilities SDK Bug Fixes --- * `aws/session`: Skip shared config on read errors [#883](https://github.com/aws/aws-sdk-go/issues/883) * `aws/signer/v4`: Add support for URL.EscapedPath to signer [#885](https://github.com/aws/aws-sdk-go/issues/885) SDK Features --- * `private/model/api`: Add docs for errors to API operations [#881](https://github.com/aws/aws-sdk-go/issues/881) * `private/model/api`: Improve field and waiter doc strings [#879](https://github.com/aws/aws-sdk-go/issues/879) * `service/dynamodb/dynamodbattribute`: Allow multiple struct tag elements [#886](https://github.com/aws/aws-sdk-go/issues/886) * Add build tags to internal SDK tools [#880](https://github.com/aws/aws-sdk-go/issues/880) Release v1.4.15 (2016-10-06) === Service Model Updates --- * `service/cognitoidentityprovider`: Update Amazon Cognito Identity Provider service model * `service/devicefarm`: Update AWS Device Farm documentation * `service/opsworks`: Update AWS OpsWorks service model * `service/s3`: Update Amazon Simple Storage Service model * `service/waf`: Update AWS WAF service model SDK Bug Fixes --- * `aws/request`: Fix HTTP Request Body race condition [#874](https://github.com/aws/aws-sdk-go/issues/874) SDK Feature Updates --- * `aws/ec2metadata`: Add support for EC2 User Data [#872](https://github.com/aws/aws-sdk-go/issues/872) * `aws/signer/v4`: Remove logic determining if request needs to be resigned [#876](https://github.com/aws/aws-sdk-go/issues/876) Release v1.4.14 (2016-09-29) === * `service/ec2`: api, documentation, and paginators updates. * `service/s3`: api and documentation updates. Release v1.4.13 (2016-09-27) === * `service/codepipeline`: documentation updates. * `service/cloudformation`: api and documentation updates. * `service/kms`: documentation updates. * `service/elasticfilesystem`: documentation updates. * `service/snowball`: documentation updates.
vendor/github.com/aws/aws-sdk-go/CHANGELOG.md
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017507054144516587, 0.00016805407358333468, 0.00016058256733231246, 0.00016834668349474669, 0.0000033120661555585684 ]
{ "id": 4, "code_window": [ " return acc;\n", " }, []);\n", "\n", " // Append one value column per data set\n", " data.forEach((_, i) => {\n", " // Value (A), Value (B),...\n", " const text = `Value #${String.fromCharCode(65 + i)}`;\n", " columnNames[text] = columns.length;\n", " columns.push({ text });\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " // Value #A, Value #B,...\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "replace", "edit_start_line_idx": 157 }
+++ title = "Provisioning" description = "" keywords = ["grafana", "provisioning"] type = "docs" [menu.docs] parent = "admin" weight = 8 +++ # Provisioning Grafana ## Config file Checkout the [configuration](/installation/configuration) page for more information about what you can configure in `grafana.ini` ### Config file locations - Default configuration from `$WORKING_DIR/conf/defaults.ini` - Custom configuration from `$WORKING_DIR/conf/custom.ini` - The custom configuration file path can be overridden using the `--config` parameter > **Note.** If you have installed Grafana using the `deb` or `rpm` > packages, then your configuration file is located at > `/etc/grafana/grafana.ini`. This path is specified in the Grafana > init.d script using `--config` file parameter. ### Using environment variables All options in the configuration file (listed below) can be overridden using environment variables using the syntax: ```bash GF_<SectionName>_<KeyName> ``` Where the section name is the text within the brackets. Everything should be upper case, `.` should be replaced by `_`. For example, given these configuration settings: ```bash # default section instance_name = ${HOSTNAME} [security] admin_user = admin [auth.google] client_secret = 0ldS3cretKey ``` Then you can override them using: ```bash export GF_DEFAULT_INSTANCE_NAME=my-instance export GF_SECURITY_ADMIN_USER=true export GF_AUTH_GOOGLE_CLIENT_SECRET=newS3cretKey ``` <hr /> ## Configuration management tools Currently we do not provide any scripts/manifests for configuring Grafana. Rather then spending time learning and creating scripts/manifests for each tool, we think our time is better spent making Grafana easier to provision. Therefor, we heavily relay on the expertise of he community. Tool | Project -----|------------ Puppet | [https://forge.puppet.com/puppet/grafana](https://forge.puppet.com/puppet/grafana) Ansible | [https://github.com/picotrading/ansible-grafana](https://github.com/picotrading/ansible-grafana) Chef | [https://github.com/JonathanTron/chef-grafana](https://github.com/JonathanTron/chef-grafana) Saltstack | [https://github.com/salt-formulas/salt-formula-grafana](https://github.com/salt-formulas/salt-formula-grafana) ## Datasources > This feature is available from v4.7 It's possible to manage datasources in Grafana by adding one or more yaml config files in the [`conf/datasources`](/installation/configuration/#datasources) directory. Each config file can contain a list of `datasources` that will be added or updated during start up. If the datasource already exists, Grafana will update it to match the configuration file. The config file can also contain a list of datasources that should be deleted. That list is called `delete_datasources`. Grafana will delete datasources listed in `delete_datasources` before inserting/updating those in the `datasource` list. ### Running multiple grafana instances. If you are running multiple instances of Grafana you might run into problems if they have different versions of the datasource.yaml configuration file. The best way to solve this problem is to add a version number to each datasource in the configuration and increase it when you update the config. Grafana will only update datasources with the same or lower version number than specified in the config. That way old configs cannot overwrite newer configs if they restart at the same time. ### Example datasource config file ```yaml # list of datasources that should be deleted from the database delete_datasources: - name: Graphite org_id: 1 # list of datasources to insert/update depending # whats available in the datbase datasources: # <string, required> name of the datasource. Required - name: Graphite # <string, required> datasource type. Required type: graphite # <string, required> access mode. direct or proxy. Required access: proxy # <int> org id. will default to org_id 1 if not specified org_id: 1 # <string> url url: http://localhost:8080 # <string> database password, if used password: # <string> database user, if used user: # <string> database name, if used database: # <bool> enable/disable basic auth basic_auth: # <string> basic auth username basic_auth_user: # <string> basic auth password basic_auth_password: # <bool> enable/disable with credentials headers with_credentials: # <bool> mark as default datasource. Max one per org is_default: # <map> fields that will be converted to json and stored in json_data json_data: graphiteVersion: "1.1" tlsAuth: true tlsAuthWithCACert: true # <string> json object of data that will be encrypted. secure_json_data: tlsCACert: "..." tlsClientCert: "..." tlsClientKey: "..." version: 1 # <bool> allow users to edit datasources from the UI. editable: false ``` #### Json data Since all datasources dont have the same configuration settings we only have the most common ones as fields. The rest should be stored as a json blob in the `json_data` field. Here are the most common settings that the core datasources use. | Name | Type | Datasource |Description | | ----| ---- | ---- | --- | | tlsAuth | boolean | *All* | Enable TLS authentication using client cert configured in secure json data | | tlsAuthWithCACert | boolean | *All* | Enable TLS authtication using CA cert | | graphiteVersion | string | Graphite | Graphite version | | timeInterval | string | Elastic, Influxdb & Prometheus | Lowest interval/step value that should be used for this data source | | esVersion | string | Elastic | Elasticsearch version | | timeField | string | Elastic | Which field that should be used as timestamp | | interval | string | Elastic | Index date time format | | authType | string | Cloudwatch | Auth provider. keys/credentials/arn | | assumeRoleArn | string | Cloudwatch | ARN of Assume Role | | defaultRegion | string | Cloudwatch | AWS region | | customMetricsNamespaces | string | Cloudwatch | Namespaces of Custom Metrics | | tsdbVersion | string | OpenTsdb | Version | | tsdbResolution | string | OpenTsdb | Resolution | | sslmode | string | Postgre | SSLmode. 'disable', 'require', 'verify-ca' or 'verify-full' | #### Secure Json data {"authType":"keys","defaultRegion":"us-west-2","timeField":"@timestamp"} Secure json data is a map of settings that will be encrypted with [secret key](/installation/configuration/#secret-key) from the grafana config. The purpose of this is only to hide content from the users of the application. This should be used for storing TLS Cert and password that Grafana will append to request on the server side. All these settings are optional. | Name | Type | Datasource | Description | | ----| ---- | ---- | --- | | tlsCACert | string | *All* |CA cert for out going requests | | tlsClientCert | string | *All* |TLS Client cert for outgoing requests | | tlsClientKey | string | *All* |TLS Client key for outgoing requests | | password | string | Postgre | password | | user | string | Postgre | user |
docs/sources/administration/provisioning.md
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017653561371844262, 0.00016901607159525156, 0.000165027187904343, 0.000168108002981171, 0.000003513054025461315 ]
{ "id": 5, "code_window": [ " throw {message: `Result of query #${String.fromCharCode(65 + noTableIndex)} is not in table format, try using another transform.`};\n", " }\n", "\n", " // Track column indexes: name -> index\n", " const columnNames = {};\n", " const columnIndexes = [];\n", "\n", " // Union of all non-value columns\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Single query returns data columns and rows as is\n", " if (data.length === 1) {\n", " model.columns = [...data[0].columns];\n", " model.rows = [...data[0].rows];\n", " return;\n", " }\n", "\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "add", "edit_start_line_idx": 175 }
import _ from 'lodash'; import flatten from '../../../core/utils/flatten'; import TimeSeries from '../../../core/time_series2'; import TableModel from '../../../core/table_model'; var transformers = {}; transformers['timeseries_to_rows'] = { description: 'Time series to rows', getColumns: function() { return []; }, transform: function(data, panel, model) { model.columns = [ {text: 'Time', type: 'date'}, {text: 'Metric'}, {text: 'Value'}, ]; for (var i = 0; i < data.length; i++) { var series = data[i]; for (var y = 0; y < series.datapoints.length; y++) { var dp = series.datapoints[y]; model.rows.push([dp[1], series.target, dp[0]]); } } }, }; transformers['timeseries_to_columns'] = { description: 'Time series to columns', getColumns: function() { return []; }, transform: function(data, panel, model) { model.columns.push({text: 'Time', type: 'date'}); // group by time var points = {}; for (let i = 0; i < data.length; i++) { var series = data[i]; model.columns.push({text: series.target}); for (var y = 0; y < series.datapoints.length; y++) { var dp = series.datapoints[y]; var timeKey = dp[1].toString(); if (!points[timeKey]) { points[timeKey] = {time: dp[1]}; points[timeKey][i] = dp[0]; } else { points[timeKey][i] = dp[0]; } } } for (var time in points) { var point = points[time]; var values = [point.time]; for (let i = 0; i < data.length; i++) { var value = point[i]; values.push(value); } model.rows.push(values); } } }; transformers['timeseries_aggregations'] = { description: 'Time series aggregations', getColumns: function() { return [ {text: 'Avg', value: 'avg'}, {text: 'Min', value: 'min'}, {text: 'Max', value: 'max'}, {text: 'Total', value: 'total'}, {text: 'Current', value: 'current'}, {text: 'Count', value: 'count'}, ]; }, transform: function(data, panel, model) { var i, y; model.columns.push({text: 'Metric'}); for (i = 0; i < panel.columns.length; i++) { model.columns.push({text: panel.columns[i].text}); } for (i = 0; i < data.length; i++) { var series = new TimeSeries({ datapoints: data[i].datapoints, alias: data[i].target, }); series.getFlotPairs('connected'); var cells = [series.alias]; for (y = 0; y < panel.columns.length; y++) { cells.push(series.stats[panel.columns[y].value]); } model.rows.push(cells); } } }; transformers['annotations'] = { description: 'Annotations', getColumns: function() { return []; }, transform: function(data, panel, model) { model.columns.push({text: 'Time', type: 'date'}); model.columns.push({text: 'Title'}); model.columns.push({text: 'Text'}); model.columns.push({text: 'Tags'}); if (!data || !data.annotations || data.annotations.length === 0) { return; } for (var i = 0; i < data.annotations.length; i++) { var evt = data.annotations[i]; model.rows.push([evt.time, evt.title, evt.text, evt.tags]); } } }; transformers['table'] = { description: 'Table', getColumns: function(data) { if (!data || data.length === 0) { return []; } // Track column indexes: name -> index const columnNames = {}; // Union of all non-value columns const columns = data.reduce((acc, d, i) => { d.columns.forEach((col, j) => { const { text } = col; if (text !== 'Value') { if (columnNames[text] === undefined) { columnNames[text] = acc.length; acc.push(col); } } }); return acc; }, []); // Append one value column per data set data.forEach((_, i) => { // Value (A), Value (B),... const text = `Value #${String.fromCharCode(65 + i)}`; columnNames[text] = columns.length; columns.push({ text }); }); return columns; }, transform: function(data, panel, model) { if (!data || data.length === 0) { return; } const noTableIndex = _.findIndex(data, d => d.type !== 'table'); if (noTableIndex > -1) { throw {message: `Result of query #${String.fromCharCode(65 + noTableIndex)} is not in table format, try using another transform.`}; } // Track column indexes: name -> index const columnNames = {}; const columnIndexes = []; // Union of all non-value columns const columns = data.reduce((acc, d, i) => { const indexes = []; d.columns.forEach((col, j) => { const { text } = col; if (text !== 'Value') { if (columnNames[text] === undefined) { columnNames[text] = acc.length; acc.push(col); } indexes[j] = columnNames[text]; } }); columnIndexes.push(indexes); return acc; }, []); const nonValueColumnCount = columns.length; // Append one value column per data set data.forEach((_, i) => { // Value #A, Value #B,... const text = `Value #${String.fromCharCode(65 + i)}`; columnNames[text] = columns.length; columns.push({ text }); columnIndexes[i].push(columnNames[text]); }); model.columns = columns; // Adjust rows to new column indexes let rows = data.reduce((acc, d, i) => { const indexes = columnIndexes[i]; d.rows.forEach((r, j) => { const alteredRow = []; indexes.forEach((to, from) => { alteredRow[to] = r[from]; }); acc.push(alteredRow); }); return acc; }, []); // Merge rows that have same columns const mergedRows = {}; rows = rows.reduce((acc, row, i) => { if (!mergedRows[i]) { const match = _.findIndex(rows, (other, j) => { let same = true; for (let index = 0; index < nonValueColumnCount; index++) { if (row[index] !== other[index]) { same = false; break; } } return same; }, i + 1); if (match > -1) { const matchedRow = rows[match]; // Merge values into current row for (let index = nonValueColumnCount; index < columns.length; index++) { if (row[index] === undefined && matchedRow[index] !== undefined) { row[index] = matchedRow[index]; break; } } mergedRows[match] = matchedRow; } acc.push(row); } return acc; }, []); model.rows = rows; } }; transformers['json'] = { description: 'JSON Data', getColumns: function(data) { if (!data || data.length === 0) { return []; } var names: any = {}; for (var i = 0; i < data.length; i++) { var series = data[i]; if (series.type !== 'docs') { continue; } // only look at 100 docs var maxDocs = Math.min(series.datapoints.length, 100); for (var y = 0; y < maxDocs; y++) { var doc = series.datapoints[y]; var flattened = flatten(doc, null); for (var propName in flattened) { names[propName] = true; } } } return _.map(names, function(value, key) { return {text: key, value: key}; }); }, transform: function(data, panel, model) { var i, y, z; for (let column of panel.columns) { var tableCol: any = {text: column.text}; // if filterable data then set columns to filterable if (data.length > 0 && data[0].filterable) { tableCol.filterable = true; } model.columns.push(tableCol); } if (model.columns.length === 0) { model.columns.push({text: 'JSON'}); } for (i = 0; i < data.length; i++) { var series = data[i]; for (y = 0; y < series.datapoints.length; y++) { var dp = series.datapoints[y]; var values = []; if (_.isObject(dp) && panel.columns.length > 0) { var flattened = flatten(dp, null); for (z = 0; z < panel.columns.length; z++) { values.push(flattened[panel.columns[z].value]); } } else { values.push(JSON.stringify(dp)); } model.rows.push(values); } } } }; function transformDataToTable(data, panel) { var model = new TableModel(); if (!data || data.length === 0) { return model; } var transformer = transformers[panel.transform]; if (!transformer) { throw {message: 'Transformer ' + panel.transform + ' not found'}; } transformer.transform(data, panel, model); return model; } export {transformers, transformDataToTable};
public/app/plugins/panel/table/transformers.ts
1
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.999215841293335, 0.2568386197090149, 0.00016372738173231483, 0.0002094552619382739, 0.4356336295604706 ]
{ "id": 5, "code_window": [ " throw {message: `Result of query #${String.fromCharCode(65 + noTableIndex)} is not in table format, try using another transform.`};\n", " }\n", "\n", " // Track column indexes: name -> index\n", " const columnNames = {};\n", " const columnIndexes = [];\n", "\n", " // Union of all non-value columns\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Single query returns data columns and rows as is\n", " if (data.length === 1) {\n", " model.columns = [...data[0].columns];\n", " model.rows = [...data[0].rows];\n", " return;\n", " }\n", "\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "add", "edit_start_line_idx": 175 }
hash[*]
vendor/github.com/jmespath/go-jmespath/fuzz/corpus/expr-627
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.000175308741745539, 0.000175308741745539, 0.000175308741745539, 0.000175308741745539, 0 ]
{ "id": 5, "code_window": [ " throw {message: `Result of query #${String.fromCharCode(65 + noTableIndex)} is not in table format, try using another transform.`};\n", " }\n", "\n", " // Track column indexes: name -> index\n", " const columnNames = {};\n", " const columnIndexes = [];\n", "\n", " // Union of all non-value columns\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Single query returns data columns and rows as is\n", " if (data.length === 1) {\n", " model.columns = [...data[0].columns];\n", " model.rows = [...data[0].rows];\n", " return;\n", " }\n", "\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "add", "edit_start_line_idx": 175 }
import _ from 'lodash'; import tinycolor from 'tinycolor2'; export const PALETTE_ROWS = 4; export const PALETTE_COLUMNS = 14; export const DEFAULT_ANNOTATION_COLOR = 'rgba(0, 211, 255, 1)'; export const OK_COLOR = "rgba(11, 237, 50, 1)"; export const ALERTING_COLOR = "rgba(237, 46, 24, 1)"; export const NO_DATA_COLOR = "rgba(150, 150, 150, 1)"; export const REGION_FILL_ALPHA = 0.09; let colors = [ "#7EB26D","#EAB839","#6ED0E0","#EF843C","#E24D42","#1F78C1","#BA43A9","#705DA0", "#508642","#CCA300","#447EBC","#C15C17","#890F02","#0A437C","#6D1F62","#584477", "#B7DBAB","#F4D598","#70DBED","#F9BA8F","#F29191","#82B5D8","#E5A8E2","#AEA2E0", "#629E51","#E5AC0E","#64B0C8","#E0752D","#BF1B00","#0A50A1","#962D82","#614D93", "#9AC48A","#F2C96D","#65C5DB","#F9934E","#EA6460","#5195CE","#D683CE","#806EB7", "#3F6833","#967302","#2F575E","#99440A","#58140C","#052B51","#511749","#3F2B5B", "#E0F9D7","#FCEACA","#CFFAFF","#F9E2D2","#FCE2DE","#BADFF4","#F9D9F9","#DEDAF7" ]; export function sortColorsByHue(hexColors) { let hslColors = _.map(hexColors, hexToHsl); let sortedHSLColors = _.sortBy(hslColors, ['h']); sortedHSLColors = _.chunk(sortedHSLColors, PALETTE_ROWS); sortedHSLColors = _.map(sortedHSLColors, chunk => { return _.sortBy(chunk, 'l'); }); sortedHSLColors = _.flattenDeep(_.zip(...sortedHSLColors)); return _.map(sortedHSLColors, hslToHex); } export function hexToHsl(color) { return tinycolor(color).toHsl(); } export function hslToHex(color) { return tinycolor(color).toHexString(); } export let sortedColors = sortColorsByHue(colors); export default colors;
public/app/core/utils/colors.ts
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.0002873289631679654, 0.00019533098384272307, 0.00016744011372793466, 0.00017481032409705222, 0.000046099343308014795 ]
{ "id": 5, "code_window": [ " throw {message: `Result of query #${String.fromCharCode(65 + noTableIndex)} is not in table format, try using another transform.`};\n", " }\n", "\n", " // Track column indexes: name -> index\n", " const columnNames = {};\n", " const columnIndexes = [];\n", "\n", " // Union of all non-value columns\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " // Single query returns data columns and rows as is\n", " if (data.length === 1) {\n", " model.columns = [...data[0].columns];\n", " model.rows = [...data[0].rows];\n", " return;\n", " }\n", "\n" ], "file_path": "public/app/plugins/panel/table/transformers.ts", "type": "add", "edit_start_line_idx": 175 }
import config from 'app/core/config'; import $ from 'jquery'; import _ from 'lodash'; import kbn from 'app/core/utils/kbn'; import {PanelCtrl} from 'app/features/panel/panel_ctrl'; import * as rangeUtil from 'app/core/utils/rangeutil'; import * as dateMath from 'app/core/utils/datemath'; import {metricsTabDirective} from './metrics_tab'; class MetricsPanelCtrl extends PanelCtrl { scope: any; datasource: any; datasourceName: any; $q: any; $timeout: any; datasourceSrv: any; timeSrv: any; templateSrv: any; timing: any; range: any; interval: any; intervalMs: any; resolution: any; timeInfo: any; skipDataOnInit: boolean; dataStream: any; dataSubscription: any; dataList: any; nextRefId: string; constructor($scope, $injector) { super($scope, $injector); // make metrics tab the default this.editorTabIndex = 1; this.$q = $injector.get('$q'); this.datasourceSrv = $injector.get('datasourceSrv'); this.timeSrv = $injector.get('timeSrv'); this.templateSrv = $injector.get('templateSrv'); this.scope = $scope; this.panel.datasource = this.panel.datasource || null; if (!this.panel.targets) { this.panel.targets = [{}]; } this.events.on('refresh', this.onMetricsPanelRefresh.bind(this)); this.events.on('init-edit-mode', this.onInitMetricsPanelEditMode.bind(this)); this.events.on('panel-teardown', this.onPanelTearDown.bind(this)); } private onPanelTearDown() { if (this.dataSubscription) { this.dataSubscription.unsubscribe(); this.dataSubscription = null; } } private onInitMetricsPanelEditMode() { this.addEditorTab('Metrics', metricsTabDirective); this.addEditorTab('Time range', 'public/app/features/panel/partials/panelTime.html'); } private onMetricsPanelRefresh() { // ignore fetching data if another panel is in fullscreen if (this.otherPanelInFullscreenMode()) { return; } // if we have snapshot data use that if (this.panel.snapshotData) { this.updateTimeRange(); var data = this.panel.snapshotData; // backward compatability if (!_.isArray(data)) { data = data.data; } this.events.emit('data-snapshot-load', data); return; } // // ignore if we have data stream if (this.dataStream) { return; } // clear loading/error state delete this.error; this.loading = true; // load datasource service this.setTimeQueryStart(); this.datasourceSrv.get(this.panel.datasource) .then(this.updateTimeRange.bind(this)) .then(this.issueQueries.bind(this)) .then(this.handleQueryResult.bind(this)) .catch(err => { // if cancelled keep loading set to true if (err.cancelled) { console.log('Panel request cancelled', err); return; } this.loading = false; this.error = err.message || "Request Error"; this.inspector = {error: err}; if (err.data) { if (err.data.message) { this.error = err.data.message; } if (err.data.error) { this.error = err.data.error; } } this.events.emit('data-error', err); console.log('Panel data error:', err); }); } setTimeQueryStart() { this.timing.queryStart = new Date().getTime(); } setTimeQueryEnd() { this.timing.queryEnd = new Date().getTime(); } updateTimeRange(datasource?) { this.datasource = datasource || this.datasource; this.range = this.timeSrv.timeRange(); this.applyPanelTimeOverrides(); if (this.panel.maxDataPoints) { this.resolution = this.panel.maxDataPoints; } else { this.resolution = Math.ceil($(window).width() * (this.panel.span / 12)); } this.calculateInterval(); return this.datasource; } calculateInterval() { var intervalOverride = this.panel.interval; // if no panel interval check datasource if (intervalOverride) { intervalOverride = this.templateSrv.replace(intervalOverride, this.panel.scopedVars); } else if (this.datasource && this.datasource.interval) { intervalOverride = this.datasource.interval; } var res = kbn.calculateInterval(this.range, this.resolution, intervalOverride); this.interval = res.interval; this.intervalMs = res.intervalMs; } applyPanelTimeOverrides() { this.timeInfo = ''; // check panel time overrrides if (this.panel.timeFrom) { var timeFromInterpolated = this.templateSrv.replace(this.panel.timeFrom, this.panel.scopedVars); var timeFromInfo = rangeUtil.describeTextRange(timeFromInterpolated); if (timeFromInfo.invalid) { this.timeInfo = 'invalid time override'; return; } if (_.isString(this.range.raw.from)) { var timeFromDate = dateMath.parse(timeFromInfo.from); this.timeInfo = timeFromInfo.display; this.range.from = timeFromDate; this.range.to = dateMath.parse(timeFromInfo.to); this.range.raw.from = timeFromInfo.from; this.range.raw.to = timeFromInfo.to; } } if (this.panel.timeShift) { var timeShiftInterpolated = this.templateSrv.replace(this.panel.timeShift, this.panel.scopedVars); var timeShiftInfo = rangeUtil.describeTextRange(timeShiftInterpolated); if (timeShiftInfo.invalid) { this.timeInfo = 'invalid timeshift'; return; } var timeShift = '-' + timeShiftInterpolated; this.timeInfo += ' timeshift ' + timeShift; this.range.from = dateMath.parseDateMath(timeShift, this.range.from, false); this.range.to = dateMath.parseDateMath(timeShift, this.range.to, true); this.range.raw = {from: this.range.from, to: this.range.to}; } if (this.panel.hideTimeOverride) { this.timeInfo = ''; } } issueQueries(datasource) { this.datasource = datasource; if (!this.panel.targets || this.panel.targets.length === 0) { return this.$q.when([]); } // make shallow copy of scoped vars, // and add built in variables interval and interval_ms var scopedVars = Object.assign({}, this.panel.scopedVars, { "__interval": {text: this.interval, value: this.interval}, "__interval_ms": {text: this.intervalMs, value: this.intervalMs}, }); var metricsQuery = { timezone: this.dashboard.getTimezone(), panelId: this.panel.id, range: this.range, rangeRaw: this.range.raw, interval: this.interval, intervalMs: this.intervalMs, targets: this.panel.targets, maxDataPoints: this.resolution, scopedVars: scopedVars, cacheTimeout: this.panel.cacheTimeout }; return datasource.query(metricsQuery); } handleQueryResult(result) { this.setTimeQueryEnd(); this.loading = false; // check for if data source returns subject if (result && result.subscribe) { this.handleDataStream(result); return; } if (this.dashboard.snapshot) { this.panel.snapshotData = result.data; } if (!result || !result.data) { console.log('Data source query result invalid, missing data field:', result); result = {data: []}; } this.events.emit('data-received', result.data); } handleDataStream(stream) { // if we already have a connection if (this.dataStream) { console.log('two stream observables!'); return; } this.dataStream = stream; this.dataSubscription = stream.subscribe({ next: (data) => { console.log('dataSubject next!'); if (data.range) { this.range = data.range; } this.events.emit('data-received', data.data); }, error: (error) => { this.events.emit('data-error', error); console.log('panel: observer got error'); }, complete: () => { console.log('panel: observer got complete'); this.dataStream = null; } }); } setDatasource(datasource) { // switching to mixed if (datasource.meta.mixed) { _.each(this.panel.targets, target => { target.datasource = this.panel.datasource; if (!target.datasource) { target.datasource = config.defaultDatasource; } }); } else if (this.datasource && this.datasource.meta.mixed) { _.each(this.panel.targets, target => { delete target.datasource; }); } this.panel.datasource = datasource.value; this.datasourceName = datasource.name; this.datasource = null; this.refresh(); } addQuery(target) { target.refId = this.dashboard.getNextQueryLetter(this.panel); this.panel.targets.push(target); this.nextRefId = this.dashboard.getNextQueryLetter(this.panel); } removeQuery(target) { var index = _.indexOf(this.panel.targets, target); this.panel.targets.splice(index, 1); this.nextRefId = this.dashboard.getNextQueryLetter(this.panel); this.refresh(); } moveQuery(target, direction) { var index = _.indexOf(this.panel.targets, target); _.move(this.panel.targets, index, index + direction); } } export {MetricsPanelCtrl};
public/app/features/panel/metrics_panel_ctrl.ts
0
https://github.com/grafana/grafana/commit/eb31833d521f03901e1d7de53301434fef72d010
[ 0.00017803246737457812, 0.0001713852398097515, 0.00016423367196694016, 0.00017124578880611807, 0.000003190421011822764 ]
{ "id": 0, "code_window": [ " .then(r => r.default || r)\n", " .then(r => typeof r === 'function' ? r() : r) as Promise<ClientManifest>\n", "\n", "const getEntryId: () => Promise<string> = () => getClientManifest().then(r => Object.values(r).find(r => r.isEntry)!.src!)\n", "\n", "// @ts-expect-error virtual file\n", "const getStaticRenderedHead = (): Promise<NuxtMeta> => import('#head-static').then(r => r.default || r)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const getEntryIds: () => Promise<string[]> = () => getClientManifest().then(r => Object.values(r).filter(r =>\n", " // @ts-expect-error internal key set by CSS inlining configuration\n", " r._globalCSS\n", ").map(r => r.src!))\n" ], "file_path": "packages/nuxt/src/core/runtime/nitro/renderer.ts", "type": "replace", "edit_start_line_idx": 68 }
import { existsSync } from 'node:fs' import * as vite from 'vite' import { basename, dirname, join, resolve } from 'pathe' import type { Nuxt, ViteConfig } from '@nuxt/schema' import { addVitePlugin, isIgnored, logger, resolvePath } from '@nuxt/kit' import replace from '@rollup/plugin-replace' import { sanitizeFilePath } from 'mlly' import { withoutLeadingSlash } from 'ufo' import { filename } from 'pathe/utils' import { resolveTSConfig } from 'pkg-types' import { consola } from 'consola' import { buildClient } from './client' import { buildServer } from './server' import virtual from './plugins/virtual' import { warmupViteServer } from './utils/warmup' import { resolveCSSOptions } from './css' import { composableKeysPlugin } from './plugins/composable-keys' import { logLevelMap } from './utils/logger' import { ssrStylesPlugin } from './plugins/ssr-styles' export interface ViteBuildContext { nuxt: Nuxt config: ViteConfig entry: string clientServer?: vite.ViteDevServer ssrServer?: vite.ViteDevServer } export async function bundle (nuxt: Nuxt) { // https://github.com/vitejs/vite/blob/8fe69524d25d45290179175ba9b9956cbce87a91/packages/vite/src/node/constants.ts#L38 const viteConfigPrefix = resolve(nuxt.options.rootDir, 'vite.config') const viteConfigFile = await resolvePath(viteConfigPrefix).catch(() => null) if (viteConfigFile && viteConfigFile !== viteConfigPrefix) { consola.warn(`Using \`${basename(viteConfigFile)}\` is not supported together with Nuxt. Use \`options.vite\` instead. You can read more in \`https://nuxt.com/docs/api/configuration/nuxt-config#vite\`.`) } const useAsyncEntry = nuxt.options.experimental.asyncEntry || (nuxt.options.vite.devBundler === 'vite-node' && nuxt.options.dev) const entry = await resolvePath(resolve(nuxt.options.appDir, useAsyncEntry ? 'entry.async' : 'entry')) let allowDirs = [ nuxt.options.appDir, nuxt.options.workspaceDir, ...nuxt.options._layers.map(l => l.config.rootDir), ...Object.values(nuxt.apps).flatMap(app => [ ...app.components.map(c => dirname(c.filePath)), ...app.plugins.map(p => dirname(p.src)), ...app.middleware.map(m => dirname(m.path)), ...Object.values(app.layouts || {}).map(l => dirname(l.file)), dirname(nuxt.apps.default.rootComponent!), dirname(nuxt.apps.default.errorComponent!) ]) ].filter(d => d && existsSync(d)) for (const dir of allowDirs) { allowDirs = allowDirs.filter(d => !d.startsWith(dir) || d === dir) } const ctx: ViteBuildContext = { nuxt, entry, config: vite.mergeConfig( { logLevel: logLevelMap[nuxt.options.logLevel] ?? logLevelMap.info, resolve: { alias: { ...nuxt.options.alias, '#app': nuxt.options.appDir, // We need this resolution to be present before the following entry, but it // will be filled in client/server configs '#build/plugins': '', '#build': nuxt.options.buildDir, 'web-streams-polyfill/ponyfill/es2018': 'unenv/runtime/mock/empty', // Cannot destructure property 'AbortController' of .. 'abort-controller': 'unenv/runtime/mock/empty' } }, optimizeDeps: { include: ['vue', '@vue/reactivity', '@vue/runtime-core', '@vue/runtime-dom', '@vue/shared'], exclude: ['nuxt/app'] }, css: resolveCSSOptions(nuxt), define: { __NUXT_VERSION__: JSON.stringify(nuxt._version) }, build: { copyPublicDir: false, rollupOptions: { output: { sourcemapIgnoreList: (relativeSourcePath) => { return relativeSourcePath.includes('node_modules') || relativeSourcePath.includes(ctx.nuxt.options.buildDir) }, sanitizeFileName: sanitizeFilePath, // https://github.com/vitejs/vite/tree/main/packages/vite/src/node/build.ts#L464-L478 assetFileNames: nuxt.options.dev ? undefined : chunk => withoutLeadingSlash(join(nuxt.options.app.buildAssetsDir, `${sanitizeFilePath(filename(chunk.name!))}.[hash].[ext]`)) } }, watch: { exclude: nuxt.options.ignore } }, plugins: [ composableKeysPlugin.vite({ sourcemap: nuxt.options.sourcemap.server || nuxt.options.sourcemap.client, rootDir: nuxt.options.rootDir, composables: nuxt.options.optimization.keyedComposables }), replace({ ...Object.fromEntries([';', '(', '{', '}', ' ', '\t', '\n'].map(d => [`${d}global.`, `${d}globalThis.`])), preventAssignment: true }), virtual(nuxt.vfs) ], vue: { reactivityTransform: nuxt.options.experimental.reactivityTransform }, server: { watch: { ignored: isIgnored }, fs: { allow: [...new Set(allowDirs)] } } } satisfies ViteConfig, nuxt.options.vite ) } // In build mode we explicitly override any vite options that vite is relying on // to detect whether to inject production or development code (such as HMR code) if (!nuxt.options.dev) { ctx.config.server!.watch = undefined ctx.config.build!.watch = undefined } // Add type-checking if (ctx.nuxt.options.typescript.typeCheck === true || (ctx.nuxt.options.typescript.typeCheck === 'build' && !ctx.nuxt.options.dev)) { const checker = await import('vite-plugin-checker').then(r => r.default) addVitePlugin(checker({ vueTsc: { tsconfigPath: await resolveTSConfig(ctx.nuxt.options.rootDir) } }), { server: nuxt.options.ssr }) } await nuxt.callHook('vite:extend', ctx) if (!ctx.nuxt.options.dev) { const chunksWithInlinedCSS = new Set<string>() const clientCSSMap = {} nuxt.hook('vite:extendConfig', (config, { isServer }) => { config.plugins!.push(ssrStylesPlugin({ srcDir: ctx.nuxt.options.srcDir, clientCSSMap, chunksWithInlinedCSS, shouldInline: ctx.nuxt.options.experimental.inlineSSRStyles, components: ctx.nuxt.apps.default.components, globalCSS: ctx.nuxt.options.css, mode: isServer ? 'server' : 'client', entry: ctx.entry })) }) // Remove CSS entries for files that will have inlined styles ctx.nuxt.hook('build:manifest', (manifest) => { for (const key in manifest) { const entry = manifest[key] const shouldRemoveCSS = chunksWithInlinedCSS.has(key) && !entry.isEntry if (shouldRemoveCSS && entry.css) { entry.css = [] } } }) } nuxt.hook('vite:serverCreated', (server: vite.ViteDevServer, env) => { // Invalidate virtual modules when templates are re-generated ctx.nuxt.hook('app:templatesGenerated', () => { for (const [id, mod] of server.moduleGraph.idToModuleMap) { if (id.startsWith('virtual:')) { server.moduleGraph.invalidateModule(mod) } } }) if ( nuxt.options.vite.warmupEntry !== false && // https://github.com/nuxt/nuxt/issues/14898 !(env.isServer && ctx.nuxt.options.vite.devBundler !== 'legacy') ) { const start = Date.now() warmupViteServer(server, [join('/@fs/', ctx.entry)], env.isServer) .then(() => logger.info(`Vite ${env.isClient ? 'client' : 'server'} warmed up in ${Date.now() - start}ms`)) .catch(logger.error) } }) await buildClient(ctx) await buildServer(ctx) }
packages/vite/src/vite.ts
1
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.00032268589711748064, 0.00017699028830975294, 0.00016282673459500074, 0.00017033643962349743, 0.00003273317270213738 ]
{ "id": 0, "code_window": [ " .then(r => r.default || r)\n", " .then(r => typeof r === 'function' ? r() : r) as Promise<ClientManifest>\n", "\n", "const getEntryId: () => Promise<string> = () => getClientManifest().then(r => Object.values(r).find(r => r.isEntry)!.src!)\n", "\n", "// @ts-expect-error virtual file\n", "const getStaticRenderedHead = (): Promise<NuxtMeta> => import('#head-static').then(r => r.default || r)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const getEntryIds: () => Promise<string[]> = () => getClientManifest().then(r => Object.values(r).filter(r =>\n", " // @ts-expect-error internal key set by CSS inlining configuration\n", " r._globalCSS\n", ").map(r => r.src!))\n" ], "file_path": "packages/nuxt/src/core/runtime/nitro/renderer.ts", "type": "replace", "edit_start_line_idx": 68 }
<template> <div> <div>Extended layout from foo</div> <NuxtPage /> </div> </template>
test/fixtures/basic/extends/node_modules/foo/layouts/default.vue
0
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.00016625710122752935, 0.00016625710122752935, 0.00016625710122752935, 0.00016625710122752935, 0 ]
{ "id": 0, "code_window": [ " .then(r => r.default || r)\n", " .then(r => typeof r === 'function' ? r() : r) as Promise<ClientManifest>\n", "\n", "const getEntryId: () => Promise<string> = () => getClientManifest().then(r => Object.values(r).find(r => r.isEntry)!.src!)\n", "\n", "// @ts-expect-error virtual file\n", "const getStaticRenderedHead = (): Promise<NuxtMeta> => import('#head-static').then(r => r.default || r)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const getEntryIds: () => Promise<string[]> = () => getClientManifest().then(r => Object.values(r).filter(r =>\n", " // @ts-expect-error internal key set by CSS inlining configuration\n", " r._globalCSS\n", ").map(r => r.src!))\n" ], "file_path": "packages/nuxt/src/core/runtime/nitro/renderer.ts", "type": "replace", "edit_start_line_idx": 68 }
export default defineNuxtPlugin(() => { return { provide: { pluginInjection: () => '' } } })
test/fixtures/basic-types/plugins/injection.ts
0
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.0003848765045404434, 0.0003848765045404434, 0.0003848765045404434, 0.0003848765045404434, 0 ]
{ "id": 0, "code_window": [ " .then(r => r.default || r)\n", " .then(r => typeof r === 'function' ? r() : r) as Promise<ClientManifest>\n", "\n", "const getEntryId: () => Promise<string> = () => getClientManifest().then(r => Object.values(r).find(r => r.isEntry)!.src!)\n", "\n", "// @ts-expect-error virtual file\n", "const getStaticRenderedHead = (): Promise<NuxtMeta> => import('#head-static').then(r => r.default || r)\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "const getEntryIds: () => Promise<string[]> = () => getClientManifest().then(r => Object.values(r).filter(r =>\n", " // @ts-expect-error internal key set by CSS inlining configuration\n", " r._globalCSS\n", ").map(r => r.src!))\n" ], "file_path": "packages/nuxt/src/core/runtime/nitro/renderer.ts", "type": "replace", "edit_start_line_idx": 68 }
/** * This file is based on Vue.js (MIT) webpack plugins * https://github.com/vuejs/vue/blob/dev/src/server/webpack-plugin/client.js */ import { normalizeWebpackManifest } from 'vue-bundle-renderer' import { dirname } from 'pathe' import hash from 'hash-sum' import { uniq } from 'lodash-es' import fse from 'fs-extra' import type { Nuxt } from '@nuxt/schema' import type { Compilation, Compiler } from 'webpack' import { isCSS, isHotUpdate, isJS } from './util' interface PluginOptions { filename: string nuxt: Nuxt } export default class VueSSRClientPlugin { options: PluginOptions constructor (options: PluginOptions) { this.options = Object.assign({ filename: null }, options) } apply (compiler: Compiler) { compiler.hooks.afterEmit.tap('VueSSRClientPlugin', async (compilation: Compilation) => { const stats = compilation.getStats().toJson() const allFiles = uniq(stats.assets! .map(a => a.name)) .filter(file => !isHotUpdate(file)) const initialFiles = uniq(Object.keys(stats.entrypoints!) .map(name => stats.entrypoints![name].assets!) .reduce((files, entryAssets) => files.concat(entryAssets.map(entryAsset => entryAsset.name)), [] as string[]) .filter(file => isJS(file) || isCSS(file))) .filter(file => !isHotUpdate(file)) const asyncFiles = allFiles .filter(file => isJS(file) || isCSS(file)) .filter(file => !initialFiles.includes(file)) .filter(file => !isHotUpdate(file)) const assetsMapping: Record<string, string[]> = {} stats.assets! .filter(({ name }) => isJS(name)) .filter(({ name }) => !isHotUpdate(name)) .forEach(({ name, chunkNames = [] }) => { const componentHash = hash(chunkNames.join('|')) if (!assetsMapping[componentHash]) { assetsMapping[componentHash] = [] } assetsMapping[componentHash].push(name) }) const webpackManifest = { publicPath: stats.publicPath, all: allFiles, initial: initialFiles, async: asyncFiles, modules: { /* [identifier: string]: Array<index: number> */ } as Record<string, number[]>, assetsMapping } const { entrypoints = {}, namedChunkGroups = {} } = stats const assetModules = stats.modules!.filter(m => m.assets!.length) const fileToIndex = (file: string) => webpackManifest.all.indexOf(file) stats.modules!.forEach((m) => { // Ignore modules duplicated in multiple chunks if (m.chunks!.length === 1) { const [cid] = m.chunks! const chunk = stats.chunks!.find(c => c.id === cid) if (!chunk || !chunk.files) { return } const id = m.identifier!.replace(/\s\w+$/, '') // remove appended hash const filesSet = new Set(chunk.files.map(fileToIndex).filter(i => i !== -1)) for (const chunkName of chunk.names!) { if (!entrypoints[chunkName]) { const chunkGroup = namedChunkGroups[chunkName] if (chunkGroup) { for (const asset of chunkGroup.assets!) { filesSet.add(fileToIndex(asset.name)) } } } } const files = Array.from(filesSet) webpackManifest.modules[hash(id)] = files // In production mode, modules may be concatenated by scope hoisting // Include ConcatenatedModule for not losing module-component mapping if (Array.isArray(m.modules)) { for (const concatenatedModule of m.modules) { const id = hash(concatenatedModule.identifier!.replace(/\s\w+$/, '')) if (!webpackManifest.modules[id]) { webpackManifest.modules[id] = files } } } // Find all asset modules associated with the same chunk assetModules.forEach((m) => { if (m.chunks!.includes(cid)) { files.push(...(m.assets as string[]).map(fileToIndex)) } }) } }) const manifest = normalizeWebpackManifest(webpackManifest as any) await this.options.nuxt.callHook('build:manifest', manifest) const src = JSON.stringify(manifest, null, 2) await fse.mkdirp(dirname(this.options.filename)) await fse.writeFile(this.options.filename, src) const mjsSrc = 'export default ' + src await fse.writeFile(this.options.filename.replace('.json', '.mjs'), mjsSrc) // assets[this.options.filename] = { // source: () => src, // size: () => src.length // } }) } }
packages/webpack/src/plugins/vue/client.ts
0
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.00017487216973677278, 0.00016911390412133187, 0.00016498551121912897, 0.00016860250616446137, 0.000003449659061516286 ]
{ "id": 1, "code_window": [ " const renderedMeta = await ssrContext.renderMeta?.() ?? {}\n", "\n", " if (process.env.NUXT_INLINE_STYLES && !islandContext) {\n", " const entryId = await getEntryId()\n", " if (ssrContext.modules) {\n", " ssrContext.modules.add(entryId)\n", " } else if (ssrContext._registeredComponents) {\n", " ssrContext._registeredComponents.add(entryId)\n", " }\n", " }\n", "\n", " // Render inline styles\n", " const inlinedStyles = (process.env.NUXT_INLINE_STYLES || Boolean(islandContext))\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const source = ssrContext.modules ?? ssrContext._registeredComponents\n", " if (source) {\n", " for (const id of await getEntryIds()) {\n", " source.add(id)\n", " }\n" ], "file_path": "packages/nuxt/src/core/runtime/nitro/renderer.ts", "type": "replace", "edit_start_line_idx": 291 }
import { createRenderer, renderResourceHeaders } from 'vue-bundle-renderer/runtime' import type { RenderResponse } from 'nitropack' import type { Manifest } from 'vite' import type { H3Event } from 'h3' import { appendResponseHeader, createError, getQuery, readBody, writeEarlyHints } from 'h3' import devalue from '@nuxt/devalue' import { stringify, uneval } from 'devalue' import destr from 'destr' import { joinURL, withoutTrailingSlash } from 'ufo' import { renderToString as _renderToString } from 'vue/server-renderer' import { hash } from 'ohash' import { defineRenderHandler, getRouteRules, useRuntimeConfig } from '#internal/nitro' import { useNitroApp } from '#internal/nitro/app' // eslint-disable-next-line import/no-restricted-paths import type { NuxtPayload, NuxtSSRContext } from '#app/nuxt' // @ts-expect-error virtual file import { appRootId, appRootTag } from '#internal/nuxt.config.mjs' // @ts-expect-error virtual file import { buildAssetsURL, publicAssetsURL } from '#paths' // @ts-expect-error private property consumed by vite-generated url helpers globalThis.__buildAssetsURL = buildAssetsURL // @ts-expect-error private property consumed by vite-generated url helpers globalThis.__publicAssetsURL = publicAssetsURL export interface NuxtRenderHTMLContext { island?: boolean htmlAttrs: string[] head: string[] bodyAttrs: string[] bodyPrepend: string[] body: string[] bodyAppend: string[] } export interface NuxtIslandContext { id?: string name: string props?: Record<string, any> url?: string } export interface NuxtIslandResponse { id?: string html: string state: Record<string, any> head: { link: (Record<string, string>)[] style: ({ innerHTML: string, key: string })[] } } export interface NuxtRenderResponse { body: string, statusCode: number, statusMessage?: string, headers: Record<string, string> } interface ClientManifest {} // @ts-expect-error file will be produced after app build const getClientManifest: () => Promise<Manifest> = () => import('#build/dist/server/client.manifest.mjs') .then(r => r.default || r) .then(r => typeof r === 'function' ? r() : r) as Promise<ClientManifest> const getEntryId: () => Promise<string> = () => getClientManifest().then(r => Object.values(r).find(r => r.isEntry)!.src!) // @ts-expect-error virtual file const getStaticRenderedHead = (): Promise<NuxtMeta> => import('#head-static').then(r => r.default || r) // @ts-expect-error file will be produced after app build const getServerEntry = () => import('#build/dist/server/server.mjs').then(r => r.default || r) // @ts-expect-error file will be produced after app build const getSSRStyles = lazyCachedFunction((): Promise<Record<string, () => Promise<string[]>>> => import('#build/dist/server/styles.mjs').then(r => r.default || r)) // -- SSR Renderer -- const getSSRRenderer = lazyCachedFunction(async () => { // Load client manifest const manifest = await getClientManifest() if (!manifest) { throw new Error('client.manifest is not available') } // Load server bundle const createSSRApp = await getServerEntry() if (!createSSRApp) { throw new Error('Server bundle is not available') } const options = { manifest, renderToString, buildAssetsURL } // Create renderer const renderer = createRenderer(createSSRApp, options) type RenderToStringParams = Parameters<typeof _renderToString> async function renderToString (input: RenderToStringParams[0], context: RenderToStringParams[1]) { const html = await _renderToString(input, context) // In development with vite-node, the manifest is on-demand and will be available after rendering if (process.dev && process.env.NUXT_VITE_NODE_OPTIONS) { renderer.rendererContext.updateManifest(await getClientManifest()) } return `<${appRootTag} id="${appRootId}">${html}</${appRootTag}>` } return renderer }) // -- SPA Renderer -- const getSPARenderer = lazyCachedFunction(async () => { const manifest = await getClientManifest() // @ts-expect-error virtual file const spaTemplate = await import('#spa-template').then(r => r.template).catch(() => '') const options = { manifest, renderToString: () => `<${appRootTag} id="${appRootId}">${spaTemplate}</${appRootTag}>`, buildAssetsURL } // Create SPA renderer and cache the result for all requests const renderer = createRenderer(() => () => {}, options) const result = await renderer.renderToString({}) const renderToString = (ssrContext: NuxtSSRContext) => { const config = useRuntimeConfig() ssrContext.modules = ssrContext.modules || new Set<string>() ssrContext!.payload = { _errors: {}, serverRendered: false, data: {}, state: {} } ssrContext.config = { public: config.public, app: config.app } ssrContext!.renderMeta = ssrContext!.renderMeta ?? getStaticRenderedHead return Promise.resolve(result) } return { rendererContext: renderer.rendererContext, renderToString } }) async function getIslandContext (event: H3Event): Promise<NuxtIslandContext> { // TODO: Strict validation for url const url = event.node.req.url?.substring('/__nuxt_island'.length + 1) || '' const [componentName, hashId] = url.split('?')[0].split('_') // TODO: Validate context const context = event.node.req.method === 'GET' ? getQuery(event) : await readBody(event) const ctx: NuxtIslandContext = { url: '/', ...context, id: hashId, name: componentName, props: destr(context.props) || {}, uid: destr(context.uid) || undefined } return ctx } const PAYLOAD_CACHE = (process.env.NUXT_PAYLOAD_EXTRACTION && process.env.prerender) ? new Map() : null // TODO: Use LRU cache const ISLAND_CACHE = (process.env.NUXT_COMPONENT_ISLANDS && process.env.prerender) ? new Map() : null // TODO: Use LRU cache const PAYLOAD_URL_RE = process.env.NUXT_JSON_PAYLOADS ? /\/_payload(\.[a-zA-Z0-9]+)?.json(\?.*)?$/ : /\/_payload(\.[a-zA-Z0-9]+)?.js(\?.*)?$/ const ROOT_NODE_REGEX = new RegExp(`^<${appRootTag} id="${appRootId}">([\\s\\S]*)</${appRootTag}>$`) const PRERENDER_NO_SSR_ROUTES = new Set(['/index.html', '/200.html', '/404.html']) export default defineRenderHandler(async (event): Promise<Partial<RenderResponse>> => { const nitroApp = useNitroApp() // Whether we're rendering an error page const ssrError = event.node.req.url?.startsWith('/__nuxt_error') ? getQuery(event) as unknown as Exclude<NuxtPayload['error'], Error> : null if (ssrError && ssrError.statusCode) { ssrError.statusCode = parseInt(ssrError.statusCode as any) } if (ssrError && event.node.req.socket.readyState !== 'readOnly' /* direct request */) { throw createError({ statusCode: 404, statusMessage: 'Page Not Found: /__nuxt_error' }) } // Check for island component rendering const islandContext = (process.env.NUXT_COMPONENT_ISLANDS && event.node.req.url?.startsWith('/__nuxt_island')) ? await getIslandContext(event) : undefined if (process.env.prerender && islandContext && ISLAND_CACHE!.has(event.node.req.url)) { return ISLAND_CACHE!.get(event.node.req.url) } // Request url let url = ssrError?.url as string || islandContext?.url || event.node.req.url! // Whether we are rendering payload route const isRenderingPayload = PAYLOAD_URL_RE.test(url) && !islandContext if (isRenderingPayload) { url = url.substring(0, url.lastIndexOf('/')) || '/' event.node.req.url = url if (process.env.prerender && PAYLOAD_CACHE!.has(url)) { return PAYLOAD_CACHE!.get(url) } } // Get route options (currently to apply `ssr: false`) const routeOptions = getRouteRules(event) // Initialize ssr context const ssrContext: NuxtSSRContext = { url, event, runtimeConfig: useRuntimeConfig() as NuxtSSRContext['runtimeConfig'], noSSR: !!(process.env.NUXT_NO_SSR) || event.context.nuxt?.noSSR || routeOptions.ssr === false || (process.env.prerender ? PRERENDER_NO_SSR_ROUTES.has(url) : false), error: !!ssrError, nuxt: undefined!, /* NuxtApp */ payload: (ssrError ? { error: ssrError } : {}) as NuxtPayload, _payloadReducers: {}, islandContext } // Whether we are prerendering route const _PAYLOAD_EXTRACTION = process.env.prerender && process.env.NUXT_PAYLOAD_EXTRACTION && !ssrContext.noSSR && !islandContext const payloadURL = _PAYLOAD_EXTRACTION ? joinURL(useRuntimeConfig().app.baseURL, url, process.env.NUXT_JSON_PAYLOADS ? '_payload.json' : '_payload.js') : undefined if (process.env.prerender) { ssrContext.payload.prerenderedAt = Date.now() } // Render app const renderer = (process.env.NUXT_NO_SSR || ssrContext.noSSR) ? await getSPARenderer() : await getSSRRenderer() // Render 103 Early Hints if (process.env.NUXT_EARLY_HINTS && !isRenderingPayload && !process.env.prerender) { const { link } = renderResourceHeaders({}, renderer.rendererContext) writeEarlyHints(event, link) } const _rendered = await renderer.renderToString(ssrContext).catch(async (error) => { // We use error to bypass full render if we have an early response we can make if (ssrContext._renderResponse && error.message === 'skipping render') { return {} as ReturnType<typeof renderer['renderToString']> } // Use explicitly thrown error in preference to subsequent rendering errors const _err = (!ssrError && ssrContext.payload?.error) || error await ssrContext.nuxt?.hooks.callHook('app:error', _err) throw _err }) await ssrContext.nuxt?.hooks.callHook('app:rendered', { ssrContext, renderResult: _rendered }) if (ssrContext._renderResponse) { return ssrContext._renderResponse } // Handle errors if (ssrContext.payload?.error && !ssrError) { throw ssrContext.payload.error } // Directly render payload routes if (isRenderingPayload) { const response = renderPayloadResponse(ssrContext) if (process.env.prerender) { PAYLOAD_CACHE!.set(url, response) } return response } if (_PAYLOAD_EXTRACTION) { // Hint nitro to prerender payload for this route appendResponseHeader(event, 'x-nitro-prerender', joinURL(url, process.env.NUXT_JSON_PAYLOADS ? '_payload.json' : '_payload.js')) // Use same ssr context to generate payload for this route PAYLOAD_CACHE!.set(withoutTrailingSlash(url), renderPayloadResponse(ssrContext)) } // Render meta const renderedMeta = await ssrContext.renderMeta?.() ?? {} if (process.env.NUXT_INLINE_STYLES && !islandContext) { const entryId = await getEntryId() if (ssrContext.modules) { ssrContext.modules.add(entryId) } else if (ssrContext._registeredComponents) { ssrContext._registeredComponents.add(entryId) } } // Render inline styles const inlinedStyles = (process.env.NUXT_INLINE_STYLES || Boolean(islandContext)) ? await renderInlineStyles(ssrContext.modules ?? ssrContext._registeredComponents ?? []) : '' const NO_SCRIPTS = process.env.NUXT_NO_SCRIPTS || routeOptions.experimentalNoScripts // Create render context const htmlContext: NuxtRenderHTMLContext = { island: Boolean(islandContext), htmlAttrs: normalizeChunks([renderedMeta.htmlAttrs]), head: normalizeChunks([ renderedMeta.headTags, process.env.NUXT_JSON_PAYLOADS ? _PAYLOAD_EXTRACTION ? `<link rel="preload" as="fetch" crossorigin="anonymous" href="${payloadURL}">` : null : _PAYLOAD_EXTRACTION ? `<link rel="modulepreload" href="${payloadURL}">` : null, NO_SCRIPTS ? null : _rendered.renderResourceHints(), _rendered.renderStyles(), inlinedStyles, ssrContext.styles ]), bodyAttrs: normalizeChunks([renderedMeta.bodyAttrs!]), bodyPrepend: normalizeChunks([ renderedMeta.bodyScriptsPrepend, ssrContext.teleports?.body ]), body: [process.env.NUXT_COMPONENT_ISLANDS ? replaceServerOnlyComponentsSlots(ssrContext, _rendered.html) : _rendered.html], bodyAppend: normalizeChunks([ NO_SCRIPTS ? undefined : (_PAYLOAD_EXTRACTION ? process.env.NUXT_JSON_PAYLOADS ? renderPayloadJsonScript({ id: '__NUXT_DATA__', ssrContext, data: splitPayload(ssrContext).initial, src: payloadURL }) : renderPayloadScript({ ssrContext, data: splitPayload(ssrContext).initial, src: payloadURL }) : process.env.NUXT_JSON_PAYLOADS ? renderPayloadJsonScript({ id: '__NUXT_DATA__', ssrContext, data: ssrContext.payload }) : renderPayloadScript({ ssrContext, data: ssrContext.payload }) ), routeOptions.experimentalNoScripts ? undefined : _rendered.renderScripts(), // Note: bodyScripts may contain tags other than <script> renderedMeta.bodyScripts ]) } // Allow hooking into the rendered result await nitroApp.hooks.callHook('render:html', htmlContext, { event }) // Response for component islands if (process.env.NUXT_COMPONENT_ISLANDS && islandContext) { const _tags = htmlContext.head.flatMap(head => extractHTMLTags(head)) const head: NuxtIslandResponse['head'] = { link: _tags.filter(tag => tag.tagName === 'link' && tag.attrs.rel === 'stylesheet' && tag.attrs.href.includes('scoped') && !tag.attrs.href.includes('pages/')).map(tag => ({ key: 'island-link-' + hash(tag.attrs.href), ...tag.attrs })), style: _tags.filter(tag => tag.tagName === 'style' && tag.innerHTML).map(tag => ({ key: 'island-style-' + hash(tag.innerHTML), innerHTML: tag.innerHTML })) } const islandResponse: NuxtIslandResponse = { id: islandContext.id, head, html: getServerComponentHTML(htmlContext.body), state: ssrContext.payload.state } await nitroApp.hooks.callHook('render:island', islandResponse, { event, islandContext }) const response = { body: JSON.stringify(islandResponse, null, 2), statusCode: event.node.res.statusCode, statusMessage: event.node.res.statusMessage, headers: { 'content-type': 'application/json;charset=utf-8', 'x-powered-by': 'Nuxt' } } satisfies RenderResponse if (process.env.prerender) { ISLAND_CACHE!.set(`/__nuxt_island/${islandContext!.name}_${islandContext!.id}`, response) } return response } // Construct HTML response const response = { body: renderHTMLDocument(htmlContext), statusCode: event.node.res.statusCode, statusMessage: event.node.res.statusMessage, headers: { 'content-type': 'text/html;charset=utf-8', 'x-powered-by': 'Nuxt' } } satisfies RenderResponse return response }) function lazyCachedFunction<T> (fn: () => Promise<T>): () => Promise<T> { let res: Promise<T> | null = null return () => { if (res === null) { res = fn().catch((err) => { res = null; throw err }) } return res } } function normalizeChunks (chunks: (string | undefined)[]) { return chunks.filter(Boolean).map(i => i!.trim()) } function joinTags (tags: string[]) { return tags.join('') } function joinAttrs (chunks: string[]) { return chunks.join(' ') } function renderHTMLDocument (html: NuxtRenderHTMLContext) { return `<!DOCTYPE html> <html ${joinAttrs(html.htmlAttrs)}> <head>${joinTags(html.head)}</head> <body ${joinAttrs(html.bodyAttrs)}>${joinTags(html.bodyPrepend)}${joinTags(html.body)}${joinTags(html.bodyAppend)}</body> </html>` } // TODO: Move to external library const HTML_TAG_RE = /<(?<tag>[a-z]+)(?<rawAttrs> [^>]*)?>(?:(?<innerHTML>[\s\S]*?)<\/\k<tag>)?/g const HTML_TAG_ATTR_RE = /(?<name>[a-z]+)="(?<value>[^"]*)"/g function extractHTMLTags (html: string) { const tags: { tagName: string, attrs: Record<string, string>, innerHTML: string }[] = [] for (const tagMatch of html.matchAll(HTML_TAG_RE)) { const attrs: Record<string, string> = {} for (const attrMatch of tagMatch.groups!.rawAttrs?.matchAll(HTML_TAG_ATTR_RE) || []) { attrs[attrMatch.groups!.name] = attrMatch.groups!.value } const innerHTML = tagMatch.groups!.innerHTML || '' tags.push({ tagName: tagMatch.groups!.tag, attrs, innerHTML }) } return tags } async function renderInlineStyles (usedModules: Set<string> | string[]) { const styleMap = await getSSRStyles() const inlinedStyles = new Set<string>() for (const mod of usedModules) { if (mod in styleMap) { for (const style of await styleMap[mod]()) { inlinedStyles.add(`<style>${style}</style>`) } } } return Array.from(inlinedStyles).join('') } function renderPayloadResponse (ssrContext: NuxtSSRContext) { return { body: process.env.NUXT_JSON_PAYLOADS ? stringify(splitPayload(ssrContext).payload, ssrContext._payloadReducers) : `export default ${devalue(splitPayload(ssrContext).payload)}`, statusCode: ssrContext.event.node.res.statusCode, statusMessage: ssrContext.event.node.res.statusMessage, headers: { 'content-type': process.env.NUXT_JSON_PAYLOADS ? 'application/json;charset=utf-8' : 'text/javascript;charset=utf-8', 'x-powered-by': 'Nuxt' } } satisfies RenderResponse } function renderPayloadJsonScript (opts: { id: string, ssrContext: NuxtSSRContext, data?: any, src?: string }) { const attrs = [ 'type="application/json"', `id="${opts.id}"`, `data-ssr="${!(process.env.NUXT_NO_SSR || opts.ssrContext.noSSR)}"`, opts.src ? `data-src="${opts.src}"` : '' ].filter(Boolean) const contents = opts.data ? stringify(opts.data, opts.ssrContext._payloadReducers) : '' return `<script ${attrs.join(' ')}>${contents}</script>` + `<script>window.__NUXT__={};window.__NUXT__.config=${uneval(opts.ssrContext.config)}</script>` } function renderPayloadScript (opts: { ssrContext: NuxtSSRContext, data?: any, src?: string }) { opts.data.config = opts.ssrContext.config const _PAYLOAD_EXTRACTION = process.env.prerender && process.env.NUXT_PAYLOAD_EXTRACTION && !opts.ssrContext.noSSR if (_PAYLOAD_EXTRACTION) { return `<script type="module">import p from "${opts.src}";window.__NUXT__={...p,...(${devalue(opts.data)})}</script>` } return `<script>window.__NUXT__=${devalue(opts.data)}</script>` } function splitPayload (ssrContext: NuxtSSRContext) { const { data, prerenderedAt, ...initial } = ssrContext.payload return { initial: { ...initial, prerenderedAt }, payload: { data, prerenderedAt } } } /** * remove the root node from the html body */ function getServerComponentHTML (body: string[]): string { const match = body[0].match(ROOT_NODE_REGEX) return match ? match[1] : body[0] } const SSR_TELEPORT_MARKER = /^uid=([^;]*);slot=(.*)$/ function replaceServerOnlyComponentsSlots (ssrContext: NuxtSSRContext, html: string): string { const { teleports, islandContext } = ssrContext if (islandContext || !teleports) { return html } for (const key in teleports) { const match = key.match(SSR_TELEPORT_MARKER) if (!match) { continue } const [, uid, slot] = match if (!uid || !slot) { continue } html = html.replace(new RegExp(`<div nuxt-ssr-component-uid="${uid}"[^>]*>((?!nuxt-ssr-slot-name="${slot}"|nuxt-ssr-component-uid)[\\s\\S])*<div [^>]*nuxt-ssr-slot-name="${slot}"[^>]*>`), (full) => { return full + teleports[key] }) } return html }
packages/nuxt/src/core/runtime/nitro/renderer.ts
1
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.9989719390869141, 0.11628346145153046, 0.00016306072939187288, 0.0009127538069151342, 0.31468892097473145 ]
{ "id": 1, "code_window": [ " const renderedMeta = await ssrContext.renderMeta?.() ?? {}\n", "\n", " if (process.env.NUXT_INLINE_STYLES && !islandContext) {\n", " const entryId = await getEntryId()\n", " if (ssrContext.modules) {\n", " ssrContext.modules.add(entryId)\n", " } else if (ssrContext._registeredComponents) {\n", " ssrContext._registeredComponents.add(entryId)\n", " }\n", " }\n", "\n", " // Render inline styles\n", " const inlinedStyles = (process.env.NUXT_INLINE_STYLES || Boolean(islandContext))\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const source = ssrContext.modules ?? ssrContext._registeredComponents\n", " if (source) {\n", " for (const id of await getEntryIds()) {\n", " source.add(id)\n", " }\n" ], "file_path": "packages/nuxt/src/core/runtime/nitro/renderer.ts", "type": "replace", "edit_start_line_idx": 291 }
export default defineNuxtRouteMiddleware(async () => { await new Promise(resolve => setTimeout(resolve, 1)) useNuxtApp() })
test/fixtures/basic-types/modules/runtime/middleware.ts
0
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.00016265867452602834, 0.00016265867452602834, 0.00016265867452602834, 0.00016265867452602834, 0 ]
{ "id": 1, "code_window": [ " const renderedMeta = await ssrContext.renderMeta?.() ?? {}\n", "\n", " if (process.env.NUXT_INLINE_STYLES && !islandContext) {\n", " const entryId = await getEntryId()\n", " if (ssrContext.modules) {\n", " ssrContext.modules.add(entryId)\n", " } else if (ssrContext._registeredComponents) {\n", " ssrContext._registeredComponents.add(entryId)\n", " }\n", " }\n", "\n", " // Render inline styles\n", " const inlinedStyles = (process.env.NUXT_INLINE_STYLES || Boolean(islandContext))\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const source = ssrContext.modules ?? ssrContext._registeredComponents\n", " if (source) {\n", " for (const id of await getEntryIds()) {\n", " source.add(id)\n", " }\n" ], "file_path": "packages/nuxt/src/core/runtime/nitro/renderer.ts", "type": "replace", "edit_start_line_idx": 291 }
export default defineNuxtRouteMiddleware((to) => { to.meta.override = 'This middleware should be overriden by bar' })
test/fixtures/basic-types/extends/node_modules/foo/middleware/override.ts
0
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.0002780765644274652, 0.0002780765644274652, 0.0002780765644274652, 0.0002780765644274652, 0 ]
{ "id": 1, "code_window": [ " const renderedMeta = await ssrContext.renderMeta?.() ?? {}\n", "\n", " if (process.env.NUXT_INLINE_STYLES && !islandContext) {\n", " const entryId = await getEntryId()\n", " if (ssrContext.modules) {\n", " ssrContext.modules.add(entryId)\n", " } else if (ssrContext._registeredComponents) {\n", " ssrContext._registeredComponents.add(entryId)\n", " }\n", " }\n", "\n", " // Render inline styles\n", " const inlinedStyles = (process.env.NUXT_INLINE_STYLES || Boolean(islandContext))\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "replace", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const source = ssrContext.modules ?? ssrContext._registeredComponents\n", " if (source) {\n", " for (const id of await getEntryIds()) {\n", " source.add(id)\n", " }\n" ], "file_path": "packages/nuxt/src/core/runtime/nitro/renderer.ts", "type": "replace", "edit_start_line_idx": 291 }
<template> <div> Single <div> {{ data }} - {{ data2 }} </div> </div> </template> <script setup lang="ts"> const { data, refresh } = await useCounter() const { data: data2, refresh: refresh2 } = await useCounter() let initial = data.value!.count // Refresh on client and server side await refresh() if (data.value!.count !== initial + 1) { throw new Error('Data not refreshed?' + data.value!.count + ' : ' + data2.value!.count) } if (data.value!.count !== data2.value!.count) { throw new Error('AsyncData not synchronised') } initial = data.value!.count await refresh2() if (data.value!.count !== initial + 1) { throw new Error('data2 refresh not syncronised?') } if (data.value!.count !== data2.value!.count) { throw new Error('AsyncData not synchronised') } </script>
test/fixtures/basic/pages/useAsyncData/refresh.vue
0
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.00017235070117749274, 0.00016820614109747112, 0.00016084997332654893, 0.00016981197404675186, 0.000004546946911432315 ]
{ "id": 2, "code_window": [ " ctx.nuxt.hook('build:manifest', (manifest) => {\n", " for (const key in manifest) {\n", " const entry = manifest[key]\n", " const shouldRemoveCSS = chunksWithInlinedCSS.has(key) && !entry.isEntry\n", " if (shouldRemoveCSS && entry.css) {\n", " entry.css = []\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (entry.isEntry && chunksWithInlinedCSS.has(key)) {\n", " // @ts-expect-error internal key\n", " entry._globalCSS = true\n", " }\n" ], "file_path": "packages/vite/src/vite.ts", "type": "add", "edit_start_line_idx": 168 }
import { createRenderer, renderResourceHeaders } from 'vue-bundle-renderer/runtime' import type { RenderResponse } from 'nitropack' import type { Manifest } from 'vite' import type { H3Event } from 'h3' import { appendResponseHeader, createError, getQuery, readBody, writeEarlyHints } from 'h3' import devalue from '@nuxt/devalue' import { stringify, uneval } from 'devalue' import destr from 'destr' import { joinURL, withoutTrailingSlash } from 'ufo' import { renderToString as _renderToString } from 'vue/server-renderer' import { hash } from 'ohash' import { defineRenderHandler, getRouteRules, useRuntimeConfig } from '#internal/nitro' import { useNitroApp } from '#internal/nitro/app' // eslint-disable-next-line import/no-restricted-paths import type { NuxtPayload, NuxtSSRContext } from '#app/nuxt' // @ts-expect-error virtual file import { appRootId, appRootTag } from '#internal/nuxt.config.mjs' // @ts-expect-error virtual file import { buildAssetsURL, publicAssetsURL } from '#paths' // @ts-expect-error private property consumed by vite-generated url helpers globalThis.__buildAssetsURL = buildAssetsURL // @ts-expect-error private property consumed by vite-generated url helpers globalThis.__publicAssetsURL = publicAssetsURL export interface NuxtRenderHTMLContext { island?: boolean htmlAttrs: string[] head: string[] bodyAttrs: string[] bodyPrepend: string[] body: string[] bodyAppend: string[] } export interface NuxtIslandContext { id?: string name: string props?: Record<string, any> url?: string } export interface NuxtIslandResponse { id?: string html: string state: Record<string, any> head: { link: (Record<string, string>)[] style: ({ innerHTML: string, key: string })[] } } export interface NuxtRenderResponse { body: string, statusCode: number, statusMessage?: string, headers: Record<string, string> } interface ClientManifest {} // @ts-expect-error file will be produced after app build const getClientManifest: () => Promise<Manifest> = () => import('#build/dist/server/client.manifest.mjs') .then(r => r.default || r) .then(r => typeof r === 'function' ? r() : r) as Promise<ClientManifest> const getEntryId: () => Promise<string> = () => getClientManifest().then(r => Object.values(r).find(r => r.isEntry)!.src!) // @ts-expect-error virtual file const getStaticRenderedHead = (): Promise<NuxtMeta> => import('#head-static').then(r => r.default || r) // @ts-expect-error file will be produced after app build const getServerEntry = () => import('#build/dist/server/server.mjs').then(r => r.default || r) // @ts-expect-error file will be produced after app build const getSSRStyles = lazyCachedFunction((): Promise<Record<string, () => Promise<string[]>>> => import('#build/dist/server/styles.mjs').then(r => r.default || r)) // -- SSR Renderer -- const getSSRRenderer = lazyCachedFunction(async () => { // Load client manifest const manifest = await getClientManifest() if (!manifest) { throw new Error('client.manifest is not available') } // Load server bundle const createSSRApp = await getServerEntry() if (!createSSRApp) { throw new Error('Server bundle is not available') } const options = { manifest, renderToString, buildAssetsURL } // Create renderer const renderer = createRenderer(createSSRApp, options) type RenderToStringParams = Parameters<typeof _renderToString> async function renderToString (input: RenderToStringParams[0], context: RenderToStringParams[1]) { const html = await _renderToString(input, context) // In development with vite-node, the manifest is on-demand and will be available after rendering if (process.dev && process.env.NUXT_VITE_NODE_OPTIONS) { renderer.rendererContext.updateManifest(await getClientManifest()) } return `<${appRootTag} id="${appRootId}">${html}</${appRootTag}>` } return renderer }) // -- SPA Renderer -- const getSPARenderer = lazyCachedFunction(async () => { const manifest = await getClientManifest() // @ts-expect-error virtual file const spaTemplate = await import('#spa-template').then(r => r.template).catch(() => '') const options = { manifest, renderToString: () => `<${appRootTag} id="${appRootId}">${spaTemplate}</${appRootTag}>`, buildAssetsURL } // Create SPA renderer and cache the result for all requests const renderer = createRenderer(() => () => {}, options) const result = await renderer.renderToString({}) const renderToString = (ssrContext: NuxtSSRContext) => { const config = useRuntimeConfig() ssrContext.modules = ssrContext.modules || new Set<string>() ssrContext!.payload = { _errors: {}, serverRendered: false, data: {}, state: {} } ssrContext.config = { public: config.public, app: config.app } ssrContext!.renderMeta = ssrContext!.renderMeta ?? getStaticRenderedHead return Promise.resolve(result) } return { rendererContext: renderer.rendererContext, renderToString } }) async function getIslandContext (event: H3Event): Promise<NuxtIslandContext> { // TODO: Strict validation for url const url = event.node.req.url?.substring('/__nuxt_island'.length + 1) || '' const [componentName, hashId] = url.split('?')[0].split('_') // TODO: Validate context const context = event.node.req.method === 'GET' ? getQuery(event) : await readBody(event) const ctx: NuxtIslandContext = { url: '/', ...context, id: hashId, name: componentName, props: destr(context.props) || {}, uid: destr(context.uid) || undefined } return ctx } const PAYLOAD_CACHE = (process.env.NUXT_PAYLOAD_EXTRACTION && process.env.prerender) ? new Map() : null // TODO: Use LRU cache const ISLAND_CACHE = (process.env.NUXT_COMPONENT_ISLANDS && process.env.prerender) ? new Map() : null // TODO: Use LRU cache const PAYLOAD_URL_RE = process.env.NUXT_JSON_PAYLOADS ? /\/_payload(\.[a-zA-Z0-9]+)?.json(\?.*)?$/ : /\/_payload(\.[a-zA-Z0-9]+)?.js(\?.*)?$/ const ROOT_NODE_REGEX = new RegExp(`^<${appRootTag} id="${appRootId}">([\\s\\S]*)</${appRootTag}>$`) const PRERENDER_NO_SSR_ROUTES = new Set(['/index.html', '/200.html', '/404.html']) export default defineRenderHandler(async (event): Promise<Partial<RenderResponse>> => { const nitroApp = useNitroApp() // Whether we're rendering an error page const ssrError = event.node.req.url?.startsWith('/__nuxt_error') ? getQuery(event) as unknown as Exclude<NuxtPayload['error'], Error> : null if (ssrError && ssrError.statusCode) { ssrError.statusCode = parseInt(ssrError.statusCode as any) } if (ssrError && event.node.req.socket.readyState !== 'readOnly' /* direct request */) { throw createError({ statusCode: 404, statusMessage: 'Page Not Found: /__nuxt_error' }) } // Check for island component rendering const islandContext = (process.env.NUXT_COMPONENT_ISLANDS && event.node.req.url?.startsWith('/__nuxt_island')) ? await getIslandContext(event) : undefined if (process.env.prerender && islandContext && ISLAND_CACHE!.has(event.node.req.url)) { return ISLAND_CACHE!.get(event.node.req.url) } // Request url let url = ssrError?.url as string || islandContext?.url || event.node.req.url! // Whether we are rendering payload route const isRenderingPayload = PAYLOAD_URL_RE.test(url) && !islandContext if (isRenderingPayload) { url = url.substring(0, url.lastIndexOf('/')) || '/' event.node.req.url = url if (process.env.prerender && PAYLOAD_CACHE!.has(url)) { return PAYLOAD_CACHE!.get(url) } } // Get route options (currently to apply `ssr: false`) const routeOptions = getRouteRules(event) // Initialize ssr context const ssrContext: NuxtSSRContext = { url, event, runtimeConfig: useRuntimeConfig() as NuxtSSRContext['runtimeConfig'], noSSR: !!(process.env.NUXT_NO_SSR) || event.context.nuxt?.noSSR || routeOptions.ssr === false || (process.env.prerender ? PRERENDER_NO_SSR_ROUTES.has(url) : false), error: !!ssrError, nuxt: undefined!, /* NuxtApp */ payload: (ssrError ? { error: ssrError } : {}) as NuxtPayload, _payloadReducers: {}, islandContext } // Whether we are prerendering route const _PAYLOAD_EXTRACTION = process.env.prerender && process.env.NUXT_PAYLOAD_EXTRACTION && !ssrContext.noSSR && !islandContext const payloadURL = _PAYLOAD_EXTRACTION ? joinURL(useRuntimeConfig().app.baseURL, url, process.env.NUXT_JSON_PAYLOADS ? '_payload.json' : '_payload.js') : undefined if (process.env.prerender) { ssrContext.payload.prerenderedAt = Date.now() } // Render app const renderer = (process.env.NUXT_NO_SSR || ssrContext.noSSR) ? await getSPARenderer() : await getSSRRenderer() // Render 103 Early Hints if (process.env.NUXT_EARLY_HINTS && !isRenderingPayload && !process.env.prerender) { const { link } = renderResourceHeaders({}, renderer.rendererContext) writeEarlyHints(event, link) } const _rendered = await renderer.renderToString(ssrContext).catch(async (error) => { // We use error to bypass full render if we have an early response we can make if (ssrContext._renderResponse && error.message === 'skipping render') { return {} as ReturnType<typeof renderer['renderToString']> } // Use explicitly thrown error in preference to subsequent rendering errors const _err = (!ssrError && ssrContext.payload?.error) || error await ssrContext.nuxt?.hooks.callHook('app:error', _err) throw _err }) await ssrContext.nuxt?.hooks.callHook('app:rendered', { ssrContext, renderResult: _rendered }) if (ssrContext._renderResponse) { return ssrContext._renderResponse } // Handle errors if (ssrContext.payload?.error && !ssrError) { throw ssrContext.payload.error } // Directly render payload routes if (isRenderingPayload) { const response = renderPayloadResponse(ssrContext) if (process.env.prerender) { PAYLOAD_CACHE!.set(url, response) } return response } if (_PAYLOAD_EXTRACTION) { // Hint nitro to prerender payload for this route appendResponseHeader(event, 'x-nitro-prerender', joinURL(url, process.env.NUXT_JSON_PAYLOADS ? '_payload.json' : '_payload.js')) // Use same ssr context to generate payload for this route PAYLOAD_CACHE!.set(withoutTrailingSlash(url), renderPayloadResponse(ssrContext)) } // Render meta const renderedMeta = await ssrContext.renderMeta?.() ?? {} if (process.env.NUXT_INLINE_STYLES && !islandContext) { const entryId = await getEntryId() if (ssrContext.modules) { ssrContext.modules.add(entryId) } else if (ssrContext._registeredComponents) { ssrContext._registeredComponents.add(entryId) } } // Render inline styles const inlinedStyles = (process.env.NUXT_INLINE_STYLES || Boolean(islandContext)) ? await renderInlineStyles(ssrContext.modules ?? ssrContext._registeredComponents ?? []) : '' const NO_SCRIPTS = process.env.NUXT_NO_SCRIPTS || routeOptions.experimentalNoScripts // Create render context const htmlContext: NuxtRenderHTMLContext = { island: Boolean(islandContext), htmlAttrs: normalizeChunks([renderedMeta.htmlAttrs]), head: normalizeChunks([ renderedMeta.headTags, process.env.NUXT_JSON_PAYLOADS ? _PAYLOAD_EXTRACTION ? `<link rel="preload" as="fetch" crossorigin="anonymous" href="${payloadURL}">` : null : _PAYLOAD_EXTRACTION ? `<link rel="modulepreload" href="${payloadURL}">` : null, NO_SCRIPTS ? null : _rendered.renderResourceHints(), _rendered.renderStyles(), inlinedStyles, ssrContext.styles ]), bodyAttrs: normalizeChunks([renderedMeta.bodyAttrs!]), bodyPrepend: normalizeChunks([ renderedMeta.bodyScriptsPrepend, ssrContext.teleports?.body ]), body: [process.env.NUXT_COMPONENT_ISLANDS ? replaceServerOnlyComponentsSlots(ssrContext, _rendered.html) : _rendered.html], bodyAppend: normalizeChunks([ NO_SCRIPTS ? undefined : (_PAYLOAD_EXTRACTION ? process.env.NUXT_JSON_PAYLOADS ? renderPayloadJsonScript({ id: '__NUXT_DATA__', ssrContext, data: splitPayload(ssrContext).initial, src: payloadURL }) : renderPayloadScript({ ssrContext, data: splitPayload(ssrContext).initial, src: payloadURL }) : process.env.NUXT_JSON_PAYLOADS ? renderPayloadJsonScript({ id: '__NUXT_DATA__', ssrContext, data: ssrContext.payload }) : renderPayloadScript({ ssrContext, data: ssrContext.payload }) ), routeOptions.experimentalNoScripts ? undefined : _rendered.renderScripts(), // Note: bodyScripts may contain tags other than <script> renderedMeta.bodyScripts ]) } // Allow hooking into the rendered result await nitroApp.hooks.callHook('render:html', htmlContext, { event }) // Response for component islands if (process.env.NUXT_COMPONENT_ISLANDS && islandContext) { const _tags = htmlContext.head.flatMap(head => extractHTMLTags(head)) const head: NuxtIslandResponse['head'] = { link: _tags.filter(tag => tag.tagName === 'link' && tag.attrs.rel === 'stylesheet' && tag.attrs.href.includes('scoped') && !tag.attrs.href.includes('pages/')).map(tag => ({ key: 'island-link-' + hash(tag.attrs.href), ...tag.attrs })), style: _tags.filter(tag => tag.tagName === 'style' && tag.innerHTML).map(tag => ({ key: 'island-style-' + hash(tag.innerHTML), innerHTML: tag.innerHTML })) } const islandResponse: NuxtIslandResponse = { id: islandContext.id, head, html: getServerComponentHTML(htmlContext.body), state: ssrContext.payload.state } await nitroApp.hooks.callHook('render:island', islandResponse, { event, islandContext }) const response = { body: JSON.stringify(islandResponse, null, 2), statusCode: event.node.res.statusCode, statusMessage: event.node.res.statusMessage, headers: { 'content-type': 'application/json;charset=utf-8', 'x-powered-by': 'Nuxt' } } satisfies RenderResponse if (process.env.prerender) { ISLAND_CACHE!.set(`/__nuxt_island/${islandContext!.name}_${islandContext!.id}`, response) } return response } // Construct HTML response const response = { body: renderHTMLDocument(htmlContext), statusCode: event.node.res.statusCode, statusMessage: event.node.res.statusMessage, headers: { 'content-type': 'text/html;charset=utf-8', 'x-powered-by': 'Nuxt' } } satisfies RenderResponse return response }) function lazyCachedFunction<T> (fn: () => Promise<T>): () => Promise<T> { let res: Promise<T> | null = null return () => { if (res === null) { res = fn().catch((err) => { res = null; throw err }) } return res } } function normalizeChunks (chunks: (string | undefined)[]) { return chunks.filter(Boolean).map(i => i!.trim()) } function joinTags (tags: string[]) { return tags.join('') } function joinAttrs (chunks: string[]) { return chunks.join(' ') } function renderHTMLDocument (html: NuxtRenderHTMLContext) { return `<!DOCTYPE html> <html ${joinAttrs(html.htmlAttrs)}> <head>${joinTags(html.head)}</head> <body ${joinAttrs(html.bodyAttrs)}>${joinTags(html.bodyPrepend)}${joinTags(html.body)}${joinTags(html.bodyAppend)}</body> </html>` } // TODO: Move to external library const HTML_TAG_RE = /<(?<tag>[a-z]+)(?<rawAttrs> [^>]*)?>(?:(?<innerHTML>[\s\S]*?)<\/\k<tag>)?/g const HTML_TAG_ATTR_RE = /(?<name>[a-z]+)="(?<value>[^"]*)"/g function extractHTMLTags (html: string) { const tags: { tagName: string, attrs: Record<string, string>, innerHTML: string }[] = [] for (const tagMatch of html.matchAll(HTML_TAG_RE)) { const attrs: Record<string, string> = {} for (const attrMatch of tagMatch.groups!.rawAttrs?.matchAll(HTML_TAG_ATTR_RE) || []) { attrs[attrMatch.groups!.name] = attrMatch.groups!.value } const innerHTML = tagMatch.groups!.innerHTML || '' tags.push({ tagName: tagMatch.groups!.tag, attrs, innerHTML }) } return tags } async function renderInlineStyles (usedModules: Set<string> | string[]) { const styleMap = await getSSRStyles() const inlinedStyles = new Set<string>() for (const mod of usedModules) { if (mod in styleMap) { for (const style of await styleMap[mod]()) { inlinedStyles.add(`<style>${style}</style>`) } } } return Array.from(inlinedStyles).join('') } function renderPayloadResponse (ssrContext: NuxtSSRContext) { return { body: process.env.NUXT_JSON_PAYLOADS ? stringify(splitPayload(ssrContext).payload, ssrContext._payloadReducers) : `export default ${devalue(splitPayload(ssrContext).payload)}`, statusCode: ssrContext.event.node.res.statusCode, statusMessage: ssrContext.event.node.res.statusMessage, headers: { 'content-type': process.env.NUXT_JSON_PAYLOADS ? 'application/json;charset=utf-8' : 'text/javascript;charset=utf-8', 'x-powered-by': 'Nuxt' } } satisfies RenderResponse } function renderPayloadJsonScript (opts: { id: string, ssrContext: NuxtSSRContext, data?: any, src?: string }) { const attrs = [ 'type="application/json"', `id="${opts.id}"`, `data-ssr="${!(process.env.NUXT_NO_SSR || opts.ssrContext.noSSR)}"`, opts.src ? `data-src="${opts.src}"` : '' ].filter(Boolean) const contents = opts.data ? stringify(opts.data, opts.ssrContext._payloadReducers) : '' return `<script ${attrs.join(' ')}>${contents}</script>` + `<script>window.__NUXT__={};window.__NUXT__.config=${uneval(opts.ssrContext.config)}</script>` } function renderPayloadScript (opts: { ssrContext: NuxtSSRContext, data?: any, src?: string }) { opts.data.config = opts.ssrContext.config const _PAYLOAD_EXTRACTION = process.env.prerender && process.env.NUXT_PAYLOAD_EXTRACTION && !opts.ssrContext.noSSR if (_PAYLOAD_EXTRACTION) { return `<script type="module">import p from "${opts.src}";window.__NUXT__={...p,...(${devalue(opts.data)})}</script>` } return `<script>window.__NUXT__=${devalue(opts.data)}</script>` } function splitPayload (ssrContext: NuxtSSRContext) { const { data, prerenderedAt, ...initial } = ssrContext.payload return { initial: { ...initial, prerenderedAt }, payload: { data, prerenderedAt } } } /** * remove the root node from the html body */ function getServerComponentHTML (body: string[]): string { const match = body[0].match(ROOT_NODE_REGEX) return match ? match[1] : body[0] } const SSR_TELEPORT_MARKER = /^uid=([^;]*);slot=(.*)$/ function replaceServerOnlyComponentsSlots (ssrContext: NuxtSSRContext, html: string): string { const { teleports, islandContext } = ssrContext if (islandContext || !teleports) { return html } for (const key in teleports) { const match = key.match(SSR_TELEPORT_MARKER) if (!match) { continue } const [, uid, slot] = match if (!uid || !slot) { continue } html = html.replace(new RegExp(`<div nuxt-ssr-component-uid="${uid}"[^>]*>((?!nuxt-ssr-slot-name="${slot}"|nuxt-ssr-component-uid)[\\s\\S])*<div [^>]*nuxt-ssr-slot-name="${slot}"[^>]*>`), (full) => { return full + teleports[key] }) } return html }
packages/nuxt/src/core/runtime/nitro/renderer.ts
1
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.0029046169947832823, 0.00033579670707695186, 0.0001637862587813288, 0.000171421910636127, 0.0005031385808251798 ]
{ "id": 2, "code_window": [ " ctx.nuxt.hook('build:manifest', (manifest) => {\n", " for (const key in manifest) {\n", " const entry = manifest[key]\n", " const shouldRemoveCSS = chunksWithInlinedCSS.has(key) && !entry.isEntry\n", " if (shouldRemoveCSS && entry.css) {\n", " entry.css = []\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (entry.isEntry && chunksWithInlinedCSS.has(key)) {\n", " // @ts-expect-error internal key\n", " entry._globalCSS = true\n", " }\n" ], "file_path": "packages/vite/src/vite.ts", "type": "add", "edit_start_line_idx": 168 }
--- title: "useError" description: useError composable returns the global Nuxt error that is being handled. --- # `useError` `useError` composable returns the global Nuxt error that is being handled and it is available on both client and server. ```ts const error = useError() ``` `useError` sets an error in the state and creates a reactive as well as SSR-friendly global Nuxt error across components. Nuxt errors have the following properties: ## Properties - **statusCode** Type: `Number` HTTP response status code - **statusMessage** Type: `String` HTTP response status message - **message** Type: `String` Error message ::ReadMore{link="/docs/getting-started/error-handling"} ::
docs/3.api/1.composables/use-error.md
0
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.0002578851708676666, 0.00019089730631094426, 0.0001657279790379107, 0.00016998803766909987, 0.000038805752410553396 ]
{ "id": 2, "code_window": [ " ctx.nuxt.hook('build:manifest', (manifest) => {\n", " for (const key in manifest) {\n", " const entry = manifest[key]\n", " const shouldRemoveCSS = chunksWithInlinedCSS.has(key) && !entry.isEntry\n", " if (shouldRemoveCSS && entry.css) {\n", " entry.css = []\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (entry.isEntry && chunksWithInlinedCSS.has(key)) {\n", " // @ts-expect-error internal key\n", " entry._globalCSS = true\n", " }\n" ], "file_path": "packages/vite/src/vite.ts", "type": "add", "edit_start_line_idx": 168 }
<template> <div> global component (client-only) registered automatically </div> </template>
test/fixtures/basic/components/global/ClientGlobal.client.vue
0
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.00016976697952486575, 0.00016976697952486575, 0.00016976697952486575, 0.00016976697952486575, 0 ]
{ "id": 2, "code_window": [ " ctx.nuxt.hook('build:manifest', (manifest) => {\n", " for (const key in manifest) {\n", " const entry = manifest[key]\n", " const shouldRemoveCSS = chunksWithInlinedCSS.has(key) && !entry.isEntry\n", " if (shouldRemoveCSS && entry.css) {\n", " entry.css = []\n", " }\n", " }\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (entry.isEntry && chunksWithInlinedCSS.has(key)) {\n", " // @ts-expect-error internal key\n", " entry._globalCSS = true\n", " }\n" ], "file_path": "packages/vite/src/vite.ts", "type": "add", "edit_start_line_idx": 168 }
name: autofix.ci # needed to securely identify the workflow on: pull_request: paths-ignore: - "docs/**" permissions: contents: read jobs: code: runs-on: ubuntu-latest steps: - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 - run: corepack enable - uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c # v3.6.0 with: node-version: 20 cache: "pnpm" - name: Install dependencies run: pnpm install - name: Dedupe dependencies if: ${{ contains(github.head_ref, 'renovate') }} run: pnpm dedupe - name: Build (stub) run: pnpm build:stub - name: Lint (code) run: pnpm lint:fix - name: Test (unit) run: pnpm test:unit -u - name: Run build run: pnpm build - name: Update bundle size run: pnpm vitest run bundle -u - uses: autofix-ci/action@8bc06253bec489732e5f9c52884c7cace15c0160
.github/workflows/autofix.yml
0
https://github.com/nuxt/nuxt/commit/87e01ccf0e22c2e359d90e78a5fde66a656e930c
[ 0.00017845770344138145, 0.00017513128113932908, 0.00017064563871826977, 0.00017567187023814768, 0.0000025253932562918635 ]
{ "id": 0, "code_window": [ " `$computed can only be used as the initializer`\n", " )\n", " })\n", "})" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " test('not transform the prototype attributes', () => {\n", " const { code } = transform(`\n", " const hasOwnProperty = Object.prototype.hasOwnProperty\n", " const hasOwn = (val, key) => hasOwnProperty.call(val, key)\n", " `)\n", " expect(code).not.toMatch('.value')\n", " })\n" ], "file_path": "packages/ref-transform/__tests__/refTransform.spec.ts", "type": "add", "edit_start_line_idx": 397 }
import { Node, Identifier, BlockStatement, CallExpression, ObjectPattern, VariableDeclaration, ArrayPattern, Program, VariableDeclarator } from '@babel/types' import MagicString, { SourceMap } from 'magic-string' import { walk } from 'estree-walker' import { extractIdentifiers, isFunctionType, isInDestructureAssignment, isReferencedIdentifier, isStaticProperty, walkFunctionParams } from '@vue/compiler-core' import { parse, ParserPlugin } from '@babel/parser' import { babelParserDefaultPlugins } from '@vue/shared' const TO_VAR_SYMBOL = '$' const TO_REF_SYMBOL = '$$' const shorthands = ['ref', 'computed', 'shallowRef'] const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/ export function shouldTransform(src: string): boolean { return transformCheckRE.test(src) } type Scope = Record<string, boolean> export interface RefTransformOptions { filename?: string sourceMap?: boolean parserPlugins?: ParserPlugin[] importHelpersFrom?: string } export interface RefTransformResults { code: string map: SourceMap | null rootVars: string[] importedHelpers: string[] } export function transform( src: string, { filename, sourceMap, parserPlugins, importHelpersFrom = 'vue' }: RefTransformOptions = {} ): RefTransformResults { const plugins: ParserPlugin[] = parserPlugins || [] if (filename) { if (/\.tsx?$/.test(filename)) { plugins.push('typescript') } if (filename.endsWith('x')) { plugins.push('jsx') } } const ast = parse(src, { sourceType: 'module', plugins: [...new Set([...babelParserDefaultPlugins, ...plugins])] }) const s = new MagicString(src) const res = transformAST(ast.program, s) // inject helper imports if (res.importedHelpers.length) { s.prepend( `import { ${res.importedHelpers .map(h => `${h} as _${h}`) .join(', ')} } from '${importHelpersFrom}'\n` ) } return { ...res, code: s.toString(), map: sourceMap ? s.generateMap({ source: filename, hires: true, includeContent: true }) : null } } export function transformAST( ast: Program, s: MagicString, offset = 0, knownRootVars?: string[] ): { rootVars: string[] importedHelpers: string[] } { // TODO remove when out of experimental warnExperimental() const importedHelpers = new Set<string>() const rootScope: Scope = {} const scopeStack: Scope[] = [rootScope] let currentScope: Scope = rootScope const excludedIds = new WeakSet<Identifier>() const parentStack: Node[] = [] if (knownRootVars) { for (const key of knownRootVars) { rootScope[key] = true } } function error(msg: string, node: Node) { const e = new Error(msg) ;(e as any).node = node throw e } function helper(msg: string) { importedHelpers.add(msg) return `_${msg}` } function registerBinding(id: Identifier, isRef = false) { excludedIds.add(id) if (currentScope) { currentScope[id.name] = isRef } else { error( 'registerBinding called without active scope, something is wrong.', id ) } } const registerRefBinding = (id: Identifier) => registerBinding(id, true) function walkScope(node: Program | BlockStatement) { for (const stmt of node.body) { if (stmt.type === 'VariableDeclaration') { if (stmt.declare) continue for (const decl of stmt.declarations) { let toVarCall if ( decl.init && decl.init.type === 'CallExpression' && decl.init.callee.type === 'Identifier' && (toVarCall = isToVarCall(decl.init.callee.name)) ) { processRefDeclaration( toVarCall, decl.init as CallExpression, decl.id, stmt ) } else { for (const id of extractIdentifiers(decl.id)) { registerBinding(id) } } } } else if ( stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration' ) { if (stmt.declare || !stmt.id) continue registerBinding(stmt.id) } } } function processRefDeclaration( method: string, call: CallExpression, id: VariableDeclarator['id'], statement: VariableDeclaration ) { excludedIds.add(call.callee as Identifier) if (statement.kind !== 'let') { error(`${method}() bindings can only be declared with let`, call) } if (method === TO_VAR_SYMBOL) { // $ // remove macro s.remove(call.callee.start! + offset, call.callee.end! + offset) if (id.type === 'Identifier') { // single variable registerRefBinding(id) } else if (id.type === 'ObjectPattern') { processRefObjectPattern(id, statement) } else if (id.type === 'ArrayPattern') { processRefArrayPattern(id, statement) } } else { // shorthands if (id.type === 'Identifier') { registerRefBinding(id) // replace call s.overwrite( call.start! + offset, call.start! + method.length + offset, helper(method.slice(1)) ) } else { error(`${method}() cannot be used with destructure patterns.`, call) } } } function processRefObjectPattern( pattern: ObjectPattern, statement: VariableDeclaration ) { for (const p of pattern.properties) { let nameId: Identifier | undefined if (p.type === 'ObjectProperty') { if (p.key.start! === p.value.start!) { // shorthand { foo } --> { foo: __foo } nameId = p.key as Identifier s.appendLeft(nameId.end! + offset, `: __${nameId.name}`) if (p.value.type === 'Identifier') { // avoid shorthand value identifier from being processed excludedIds.add(p.value) } else if ( p.value.type === 'AssignmentPattern' && p.value.left.type === 'Identifier' ) { // { foo = 1 } excludedIds.add(p.value.left) } } else { if (p.value.type === 'Identifier') { // { foo: bar } --> { foo: __bar } nameId = p.value s.prependRight(nameId.start! + offset, `__`) } else if (p.value.type === 'ObjectPattern') { processRefObjectPattern(p.value, statement) } else if (p.value.type === 'ArrayPattern') { processRefArrayPattern(p.value, statement) } else if (p.value.type === 'AssignmentPattern') { // { foo: bar = 1 } --> { foo: __bar = 1 } nameId = p.value.left as Identifier s.prependRight(nameId.start! + offset, `__`) } } } else { // rest element { ...foo } --> { ...__foo } nameId = p.argument as Identifier s.prependRight(nameId.start! + offset, `__`) } if (nameId) { registerRefBinding(nameId) // append binding declarations after the parent statement s.appendLeft( statement.end! + offset, `\nconst ${nameId.name} = ${helper('shallowRef')}(__${nameId.name});` ) } } } function processRefArrayPattern( pattern: ArrayPattern, statement: VariableDeclaration ) { for (const e of pattern.elements) { if (!e) continue let nameId: Identifier | undefined if (e.type === 'Identifier') { // [a] --> [__a] nameId = e } else if (e.type === 'AssignmentPattern') { // [a = 1] --> [__a = 1] nameId = e.left as Identifier } else if (e.type === 'RestElement') { // [...a] --> [...__a] nameId = e.argument as Identifier } else if (e.type === 'ObjectPattern') { processRefObjectPattern(e, statement) } else if (e.type === 'ArrayPattern') { processRefArrayPattern(e, statement) } if (nameId) { registerRefBinding(nameId) // prefix original s.prependRight(nameId.start! + offset, `__`) // append binding declarations after the parent statement s.appendLeft( statement.end! + offset, `\nconst ${nameId.name} = ${helper('shallowRef')}(__${nameId.name});` ) } } } function checkRefId( scope: Scope, id: Identifier, parent: Node, parentStack: Node[] ): boolean { if (id.name in scope) { if (scope[id.name]) { if (isStaticProperty(parent) && parent.shorthand) { // let binding used in a property shorthand // { foo } -> { foo: foo.value } // skip for destructure patterns if ( !(parent as any).inPattern || isInDestructureAssignment(parent, parentStack) ) { s.appendLeft(id.end! + offset, `: ${id.name}.value`) } } else { s.appendLeft(id.end! + offset, '.value') } } return true } return false } // check root scope first walkScope(ast) ;(walk as any)(ast, { enter(node: Node, parent?: Node) { parent && parentStack.push(parent) // function scopes if (isFunctionType(node)) { scopeStack.push((currentScope = {})) walkFunctionParams(node, registerBinding) if (node.body.type === 'BlockStatement') { walkScope(node.body) } return } // non-function block scopes if (node.type === 'BlockStatement' && !isFunctionType(parent!)) { scopeStack.push((currentScope = {})) walkScope(node) return } if ( parent && parent.type.startsWith('TS') && parent.type !== 'TSAsExpression' && parent.type !== 'TSNonNullExpression' && parent.type !== 'TSTypeAssertion' ) { return this.skip() } if ( node.type === 'Identifier' && isReferencedIdentifier(node, parent!, parentStack) && !excludedIds.has(node) ) { // walk up the scope chain to check if id should be appended .value let i = scopeStack.length while (i--) { if (checkRefId(scopeStack[i], node, parent!, parentStack)) { return } } } if (node.type === 'CallExpression' && node.callee.type === 'Identifier') { const callee = node.callee.name const toVarCall = isToVarCall(callee) if (toVarCall && (!parent || parent.type !== 'VariableDeclarator')) { return error( `${toVarCall} can only be used as the initializer of ` + `a variable declaration.`, node ) } if (callee === TO_REF_SYMBOL) { s.remove(node.callee.start! + offset, node.callee.end! + offset) return this.skip() } // TODO remove when out of experimental if (callee === '$raw') { error( `$raw() has been replaced by $$(). ` + `See ${RFC_LINK} for latest updates.`, node ) } if (callee === '$fromRef') { error( `$fromRef() has been replaced by $(). ` + `See ${RFC_LINK} for latest updates.`, node ) } } }, leave(node: Node, parent?: Node) { parent && parentStack.pop() if ( (node.type === 'BlockStatement' && !isFunctionType(parent!)) || isFunctionType(node) ) { scopeStack.pop() currentScope = scopeStack[scopeStack.length - 1] || null } } }) return { rootVars: Object.keys(rootScope).filter(key => rootScope[key]), importedHelpers: [...importedHelpers] } } function isToVarCall(callee: string): string | false { if (callee === TO_VAR_SYMBOL) { return TO_VAR_SYMBOL } if (callee[0] === TO_VAR_SYMBOL && shorthands.includes(callee.slice(1))) { return callee } return false } const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369` const hasWarned: Record<string, boolean> = {} function warnExperimental() { // eslint-disable-next-line if (typeof window !== 'undefined') { return } warnOnce( `@vue/ref-transform is an experimental feature.\n` + `Experimental features may change behavior between patch versions.\n` + `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` + `You can follow the proposal's status at ${RFC_LINK}.` ) } function warnOnce(msg: string) { const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production' if (!isNodeProd && !__TEST__ && !hasWarned[msg]) { hasWarned[msg] = true warn(msg) } } function warn(msg: string) { console.warn( `\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n` ) }
packages/ref-transform/src/refTransform.ts
1
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.0022164604160934687, 0.00022807686764281243, 0.00016555265756323934, 0.00016958100604824722, 0.0003002456796821207 ]
{ "id": 0, "code_window": [ " `$computed can only be used as the initializer`\n", " )\n", " })\n", "})" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " test('not transform the prototype attributes', () => {\n", " const { code } = transform(`\n", " const hasOwnProperty = Object.prototype.hasOwnProperty\n", " const hasOwn = (val, key) => hasOwnProperty.call(val, key)\n", " `)\n", " expect(code).not.toMatch('.value')\n", " })\n" ], "file_path": "packages/ref-transform/__tests__/refTransform.spec.ts", "type": "add", "edit_start_line_idx": 397 }
import { DirectiveTransform } from '../transform' import { createObjectProperty, createSimpleExpression, ExpressionNode, NodeTypes } from '../ast' import { createCompilerError, ErrorCodes } from '../errors' import { camelize } from '@vue/shared' import { CAMELIZE } from '../runtimeHelpers' // v-bind without arg is handled directly in ./transformElements.ts due to it affecting // codegen for the entire props object. This transform here is only for v-bind // *with* args. export const transformBind: DirectiveTransform = (dir, _node, context) => { const { exp, modifiers, loc } = dir const arg = dir.arg! if (arg.type !== NodeTypes.SIMPLE_EXPRESSION) { arg.children.unshift(`(`) arg.children.push(`) || ""`) } else if (!arg.isStatic) { arg.content = `${arg.content} || ""` } // .sync is replaced by v-model:arg if (modifiers.includes('camel')) { if (arg.type === NodeTypes.SIMPLE_EXPRESSION) { if (arg.isStatic) { arg.content = camelize(arg.content) } else { arg.content = `${context.helperString(CAMELIZE)}(${arg.content})` } } else { arg.children.unshift(`${context.helperString(CAMELIZE)}(`) arg.children.push(`)`) } } if (!context.inSSR) { if (modifiers.includes('prop')) { injectPrefix(arg, '.') } if (modifiers.includes('attr')) { injectPrefix(arg, '^') } } if ( !exp || (exp.type === NodeTypes.SIMPLE_EXPRESSION && !exp.content.trim()) ) { context.onError(createCompilerError(ErrorCodes.X_V_BIND_NO_EXPRESSION, loc)) return { props: [createObjectProperty(arg, createSimpleExpression('', true, loc))] } } return { props: [createObjectProperty(arg, exp)] } } const injectPrefix = (arg: ExpressionNode, prefix: string) => { if (arg.type === NodeTypes.SIMPLE_EXPRESSION) { if (arg.isStatic) { arg.content = prefix + arg.content } else { arg.content = `\`${prefix}\${${arg.content}}\`` } } else { arg.children.unshift(`'${prefix}' + (`) arg.children.push(`)`) } }
packages/compiler-core/src/transforms/vBind.ts
0
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.00017251644749194384, 0.00016826817591208965, 0.00016652538033667952, 0.00016732083167880774, 0.0000019655963114928454 ]
{ "id": 0, "code_window": [ " `$computed can only be used as the initializer`\n", " )\n", " })\n", "})" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " test('not transform the prototype attributes', () => {\n", " const { code } = transform(`\n", " const hasOwnProperty = Object.prototype.hasOwnProperty\n", " const hasOwn = (val, key) => hasOwnProperty.call(val, key)\n", " `)\n", " expect(code).not.toMatch('.value')\n", " })\n" ], "file_path": "packages/ref-transform/__tests__/refTransform.spec.ts", "type": "add", "edit_start_line_idx": 397 }
import { Position } from '../src/ast' import { getInnerRange, advancePositionWithClone, isMemberExpression, toValidAssetId } from '../src/utils' function p(line: number, column: number, offset: number): Position { return { column, line, offset } } describe('advancePositionWithClone', () => { test('same line', () => { const pos = p(1, 1, 0) const newPos = advancePositionWithClone(pos, 'foo\nbar', 2) expect(newPos.column).toBe(3) expect(newPos.line).toBe(1) expect(newPos.offset).toBe(2) }) test('same line', () => { const pos = p(1, 1, 0) const newPos = advancePositionWithClone(pos, 'foo\nbar', 4) expect(newPos.column).toBe(1) expect(newPos.line).toBe(2) expect(newPos.offset).toBe(4) }) test('multiple lines', () => { const pos = p(1, 1, 0) const newPos = advancePositionWithClone(pos, 'foo\nbar\nbaz', 10) expect(newPos.column).toBe(3) expect(newPos.line).toBe(3) expect(newPos.offset).toBe(10) }) }) describe('getInnerRange', () => { const loc1 = { source: 'foo\nbar\nbaz', start: p(1, 1, 0), end: p(3, 3, 11) } test('at start', () => { const loc2 = getInnerRange(loc1, 0, 4) expect(loc2.start).toEqual(loc1.start) expect(loc2.end.column).toBe(1) expect(loc2.end.line).toBe(2) expect(loc2.end.offset).toBe(4) }) test('at end', () => { const loc2 = getInnerRange(loc1, 4) expect(loc2.start.column).toBe(1) expect(loc2.start.line).toBe(2) expect(loc2.start.offset).toBe(4) expect(loc2.end).toEqual(loc1.end) }) test('in between', () => { const loc2 = getInnerRange(loc1, 4, 3) expect(loc2.start.column).toBe(1) expect(loc2.start.line).toBe(2) expect(loc2.start.offset).toBe(4) expect(loc2.end.column).toBe(4) expect(loc2.end.line).toBe(2) expect(loc2.end.offset).toBe(7) }) }) test('isMemberExpression', () => { // should work expect(isMemberExpression('obj.foo')).toBe(true) expect(isMemberExpression('obj[foo]')).toBe(true) expect(isMemberExpression('obj[arr[0]]')).toBe(true) expect(isMemberExpression('obj[arr[ret.bar]]')).toBe(true) expect(isMemberExpression('obj[arr[ret[bar]]]')).toBe(true) expect(isMemberExpression('obj[arr[ret[bar]]].baz')).toBe(true) expect(isMemberExpression('obj[1 + 1]')).toBe(true) expect(isMemberExpression(`obj[x[0]]`)).toBe(true) expect(isMemberExpression('obj[1][2]')).toBe(true) expect(isMemberExpression('obj[1][2].foo[3].bar.baz')).toBe(true) expect(isMemberExpression(`a[b[c.d]][0]`)).toBe(true) expect(isMemberExpression('obj?.foo')).toBe(true) expect(isMemberExpression('foo().test')).toBe(true) // strings expect(isMemberExpression(`a['foo' + bar[baz]["qux"]]`)).toBe(true) // multiline whitespaces expect(isMemberExpression('obj \n .foo \n [bar \n + baz]')).toBe(true) expect(isMemberExpression(`\n model\n.\nfoo \n`)).toBe(true) // should fail expect(isMemberExpression('a \n b')).toBe(false) expect(isMemberExpression('obj[foo')).toBe(false) expect(isMemberExpression('objfoo]')).toBe(false) expect(isMemberExpression('obj[arr[0]')).toBe(false) expect(isMemberExpression('obj[arr0]]')).toBe(false) expect(isMemberExpression('123[a]')).toBe(false) expect(isMemberExpression('a + b')).toBe(false) expect(isMemberExpression('foo()')).toBe(false) expect(isMemberExpression('a?b:c')).toBe(false) expect(isMemberExpression(`state['text'] = $event`)).toBe(false) }) test('toValidAssetId', () => { expect(toValidAssetId('foo', 'component')).toBe('_component_foo') expect(toValidAssetId('p', 'directive')).toBe('_directive_p') expect(toValidAssetId('div', 'filter')).toBe('_filter_div') expect(toValidAssetId('foo-bar', 'component')).toBe('_component_foo_bar') expect(toValidAssetId('test-测试-1', 'component')).toBe( '_component_test_2797935797_1' ) })
packages/compiler-core/__tests__/utils.spec.ts
0
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.0001823238271754235, 0.00016977681661956012, 0.0001650523772696033, 0.0001685251045273617, 0.000004307725248509087 ]
{ "id": 0, "code_window": [ " `$computed can only be used as the initializer`\n", " )\n", " })\n", "})" ], "labels": [ "keep", "keep", "add", "keep" ], "after_edit": [ "\n", " test('not transform the prototype attributes', () => {\n", " const { code } = transform(`\n", " const hasOwnProperty = Object.prototype.hasOwnProperty\n", " const hasOwn = (val, key) => hasOwnProperty.call(val, key)\n", " `)\n", " expect(code).not.toMatch('.value')\n", " })\n" ], "file_path": "packages/ref-transform/__tests__/refTransform.spec.ts", "type": "add", "edit_start_line_idx": 397 }
import { baseParse as parse } from '../../src/parse' import { transform } from '../../src/transform' import { transformIf } from '../../src/transforms/vIf' import { transformElement } from '../../src/transforms/transformElement' import { transformSlotOutlet } from '../../src/transforms/transformSlotOutlet' import { CommentNode, ConditionalExpression, ElementNode, ElementTypes, IfBranchNode, IfConditionalExpression, IfNode, NodeTypes, SimpleExpressionNode, TextNode, VNodeCall } from '../../src/ast' import { ErrorCodes } from '../../src/errors' import { CompilerOptions, generate, TO_HANDLERS } from '../../src' import { CREATE_COMMENT, FRAGMENT, MERGE_PROPS, NORMALIZE_PROPS, RENDER_SLOT } from '../../src/runtimeHelpers' import { createObjectMatcher } from '../testUtils' function parseWithIfTransform( template: string, options: CompilerOptions = {}, returnIndex: number = 0, childrenLen: number = 1 ) { const ast = parse(template, options) transform(ast, { nodeTransforms: [transformIf, transformSlotOutlet, transformElement], ...options }) if (!options.onError) { expect(ast.children.length).toBe(childrenLen) for (let i = 0; i < childrenLen; i++) { expect(ast.children[i].type).toBe(NodeTypes.IF) } } return { root: ast, node: ast.children[returnIndex] as IfNode & { codegenNode: IfConditionalExpression } } } describe('compiler: v-if', () => { describe('transform', () => { test('basic v-if', () => { const { node } = parseWithIfTransform(`<div v-if="ok"/>`) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(1) expect((node.branches[0].condition as SimpleExpressionNode).content).toBe( `ok` ) expect(node.branches[0].children.length).toBe(1) expect(node.branches[0].children[0].type).toBe(NodeTypes.ELEMENT) expect((node.branches[0].children[0] as ElementNode).tag).toBe(`div`) }) test('template v-if', () => { const { node } = parseWithIfTransform( `<template v-if="ok"><div/>hello<p/></template>` ) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(1) expect((node.branches[0].condition as SimpleExpressionNode).content).toBe( `ok` ) expect(node.branches[0].children.length).toBe(3) expect(node.branches[0].children[0].type).toBe(NodeTypes.ELEMENT) expect((node.branches[0].children[0] as ElementNode).tag).toBe(`div`) expect(node.branches[0].children[1].type).toBe(NodeTypes.TEXT) expect((node.branches[0].children[1] as TextNode).content).toBe(`hello`) expect(node.branches[0].children[2].type).toBe(NodeTypes.ELEMENT) expect((node.branches[0].children[2] as ElementNode).tag).toBe(`p`) }) test('component v-if', () => { const { node } = parseWithIfTransform(`<Component v-if="ok"></Component>`) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(1) expect((node.branches[0].children[0] as ElementNode).tag).toBe( `Component` ) expect((node.branches[0].children[0] as ElementNode).tagType).toBe( ElementTypes.COMPONENT ) // #2058 since a component may fail to resolve and fallback to a plain // element, it still needs to be made a block expect( ((node.branches[0].children[0] as ElementNode)! .codegenNode as VNodeCall)!.isBlock ).toBe(true) }) test('v-if + v-else', () => { const { node } = parseWithIfTransform(`<div v-if="ok"/><p v-else/>`) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(2) const b1 = node.branches[0] expect((b1.condition as SimpleExpressionNode).content).toBe(`ok`) expect(b1.children.length).toBe(1) expect(b1.children[0].type).toBe(NodeTypes.ELEMENT) expect((b1.children[0] as ElementNode).tag).toBe(`div`) const b2 = node.branches[1] expect(b2.condition).toBeUndefined() expect(b2.children.length).toBe(1) expect(b2.children[0].type).toBe(NodeTypes.ELEMENT) expect((b2.children[0] as ElementNode).tag).toBe(`p`) }) test('v-if + v-else-if', () => { const { node } = parseWithIfTransform( `<div v-if="ok"/><p v-else-if="orNot"/>` ) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(2) const b1 = node.branches[0] expect((b1.condition as SimpleExpressionNode).content).toBe(`ok`) expect(b1.children.length).toBe(1) expect(b1.children[0].type).toBe(NodeTypes.ELEMENT) expect((b1.children[0] as ElementNode).tag).toBe(`div`) const b2 = node.branches[1] expect((b2.condition as SimpleExpressionNode).content).toBe(`orNot`) expect(b2.children.length).toBe(1) expect(b2.children[0].type).toBe(NodeTypes.ELEMENT) expect((b2.children[0] as ElementNode).tag).toBe(`p`) }) test('v-if + v-else-if + v-else', () => { const { node } = parseWithIfTransform( `<div v-if="ok"/><p v-else-if="orNot"/><template v-else>fine</template>` ) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(3) const b1 = node.branches[0] expect((b1.condition as SimpleExpressionNode).content).toBe(`ok`) expect(b1.children.length).toBe(1) expect(b1.children[0].type).toBe(NodeTypes.ELEMENT) expect((b1.children[0] as ElementNode).tag).toBe(`div`) const b2 = node.branches[1] expect((b2.condition as SimpleExpressionNode).content).toBe(`orNot`) expect(b2.children.length).toBe(1) expect(b2.children[0].type).toBe(NodeTypes.ELEMENT) expect((b2.children[0] as ElementNode).tag).toBe(`p`) const b3 = node.branches[2] expect(b3.condition).toBeUndefined() expect(b3.children.length).toBe(1) expect(b3.children[0].type).toBe(NodeTypes.TEXT) expect((b3.children[0] as TextNode).content).toBe(`fine`) }) test('comment between branches', () => { const { node } = parseWithIfTransform(` <div v-if="ok"/> <!--foo--> <p v-else-if="orNot"/> <!--bar--> <template v-else>fine</template> `) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(3) const b1 = node.branches[0] expect((b1.condition as SimpleExpressionNode).content).toBe(`ok`) expect(b1.children.length).toBe(1) expect(b1.children[0].type).toBe(NodeTypes.ELEMENT) expect((b1.children[0] as ElementNode).tag).toBe(`div`) const b2 = node.branches[1] expect((b2.condition as SimpleExpressionNode).content).toBe(`orNot`) expect(b2.children.length).toBe(2) expect(b2.children[0].type).toBe(NodeTypes.COMMENT) expect((b2.children[0] as CommentNode).content).toBe(`foo`) expect(b2.children[1].type).toBe(NodeTypes.ELEMENT) expect((b2.children[1] as ElementNode).tag).toBe(`p`) const b3 = node.branches[2] expect(b3.condition).toBeUndefined() expect(b3.children.length).toBe(2) expect(b3.children[0].type).toBe(NodeTypes.COMMENT) expect((b3.children[0] as CommentNode).content).toBe(`bar`) expect(b3.children[1].type).toBe(NodeTypes.TEXT) expect((b3.children[1] as TextNode).content).toBe(`fine`) }) test('should prefix v-if condition', () => { const { node } = parseWithIfTransform(`<div v-if="ok"/>`, { prefixIdentifiers: true }) expect(node.branches[0].condition).toMatchObject({ type: NodeTypes.SIMPLE_EXPRESSION, content: `_ctx.ok` }) }) }) describe('errors', () => { test('error on v-else missing adjacent v-if', () => { const onError = jest.fn() const { node: node1 } = parseWithIfTransform(`<div v-else/>`, { onError }) expect(onError.mock.calls[0]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node1.loc } ]) const { node: node2 } = parseWithIfTransform( `<div/><div v-else/>`, { onError }, 1 ) expect(onError.mock.calls[1]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node2.loc } ]) const { node: node3 } = parseWithIfTransform( `<div/>foo<div v-else/>`, { onError }, 2 ) expect(onError.mock.calls[2]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node3.loc } ]) }) test('error on v-else-if missing adjacent v-if', () => { const onError = jest.fn() const { node: node1 } = parseWithIfTransform(`<div v-else-if="foo"/>`, { onError }) expect(onError.mock.calls[0]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node1.loc } ]) const { node: node2 } = parseWithIfTransform( `<div/><div v-else-if="foo"/>`, { onError }, 1 ) expect(onError.mock.calls[1]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node2.loc } ]) const { node: node3 } = parseWithIfTransform( `<div/>foo<div v-else-if="foo"/>`, { onError }, 2 ) expect(onError.mock.calls[2]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node3.loc } ]) }) test('error on user key', () => { const onError = jest.fn() // dynamic parseWithIfTransform( `<div v-if="ok" :key="a + 1" /><div v-else :key="a + 1" />`, { onError } ) expect(onError.mock.calls[0]).toMatchObject([ { code: ErrorCodes.X_V_IF_SAME_KEY } ]) // static parseWithIfTransform(`<div v-if="ok" key="1" /><div v-else key="1" />`, { onError }) expect(onError.mock.calls[1]).toMatchObject([ { code: ErrorCodes.X_V_IF_SAME_KEY } ]) }) }) describe('codegen', () => { function assertSharedCodegen( node: IfConditionalExpression, depth: number = 0, hasElse: boolean = false ) { expect(node).toMatchObject({ type: NodeTypes.JS_CONDITIONAL_EXPRESSION, test: { content: `ok` }, consequent: { type: NodeTypes.VNODE_CALL, isBlock: true }, alternate: depth < 1 ? hasElse ? { type: NodeTypes.VNODE_CALL, isBlock: true } : { type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_COMMENT } : { type: NodeTypes.JS_CONDITIONAL_EXPRESSION, test: { content: `orNot` }, consequent: { type: NodeTypes.VNODE_CALL, isBlock: true }, alternate: hasElse ? { type: NodeTypes.VNODE_CALL, isBlock: true } : { type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_COMMENT } } }) } test('basic v-if', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok"/>`) assertSharedCodegen(codegenNode) expect(codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) expect(codegenNode.alternate).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_COMMENT }) expect(generate(root).code).toMatchSnapshot() }) test('template v-if', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<template v-if="ok"><div/>hello<p/></template>`) assertSharedCodegen(codegenNode) expect(codegenNode.consequent).toMatchObject({ tag: FRAGMENT, props: createObjectMatcher({ key: `[0]` }), children: [ { type: NodeTypes.ELEMENT, tag: 'div' }, { type: NodeTypes.TEXT, content: `hello` }, { type: NodeTypes.ELEMENT, tag: 'p' } ] }) expect(codegenNode.alternate).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_COMMENT }) expect(generate(root).code).toMatchSnapshot() }) test('template v-if w/ single <slot/> child', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<template v-if="ok"><slot/></template>`) expect(codegenNode.consequent).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: RENDER_SLOT, arguments: ['$slots', '"default"', createObjectMatcher({ key: `[0]` })] }) expect(generate(root).code).toMatchSnapshot() }) test('v-if on <slot/>', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<slot v-if="ok"></slot>`) expect(codegenNode.consequent).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: RENDER_SLOT, arguments: ['$slots', '"default"', createObjectMatcher({ key: `[0]` })] }) expect(generate(root).code).toMatchSnapshot() }) test('v-if + v-else', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok"/><p v-else/>`) assertSharedCodegen(codegenNode, 0, true) expect(codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) expect(codegenNode.alternate).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[1]` }) }) expect(generate(root).code).toMatchSnapshot() }) test('v-if + v-else-if', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok"/><p v-else-if="orNot" />`) assertSharedCodegen(codegenNode, 1) expect(codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) const branch2 = codegenNode.alternate as ConditionalExpression expect(branch2.consequent).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[1]` }) }) expect(generate(root).code).toMatchSnapshot() }) test('v-if + v-else-if + v-else', () => { const { root, node: { codegenNode } } = parseWithIfTransform( `<div v-if="ok"/><p v-else-if="orNot"/><template v-else>fine</template>` ) assertSharedCodegen(codegenNode, 1, true) expect(codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) const branch2 = codegenNode.alternate as ConditionalExpression expect(branch2.consequent).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[1]` }) }) expect(branch2.alternate).toMatchObject({ tag: FRAGMENT, props: createObjectMatcher({ key: `[2]` }), children: [ { type: NodeTypes.TEXT, content: `fine` } ] }) expect(generate(root).code).toMatchSnapshot() }) test('multiple v-if that are sibling nodes should have different keys', () => { const { root } = parseWithIfTransform( `<div v-if="ok"/><p v-if="orNot"/>`, {}, 0 /* returnIndex, just give the default value */, 2 /* childrenLen */ ) const ifNode = root.children[0] as IfNode & { codegenNode: IfConditionalExpression } expect(ifNode.codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) const ifNode2 = root.children[1] as IfNode & { codegenNode: IfConditionalExpression } expect(ifNode2.codegenNode.consequent).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[1]` }) }) expect(generate(root).code).toMatchSnapshot() }) test('increasing key: v-if + v-else-if + v-else', () => { const { root } = parseWithIfTransform( `<div v-if="ok"/><p v-else/><div v-if="another"/><p v-else-if="orNot"/><p v-else/>`, {}, 0 /* returnIndex, just give the default value */, 2 /* childrenLen */ ) const ifNode = root.children[0] as IfNode & { codegenNode: IfConditionalExpression } expect(ifNode.codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) expect(ifNode.codegenNode.alternate).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[1]` }) }) const ifNode2 = root.children[1] as IfNode & { codegenNode: IfConditionalExpression } expect(ifNode2.codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[2]` }) }) const branch = ifNode2.codegenNode.alternate as IfConditionalExpression expect(branch.consequent).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[3]` }) }) expect(branch.alternate).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[4]` }) }) expect(generate(root).code).toMatchSnapshot() }) test('key injection (only v-bind)', () => { const { node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok" v-bind="obj"/>`) const branch1 = codegenNode.consequent as VNodeCall expect(branch1.props).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: NORMALIZE_PROPS, arguments: [ { type: NodeTypes.JS_CALL_EXPRESSION, callee: MERGE_PROPS, arguments: [createObjectMatcher({ key: `[0]` }), { content: `obj` }] } ] }) }) test('key injection (before v-bind)', () => { const { node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok" id="foo" v-bind="obj"/>`) const branch1 = codegenNode.consequent as VNodeCall expect(branch1.props).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: MERGE_PROPS, arguments: [ createObjectMatcher({ key: '[0]', id: 'foo' }), { content: `obj` } ] }) }) test('key injection (after v-bind)', () => { const { node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok" v-bind="obj" id="foo"/>`) const branch1 = codegenNode.consequent as VNodeCall expect(branch1.props).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: MERGE_PROPS, arguments: [ createObjectMatcher({ key: `[0]` }), { content: `obj` }, createObjectMatcher({ id: 'foo' }) ] }) }) test('key injection (w/ custom directive)', () => { const { node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok" v-foo />`) const branch1 = codegenNode.consequent as VNodeCall expect(branch1.directives).not.toBeUndefined() expect(branch1.props).toMatchObject(createObjectMatcher({ key: `[0]` })) }) test('with spaces between branches', () => { const { node: { codegenNode } } = parseWithIfTransform( `<div v-if="ok"/> <div v-else-if="no"/> <div v-else/>` ) expect(codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) const branch = codegenNode.alternate as ConditionalExpression expect(branch.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[1]` }) }) expect(branch.alternate).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[2]` }) }) }) test('with comments', () => { const { node } = parseWithIfTransform(` <template v-if="ok"> <!--comment1--> <div v-if="ok2"> <!--comment2--> </div> <!--comment3--> <b v-else/> <!--comment4--> <p/> </template> `) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(1) const b1 = node.branches[0] expect((b1.condition as SimpleExpressionNode).content).toBe(`ok`) expect(b1.children.length).toBe(4) expect(b1.children[0].type).toBe(NodeTypes.COMMENT) expect((b1.children[0] as CommentNode).content).toBe(`comment1`) expect(b1.children[1].type).toBe(NodeTypes.IF) expect((b1.children[1] as IfNode).branches.length).toBe(2) const b1b1: ElementNode = (b1.children[1] as IfNode).branches[0] .children[0] as ElementNode expect(b1b1.type).toBe(NodeTypes.ELEMENT) expect(b1b1.tag).toBe('div') expect(b1b1.children[0].type).toBe(NodeTypes.COMMENT) expect((b1b1.children[0] as CommentNode).content).toBe('comment2') const b1b2: IfBranchNode = (b1.children[1] as IfNode) .branches[1] as IfBranchNode expect(b1b2.children[0].type).toBe(NodeTypes.COMMENT) expect((b1b2.children[0] as CommentNode).content).toBe(`comment3`) expect(b1b2.children[1].type).toBe(NodeTypes.ELEMENT) expect((b1b2.children[1] as ElementNode).tag).toBe(`b`) expect(b1.children[2].type).toBe(NodeTypes.COMMENT) expect((b1.children[2] as CommentNode).content).toBe(`comment4`) expect(b1.children[3].type).toBe(NodeTypes.ELEMENT) expect((b1.children[3] as ElementNode).tag).toBe(`p`) }) }) test('v-on with v-if', () => { const { node: { codegenNode } } = parseWithIfTransform( `<button v-on="{ click: clickEvent }" v-if="true">w/ v-if</button>` ) expect((codegenNode.consequent as any).props.type).toBe( NodeTypes.JS_CALL_EXPRESSION ) expect((codegenNode.consequent as any).props.callee).toBe(MERGE_PROPS) expect( (codegenNode.consequent as any).props.arguments[0].properties[0].value .content ).toBe('0') expect((codegenNode.consequent as any).props.arguments[1].callee).toBe( TO_HANDLERS ) }) })
packages/compiler-core/__tests__/transforms/vIf.spec.ts
0
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.0003704773262143135, 0.0001725615147734061, 0.00016463302017655224, 0.0001693735976004973, 0.00002431127541058231 ]
{ "id": 1, "code_window": [ " isStaticProperty,\n", " walkFunctionParams\n", "} from '@vue/compiler-core'\n", "import { parse, ParserPlugin } from '@babel/parser'\n", "import { babelParserDefaultPlugins } from '@vue/shared'\n", "\n", "const TO_VAR_SYMBOL = '$'\n", "const TO_REF_SYMBOL = '$$'\n", "const shorthands = ['ref', 'computed', 'shallowRef']\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { babelParserDefaultPlugins, hasOwn } from '@vue/shared'\n" ], "file_path": "packages/ref-transform/src/refTransform.ts", "type": "replace", "edit_start_line_idx": 22 }
import { Node, Identifier, BlockStatement, CallExpression, ObjectPattern, VariableDeclaration, ArrayPattern, Program, VariableDeclarator } from '@babel/types' import MagicString, { SourceMap } from 'magic-string' import { walk } from 'estree-walker' import { extractIdentifiers, isFunctionType, isInDestructureAssignment, isReferencedIdentifier, isStaticProperty, walkFunctionParams } from '@vue/compiler-core' import { parse, ParserPlugin } from '@babel/parser' import { babelParserDefaultPlugins } from '@vue/shared' const TO_VAR_SYMBOL = '$' const TO_REF_SYMBOL = '$$' const shorthands = ['ref', 'computed', 'shallowRef'] const transformCheckRE = /[^\w]\$(?:\$|ref|computed|shallowRef)?\s*(\(|\<)/ export function shouldTransform(src: string): boolean { return transformCheckRE.test(src) } type Scope = Record<string, boolean> export interface RefTransformOptions { filename?: string sourceMap?: boolean parserPlugins?: ParserPlugin[] importHelpersFrom?: string } export interface RefTransformResults { code: string map: SourceMap | null rootVars: string[] importedHelpers: string[] } export function transform( src: string, { filename, sourceMap, parserPlugins, importHelpersFrom = 'vue' }: RefTransformOptions = {} ): RefTransformResults { const plugins: ParserPlugin[] = parserPlugins || [] if (filename) { if (/\.tsx?$/.test(filename)) { plugins.push('typescript') } if (filename.endsWith('x')) { plugins.push('jsx') } } const ast = parse(src, { sourceType: 'module', plugins: [...new Set([...babelParserDefaultPlugins, ...plugins])] }) const s = new MagicString(src) const res = transformAST(ast.program, s) // inject helper imports if (res.importedHelpers.length) { s.prepend( `import { ${res.importedHelpers .map(h => `${h} as _${h}`) .join(', ')} } from '${importHelpersFrom}'\n` ) } return { ...res, code: s.toString(), map: sourceMap ? s.generateMap({ source: filename, hires: true, includeContent: true }) : null } } export function transformAST( ast: Program, s: MagicString, offset = 0, knownRootVars?: string[] ): { rootVars: string[] importedHelpers: string[] } { // TODO remove when out of experimental warnExperimental() const importedHelpers = new Set<string>() const rootScope: Scope = {} const scopeStack: Scope[] = [rootScope] let currentScope: Scope = rootScope const excludedIds = new WeakSet<Identifier>() const parentStack: Node[] = [] if (knownRootVars) { for (const key of knownRootVars) { rootScope[key] = true } } function error(msg: string, node: Node) { const e = new Error(msg) ;(e as any).node = node throw e } function helper(msg: string) { importedHelpers.add(msg) return `_${msg}` } function registerBinding(id: Identifier, isRef = false) { excludedIds.add(id) if (currentScope) { currentScope[id.name] = isRef } else { error( 'registerBinding called without active scope, something is wrong.', id ) } } const registerRefBinding = (id: Identifier) => registerBinding(id, true) function walkScope(node: Program | BlockStatement) { for (const stmt of node.body) { if (stmt.type === 'VariableDeclaration') { if (stmt.declare) continue for (const decl of stmt.declarations) { let toVarCall if ( decl.init && decl.init.type === 'CallExpression' && decl.init.callee.type === 'Identifier' && (toVarCall = isToVarCall(decl.init.callee.name)) ) { processRefDeclaration( toVarCall, decl.init as CallExpression, decl.id, stmt ) } else { for (const id of extractIdentifiers(decl.id)) { registerBinding(id) } } } } else if ( stmt.type === 'FunctionDeclaration' || stmt.type === 'ClassDeclaration' ) { if (stmt.declare || !stmt.id) continue registerBinding(stmt.id) } } } function processRefDeclaration( method: string, call: CallExpression, id: VariableDeclarator['id'], statement: VariableDeclaration ) { excludedIds.add(call.callee as Identifier) if (statement.kind !== 'let') { error(`${method}() bindings can only be declared with let`, call) } if (method === TO_VAR_SYMBOL) { // $ // remove macro s.remove(call.callee.start! + offset, call.callee.end! + offset) if (id.type === 'Identifier') { // single variable registerRefBinding(id) } else if (id.type === 'ObjectPattern') { processRefObjectPattern(id, statement) } else if (id.type === 'ArrayPattern') { processRefArrayPattern(id, statement) } } else { // shorthands if (id.type === 'Identifier') { registerRefBinding(id) // replace call s.overwrite( call.start! + offset, call.start! + method.length + offset, helper(method.slice(1)) ) } else { error(`${method}() cannot be used with destructure patterns.`, call) } } } function processRefObjectPattern( pattern: ObjectPattern, statement: VariableDeclaration ) { for (const p of pattern.properties) { let nameId: Identifier | undefined if (p.type === 'ObjectProperty') { if (p.key.start! === p.value.start!) { // shorthand { foo } --> { foo: __foo } nameId = p.key as Identifier s.appendLeft(nameId.end! + offset, `: __${nameId.name}`) if (p.value.type === 'Identifier') { // avoid shorthand value identifier from being processed excludedIds.add(p.value) } else if ( p.value.type === 'AssignmentPattern' && p.value.left.type === 'Identifier' ) { // { foo = 1 } excludedIds.add(p.value.left) } } else { if (p.value.type === 'Identifier') { // { foo: bar } --> { foo: __bar } nameId = p.value s.prependRight(nameId.start! + offset, `__`) } else if (p.value.type === 'ObjectPattern') { processRefObjectPattern(p.value, statement) } else if (p.value.type === 'ArrayPattern') { processRefArrayPattern(p.value, statement) } else if (p.value.type === 'AssignmentPattern') { // { foo: bar = 1 } --> { foo: __bar = 1 } nameId = p.value.left as Identifier s.prependRight(nameId.start! + offset, `__`) } } } else { // rest element { ...foo } --> { ...__foo } nameId = p.argument as Identifier s.prependRight(nameId.start! + offset, `__`) } if (nameId) { registerRefBinding(nameId) // append binding declarations after the parent statement s.appendLeft( statement.end! + offset, `\nconst ${nameId.name} = ${helper('shallowRef')}(__${nameId.name});` ) } } } function processRefArrayPattern( pattern: ArrayPattern, statement: VariableDeclaration ) { for (const e of pattern.elements) { if (!e) continue let nameId: Identifier | undefined if (e.type === 'Identifier') { // [a] --> [__a] nameId = e } else if (e.type === 'AssignmentPattern') { // [a = 1] --> [__a = 1] nameId = e.left as Identifier } else if (e.type === 'RestElement') { // [...a] --> [...__a] nameId = e.argument as Identifier } else if (e.type === 'ObjectPattern') { processRefObjectPattern(e, statement) } else if (e.type === 'ArrayPattern') { processRefArrayPattern(e, statement) } if (nameId) { registerRefBinding(nameId) // prefix original s.prependRight(nameId.start! + offset, `__`) // append binding declarations after the parent statement s.appendLeft( statement.end! + offset, `\nconst ${nameId.name} = ${helper('shallowRef')}(__${nameId.name});` ) } } } function checkRefId( scope: Scope, id: Identifier, parent: Node, parentStack: Node[] ): boolean { if (id.name in scope) { if (scope[id.name]) { if (isStaticProperty(parent) && parent.shorthand) { // let binding used in a property shorthand // { foo } -> { foo: foo.value } // skip for destructure patterns if ( !(parent as any).inPattern || isInDestructureAssignment(parent, parentStack) ) { s.appendLeft(id.end! + offset, `: ${id.name}.value`) } } else { s.appendLeft(id.end! + offset, '.value') } } return true } return false } // check root scope first walkScope(ast) ;(walk as any)(ast, { enter(node: Node, parent?: Node) { parent && parentStack.push(parent) // function scopes if (isFunctionType(node)) { scopeStack.push((currentScope = {})) walkFunctionParams(node, registerBinding) if (node.body.type === 'BlockStatement') { walkScope(node.body) } return } // non-function block scopes if (node.type === 'BlockStatement' && !isFunctionType(parent!)) { scopeStack.push((currentScope = {})) walkScope(node) return } if ( parent && parent.type.startsWith('TS') && parent.type !== 'TSAsExpression' && parent.type !== 'TSNonNullExpression' && parent.type !== 'TSTypeAssertion' ) { return this.skip() } if ( node.type === 'Identifier' && isReferencedIdentifier(node, parent!, parentStack) && !excludedIds.has(node) ) { // walk up the scope chain to check if id should be appended .value let i = scopeStack.length while (i--) { if (checkRefId(scopeStack[i], node, parent!, parentStack)) { return } } } if (node.type === 'CallExpression' && node.callee.type === 'Identifier') { const callee = node.callee.name const toVarCall = isToVarCall(callee) if (toVarCall && (!parent || parent.type !== 'VariableDeclarator')) { return error( `${toVarCall} can only be used as the initializer of ` + `a variable declaration.`, node ) } if (callee === TO_REF_SYMBOL) { s.remove(node.callee.start! + offset, node.callee.end! + offset) return this.skip() } // TODO remove when out of experimental if (callee === '$raw') { error( `$raw() has been replaced by $$(). ` + `See ${RFC_LINK} for latest updates.`, node ) } if (callee === '$fromRef') { error( `$fromRef() has been replaced by $(). ` + `See ${RFC_LINK} for latest updates.`, node ) } } }, leave(node: Node, parent?: Node) { parent && parentStack.pop() if ( (node.type === 'BlockStatement' && !isFunctionType(parent!)) || isFunctionType(node) ) { scopeStack.pop() currentScope = scopeStack[scopeStack.length - 1] || null } } }) return { rootVars: Object.keys(rootScope).filter(key => rootScope[key]), importedHelpers: [...importedHelpers] } } function isToVarCall(callee: string): string | false { if (callee === TO_VAR_SYMBOL) { return TO_VAR_SYMBOL } if (callee[0] === TO_VAR_SYMBOL && shorthands.includes(callee.slice(1))) { return callee } return false } const RFC_LINK = `https://github.com/vuejs/rfcs/discussions/369` const hasWarned: Record<string, boolean> = {} function warnExperimental() { // eslint-disable-next-line if (typeof window !== 'undefined') { return } warnOnce( `@vue/ref-transform is an experimental feature.\n` + `Experimental features may change behavior between patch versions.\n` + `It is recommended to pin your vue dependencies to exact versions to avoid breakage.\n` + `You can follow the proposal's status at ${RFC_LINK}.` ) } function warnOnce(msg: string) { const isNodeProd = typeof process !== 'undefined' && process.env.NODE_ENV === 'production' if (!isNodeProd && !__TEST__ && !hasWarned[msg]) { hasWarned[msg] = true warn(msg) } } function warn(msg: string) { console.warn( `\x1b[1m\x1b[33m[@vue/compiler-sfc]\x1b[0m\x1b[33m ${msg}\x1b[0m\n` ) }
packages/ref-transform/src/refTransform.ts
1
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.9993120431900024, 0.1047336682677269, 0.00016600998060312122, 0.0001811942202039063, 0.30412590503692627 ]
{ "id": 1, "code_window": [ " isStaticProperty,\n", " walkFunctionParams\n", "} from '@vue/compiler-core'\n", "import { parse, ParserPlugin } from '@babel/parser'\n", "import { babelParserDefaultPlugins } from '@vue/shared'\n", "\n", "const TO_VAR_SYMBOL = '$'\n", "const TO_REF_SYMBOL = '$$'\n", "const shorthands = ['ref', 'computed', 'shallowRef']\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { babelParserDefaultPlugins, hasOwn } from '@vue/shared'\n" ], "file_path": "packages/ref-transform/src/refTransform.ts", "type": "replace", "edit_start_line_idx": 22 }
import path from 'path' import { setupPuppeteer, E2E_TIMEOUT } from '../../__tests__/e2eUtils' describe('e2e: tree', () => { const { page, click, count, text, children, isVisible } = setupPuppeteer() async function testTree(apiType: 'classic' | 'composition') { const baseUrl = `file://${path.resolve( __dirname, `../${apiType}/tree.html` )}` await page().goto(baseUrl) expect(await count('.item')).toBe(12) expect(await count('.add')).toBe(4) expect(await count('.item > ul')).toBe(4) expect(await isVisible('#demo li ul')).toBe(false) expect(await text('#demo li div span')).toBe('[+]') // expand root await click('.bold') expect(await isVisible('#demo ul')).toBe(true) expect((await children('#demo li ul')).length).toBe(4) expect(await text('#demo li div span')).toContain('[-]') expect(await text('#demo > .item > ul > .item:nth-child(1)')).toContain( 'hello' ) expect(await text('#demo > .item > ul > .item:nth-child(2)')).toContain( 'wat' ) expect(await text('#demo > .item > ul > .item:nth-child(3)')).toContain( 'child folder' ) expect(await text('#demo > .item > ul > .item:nth-child(3)')).toContain( '[+]' ) // add items to root await click('#demo > .item > ul > .add') expect((await children('#demo li ul')).length).toBe(5) expect(await text('#demo > .item > ul > .item:nth-child(1)')).toContain( 'hello' ) expect(await text('#demo > .item > ul > .item:nth-child(2)')).toContain( 'wat' ) expect(await text('#demo > .item > ul > .item:nth-child(3)')).toContain( 'child folder' ) expect(await text('#demo > .item > ul > .item:nth-child(3)')).toContain( '[+]' ) expect(await text('#demo > .item > ul > .item:nth-child(4)')).toContain( 'new stuff' ) // add another item await click('#demo > .item > ul > .add') expect((await children('#demo li ul')).length).toBe(6) expect(await text('#demo > .item > ul > .item:nth-child(1)')).toContain( 'hello' ) expect(await text('#demo > .item > ul > .item:nth-child(2)')).toContain( 'wat' ) expect(await text('#demo > .item > ul > .item:nth-child(3)')).toContain( 'child folder' ) expect(await text('#demo > .item > ul > .item:nth-child(3)')).toContain( '[+]' ) expect(await text('#demo > .item > ul > .item:nth-child(4)')).toContain( 'new stuff' ) expect(await text('#demo > .item > ul > .item:nth-child(5)')).toContain( 'new stuff' ) await click('#demo ul .bold') expect(await isVisible('#demo ul ul')).toBe(true) expect(await text('#demo ul > .item:nth-child(3)')).toContain('[-]') expect((await children('#demo ul ul')).length).toBe(5) await click('.bold') expect(await isVisible('#demo ul')).toBe(false) expect(await text('#demo li div span')).toContain('[+]') await click('.bold') expect(await isVisible('#demo ul')).toBe(true) expect(await text('#demo li div span')).toContain('[-]') await click('#demo ul > .item div', { clickCount: 2 }) expect(await count('.item')).toBe(15) expect(await count('.item > ul')).toBe(5) expect(await text('#demo ul > .item:nth-child(1)')).toContain('[-]') expect((await children('#demo ul > .item:nth-child(1) > ul')).length).toBe( 2 ) } test( 'classic', async () => { await testTree('classic') }, E2E_TIMEOUT ) test( 'composition', async () => { await testTree('composition') }, E2E_TIMEOUT ) })
packages/vue/examples/__tests__/tree.spec.ts
0
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.00017707861843518913, 0.00017400208162143826, 0.00016950914869084954, 0.00017428150749765337, 0.0000023788888938724995 ]
{ "id": 1, "code_window": [ " isStaticProperty,\n", " walkFunctionParams\n", "} from '@vue/compiler-core'\n", "import { parse, ParserPlugin } from '@babel/parser'\n", "import { babelParserDefaultPlugins } from '@vue/shared'\n", "\n", "const TO_VAR_SYMBOL = '$'\n", "const TO_REF_SYMBOL = '$$'\n", "const shorthands = ['ref', 'computed', 'shallowRef']\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { babelParserDefaultPlugins, hasOwn } from '@vue/shared'\n" ], "file_path": "packages/ref-transform/src/refTransform.ts", "type": "replace", "edit_start_line_idx": 22 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`compile should contain standard transforms 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { toDisplayString: _toDisplayString, createElementVNode: _createElementVNode, normalizeStyle: _normalizeStyle, Fragment: _Fragment, openBlock: _openBlock, createElementBlock: _createElementBlock } = _Vue return (_openBlock(), _createElementBlock(_Fragment, null, [ _createElementVNode(\\"div\\", { textContent: _toDisplayString(text) }, null, 8 /* PROPS */, [\\"textContent\\"]), _createElementVNode(\\"div\\", { innerHTML: html }, null, 8 /* PROPS */, [\\"innerHTML\\"]), _createElementVNode(\\"div\\", null, \\"test\\"), _createElementVNode(\\"div\\", { style: {\\"color\\":\\"red\\"} }, \\"red\\"), _createElementVNode(\\"div\\", { style: _normalizeStyle({color: 'green'}) }, null, 4 /* STYLE */) ], 64 /* STABLE_FRAGMENT */)) } }" `;
packages/compiler-dom/__tests__/__snapshots__/index.spec.ts.snap
0
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.0001744320325087756, 0.0001720266736811027, 0.00016995762416627258, 0.00017169034981634468, 0.0000018420849983158405 ]
{ "id": 1, "code_window": [ " isStaticProperty,\n", " walkFunctionParams\n", "} from '@vue/compiler-core'\n", "import { parse, ParserPlugin } from '@babel/parser'\n", "import { babelParserDefaultPlugins } from '@vue/shared'\n", "\n", "const TO_VAR_SYMBOL = '$'\n", "const TO_REF_SYMBOL = '$$'\n", "const shorthands = ['ref', 'computed', 'shallowRef']\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { babelParserDefaultPlugins, hasOwn } from '@vue/shared'\n" ], "file_path": "packages/ref-transform/src/refTransform.ts", "type": "replace", "edit_start_line_idx": 22 }
import { baseParse as parse } from '../../src/parse' import { transform } from '../../src/transform' import { transformIf } from '../../src/transforms/vIf' import { transformElement } from '../../src/transforms/transformElement' import { transformSlotOutlet } from '../../src/transforms/transformSlotOutlet' import { CommentNode, ConditionalExpression, ElementNode, ElementTypes, IfBranchNode, IfConditionalExpression, IfNode, NodeTypes, SimpleExpressionNode, TextNode, VNodeCall } from '../../src/ast' import { ErrorCodes } from '../../src/errors' import { CompilerOptions, generate, TO_HANDLERS } from '../../src' import { CREATE_COMMENT, FRAGMENT, MERGE_PROPS, NORMALIZE_PROPS, RENDER_SLOT } from '../../src/runtimeHelpers' import { createObjectMatcher } from '../testUtils' function parseWithIfTransform( template: string, options: CompilerOptions = {}, returnIndex: number = 0, childrenLen: number = 1 ) { const ast = parse(template, options) transform(ast, { nodeTransforms: [transformIf, transformSlotOutlet, transformElement], ...options }) if (!options.onError) { expect(ast.children.length).toBe(childrenLen) for (let i = 0; i < childrenLen; i++) { expect(ast.children[i].type).toBe(NodeTypes.IF) } } return { root: ast, node: ast.children[returnIndex] as IfNode & { codegenNode: IfConditionalExpression } } } describe('compiler: v-if', () => { describe('transform', () => { test('basic v-if', () => { const { node } = parseWithIfTransform(`<div v-if="ok"/>`) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(1) expect((node.branches[0].condition as SimpleExpressionNode).content).toBe( `ok` ) expect(node.branches[0].children.length).toBe(1) expect(node.branches[0].children[0].type).toBe(NodeTypes.ELEMENT) expect((node.branches[0].children[0] as ElementNode).tag).toBe(`div`) }) test('template v-if', () => { const { node } = parseWithIfTransform( `<template v-if="ok"><div/>hello<p/></template>` ) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(1) expect((node.branches[0].condition as SimpleExpressionNode).content).toBe( `ok` ) expect(node.branches[0].children.length).toBe(3) expect(node.branches[0].children[0].type).toBe(NodeTypes.ELEMENT) expect((node.branches[0].children[0] as ElementNode).tag).toBe(`div`) expect(node.branches[0].children[1].type).toBe(NodeTypes.TEXT) expect((node.branches[0].children[1] as TextNode).content).toBe(`hello`) expect(node.branches[0].children[2].type).toBe(NodeTypes.ELEMENT) expect((node.branches[0].children[2] as ElementNode).tag).toBe(`p`) }) test('component v-if', () => { const { node } = parseWithIfTransform(`<Component v-if="ok"></Component>`) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(1) expect((node.branches[0].children[0] as ElementNode).tag).toBe( `Component` ) expect((node.branches[0].children[0] as ElementNode).tagType).toBe( ElementTypes.COMPONENT ) // #2058 since a component may fail to resolve and fallback to a plain // element, it still needs to be made a block expect( ((node.branches[0].children[0] as ElementNode)! .codegenNode as VNodeCall)!.isBlock ).toBe(true) }) test('v-if + v-else', () => { const { node } = parseWithIfTransform(`<div v-if="ok"/><p v-else/>`) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(2) const b1 = node.branches[0] expect((b1.condition as SimpleExpressionNode).content).toBe(`ok`) expect(b1.children.length).toBe(1) expect(b1.children[0].type).toBe(NodeTypes.ELEMENT) expect((b1.children[0] as ElementNode).tag).toBe(`div`) const b2 = node.branches[1] expect(b2.condition).toBeUndefined() expect(b2.children.length).toBe(1) expect(b2.children[0].type).toBe(NodeTypes.ELEMENT) expect((b2.children[0] as ElementNode).tag).toBe(`p`) }) test('v-if + v-else-if', () => { const { node } = parseWithIfTransform( `<div v-if="ok"/><p v-else-if="orNot"/>` ) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(2) const b1 = node.branches[0] expect((b1.condition as SimpleExpressionNode).content).toBe(`ok`) expect(b1.children.length).toBe(1) expect(b1.children[0].type).toBe(NodeTypes.ELEMENT) expect((b1.children[0] as ElementNode).tag).toBe(`div`) const b2 = node.branches[1] expect((b2.condition as SimpleExpressionNode).content).toBe(`orNot`) expect(b2.children.length).toBe(1) expect(b2.children[0].type).toBe(NodeTypes.ELEMENT) expect((b2.children[0] as ElementNode).tag).toBe(`p`) }) test('v-if + v-else-if + v-else', () => { const { node } = parseWithIfTransform( `<div v-if="ok"/><p v-else-if="orNot"/><template v-else>fine</template>` ) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(3) const b1 = node.branches[0] expect((b1.condition as SimpleExpressionNode).content).toBe(`ok`) expect(b1.children.length).toBe(1) expect(b1.children[0].type).toBe(NodeTypes.ELEMENT) expect((b1.children[0] as ElementNode).tag).toBe(`div`) const b2 = node.branches[1] expect((b2.condition as SimpleExpressionNode).content).toBe(`orNot`) expect(b2.children.length).toBe(1) expect(b2.children[0].type).toBe(NodeTypes.ELEMENT) expect((b2.children[0] as ElementNode).tag).toBe(`p`) const b3 = node.branches[2] expect(b3.condition).toBeUndefined() expect(b3.children.length).toBe(1) expect(b3.children[0].type).toBe(NodeTypes.TEXT) expect((b3.children[0] as TextNode).content).toBe(`fine`) }) test('comment between branches', () => { const { node } = parseWithIfTransform(` <div v-if="ok"/> <!--foo--> <p v-else-if="orNot"/> <!--bar--> <template v-else>fine</template> `) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(3) const b1 = node.branches[0] expect((b1.condition as SimpleExpressionNode).content).toBe(`ok`) expect(b1.children.length).toBe(1) expect(b1.children[0].type).toBe(NodeTypes.ELEMENT) expect((b1.children[0] as ElementNode).tag).toBe(`div`) const b2 = node.branches[1] expect((b2.condition as SimpleExpressionNode).content).toBe(`orNot`) expect(b2.children.length).toBe(2) expect(b2.children[0].type).toBe(NodeTypes.COMMENT) expect((b2.children[0] as CommentNode).content).toBe(`foo`) expect(b2.children[1].type).toBe(NodeTypes.ELEMENT) expect((b2.children[1] as ElementNode).tag).toBe(`p`) const b3 = node.branches[2] expect(b3.condition).toBeUndefined() expect(b3.children.length).toBe(2) expect(b3.children[0].type).toBe(NodeTypes.COMMENT) expect((b3.children[0] as CommentNode).content).toBe(`bar`) expect(b3.children[1].type).toBe(NodeTypes.TEXT) expect((b3.children[1] as TextNode).content).toBe(`fine`) }) test('should prefix v-if condition', () => { const { node } = parseWithIfTransform(`<div v-if="ok"/>`, { prefixIdentifiers: true }) expect(node.branches[0].condition).toMatchObject({ type: NodeTypes.SIMPLE_EXPRESSION, content: `_ctx.ok` }) }) }) describe('errors', () => { test('error on v-else missing adjacent v-if', () => { const onError = jest.fn() const { node: node1 } = parseWithIfTransform(`<div v-else/>`, { onError }) expect(onError.mock.calls[0]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node1.loc } ]) const { node: node2 } = parseWithIfTransform( `<div/><div v-else/>`, { onError }, 1 ) expect(onError.mock.calls[1]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node2.loc } ]) const { node: node3 } = parseWithIfTransform( `<div/>foo<div v-else/>`, { onError }, 2 ) expect(onError.mock.calls[2]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node3.loc } ]) }) test('error on v-else-if missing adjacent v-if', () => { const onError = jest.fn() const { node: node1 } = parseWithIfTransform(`<div v-else-if="foo"/>`, { onError }) expect(onError.mock.calls[0]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node1.loc } ]) const { node: node2 } = parseWithIfTransform( `<div/><div v-else-if="foo"/>`, { onError }, 1 ) expect(onError.mock.calls[1]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node2.loc } ]) const { node: node3 } = parseWithIfTransform( `<div/>foo<div v-else-if="foo"/>`, { onError }, 2 ) expect(onError.mock.calls[2]).toMatchObject([ { code: ErrorCodes.X_V_ELSE_NO_ADJACENT_IF, loc: node3.loc } ]) }) test('error on user key', () => { const onError = jest.fn() // dynamic parseWithIfTransform( `<div v-if="ok" :key="a + 1" /><div v-else :key="a + 1" />`, { onError } ) expect(onError.mock.calls[0]).toMatchObject([ { code: ErrorCodes.X_V_IF_SAME_KEY } ]) // static parseWithIfTransform(`<div v-if="ok" key="1" /><div v-else key="1" />`, { onError }) expect(onError.mock.calls[1]).toMatchObject([ { code: ErrorCodes.X_V_IF_SAME_KEY } ]) }) }) describe('codegen', () => { function assertSharedCodegen( node: IfConditionalExpression, depth: number = 0, hasElse: boolean = false ) { expect(node).toMatchObject({ type: NodeTypes.JS_CONDITIONAL_EXPRESSION, test: { content: `ok` }, consequent: { type: NodeTypes.VNODE_CALL, isBlock: true }, alternate: depth < 1 ? hasElse ? { type: NodeTypes.VNODE_CALL, isBlock: true } : { type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_COMMENT } : { type: NodeTypes.JS_CONDITIONAL_EXPRESSION, test: { content: `orNot` }, consequent: { type: NodeTypes.VNODE_CALL, isBlock: true }, alternate: hasElse ? { type: NodeTypes.VNODE_CALL, isBlock: true } : { type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_COMMENT } } }) } test('basic v-if', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok"/>`) assertSharedCodegen(codegenNode) expect(codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) expect(codegenNode.alternate).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_COMMENT }) expect(generate(root).code).toMatchSnapshot() }) test('template v-if', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<template v-if="ok"><div/>hello<p/></template>`) assertSharedCodegen(codegenNode) expect(codegenNode.consequent).toMatchObject({ tag: FRAGMENT, props: createObjectMatcher({ key: `[0]` }), children: [ { type: NodeTypes.ELEMENT, tag: 'div' }, { type: NodeTypes.TEXT, content: `hello` }, { type: NodeTypes.ELEMENT, tag: 'p' } ] }) expect(codegenNode.alternate).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: CREATE_COMMENT }) expect(generate(root).code).toMatchSnapshot() }) test('template v-if w/ single <slot/> child', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<template v-if="ok"><slot/></template>`) expect(codegenNode.consequent).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: RENDER_SLOT, arguments: ['$slots', '"default"', createObjectMatcher({ key: `[0]` })] }) expect(generate(root).code).toMatchSnapshot() }) test('v-if on <slot/>', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<slot v-if="ok"></slot>`) expect(codegenNode.consequent).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: RENDER_SLOT, arguments: ['$slots', '"default"', createObjectMatcher({ key: `[0]` })] }) expect(generate(root).code).toMatchSnapshot() }) test('v-if + v-else', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok"/><p v-else/>`) assertSharedCodegen(codegenNode, 0, true) expect(codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) expect(codegenNode.alternate).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[1]` }) }) expect(generate(root).code).toMatchSnapshot() }) test('v-if + v-else-if', () => { const { root, node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok"/><p v-else-if="orNot" />`) assertSharedCodegen(codegenNode, 1) expect(codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) const branch2 = codegenNode.alternate as ConditionalExpression expect(branch2.consequent).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[1]` }) }) expect(generate(root).code).toMatchSnapshot() }) test('v-if + v-else-if + v-else', () => { const { root, node: { codegenNode } } = parseWithIfTransform( `<div v-if="ok"/><p v-else-if="orNot"/><template v-else>fine</template>` ) assertSharedCodegen(codegenNode, 1, true) expect(codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) const branch2 = codegenNode.alternate as ConditionalExpression expect(branch2.consequent).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[1]` }) }) expect(branch2.alternate).toMatchObject({ tag: FRAGMENT, props: createObjectMatcher({ key: `[2]` }), children: [ { type: NodeTypes.TEXT, content: `fine` } ] }) expect(generate(root).code).toMatchSnapshot() }) test('multiple v-if that are sibling nodes should have different keys', () => { const { root } = parseWithIfTransform( `<div v-if="ok"/><p v-if="orNot"/>`, {}, 0 /* returnIndex, just give the default value */, 2 /* childrenLen */ ) const ifNode = root.children[0] as IfNode & { codegenNode: IfConditionalExpression } expect(ifNode.codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) const ifNode2 = root.children[1] as IfNode & { codegenNode: IfConditionalExpression } expect(ifNode2.codegenNode.consequent).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[1]` }) }) expect(generate(root).code).toMatchSnapshot() }) test('increasing key: v-if + v-else-if + v-else', () => { const { root } = parseWithIfTransform( `<div v-if="ok"/><p v-else/><div v-if="another"/><p v-else-if="orNot"/><p v-else/>`, {}, 0 /* returnIndex, just give the default value */, 2 /* childrenLen */ ) const ifNode = root.children[0] as IfNode & { codegenNode: IfConditionalExpression } expect(ifNode.codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) expect(ifNode.codegenNode.alternate).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[1]` }) }) const ifNode2 = root.children[1] as IfNode & { codegenNode: IfConditionalExpression } expect(ifNode2.codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[2]` }) }) const branch = ifNode2.codegenNode.alternate as IfConditionalExpression expect(branch.consequent).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[3]` }) }) expect(branch.alternate).toMatchObject({ tag: `"p"`, props: createObjectMatcher({ key: `[4]` }) }) expect(generate(root).code).toMatchSnapshot() }) test('key injection (only v-bind)', () => { const { node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok" v-bind="obj"/>`) const branch1 = codegenNode.consequent as VNodeCall expect(branch1.props).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: NORMALIZE_PROPS, arguments: [ { type: NodeTypes.JS_CALL_EXPRESSION, callee: MERGE_PROPS, arguments: [createObjectMatcher({ key: `[0]` }), { content: `obj` }] } ] }) }) test('key injection (before v-bind)', () => { const { node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok" id="foo" v-bind="obj"/>`) const branch1 = codegenNode.consequent as VNodeCall expect(branch1.props).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: MERGE_PROPS, arguments: [ createObjectMatcher({ key: '[0]', id: 'foo' }), { content: `obj` } ] }) }) test('key injection (after v-bind)', () => { const { node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok" v-bind="obj" id="foo"/>`) const branch1 = codegenNode.consequent as VNodeCall expect(branch1.props).toMatchObject({ type: NodeTypes.JS_CALL_EXPRESSION, callee: MERGE_PROPS, arguments: [ createObjectMatcher({ key: `[0]` }), { content: `obj` }, createObjectMatcher({ id: 'foo' }) ] }) }) test('key injection (w/ custom directive)', () => { const { node: { codegenNode } } = parseWithIfTransform(`<div v-if="ok" v-foo />`) const branch1 = codegenNode.consequent as VNodeCall expect(branch1.directives).not.toBeUndefined() expect(branch1.props).toMatchObject(createObjectMatcher({ key: `[0]` })) }) test('with spaces between branches', () => { const { node: { codegenNode } } = parseWithIfTransform( `<div v-if="ok"/> <div v-else-if="no"/> <div v-else/>` ) expect(codegenNode.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[0]` }) }) const branch = codegenNode.alternate as ConditionalExpression expect(branch.consequent).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[1]` }) }) expect(branch.alternate).toMatchObject({ tag: `"div"`, props: createObjectMatcher({ key: `[2]` }) }) }) test('with comments', () => { const { node } = parseWithIfTransform(` <template v-if="ok"> <!--comment1--> <div v-if="ok2"> <!--comment2--> </div> <!--comment3--> <b v-else/> <!--comment4--> <p/> </template> `) expect(node.type).toBe(NodeTypes.IF) expect(node.branches.length).toBe(1) const b1 = node.branches[0] expect((b1.condition as SimpleExpressionNode).content).toBe(`ok`) expect(b1.children.length).toBe(4) expect(b1.children[0].type).toBe(NodeTypes.COMMENT) expect((b1.children[0] as CommentNode).content).toBe(`comment1`) expect(b1.children[1].type).toBe(NodeTypes.IF) expect((b1.children[1] as IfNode).branches.length).toBe(2) const b1b1: ElementNode = (b1.children[1] as IfNode).branches[0] .children[0] as ElementNode expect(b1b1.type).toBe(NodeTypes.ELEMENT) expect(b1b1.tag).toBe('div') expect(b1b1.children[0].type).toBe(NodeTypes.COMMENT) expect((b1b1.children[0] as CommentNode).content).toBe('comment2') const b1b2: IfBranchNode = (b1.children[1] as IfNode) .branches[1] as IfBranchNode expect(b1b2.children[0].type).toBe(NodeTypes.COMMENT) expect((b1b2.children[0] as CommentNode).content).toBe(`comment3`) expect(b1b2.children[1].type).toBe(NodeTypes.ELEMENT) expect((b1b2.children[1] as ElementNode).tag).toBe(`b`) expect(b1.children[2].type).toBe(NodeTypes.COMMENT) expect((b1.children[2] as CommentNode).content).toBe(`comment4`) expect(b1.children[3].type).toBe(NodeTypes.ELEMENT) expect((b1.children[3] as ElementNode).tag).toBe(`p`) }) }) test('v-on with v-if', () => { const { node: { codegenNode } } = parseWithIfTransform( `<button v-on="{ click: clickEvent }" v-if="true">w/ v-if</button>` ) expect((codegenNode.consequent as any).props.type).toBe( NodeTypes.JS_CALL_EXPRESSION ) expect((codegenNode.consequent as any).props.callee).toBe(MERGE_PROPS) expect( (codegenNode.consequent as any).props.arguments[0].properties[0].value .content ).toBe('0') expect((codegenNode.consequent as any).props.arguments[1].callee).toBe( TO_HANDLERS ) }) })
packages/compiler-core/__tests__/transforms/vIf.spec.ts
0
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.00040582442306913435, 0.00017614407988730818, 0.0001680421264609322, 0.0001718880666885525, 0.00002805205440381542 ]
{ "id": 2, "code_window": [ " scope: Scope,\n", " id: Identifier,\n", " parent: Node,\n", " parentStack: Node[]\n", " ): boolean {\n", " if (id.name in scope) {\n", " if (scope[id.name]) {\n", " if (isStaticProperty(parent) && parent.shorthand) {\n", " // let binding used in a property shorthand\n", " // { foo } -> { foo: foo.value }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (hasOwn(scope, id.name)) {\n" ], "file_path": "packages/ref-transform/src/refTransform.ts", "type": "replace", "edit_start_line_idx": 311 }
import { parse } from '@babel/parser' import { babelParserDefaultPlugins } from '@vue/shared' import { transform } from '../src' function assertCode(code: string) { // parse the generated code to make sure it is valid try { parse(code, { sourceType: 'module', plugins: [...babelParserDefaultPlugins, 'typescript'] }) } catch (e: any) { console.log(code) throw e } expect(code).toMatchSnapshot() } test('$ unwrapping', () => { const { code, rootVars } = transform(` import { ref, shallowRef } from 'vue' let foo = $(ref()) let a = $(ref(1)) let b = $(shallowRef({ count: 0 })) let c = () => {} let d `) expect(code).not.toMatch(`$(ref())`) expect(code).not.toMatch(`$(ref(1))`) expect(code).not.toMatch(`$(shallowRef({`) expect(code).toMatch(`let foo = (ref())`) expect(code).toMatch(`let a = (ref(1))`) expect(code).toMatch(` let b = (shallowRef({ count: 0 })) `) // normal declarations left untouched expect(code).toMatch(`let c = () => {}`) expect(code).toMatch(`let d`) expect(rootVars).toStrictEqual(['foo', 'a', 'b']) assertCode(code) }) test('$ref & $shallowRef declarations', () => { const { code, rootVars, importedHelpers } = transform(` let foo = $ref() let a = $ref(1) let b = $shallowRef({ count: 0 }) let c = () => {} let d `) expect(code).toMatch( `import { ref as _ref, shallowRef as _shallowRef } from 'vue'` ) expect(code).not.toMatch(`$ref()`) expect(code).not.toMatch(`$ref(1)`) expect(code).not.toMatch(`$shallowRef({`) expect(code).toMatch(`let foo = _ref()`) expect(code).toMatch(`let a = _ref(1)`) expect(code).toMatch(` let b = _shallowRef({ count: 0 }) `) // normal declarations left untouched expect(code).toMatch(`let c = () => {}`) expect(code).toMatch(`let d`) expect(rootVars).toStrictEqual(['foo', 'a', 'b']) expect(importedHelpers).toStrictEqual(['ref', 'shallowRef']) assertCode(code) }) test('multi $ref declarations', () => { const { code, rootVars, importedHelpers } = transform(` let a = $ref(1), b = $ref(2), c = $ref({ count: 0 }) `) expect(code).toMatch(` let a = _ref(1), b = _ref(2), c = _ref({ count: 0 }) `) expect(rootVars).toStrictEqual(['a', 'b', 'c']) expect(importedHelpers).toStrictEqual(['ref']) assertCode(code) }) test('$computed declaration', () => { const { code, rootVars, importedHelpers } = transform(` let a = $computed(() => 1) `) expect(code).toMatch(` let a = _computed(() => 1) `) expect(rootVars).toStrictEqual(['a']) expect(importedHelpers).toStrictEqual(['computed']) assertCode(code) }) test('mixing $ref & $computed declarations', () => { const { code, rootVars, importedHelpers } = transform(` let a = $ref(1), b = $computed(() => a + 1) `) expect(code).toMatch(` let a = _ref(1), b = _computed(() => a.value + 1) `) expect(rootVars).toStrictEqual(['a', 'b']) expect(importedHelpers).toStrictEqual(['ref', 'computed']) assertCode(code) }) test('accessing ref binding', () => { const { code } = transform(` let a = $ref(1) console.log(a) function get() { return a + 1 } `) expect(code).toMatch(`console.log(a.value)`) expect(code).toMatch(`return a.value + 1`) assertCode(code) }) test('cases that should not append .value', () => { const { code } = transform(` let a = $ref(1) console.log(b.a) function get(a) { return a + 1 } `) expect(code).not.toMatch(`a.value`) }) test('mutating ref binding', () => { const { code } = transform(` let a = $ref(1) let b = $ref({ count: 0 }) function inc() { a++ a = a + 1 b.count++ b.count = b.count + 1 ;({ a } = { a: 2 }) ;[a] = [1] } `) expect(code).toMatch(`a.value++`) expect(code).toMatch(`a.value = a.value + 1`) expect(code).toMatch(`b.value.count++`) expect(code).toMatch(`b.value.count = b.value.count + 1`) expect(code).toMatch(`;({ a: a.value } = { a: 2 })`) expect(code).toMatch(`;[a.value] = [1]`) assertCode(code) }) test('using ref binding in property shorthand', () => { const { code } = transform(` let a = $ref(1) const b = { a } function test() { const { a } = b } `) expect(code).toMatch(`const b = { a: a.value }`) // should not convert destructure expect(code).toMatch(`const { a } = b`) assertCode(code) }) test('should not rewrite scope variable', () => { const { code } = transform(` let a = $ref(1) let b = $ref(1) let d = $ref(1) const e = 1 function test() { const a = 2 console.log(a) console.log(b) let c = { c: 3 } console.log(c) console.log(d) console.log(e) } `) expect(code).toMatch('console.log(a)') expect(code).toMatch('console.log(b.value)') expect(code).toMatch('console.log(c)') expect(code).toMatch('console.log(d.value)') expect(code).toMatch('console.log(e)') assertCode(code) }) test('object destructure', () => { const { code, rootVars } = transform(` let n = $ref(1), { a, b: c, d = 1, e: f = 2, ...g } = $(useFoo()) let { foo } = $(useSomthing(() => 1)); console.log(n, a, c, d, f, g, foo) `) expect(code).toMatch( `let n = _ref(1), { a: __a, b: __c, d: __d = 1, e: __f = 2, ...__g } = (useFoo())` ) expect(code).toMatch(`let { foo: __foo } = (useSomthing(() => 1))`) expect(code).toMatch(`\nconst a = _shallowRef(__a);`) expect(code).not.toMatch(`\nconst b = _shallowRef(__b);`) expect(code).toMatch(`\nconst c = _shallowRef(__c);`) expect(code).toMatch(`\nconst d = _shallowRef(__d);`) expect(code).not.toMatch(`\nconst e = _shallowRef(__e);`) expect(code).toMatch(`\nconst f = _shallowRef(__f);`) expect(code).toMatch(`\nconst g = _shallowRef(__g);`) expect(code).toMatch(`\nconst foo = _shallowRef(__foo);`) expect(code).toMatch( `console.log(n.value, a.value, c.value, d.value, f.value, g.value, foo.value)` ) expect(rootVars).toStrictEqual(['n', 'a', 'c', 'd', 'f', 'g', 'foo']) assertCode(code) }) test('array destructure', () => { const { code, rootVars } = transform(` let n = $ref(1), [a, b = 1, ...c] = $(useFoo()) console.log(n, a, b, c) `) expect(code).toMatch(`let n = _ref(1), [__a, __b = 1, ...__c] = (useFoo())`) expect(code).toMatch(`\nconst a = _shallowRef(__a);`) expect(code).toMatch(`\nconst b = _shallowRef(__b);`) expect(code).toMatch(`\nconst c = _shallowRef(__c);`) expect(code).toMatch(`console.log(n.value, a.value, b.value, c.value)`) expect(rootVars).toStrictEqual(['n', 'a', 'b', 'c']) assertCode(code) }) test('nested destructure', () => { const { code, rootVars } = transform(` let [{ a: { b }}] = $(useFoo()) let { c: [d, e] } = $(useBar()) console.log(b, d, e) `) expect(code).toMatch(`let [{ a: { b: __b }}] = (useFoo())`) expect(code).toMatch(`let { c: [__d, __e] } = (useBar())`) expect(code).not.toMatch(`\nconst a = _shallowRef(__a);`) expect(code).not.toMatch(`\nconst c = _shallowRef(__c);`) expect(code).toMatch(`\nconst b = _shallowRef(__b);`) expect(code).toMatch(`\nconst d = _shallowRef(__d);`) expect(code).toMatch(`\nconst e = _shallowRef(__e);`) expect(rootVars).toStrictEqual(['b', 'd', 'e']) assertCode(code) }) test('$$', () => { const { code } = transform(` let a = $ref(1) const b = $$(a) const c = $$({ a }) callExternal($$(a)) `) expect(code).toMatch(`const b = (a)`) expect(code).toMatch(`const c = ({ a })`) expect(code).toMatch(`callExternal((a))`) assertCode(code) }) test('nested scopes', () => { const { code, rootVars } = transform(` let a = $ref(0) let b = $ref(0) let c = 0 a++ // outer a b++ // outer b c++ // outer c let bar = $ref(0) bar++ // outer bar function foo({ a }) { a++ // inner a b++ // inner b let c = $ref(0) c++ // inner c let d = $ref(0) function bar(c) { c++ // nested c d++ // nested d } bar() // inner bar if (true) { let a = $ref(0) a++ // if block a } return $$({ a, b, c, d }) } `) expect(rootVars).toStrictEqual(['a', 'b', 'bar']) expect(code).toMatch('a.value++ // outer a') expect(code).toMatch('b.value++ // outer b') expect(code).toMatch('c++ // outer c') expect(code).toMatch('a++ // inner a') // shadowed by function arg expect(code).toMatch('b.value++ // inner b') expect(code).toMatch('c.value++ // inner c') // shadowed by local ref binding expect(code).toMatch('c++ // nested c') // shadowed by inline fn arg expect(code).toMatch(`d.value++ // nested d`) expect(code).toMatch(`a.value++ // if block a`) // if block expect(code).toMatch(`bar.value++ // outer bar`) // inner bar shadowed by function declaration expect(code).toMatch(`bar() // inner bar`) expect(code).toMatch(`return ({ a, b, c, d })`) assertCode(code) }) //#4062 test('should not rewrite type identifiers', () => { const { code } = transform( `const props = defineProps<{msg: string; ids?: string[]}>() let ids = $ref([])`, { parserPlugins: ['typescript'] } ) expect(code).not.toMatch('.value') assertCode(code) }) // #4254 test('handle TS casting syntax', () => { const { code } = transform( ` let a = $ref(1) console.log(a!) console.log(a! + 1) console.log(a as number) console.log((a as number) + 1) console.log(<number>a) console.log(<number>a + 1) console.log(a! + (a as number)) console.log(a! + <number>a) console.log((a as number) + <number>a) `, { parserPlugins: ['typescript'] } ) expect(code).toMatch('console.log(a.value!)') expect(code).toMatch('console.log(a.value as number)') expect(code).toMatch('console.log(<number>a.value)') assertCode(code) }) describe('errors', () => { test('non-let $ref declaration', () => { expect(() => transform(`const a = $ref(1)`)).toThrow( `$ref() bindings can only be declared with let` ) }) test('$ref w/ destructure', () => { expect(() => transform(`let { a } = $ref(1)`)).toThrow( `cannot be used with destructure` ) }) test('$computed w/ destructure', () => { expect(() => transform(`let { a } = $computed(() => 1)`)).toThrow( `cannot be used with destructure` ) }) test('warn usage in non-init positions', () => { expect(() => transform( `let bar = $ref(1) bar = $ref(2)` ) ).toThrow(`$ref can only be used as the initializer`) expect(() => transform(`let bar = { foo: $computed(1) }`)).toThrow( `$computed can only be used as the initializer` ) }) })
packages/ref-transform/__tests__/refTransform.spec.ts
1
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.0017243515467271209, 0.0002526295720599592, 0.00016278591647278517, 0.0001755802077241242, 0.00030642456840723753 ]
{ "id": 2, "code_window": [ " scope: Scope,\n", " id: Identifier,\n", " parent: Node,\n", " parentStack: Node[]\n", " ): boolean {\n", " if (id.name in scope) {\n", " if (scope[id.name]) {\n", " if (isStaticProperty(parent) && parent.shorthand) {\n", " // let binding used in a property shorthand\n", " // { foo } -> { foo: foo.value }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (hasOwn(scope, id.name)) {\n" ], "file_path": "packages/ref-transform/src/refTransform.ts", "type": "replace", "edit_start_line_idx": 311 }
// since v-memo really is a compiler + runtime combo feature, we are performing // more of an itegration test here. import { ComponentOptions, createApp, nextTick } from 'vue' describe('v-memo', () => { function mount(options: ComponentOptions): [HTMLElement, any] { const app = createApp(options) const el = document.createElement('div') const vm = app.mount(el) return [el, vm] } test('on with external array', async () => { const [el, vm] = mount({ template: `<div v-memo="arr">{{ arr[0] }} {{ arr[1] }} {{arr[2] ?? '_' }} ({{c}})</div>{{c}}`, data: () => ({ arr: [0, 0], c: 0 }) }) expect(el.innerHTML).toBe(`<div>0 0 _ (0)</div>0`) let [x, y, z] = [0, 1, 2] // change at index x - should update vm.arr[x]++ vm.c++ await nextTick() expect(el.innerHTML).toBe(`<div>1 0 _ (1)</div>1`) // change at index y - should update vm.arr[y]++ vm.c++ await nextTick() expect(el.innerHTML).toBe(`<div>1 1 _ (2)</div>2`) // noop change - should NOT update vm.arr[x] = vm.arr[0] vm.arr[y] = vm.arr[1] vm.c++ await nextTick() expect(el.innerHTML).toBe(`<div>1 1 _ (2)</div>3`) // add item 3rd item - should update vm.arr[z] = 0 vm.c++ await nextTick() expect(el.innerHTML).toBe(`<div>1 1 0 (4)</div>4`) // remove 3rd item - should update vm.arr = vm.arr.slice(0, vm.arr.length - 1) vm.c++ await nextTick() expect(el.innerHTML).toBe(`<div>1 1 _ (5)</div>5`) }) test('on normal element', async () => { const [el, vm] = mount({ template: `<div v-memo="[x]">{{ x }} {{ y }}</div>`, data: () => ({ x: 0, y: 0 }) }) expect(el.innerHTML).toBe(`<div>0 0</div>`) vm.x++ // should update await nextTick() expect(el.innerHTML).toBe(`<div>1 0</div>`) vm.y++ // should not update await nextTick() expect(el.innerHTML).toBe(`<div>1 0</div>`) vm.x++ // should update await nextTick() expect(el.innerHTML).toBe(`<div>2 1</div>`) }) test('on component', async () => { const [el, vm] = mount({ template: `<Comp v-memo="[x]" :x="x" :y="y"></Comp>`, data: () => ({ x: 0, y: 0 }), components: { Comp: { props: ['x', 'y'], template: `<div>{{x}} {{y}}</div>` } } }) expect(el.innerHTML).toBe(`<div>0 0</div>`) vm.x++ // should update await nextTick() expect(el.innerHTML).toBe(`<div>1 0</div>`) vm.y++ // should not update await nextTick() expect(el.innerHTML).toBe(`<div>1 0</div>`) vm.x++ // should update await nextTick() expect(el.innerHTML).toBe(`<div>2 1</div>`) }) test('on v-if', async () => { const [el, vm] = mount({ template: `<div v-if="ok" v-memo="[x]">{{ x }} {{ y }}</div> <div v-else v-memo="[y]">{{ y }} {{ x }}</div>`, data: () => ({ ok: true, x: 0, y: 0 }) }) expect(el.innerHTML).toBe(`<div>0 0</div>`) vm.x++ // should update await nextTick() expect(el.innerHTML).toBe(`<div>1 0</div>`) vm.y++ // should not update await nextTick() expect(el.innerHTML).toBe(`<div>1 0</div>`) vm.x++ // should update await nextTick() expect(el.innerHTML).toBe(`<div>2 1</div>`) vm.ok = false await nextTick() expect(el.innerHTML).toBe(`<div>1 2</div>`) vm.y++ // should update await nextTick() expect(el.innerHTML).toBe(`<div>2 2</div>`) vm.x++ // should not update await nextTick() expect(el.innerHTML).toBe(`<div>2 2</div>`) vm.y++ // should update await nextTick() expect(el.innerHTML).toBe(`<div>3 3</div>`) }) test('on v-for', async () => { const [el, vm] = mount({ template: `<div v-for="{ x } in list" :key="x" v-memo="[x, x === y]">` + `{{ x }} {{ x === y ? 'yes' : 'no' }} {{ z }}` + `</div>`, data: () => ({ list: [{ x: 1 }, { x: 2 }, { x: 3 }], y: 1, z: 'z' }) }) expect(el.innerHTML).toBe( `<div>1 yes z</div><div>2 no z</div><div>3 no z</div>` ) vm.y = 2 await nextTick() expect(el.innerHTML).toBe( `<div>1 no z</div><div>2 yes z</div><div>3 no z</div>` ) vm.list[0].x = 4 await nextTick() expect(el.innerHTML).toBe( `<div>4 no z</div><div>2 yes z</div><div>3 no z</div>` ) vm.list[0].x = 5 vm.y = 5 await nextTick() expect(el.innerHTML).toBe( `<div>5 yes z</div><div>2 no z</div><div>3 no z</div>` ) vm.z = 'zz' await nextTick() // should not update expect(el.innerHTML).toBe( `<div>5 yes z</div><div>2 no z</div><div>3 no z</div>` ) }) test('on v-for /w constant expression ', async () => { const [el, vm] = mount({ template: `<div v-for="item in 3" v-memo="[count < 2 ? true : count]"> {{count}} </div>`, data: () => ({ count: 0 }) }) expect(el.innerHTML).toBe(`<div>0</div><div>0</div><div>0</div>`) vm.count = 1 await nextTick() // should not update expect(el.innerHTML).toBe(`<div>0</div><div>0</div><div>0</div>`) vm.count = 2 await nextTick() // should update expect(el.innerHTML).toBe(`<div>2</div><div>2</div><div>2</div>`) }) })
packages/runtime-core/__tests__/helpers/withMemo.spec.ts
0
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.000179673355887644, 0.00017669038788881153, 0.00016555629554204643, 0.0001774789998307824, 0.0000030105916266620625 ]
{ "id": 2, "code_window": [ " scope: Scope,\n", " id: Identifier,\n", " parent: Node,\n", " parentStack: Node[]\n", " ): boolean {\n", " if (id.name in scope) {\n", " if (scope[id.name]) {\n", " if (isStaticProperty(parent) && parent.shorthand) {\n", " // let binding used in a property shorthand\n", " // { foo } -> { foo: foo.value }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (hasOwn(scope, id.name)) {\n" ], "file_path": "packages/ref-transform/src/refTransform.ts", "type": "replace", "edit_start_line_idx": 311 }
import { getCurrentInstance, SetupContext, ComponentInternalInstance, ComponentOptions } from '../component' import { cloneVNode, Comment, isSameVNodeType, VNode, VNodeArrayChildren, Fragment } from '../vnode' import { warn } from '../warning' import { isKeepAlive } from './KeepAlive' import { toRaw } from '@vue/reactivity' import { callWithAsyncErrorHandling, ErrorCodes } from '../errorHandling' import { ShapeFlags, PatchFlags } from '@vue/shared' import { onBeforeUnmount, onMounted } from '../apiLifecycle' import { RendererElement } from '../renderer' export interface BaseTransitionProps<HostElement = RendererElement> { mode?: 'in-out' | 'out-in' | 'default' appear?: boolean // If true, indicates this is a transition that doesn't actually insert/remove // the element, but toggles the show / hidden status instead. // The transition hooks are injected, but will be skipped by the renderer. // Instead, a custom directive can control the transition by calling the // injected hooks (e.g. v-show). persisted?: boolean // Hooks. Using camel case for easier usage in render functions & JSX. // In templates these can be written as @before-enter="xxx" as prop names // are camelized. onBeforeEnter?: (el: HostElement) => void onEnter?: (el: HostElement, done: () => void) => void onAfterEnter?: (el: HostElement) => void onEnterCancelled?: (el: HostElement) => void // leave onBeforeLeave?: (el: HostElement) => void onLeave?: (el: HostElement, done: () => void) => void onAfterLeave?: (el: HostElement) => void onLeaveCancelled?: (el: HostElement) => void // only fired in persisted mode // appear onBeforeAppear?: (el: HostElement) => void onAppear?: (el: HostElement, done: () => void) => void onAfterAppear?: (el: HostElement) => void onAppearCancelled?: (el: HostElement) => void } export interface TransitionHooks< HostElement extends RendererElement = RendererElement > { mode: BaseTransitionProps['mode'] persisted: boolean beforeEnter(el: HostElement): void enter(el: HostElement): void leave(el: HostElement, remove: () => void): void clone(vnode: VNode): TransitionHooks<HostElement> // optional afterLeave?(): void delayLeave?( el: HostElement, earlyRemove: () => void, delayedLeave: () => void ): void delayedLeave?(): void } export type TransitionHookCaller = ( hook: ((el: any) => void) | Array<(el: any) => void> | undefined, args?: any[] ) => void export type PendingCallback = (cancelled?: boolean) => void export interface TransitionState { isMounted: boolean isLeaving: boolean isUnmounting: boolean // Track pending leave callbacks for children of the same key. // This is used to force remove leaving a child when a new copy is entering. leavingVNodes: Map<any, Record<string, VNode>> } export interface TransitionElement { // in persisted mode (e.g. v-show), the same element is toggled, so the // pending enter/leave callbacks may need to be cancelled if the state is toggled // before it finishes. _enterCb?: PendingCallback _leaveCb?: PendingCallback } export function useTransitionState(): TransitionState { const state: TransitionState = { isMounted: false, isLeaving: false, isUnmounting: false, leavingVNodes: new Map() } onMounted(() => { state.isMounted = true }) onBeforeUnmount(() => { state.isUnmounting = true }) return state } const TransitionHookValidator = [Function, Array] const BaseTransitionImpl: ComponentOptions = { name: `BaseTransition`, props: { mode: String, appear: Boolean, persisted: Boolean, // enter onBeforeEnter: TransitionHookValidator, onEnter: TransitionHookValidator, onAfterEnter: TransitionHookValidator, onEnterCancelled: TransitionHookValidator, // leave onBeforeLeave: TransitionHookValidator, onLeave: TransitionHookValidator, onAfterLeave: TransitionHookValidator, onLeaveCancelled: TransitionHookValidator, // appear onBeforeAppear: TransitionHookValidator, onAppear: TransitionHookValidator, onAfterAppear: TransitionHookValidator, onAppearCancelled: TransitionHookValidator }, setup(props: BaseTransitionProps, { slots }: SetupContext) { const instance = getCurrentInstance()! const state = useTransitionState() let prevTransitionKey: any return () => { const children = slots.default && getTransitionRawChildren(slots.default(), true) if (!children || !children.length) { return } // warn multiple elements if (__DEV__ && children.length > 1) { warn( '<transition> can only be used on a single element or component. Use ' + '<transition-group> for lists.' ) } // there's no need to track reactivity for these props so use the raw // props for a bit better perf const rawProps = toRaw(props) const { mode } = rawProps // check mode if (__DEV__ && mode && !['in-out', 'out-in', 'default'].includes(mode)) { warn(`invalid <transition> mode: ${mode}`) } // at this point children has a guaranteed length of 1. const child = children[0] if (state.isLeaving) { return emptyPlaceholder(child) } // in the case of <transition><keep-alive/></transition>, we need to // compare the type of the kept-alive children. const innerChild = getKeepAliveChild(child) if (!innerChild) { return emptyPlaceholder(child) } const enterHooks = resolveTransitionHooks( innerChild, rawProps, state, instance ) setTransitionHooks(innerChild, enterHooks) const oldChild = instance.subTree const oldInnerChild = oldChild && getKeepAliveChild(oldChild) let transitionKeyChanged = false const { getTransitionKey } = innerChild.type as any if (getTransitionKey) { const key = getTransitionKey() if (prevTransitionKey === undefined) { prevTransitionKey = key } else if (key !== prevTransitionKey) { prevTransitionKey = key transitionKeyChanged = true } } // handle mode if ( oldInnerChild && oldInnerChild.type !== Comment && (!isSameVNodeType(innerChild, oldInnerChild) || transitionKeyChanged) ) { const leavingHooks = resolveTransitionHooks( oldInnerChild, rawProps, state, instance ) // update old tree's hooks in case of dynamic transition setTransitionHooks(oldInnerChild, leavingHooks) // switching between different views if (mode === 'out-in') { state.isLeaving = true // return placeholder node and queue update when leave finishes leavingHooks.afterLeave = () => { state.isLeaving = false instance.update() } return emptyPlaceholder(child) } else if (mode === 'in-out' && innerChild.type !== Comment) { leavingHooks.delayLeave = ( el: TransitionElement, earlyRemove, delayedLeave ) => { const leavingVNodesCache = getLeavingNodesForType( state, oldInnerChild ) leavingVNodesCache[String(oldInnerChild.key)] = oldInnerChild // early removal callback el._leaveCb = () => { earlyRemove() el._leaveCb = undefined delete enterHooks.delayedLeave } enterHooks.delayedLeave = delayedLeave } } } return child } } } if (__COMPAT__) { BaseTransitionImpl.__isBuiltIn = true } // export the public type for h/tsx inference // also to avoid inline import() in generated d.ts files export const BaseTransition = BaseTransitionImpl as any as { new (): { $props: BaseTransitionProps<any> } } function getLeavingNodesForType( state: TransitionState, vnode: VNode ): Record<string, VNode> { const { leavingVNodes } = state let leavingVNodesCache = leavingVNodes.get(vnode.type)! if (!leavingVNodesCache) { leavingVNodesCache = Object.create(null) leavingVNodes.set(vnode.type, leavingVNodesCache) } return leavingVNodesCache } // The transition hooks are attached to the vnode as vnode.transition // and will be called at appropriate timing in the renderer. export function resolveTransitionHooks( vnode: VNode, props: BaseTransitionProps<any>, state: TransitionState, instance: ComponentInternalInstance ): TransitionHooks { const { appear, mode, persisted = false, onBeforeEnter, onEnter, onAfterEnter, onEnterCancelled, onBeforeLeave, onLeave, onAfterLeave, onLeaveCancelled, onBeforeAppear, onAppear, onAfterAppear, onAppearCancelled } = props const key = String(vnode.key) const leavingVNodesCache = getLeavingNodesForType(state, vnode) const callHook: TransitionHookCaller = (hook, args) => { hook && callWithAsyncErrorHandling( hook, instance, ErrorCodes.TRANSITION_HOOK, args ) } const hooks: TransitionHooks<TransitionElement> = { mode, persisted, beforeEnter(el) { let hook = onBeforeEnter if (!state.isMounted) { if (appear) { hook = onBeforeAppear || onBeforeEnter } else { return } } // for same element (v-show) if (el._leaveCb) { el._leaveCb(true /* cancelled */) } // for toggled element with same key (v-if) const leavingVNode = leavingVNodesCache[key] if ( leavingVNode && isSameVNodeType(vnode, leavingVNode) && leavingVNode.el!._leaveCb ) { // force early removal (not cancelled) leavingVNode.el!._leaveCb() } callHook(hook, [el]) }, enter(el) { let hook = onEnter let afterHook = onAfterEnter let cancelHook = onEnterCancelled if (!state.isMounted) { if (appear) { hook = onAppear || onEnter afterHook = onAfterAppear || onAfterEnter cancelHook = onAppearCancelled || onEnterCancelled } else { return } } let called = false const done = (el._enterCb = (cancelled?) => { if (called) return called = true if (cancelled) { callHook(cancelHook, [el]) } else { callHook(afterHook, [el]) } if (hooks.delayedLeave) { hooks.delayedLeave() } el._enterCb = undefined }) if (hook) { hook(el, done) if (hook.length <= 1) { done() } } else { done() } }, leave(el, remove) { const key = String(vnode.key) if (el._enterCb) { el._enterCb(true /* cancelled */) } if (state.isUnmounting) { return remove() } callHook(onBeforeLeave, [el]) let called = false const done = (el._leaveCb = (cancelled?) => { if (called) return called = true remove() if (cancelled) { callHook(onLeaveCancelled, [el]) } else { callHook(onAfterLeave, [el]) } el._leaveCb = undefined if (leavingVNodesCache[key] === vnode) { delete leavingVNodesCache[key] } }) leavingVNodesCache[key] = vnode if (onLeave) { onLeave(el, done) if (onLeave.length <= 1) { done() } } else { done() } }, clone(vnode) { return resolveTransitionHooks(vnode, props, state, instance) } } return hooks } // the placeholder really only handles one special case: KeepAlive // in the case of a KeepAlive in a leave phase we need to return a KeepAlive // placeholder with empty content to avoid the KeepAlive instance from being // unmounted. function emptyPlaceholder(vnode: VNode): VNode | undefined { if (isKeepAlive(vnode)) { vnode = cloneVNode(vnode) vnode.children = null return vnode } } function getKeepAliveChild(vnode: VNode): VNode | undefined { return isKeepAlive(vnode) ? vnode.children ? ((vnode.children as VNodeArrayChildren)[0] as VNode) : undefined : vnode } export function setTransitionHooks(vnode: VNode, hooks: TransitionHooks) { if (vnode.shapeFlag & ShapeFlags.COMPONENT && vnode.component) { setTransitionHooks(vnode.component.subTree, hooks) } else if (__FEATURE_SUSPENSE__ && vnode.shapeFlag & ShapeFlags.SUSPENSE) { vnode.ssContent!.transition = hooks.clone(vnode.ssContent!) vnode.ssFallback!.transition = hooks.clone(vnode.ssFallback!) } else { vnode.transition = hooks } } export function getTransitionRawChildren( children: VNode[], keepComment: boolean = false ): VNode[] { let ret: VNode[] = [] let keyedFragmentCount = 0 for (let i = 0; i < children.length; i++) { const child = children[i] // handle fragment children case, e.g. v-for if (child.type === Fragment) { if (child.patchFlag & PatchFlags.KEYED_FRAGMENT) keyedFragmentCount++ ret = ret.concat( getTransitionRawChildren(child.children as VNode[], keepComment) ) } // comment placeholders should be skipped, e.g. v-if else if (keepComment || child.type !== Comment) { ret.push(child) } } // #1126 if a transition children list contains multiple sub fragments, these // fragments will be merged into a flat children array. Since each v-for // fragment may contain different static bindings inside, we need to de-op // these children to force full diffs to ensure correct behavior. if (keyedFragmentCount > 1) { for (let i = 0; i < ret.length; i++) { ret[i].patchFlag = PatchFlags.BAIL } } return ret }
packages/runtime-core/src/components/BaseTransition.ts
0
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.00017744439537636936, 0.0001722794841043651, 0.00016195126227103174, 0.00017316760204266757, 0.0000032065236155176535 ]
{ "id": 2, "code_window": [ " scope: Scope,\n", " id: Identifier,\n", " parent: Node,\n", " parentStack: Node[]\n", " ): boolean {\n", " if (id.name in scope) {\n", " if (scope[id.name]) {\n", " if (isStaticProperty(parent) && parent.shorthand) {\n", " // let binding used in a property shorthand\n", " // { foo } -> { foo: foo.value }\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " if (hasOwn(scope, id.name)) {\n" ], "file_path": "packages/ref-transform/src/refTransform.ts", "type": "replace", "edit_start_line_idx": 311 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`compiler: v-if codegen basic v-if 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { openBlock: _openBlock, createElementBlock: _createElementBlock, createCommentVNode: _createCommentVNode } = _Vue return ok ? (_openBlock(), _createElementBlock(\\"div\\", { key: 0 })) : _createCommentVNode(\\"v-if\\", true) } }" `; exports[`compiler: v-if codegen increasing key: v-if + v-else-if + v-else 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { openBlock: _openBlock, createElementBlock: _createElementBlock, createCommentVNode: _createCommentVNode, Fragment: _Fragment } = _Vue return (_openBlock(), _createElementBlock(_Fragment, null, [ ok ? (_openBlock(), _createElementBlock(\\"div\\", { key: 0 })) : (_openBlock(), _createElementBlock(\\"p\\", { key: 1 })), another ? (_openBlock(), _createElementBlock(\\"div\\", { key: 2 })) : orNot ? (_openBlock(), _createElementBlock(\\"p\\", { key: 3 })) : (_openBlock(), _createElementBlock(\\"p\\", { key: 4 })) ], 64 /* STABLE_FRAGMENT */)) } }" `; exports[`compiler: v-if codegen multiple v-if that are sibling nodes should have different keys 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { openBlock: _openBlock, createElementBlock: _createElementBlock, createCommentVNode: _createCommentVNode, Fragment: _Fragment } = _Vue return (_openBlock(), _createElementBlock(_Fragment, null, [ ok ? (_openBlock(), _createElementBlock(\\"div\\", { key: 0 })) : _createCommentVNode(\\"v-if\\", true), orNot ? (_openBlock(), _createElementBlock(\\"p\\", { key: 1 })) : _createCommentVNode(\\"v-if\\", true) ], 64 /* STABLE_FRAGMENT */)) } }" `; exports[`compiler: v-if codegen template v-if 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { createElementVNode: _createElementVNode, Fragment: _Fragment, openBlock: _openBlock, createElementBlock: _createElementBlock, createCommentVNode: _createCommentVNode } = _Vue return ok ? (_openBlock(), _createElementBlock(_Fragment, { key: 0 }, [ _createElementVNode(\\"div\\"), \\"hello\\", _createElementVNode(\\"p\\") ], 64 /* STABLE_FRAGMENT */)) : _createCommentVNode(\\"v-if\\", true) } }" `; exports[`compiler: v-if codegen template v-if w/ single <slot/> child 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderSlot: _renderSlot, createCommentVNode: _createCommentVNode } = _Vue return ok ? _renderSlot($slots, \\"default\\", { key: 0 }) : _createCommentVNode(\\"v-if\\", true) } }" `; exports[`compiler: v-if codegen v-if + v-else 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { openBlock: _openBlock, createElementBlock: _createElementBlock, createCommentVNode: _createCommentVNode } = _Vue return ok ? (_openBlock(), _createElementBlock(\\"div\\", { key: 0 })) : (_openBlock(), _createElementBlock(\\"p\\", { key: 1 })) } }" `; exports[`compiler: v-if codegen v-if + v-else-if + v-else 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { openBlock: _openBlock, createElementBlock: _createElementBlock, createCommentVNode: _createCommentVNode, Fragment: _Fragment } = _Vue return ok ? (_openBlock(), _createElementBlock(\\"div\\", { key: 0 })) : orNot ? (_openBlock(), _createElementBlock(\\"p\\", { key: 1 })) : (_openBlock(), _createElementBlock(_Fragment, { key: 2 }, [\\"fine\\"], 2112 /* STABLE_FRAGMENT, DEV_ROOT_FRAGMENT */)) } }" `; exports[`compiler: v-if codegen v-if + v-else-if 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { openBlock: _openBlock, createElementBlock: _createElementBlock, createCommentVNode: _createCommentVNode } = _Vue return ok ? (_openBlock(), _createElementBlock(\\"div\\", { key: 0 })) : orNot ? (_openBlock(), _createElementBlock(\\"p\\", { key: 1 })) : _createCommentVNode(\\"v-if\\", true) } }" `; exports[`compiler: v-if codegen v-if on <slot/> 1`] = ` "const _Vue = Vue return function render(_ctx, _cache) { with (_ctx) { const { renderSlot: _renderSlot, createCommentVNode: _createCommentVNode } = _Vue return ok ? _renderSlot($slots, \\"default\\", { key: 0 }) : _createCommentVNode(\\"v-if\\", true) } }" `;
packages/compiler-core/__tests__/transforms/__snapshots__/vIf.spec.ts.snap
0
https://github.com/vuejs/core/commit/0178f4ed3187dff439ed3097c8c89555b2a6749f
[ 0.00017567187023814768, 0.00017121536075137556, 0.00016314875392708927, 0.00017216807464137673, 0.0000035549815038393717 ]
{ "id": 0, "code_window": [ " dispatch(notifyApp(createSuccessNotification('Dashboard Imported', dashboardTitle)));\n", " dispatch(loadPluginDashboards());\n", " };\n", "}\n", "\n", "export function removeDashboard(uri: string): ThunkResult<void> {\n", " return async (dispatch) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export function removeDashboard(uid: string): ThunkResult<void> {\n" ], "file_path": "public/app/features/dashboard/state/actions.ts", "type": "replace", "edit_start_line_idx": 108 }
// Libraries import React, { PureComponent } from 'react'; import { connect, ConnectedProps } from 'react-redux'; // Components import Page from 'app/core/components/Page/Page'; import DashboardTable from './DashboardsTable'; // Actions & Selectors import { getNavModel } from 'app/core/selectors/navModel'; import { loadDataSource } from './state/actions'; import { loadPluginDashboards } from '../plugins/admin/state/actions'; import { importDashboard, removeDashboard } from '../dashboard/state/actions'; import { getDataSource } from './state/selectors'; // Types import { PluginDashboard, StoreState } from 'app/types'; import { GrafanaRouteComponentProps } from 'app/core/navigation/types'; export interface OwnProps extends GrafanaRouteComponentProps<{ uid: string }> {} function mapStateToProps(state: StoreState, props: OwnProps) { const dataSourceId = props.match.params.uid; return { navModel: getNavModel(state.navIndex, `datasource-dashboards-${dataSourceId}`), dashboards: state.plugins.dashboards, dataSource: getDataSource(state.dataSources, dataSourceId), isLoading: state.plugins.isLoadingPluginDashboards, dataSourceId, }; } const mapDispatchToProps = { importDashboard, loadDataSource, loadPluginDashboards, removeDashboard, }; const connector = connect(mapStateToProps, mapDispatchToProps); export type Props = OwnProps & ConnectedProps<typeof connector>; export class DataSourceDashboards extends PureComponent<Props> { async componentDidMount() { const { loadDataSource, dataSourceId } = this.props; await loadDataSource(dataSourceId); this.props.loadPluginDashboards(); } onImport = (dashboard: PluginDashboard, overwrite: boolean) => { const { dataSource, importDashboard } = this.props; const data: any = { pluginId: dashboard.pluginId, path: dashboard.path, overwrite, inputs: [], }; if (dataSource) { data.inputs.push({ name: '*', type: 'datasource', pluginId: dataSource.type, value: dataSource.name, }); } importDashboard(data, dashboard.title); }; onRemove = (dashboard: PluginDashboard) => { this.props.removeDashboard(dashboard.importedUri); }; render() { const { dashboards, navModel, isLoading } = this.props; return ( <Page navModel={navModel}> <Page.Contents isLoading={isLoading}> <DashboardTable dashboards={dashboards} onImport={(dashboard, overwrite) => this.onImport(dashboard, overwrite)} onRemove={(dashboard) => this.onRemove(dashboard)} /> </Page.Contents> </Page> ); } } export default connector(DataSourceDashboards);
public/app/features/datasources/DataSourceDashboards.tsx
1
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.9990478157997131, 0.2730857729911804, 0.00024819481768645346, 0.0036445902660489082, 0.41979676485061646 ]
{ "id": 0, "code_window": [ " dispatch(notifyApp(createSuccessNotification('Dashboard Imported', dashboardTitle)));\n", " dispatch(loadPluginDashboards());\n", " };\n", "}\n", "\n", "export function removeDashboard(uri: string): ThunkResult<void> {\n", " return async (dispatch) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export function removeDashboard(uid: string): ThunkResult<void> {\n" ], "file_path": "public/app/features/dashboard/state/actions.ts", "type": "replace", "edit_start_line_idx": 108 }
package build import ( "bytes" "flag" "fmt" "go/build" "log" "os" "path/filepath" "strconv" "strings" "time" ) const ( GoOSWindows = "windows" GoOSLinux = "linux" ServerBinary = "grafana-server" CLIBinary = "grafana-cli" ) var binaries = []string{ServerBinary, CLIBinary} func logError(message string, err error) int { log.Println(message, err) return 1 } // RunCmd runs the build command and returns the exit code func RunCmd() int { opts := BuildOptsFromFlags() wd, err := os.Getwd() if err != nil { return logError("Error getting working directory", err) } packageJSON, err := OpenPackageJSON(wd) if err != nil { return logError("Error opening package json", err) } opts.version = packageJSON.Version version, iteration := LinuxPackageVersion(packageJSON.Version, opts.buildID) if opts.printGenVersion { fmt.Print(genPackageVersion(version, iteration)) return 0 } log.Printf("Version: %s, Linux Version: %s, Package Iteration: %s\n", version, version, iteration) if flag.NArg() == 0 { log.Println("Usage: go run build.go build") return 1 } for _, cmd := range flag.Args() { switch cmd { case "setup": setup(opts.goos) case "build-srv", "build-server": if !opts.isDev { clean(opts) } if err := doBuild("grafana-server", "./pkg/cmd/grafana-server", opts); err != nil { log.Println(err) return 1 } case "build-cli": clean(opts) if err := doBuild("grafana-cli", "./pkg/cmd/grafana-cli", opts); err != nil { log.Println(err) return 1 } case "build": //clean() for _, binary := range binaries { log.Println("building binaries", cmd) // Can't use filepath.Join here because filepath.Join calls filepath.Clean, which removes the `./` from this path, which upsets `go build` if err := doBuild(binary, fmt.Sprintf("./pkg/cmd/%s", binary), opts); err != nil { log.Println(err) return 1 } } case "build-frontend": yarn("build") case "sha-dist": if err := shaDir("dist"); err != nil { return logError("error packaging dist directory", err) } case "clean": clean(opts) default: log.Println("Unknown command", cmd) return 1 } } return 0 } func yarn(params ...string) { runPrint(`yarn run`, params...) } func genPackageVersion(version string, iteration string) string { if iteration != "" { return fmt.Sprintf("%v-%v", version, iteration) } else { return version } } func setup(goos string) { args := []string{"install", "-v"} if goos == GoOSWindows { args = append(args, "-buildmode=exe") } args = append(args, "./pkg/cmd/grafana-server") runPrint("go", args...) } func doBuild(binaryName, pkg string, opts BuildOpts) error { log.Println("building", binaryName, pkg) libcPart := "" if opts.libc != "" { libcPart = fmt.Sprintf("-%s", opts.libc) } binary := fmt.Sprintf("./bin/%s", binaryName) //don't include os/arch/libc in output path in dev environment if !opts.isDev { binary = fmt.Sprintf("./bin/%s-%s%s/%s", opts.goos, opts.goarch, libcPart, binaryName) } if opts.goos == GoOSWindows { binary += ".exe" } if !opts.isDev { rmr(binary, binary+".md5") } lf, err := ldflags(opts) if err != nil { return err } args := []string{"build", "-ldflags", lf} if opts.goos == GoOSWindows { // Work around a linking error on Windows: "export ordinal too large" args = append(args, "-buildmode=exe") } if len(opts.buildTags) > 0 { args = append(args, "-tags", strings.Join(opts.buildTags, ",")) } if opts.race { args = append(args, "-race") } args = append(args, "-o", binary) args = append(args, pkg) runPrint("go", args...) if opts.isDev { return nil } if err := setBuildEnv(opts); err != nil { return err } runPrint("go", "version") libcPart = "" if opts.libc != "" { libcPart = fmt.Sprintf("/%s", opts.libc) } fmt.Printf("Targeting %s/%s%s\n", opts.goos, opts.goarch, libcPart) // Create an md5 checksum of the binary, to be included in the archive for // automatic upgrades. return md5File(binary) } func ldflags(opts BuildOpts) (string, error) { buildStamp, err := buildStamp() if err != nil { return "", err } var b bytes.Buffer b.WriteString("-w") b.WriteString(fmt.Sprintf(" -X main.version=%s", opts.version)) b.WriteString(fmt.Sprintf(" -X main.commit=%s", getGitSha())) b.WriteString(fmt.Sprintf(" -X main.buildstamp=%d", buildStamp)) b.WriteString(fmt.Sprintf(" -X main.buildBranch=%s", getGitBranch())) if v := os.Getenv("LDFLAGS"); v != "" { b.WriteString(fmt.Sprintf(" -extldflags \"%s\"", v)) } return b.String(), nil } func setBuildEnv(opts BuildOpts) error { if err := os.Setenv("GOOS", opts.goos); err != nil { return err } if opts.goos == GoOSWindows { // require windows >=7 if err := os.Setenv("CGO_CFLAGS", "-D_WIN32_WINNT=0x0601"); err != nil { return err } } if opts.goarch != "amd64" || opts.goos != GoOSLinux { // needed for all other archs opts.cgo = true } if strings.HasPrefix(opts.goarch, "armv") { if err := os.Setenv("GOARCH", "arm"); err != nil { return err } if err := os.Setenv("GOARM", opts.goarch[4:]); err != nil { return err } } else { if err := os.Setenv("GOARCH", opts.goarch); err != nil { return err } } if opts.cgo { if err := os.Setenv("CGO_ENABLED", "1"); err != nil { return err } } if opts.gocc == "" { return nil } return os.Setenv("CC", opts.gocc) } func buildStamp() (int64, error) { // use SOURCE_DATE_EPOCH if set. if v, ok := os.LookupEnv("SOURCE_DATE_EPOCH"); ok { return strconv.ParseInt(v, 10, 64) } bs, err := runError("git", "show", "-s", "--format=%ct") if err != nil { return time.Now().Unix(), nil } return strconv.ParseInt(string(bs), 10, 64) } func clean(opts BuildOpts) { rmr("dist") rmr("tmp") rmr(filepath.Join(build.Default.GOPATH, fmt.Sprintf("pkg/%s_%s/github.com/grafana", opts.goos, opts.goarch))) }
pkg/build/cmd.go
0
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.0001779586455086246, 0.00017373966693412513, 0.000166137600899674, 0.0001747846690705046, 0.000003266064140916569 ]
{ "id": 0, "code_window": [ " dispatch(notifyApp(createSuccessNotification('Dashboard Imported', dashboardTitle)));\n", " dispatch(loadPluginDashboards());\n", " };\n", "}\n", "\n", "export function removeDashboard(uri: string): ThunkResult<void> {\n", " return async (dispatch) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export function removeDashboard(uid: string): ThunkResult<void> {\n" ], "file_path": "public/app/features/dashboard/state/actions.ts", "type": "replace", "edit_start_line_idx": 108 }
import React, { useCallback, useState } from 'react'; import { IconSize } from '../../types/icon'; import { IconButton } from '../IconButton/IconButton'; import { HorizontalGroup } from '../Layout/Layout'; import { TooltipPlacement } from '../Tooltip'; import { TableCellInspectModal } from './TableCellInspectModal'; import { FILTER_FOR_OPERATOR, FILTER_OUT_OPERATOR, TableCellProps, TableFieldOptions } from './types'; import { getTextAlign } from './utils'; interface CellActionProps extends TableCellProps { previewMode: 'text' | 'code'; } export function CellActions({ field, cell, previewMode, onCellFilterAdded }: CellActionProps) { const [isInspecting, setIsInspecting] = useState(false); const isRightAligned = getTextAlign(field) === 'flex-end'; const showFilters = Boolean(field.config.filterable) && cell.value !== undefined; const inspectEnabled = Boolean((field.config.custom as TableFieldOptions)?.inspect); const commonButtonProps = { size: 'sm' as IconSize, tooltipPlacement: 'top' as TooltipPlacement, }; const onFilterFor = useCallback( (event: React.MouseEvent<HTMLButtonElement>) => onCellFilterAdded({ key: field.name, operator: FILTER_FOR_OPERATOR, value: cell.value }), [cell, field, onCellFilterAdded] ); const onFilterOut = useCallback( (event: React.MouseEvent<HTMLButtonElement>) => onCellFilterAdded({ key: field.name, operator: FILTER_OUT_OPERATOR, value: cell.value }), [cell, field, onCellFilterAdded] ); return ( <> <div className={`cellActions ${isRightAligned ? 'cellActionsLeft' : ''}`}> <HorizontalGroup spacing="xs"> {inspectEnabled && ( <IconButton name="eye" tooltip="Inspect value" onClick={() => { setIsInspecting(true); }} {...commonButtonProps} /> )} {showFilters && ( <IconButton name={'search-plus'} onClick={onFilterFor} tooltip="Filter for value" {...commonButtonProps} /> )} {showFilters && ( <IconButton name={'search-minus'} onClick={onFilterOut} tooltip="Filter out value" {...commonButtonProps} /> )} </HorizontalGroup> </div> {isInspecting && ( <TableCellInspectModal mode={previewMode} value={cell.value} onDismiss={() => { setIsInspecting(false); }} /> )} </> ); }
packages/grafana-ui/src/components/Table/CellActions.tsx
0
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.00017763789219316095, 0.00017503270646557212, 0.00017254918930120766, 0.00017515177023597062, 0.0000016883237776710303 ]
{ "id": 0, "code_window": [ " dispatch(notifyApp(createSuccessNotification('Dashboard Imported', dashboardTitle)));\n", " dispatch(loadPluginDashboards());\n", " };\n", "}\n", "\n", "export function removeDashboard(uri: string): ThunkResult<void> {\n", " return async (dispatch) => {\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep" ], "after_edit": [ "export function removeDashboard(uid: string): ThunkResult<void> {\n" ], "file_path": "public/app/features/dashboard/state/actions.ts", "type": "replace", "edit_start_line_idx": 108 }
import { ArrayVector, DataFrame, Field, FieldType, getFieldDisplayName, GrafanaTheme2, outerJoinDataFrames, } from '@grafana/data'; import { findField } from 'app/features/dimensions'; import { prepareGraphableFields } from '../timeseries/utils'; import { CandlestickOptions, CandlestickFieldMap, VizDisplayMode } from './models.gen'; export interface FieldPickerInfo { /** property name */ key: keyof CandlestickFieldMap; /** The display name */ name: string; /** by default pick these fields */ defaults: string[]; /** How is the field used */ description: string; } export const candlestickFieldsInfo: Record<keyof CandlestickFieldMap, FieldPickerInfo> = { open: { key: 'open', name: 'Open', defaults: ['open', 'o'], description: 'Value at the start of the period', }, high: { key: 'high', name: 'High', defaults: ['high', 'h', 'max'], description: 'Maximum value within the period', }, low: { key: 'low', name: 'Low', defaults: ['low', 'l', 'min'], description: 'Minimum value within the period', }, close: { key: 'close', name: 'Close', defaults: ['close', 'c'], description: 'Value at the end of the period', }, volume: { key: 'volume', name: 'Volume', defaults: ['volume', 'v'], description: 'Sample count within the period', }, }; export interface CandlestickData { autoOpenClose?: boolean; // Special fields open?: Field; high?: Field; low?: Field; close?: Field; volume?: Field; // All incoming values aligned: DataFrame; // The stuff passed to GraphNG frame: DataFrame; // The real names used names: CandlestickFieldMap; } function findFieldOrAuto(frame: DataFrame, info: FieldPickerInfo, options: CandlestickFieldMap): Field | undefined { const field = findField(frame, options[info.key]); if (!field) { for (const field of frame.fields) { const name = getFieldDisplayName(field, frame).toLowerCase(); if (info.defaults.includes(name) || info.defaults.includes(field.name)) { return field; } } } return field; } export function prepareCandlestickFields( series: DataFrame[] | undefined, options: CandlestickOptions, theme: GrafanaTheme2 ): CandlestickData | null { if (!series?.length) { return null; } // All fields const fieldMap = options.fields ?? {}; const aligned = series.length === 1 ? series[0] : outerJoinDataFrames({ frames: series, enforceSort: true }); if (!aligned?.length) { return null; } const data: CandlestickData = { aligned, frame: aligned, names: {} }; // Apply same filter as everythign else in timeseries const timeSeriesFrames = prepareGraphableFields([aligned], theme); if (!timeSeriesFrames) { return null; } const frame = (data.frame = timeSeriesFrames[0]); const timeIndex = frame.fields.findIndex((f) => f.type === FieldType.time); if (timeIndex < 0) { return null; } // Find the known fields const used = new Set<Field>(); for (const info of Object.values(candlestickFieldsInfo)) { const field = findFieldOrAuto(frame, info, fieldMap); if (field) { data[info.key] = field; used.add(field); } } // Use first numeric value as open if (!data.open && !data.close) { data.open = frame.fields.find((f) => f.type === FieldType.number); if (data.open) { used.add(data.open); } } // Use next open as 'close' value if (data.open && !data.close && !fieldMap.close) { const values = data.open.values.toArray().slice(1); values.push(values[values.length - 1]); // duplicate last value data.close = { ...data.open, values: new ArrayVector(values), name: 'Next open', state: undefined, }; used.add(data.close); frame.fields.push(data.close); data.autoOpenClose = true; } // Use previous close as 'open' value if (data.close && !data.open && !fieldMap.open) { const values = data.close.values.toArray().slice(); values.unshift(values[0]); // duplicate first value values.length = frame.length; data.open = { ...data.close, values: new ArrayVector(values), name: 'Previous close', state: undefined, }; used.add(data.open); frame.fields.push(data.open); data.autoOpenClose = true; } // Use the open field for min/max if nothing is set if (!data.high && !fieldMap.high) { data.high = data.open; } if (!data.low && !fieldMap.low) { data.low = data.open; } // unmap low and high fields in volume-only mode, and volume field in candles-only mode // so they fall through to unmapped fields and get appropriate includeAllFields treatment if (options.mode === VizDisplayMode.Volume) { if (data.high) { if (data.high !== data.open) { used.delete(data.high); } data.high = undefined; } if (data.low) { if (data.low !== data.open) { used.delete(data.low); } data.low = undefined; } } else if (options.mode === VizDisplayMode.Candles) { if (data.volume) { used.delete(data.volume); data.volume = undefined; } } // Register the name of each mapped field for (const info of Object.values(candlestickFieldsInfo)) { const f = data[info.key]; if (f) { data.names[info.key] = getFieldDisplayName(f, data.frame); } } const timeField = frame.fields[timeIndex]; // Make sure first field is time! const fields: Field[] = [timeField]; if (!options.includeAllFields) { fields.push(...used); } else { fields.push(...frame.fields.filter((f) => f !== timeField)); } data.frame = { ...data.frame, fields, }; // Force update all the indicies for (let i = 0; i < data.frame.fields.length; i++) { const field = data.frame.fields[i]; field.state = { ...field.state, // time is unused (-1), y series enumerate from 0 seriesIndex: i - 1, origin: { fieldIndex: i, frameIndex: 0, }, }; } return data; }
public/app/plugins/panel/candlestick/fields.ts
0
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.0001807181688491255, 0.00017649562505539507, 0.0001690339995548129, 0.00017731990374159068, 0.0000030680844247399364 ]
{ "id": 1, "code_window": [ " return async (dispatch) => {\n", " await getBackendSrv().delete(`/api/dashboards/${uri}`);\n", " dispatch(loadPluginDashboards());\n", " };\n", "}\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await getBackendSrv().delete(`/api/dashboards/uid/${uid}`);\n" ], "file_path": "public/app/features/dashboard/state/actions.ts", "type": "replace", "edit_start_line_idx": 110 }
// Services & Utils import { getBackendSrv } from '@grafana/runtime'; import { createSuccessNotification } from 'app/core/copy/appNotification'; // Actions import { loadPluginDashboards } from '../../plugins/admin/state/actions'; import { cleanUpDashboard, loadDashboardPermissions } from './reducers'; import { notifyApp } from 'app/core/actions'; import { updateTimeZoneForSession, updateWeekStartForSession } from 'app/features/profile/state/reducers'; // Types import { DashboardAcl, DashboardAclUpdateDTO, NewDashboardAclItem, PermissionLevel, ThunkResult } from 'app/types'; import { cancelVariables } from '../../variables/state/actions'; import { getTimeSrv } from '../services/TimeSrv'; import { TimeZone } from '@grafana/data'; export function getDashboardPermissions(id: number): ThunkResult<void> { return async (dispatch) => { const permissions = await getBackendSrv().get(`/api/dashboards/id/${id}/permissions`); dispatch(loadDashboardPermissions(permissions)); }; } function toUpdateItem(item: DashboardAcl): DashboardAclUpdateDTO { return { userId: item.userId, teamId: item.teamId, role: item.role, permission: item.permission, }; } export function updateDashboardPermission( dashboardId: number, itemToUpdate: DashboardAcl, level: PermissionLevel ): ThunkResult<void> { return async (dispatch, getStore) => { const { dashboard } = getStore(); const itemsToUpdate = []; for (const item of dashboard.permissions) { if (item.inherited) { continue; } const updated = toUpdateItem(item); // if this is the item we want to update, update it's permission if (itemToUpdate === item) { updated.permission = level; } itemsToUpdate.push(updated); } await getBackendSrv().post(`/api/dashboards/id/${dashboardId}/permissions`, { items: itemsToUpdate }); await dispatch(getDashboardPermissions(dashboardId)); }; } export function removeDashboardPermission(dashboardId: number, itemToDelete: DashboardAcl): ThunkResult<void> { return async (dispatch, getStore) => { const dashboard = getStore().dashboard; const itemsToUpdate = []; for (const item of dashboard.permissions) { if (item.inherited || item === itemToDelete) { continue; } itemsToUpdate.push(toUpdateItem(item)); } await getBackendSrv().post(`/api/dashboards/id/${dashboardId}/permissions`, { items: itemsToUpdate }); await dispatch(getDashboardPermissions(dashboardId)); }; } export function addDashboardPermission(dashboardId: number, newItem: NewDashboardAclItem): ThunkResult<void> { return async (dispatch, getStore) => { const { dashboard } = getStore(); const itemsToUpdate = []; for (const item of dashboard.permissions) { if (item.inherited) { continue; } itemsToUpdate.push(toUpdateItem(item)); } itemsToUpdate.push({ userId: newItem.userId, teamId: newItem.teamId, role: newItem.role, permission: newItem.permission, }); await getBackendSrv().post(`/api/dashboards/id/${dashboardId}/permissions`, { items: itemsToUpdate }); await dispatch(getDashboardPermissions(dashboardId)); }; } export function importDashboard(data: any, dashboardTitle: string): ThunkResult<void> { return async (dispatch) => { await getBackendSrv().post('/api/dashboards/import', data); dispatch(notifyApp(createSuccessNotification('Dashboard Imported', dashboardTitle))); dispatch(loadPluginDashboards()); }; } export function removeDashboard(uri: string): ThunkResult<void> { return async (dispatch) => { await getBackendSrv().delete(`/api/dashboards/${uri}`); dispatch(loadPluginDashboards()); }; } export const cleanUpDashboardAndVariables = (): ThunkResult<void> => (dispatch, getStore) => { const store = getStore(); const dashboard = store.dashboard.getModel(); if (dashboard) { dashboard.destroy(); dispatch(cancelVariables(dashboard.uid)); } getTimeSrv().stopAutoRefresh(); dispatch(cleanUpDashboard()); }; export const updateTimeZoneDashboard = (timeZone: TimeZone): ThunkResult<void> => (dispatch) => { dispatch(updateTimeZoneForSession(timeZone)); getTimeSrv().refreshTimeModel(); }; export const updateWeekStartDashboard = (weekStart: string): ThunkResult<void> => (dispatch) => { dispatch(updateWeekStartForSession(weekStart)); getTimeSrv().refreshTimeModel(); };
public/app/features/dashboard/state/actions.ts
1
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.606242299079895, 0.05393237620592117, 0.00017225902411155403, 0.011951521039009094, 0.14890934526920319 ]
{ "id": 1, "code_window": [ " return async (dispatch) => {\n", " await getBackendSrv().delete(`/api/dashboards/${uri}`);\n", " dispatch(loadPluginDashboards());\n", " };\n", "}\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await getBackendSrv().delete(`/api/dashboards/uid/${uid}`);\n" ], "file_path": "public/app/features/dashboard/state/actions.ts", "type": "replace", "edit_start_line_idx": 110 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><rect width="9" height="9" x="2" y="2" rx="1"/><rect width="9" height="9" x="2" y="13" rx="1" opacity=".6"/><rect width="9" height="9" x="13" y="2" rx="1" opacity=".6"/><rect width="9" height="9" x="13" y="13" rx="1" opacity=".6"/></svg>
public/img/icons/mono/apps.svg
0
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.00017110542103182524, 0.00017110542103182524, 0.00017110542103182524, 0.00017110542103182524, 0 ]
{ "id": 1, "code_window": [ " return async (dispatch) => {\n", " await getBackendSrv().delete(`/api/dashboards/${uri}`);\n", " dispatch(loadPluginDashboards());\n", " };\n", "}\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await getBackendSrv().delete(`/api/dashboards/uid/${uid}`);\n" ], "file_path": "public/app/features/dashboard/state/actions.ts", "type": "replace", "edit_start_line_idx": 110 }
alert_webhook_listener: build: docker/blocks/alert_webhook_listener network_mode: host ports: - "3010:3010"
devenv/docker/blocks/alert_webhook_listener/docker-compose.yaml
0
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.00018117157742381096, 0.00018117157742381096, 0.00018117157742381096, 0.00018117157742381096, 0 ]
{ "id": 1, "code_window": [ " return async (dispatch) => {\n", " await getBackendSrv().delete(`/api/dashboards/${uri}`);\n", " dispatch(loadPluginDashboards());\n", " };\n", "}\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " await getBackendSrv().delete(`/api/dashboards/uid/${uid}`);\n" ], "file_path": "public/app/features/dashboard/state/actions.ts", "type": "replace", "edit_start_line_idx": 110 }
package dashdiffs import ( "bytes" "html/template" diff "github.com/yudai/gojsondiff" ) // A BasicDiff holds the stateful values that are used when generating a basic // diff from JSON tokens. type BasicDiff struct { narrow string keysIdent int writing bool LastIndent int Block *BasicBlock Change *BasicChange Summary *BasicSummary } // A BasicBlock represents a top-level element in a basic diff. type BasicBlock struct { Title string Old interface{} New interface{} Change ChangeType Changes []*BasicChange Summaries []*BasicSummary LineStart int LineEnd int } // A BasicChange represents the change from an old to new value. There are many // BasicChanges in a BasicBlock. type BasicChange struct { Key string Old interface{} New interface{} Change ChangeType LineStart int LineEnd int } // A BasicSummary represents the changes within a basic block that're too deep // or verbose to be represented in the top-level BasicBlock element, or in the // BasicChange. Instead of showing the values in this case, we simply print // the key and count how many times the given change was applied to that // element. type BasicSummary struct { Key string Change ChangeType Count int LineStart int LineEnd int } type BasicFormatter struct { jsonDiff *JSONFormatter tpl *template.Template } func NewBasicFormatter(left interface{}) *BasicFormatter { tpl := template.Must(template.New("block").Funcs(tplFuncMap).Parse(tplBlock)) tpl = template.Must(tpl.New("change").Funcs(tplFuncMap).Parse(tplChange)) tpl = template.Must(tpl.New("summary").Funcs(tplFuncMap).Parse(tplSummary)) return &BasicFormatter{ jsonDiff: NewJSONFormatter(left), tpl: tpl, } } // Format takes the diff of two JSON documents, and returns the difference // between them summarized in an HTML document. func (b *BasicFormatter) Format(d diff.Diff) ([]byte, error) { // calling jsonDiff.Format(d) populates the JSON diff's "Lines" value, // which we use to compute the basic dif _, err := b.jsonDiff.Format(d) if err != nil { return nil, err } bd := &BasicDiff{} blocks := bd.Basic(b.jsonDiff.Lines) buf := &bytes.Buffer{} err = b.tpl.ExecuteTemplate(buf, "block", blocks) if err != nil { return nil, err } return buf.Bytes(), nil } // Basic transforms a slice of JSONLines into a slice of BasicBlocks. func (b *BasicDiff) Basic(lines []*JSONLine) []*BasicBlock { // init an array you can append to for the basic "blocks" blocks := make([]*BasicBlock, 0) for _, line := range lines { if b.returnToTopLevelKey(line) { if b.Block != nil { blocks = append(blocks, b.Block) } } // Record the last indent level at each pass in case we need to // check for a change in depth inside the JSON data structures. b.LastIndent = line.Indent if line.Indent == 1 { if block, ok := b.handleTopLevelChange(line); ok { blocks = append(blocks, block) } } // Here is where we handle changes for all types, appending each change // to the current block based on the value. // // Values which only occupy a single line in JSON (like a string or // int, for example) are treated as "Basic Changes" that we append to // the current block as soon as they're detected. // // Values which occupy multiple lines (either slices or maps) are // treated as "Basic Summaries". When we detect the "ChangeNil" type, // we know we've encountered one of these types, so we record the // starting position as well the type of the change, and stop // performing comparisons until we find the end of that change. Upon // finding the change, we append it to the current block, and begin // performing comparisons again. if line.Indent > 1 { // check to ensure a single line change if b.isSingleLineChange(line) { switch line.Change { case ChangeAdded, ChangeDeleted: b.Block.Changes = append(b.Block.Changes, &BasicChange{ Key: line.Key, Change: line.Change, New: line.Val, LineStart: line.LineNum, }) case ChangeOld: b.Change = &BasicChange{ Key: line.Key, Change: line.Change, Old: line.Val, LineStart: line.LineNum, } case ChangeNew: b.Change.New = line.Val b.Change.LineEnd = line.LineNum b.Block.Changes = append(b.Block.Changes, b.Change) default: // ok } // otherwise, we're dealing with a change at a deeper level. We // know there's a change somewhere in the JSON tree, but we // don't know exactly where, so we go deeper. } else { // if the change is anything but unchanged, continue processing // // we keep "narrowing" the key as we go deeper, in order to // correctly report the key name for changes found within an // object or array. if line.Change != ChangeUnchanged { if line.Key != "" { b.narrow = line.Key b.keysIdent = line.Indent } // if the change isn't nil, and we're not already writing // out a change, then we've found something. // // First, try to determine the title of the embedded JSON // object. If it's an empty string, then we're in an object // or array, so we default to using the "narrowed" key. // // We also start recording the basic summary, until we find // the next `ChangeUnchanged`. if line.Change != ChangeNil { if !b.writing { b.writing = true key := b.Block.Title if b.narrow != "" { key = b.narrow if b.keysIdent > line.Indent { key = b.Block.Title } } b.Summary = &BasicSummary{ Key: key, Change: line.Change, LineStart: line.LineNum, } } } // if we find a `ChangeUnchanged`, we do one of two things: // // - if we're recording a change already, then we know // we've come to the end of that change block, so we write // that change out be recording the line number of where // that change ends, and append it to the current block's // summary. // // - if we're not recording a change, then we do nothing, // since the BasicDiff doesn't report on unchanged JSON // values. } else if b.writing { b.writing = false b.Summary.LineEnd = line.LineNum b.Block.Summaries = append(b.Block.Summaries, b.Summary) } } } } return blocks } // returnToTopLevelKey indicates that we've moved from a key at one level deep // in the JSON document to a top level key. // // In order to produce distinct "blocks" when rendering the basic diff, // we need a way to distinguish between different sections of data. // To do this, we consider the value(s) of each top-level JSON key to // represent a distinct block for Grafana's JSON data structure, so // we perform this check to see if we've entered a new "block". If we // have, we simply append the existing block to the array of blocks. func (b *BasicDiff) returnToTopLevelKey(line *JSONLine) bool { return b.LastIndent == 2 && line.Indent == 1 && line.Change == ChangeNil } // handleTopLevelChange handles a change on one of the top-level keys on a JSON // document. // // If the line's indentation is at level 1, then we know it's a top // level key in the JSON document. As mentioned earlier, we treat these // specially as they indicate their values belong to distinct blocks. // // At level 1, we only record single-line changes, ie, the "added", // "deleted", "old" or "new" cases, since we know those values aren't // arrays or maps. We only handle these cases at level 2 or deeper, // since for those we either output a "change" or "summary". This is // done for formatting reasons only, so we have logical "blocks" to // display. func (b *BasicDiff) handleTopLevelChange(line *JSONLine) (*BasicBlock, bool) { switch line.Change { case ChangeNil: if line.Change == ChangeNil { if line.Key != "" { b.Block = &BasicBlock{ Title: line.Key, Change: line.Change, } } } case ChangeAdded, ChangeDeleted: return &BasicBlock{ Title: line.Key, Change: line.Change, New: line.Val, LineStart: line.LineNum, }, true case ChangeOld: b.Block = &BasicBlock{ Title: line.Key, Old: line.Val, Change: line.Change, LineStart: line.LineNum, } case ChangeNew: b.Block.New = line.Val b.Block.LineEnd = line.LineNum // For every "old" change there is a corresponding "new", which // is why we wait until we detect the "new" change before // appending the change. return b.Block, true default: // ok } return nil, false } // isSingleLineChange ensures we're iterating over a single line change (ie, // either a single line or a old-new value pair was changed in the JSON file). func (b *BasicDiff) isSingleLineChange(line *JSONLine) bool { return line.Key != "" && line.Val != nil && !b.writing } // encStateMap is used in the template helper var ( encStateMap = map[ChangeType]string{ ChangeAdded: "added", ChangeDeleted: "deleted", ChangeOld: "changed", ChangeNew: "changed", } // tplFuncMap is the function map for each template tplFuncMap = template.FuncMap{ "getChange": func(c ChangeType) string { state, ok := encStateMap[c] if !ok { return "changed" } return state }, } ) var ( // tplBlock is the container for the basic diff. It iterates over each // basic block, expanding each "change" and "summary" belonging to every // block. tplBlock = `{{ define "block" -}} {{ range . }} <div class="diff-group"> <div class="diff-block"> <h2 class="diff-block-title"> <icon class="diff-circle diff-circle-{{ getChange .Change }}" name="'circle'" type="'mono'"></icon> <strong class="diff-title">{{ .Title }}</strong> {{ getChange .Change }} </h2> <!-- Overview --> {{ if .Old }} <div class="diff-label" ng-non-bindable>{{ .Old }}</div> <icon name="'arrow-right'"></icon> {{ end }} {{ if .New }} <div class="diff-label" ng-non-bindable>{{ .New }}</div> {{ end }} {{ if .LineStart }} <diff-link-json line-link="{{ .LineStart }}" line-display="{{ .LineStart }}{{ if .LineEnd }} - {{ .LineEnd }}{{ end }}" switch-view="ctrl.getDiff('html')" /> {{ end }} </div> <!-- Basic Changes --> {{ range .Changes }} <ul class="diff-change-container"> {{ template "change" . }} </ul> {{ end }} <!-- Basic Summary --> {{ range .Summaries }} {{ template "summary" . }} {{ end }} </div> {{ end }} {{ end }}` // tplChange is the template for basic changes. tplChange = `{{ define "change" -}} <li class="diff-change-group"> <span class="bullet-position-container"> <div class="diff-change-item diff-change-title">{{ getChange .Change }} {{ .Key }}</div> <div class="diff-change-item"> {{ if .Old }} <div class="diff-label" ng-non-bindable>{{ .Old }}</div> <icon name="'arrow-right'"></icon> {{ end }} {{ if .New }} <div class="diff-label" ng-non-bindable>{{ .New }}</div> {{ end }} </div> {{ if .LineStart }} <diff-link-json line-link="{{ .LineStart }}" line-display="{{ .LineStart }}{{ if .LineEnd }} - {{ .LineEnd }}{{ end }}" switch-view="ctrl.getDiff('json')" /> {{ end }} </span> </li> {{ end }}` // tplSummary is for basic summaries. tplSummary = `{{ define "summary" -}} <div class="diff-group-name"> <icon class="diff-circle diff-circle-{{ getChange .Change }} diff-list-circle" name="'circle'"></icon> {{ if .Count }} <strong>{{ .Count }}</strong> {{ end }} {{ if .Key }} <strong class="diff-summary-key">{{ .Key }}</strong> {{ getChange .Change }} {{ end }} {{ if .LineStart }} <diff-link-json line-link="{{ .LineStart }}" line-display="{{ .LineStart }}{{ if .LineEnd }} - {{ .LineEnd }}{{ end }}" switch-view="ctrl.getDiff('json')" /> {{ end }} </div> {{ end }}` )
pkg/components/dashdiffs/formatter_basic.go
0
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.0009517191792838275, 0.00018867538892664015, 0.00016214363859035075, 0.00017114882939495146, 0.00011778010957641527 ]
{ "id": 2, "code_window": [ " };\n", "\n", " onRemove = (dashboard: PluginDashboard) => {\n", " this.props.removeDashboard(dashboard.importedUri);\n", " };\n", "\n", " render() {\n", " const { dashboards, navModel, isLoading } = this.props;\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.props.removeDashboard(dashboard.uid);\n" ], "file_path": "public/app/features/datasources/DataSourceDashboards.tsx", "type": "replace", "edit_start_line_idx": 73 }
// Services & Utils import { getBackendSrv } from '@grafana/runtime'; import { createSuccessNotification } from 'app/core/copy/appNotification'; // Actions import { loadPluginDashboards } from '../../plugins/admin/state/actions'; import { cleanUpDashboard, loadDashboardPermissions } from './reducers'; import { notifyApp } from 'app/core/actions'; import { updateTimeZoneForSession, updateWeekStartForSession } from 'app/features/profile/state/reducers'; // Types import { DashboardAcl, DashboardAclUpdateDTO, NewDashboardAclItem, PermissionLevel, ThunkResult } from 'app/types'; import { cancelVariables } from '../../variables/state/actions'; import { getTimeSrv } from '../services/TimeSrv'; import { TimeZone } from '@grafana/data'; export function getDashboardPermissions(id: number): ThunkResult<void> { return async (dispatch) => { const permissions = await getBackendSrv().get(`/api/dashboards/id/${id}/permissions`); dispatch(loadDashboardPermissions(permissions)); }; } function toUpdateItem(item: DashboardAcl): DashboardAclUpdateDTO { return { userId: item.userId, teamId: item.teamId, role: item.role, permission: item.permission, }; } export function updateDashboardPermission( dashboardId: number, itemToUpdate: DashboardAcl, level: PermissionLevel ): ThunkResult<void> { return async (dispatch, getStore) => { const { dashboard } = getStore(); const itemsToUpdate = []; for (const item of dashboard.permissions) { if (item.inherited) { continue; } const updated = toUpdateItem(item); // if this is the item we want to update, update it's permission if (itemToUpdate === item) { updated.permission = level; } itemsToUpdate.push(updated); } await getBackendSrv().post(`/api/dashboards/id/${dashboardId}/permissions`, { items: itemsToUpdate }); await dispatch(getDashboardPermissions(dashboardId)); }; } export function removeDashboardPermission(dashboardId: number, itemToDelete: DashboardAcl): ThunkResult<void> { return async (dispatch, getStore) => { const dashboard = getStore().dashboard; const itemsToUpdate = []; for (const item of dashboard.permissions) { if (item.inherited || item === itemToDelete) { continue; } itemsToUpdate.push(toUpdateItem(item)); } await getBackendSrv().post(`/api/dashboards/id/${dashboardId}/permissions`, { items: itemsToUpdate }); await dispatch(getDashboardPermissions(dashboardId)); }; } export function addDashboardPermission(dashboardId: number, newItem: NewDashboardAclItem): ThunkResult<void> { return async (dispatch, getStore) => { const { dashboard } = getStore(); const itemsToUpdate = []; for (const item of dashboard.permissions) { if (item.inherited) { continue; } itemsToUpdate.push(toUpdateItem(item)); } itemsToUpdate.push({ userId: newItem.userId, teamId: newItem.teamId, role: newItem.role, permission: newItem.permission, }); await getBackendSrv().post(`/api/dashboards/id/${dashboardId}/permissions`, { items: itemsToUpdate }); await dispatch(getDashboardPermissions(dashboardId)); }; } export function importDashboard(data: any, dashboardTitle: string): ThunkResult<void> { return async (dispatch) => { await getBackendSrv().post('/api/dashboards/import', data); dispatch(notifyApp(createSuccessNotification('Dashboard Imported', dashboardTitle))); dispatch(loadPluginDashboards()); }; } export function removeDashboard(uri: string): ThunkResult<void> { return async (dispatch) => { await getBackendSrv().delete(`/api/dashboards/${uri}`); dispatch(loadPluginDashboards()); }; } export const cleanUpDashboardAndVariables = (): ThunkResult<void> => (dispatch, getStore) => { const store = getStore(); const dashboard = store.dashboard.getModel(); if (dashboard) { dashboard.destroy(); dispatch(cancelVariables(dashboard.uid)); } getTimeSrv().stopAutoRefresh(); dispatch(cleanUpDashboard()); }; export const updateTimeZoneDashboard = (timeZone: TimeZone): ThunkResult<void> => (dispatch) => { dispatch(updateTimeZoneForSession(timeZone)); getTimeSrv().refreshTimeModel(); }; export const updateWeekStartDashboard = (weekStart: string): ThunkResult<void> => (dispatch) => { dispatch(updateWeekStartForSession(weekStart)); getTimeSrv().refreshTimeModel(); };
public/app/features/dashboard/state/actions.ts
1
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.6760398745536804, 0.06348299235105515, 0.00016933387087192386, 0.006001484580338001, 0.16715191304683685 ]
{ "id": 2, "code_window": [ " };\n", "\n", " onRemove = (dashboard: PluginDashboard) => {\n", " this.props.removeDashboard(dashboard.importedUri);\n", " };\n", "\n", " render() {\n", " const { dashboards, navModel, isLoading } = this.props;\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.props.removeDashboard(dashboard.uid);\n" ], "file_path": "public/app/features/datasources/DataSourceDashboards.tsx", "type": "replace", "edit_start_line_idx": 73 }
# Merge a pull request When a pull request has been reviewed and approved by at least one person and all checks have passed it's time to merge the pull request. ## Who is expected to merge a pull request? Maintainers are responsible for merging all pull requests. If a maintainer has opened a pull request the general rule is that the same maintainer merges the pull request. If a non-maintainer has opened a pull request it's suggested that one of the maintainers reviewing the pull request merges the pull request. ## Checklist/summary The following checklist/summary should give you a quick overview of what to ask/consider before merging a pull request. - Reviewed and approved? - All checks passed? - Proper pull request title? - Milestone assigned? - Add to changelog/release notes? - Needs backporting? ## Before merge Before actually merging a pull request there's a couple of things to take into consideration. ### Status checks Before you can merge a pull request, it must have a review approval, and all the required status checks must pass. ### Format the pull request title The pull request title should be formatted according to `<Area>: <Summary>`. Keep the summary short and understandable for the community as a whole. All commits in a pull request are squashed when merged and the pull request title will be the default subject line of the squashed commit message. It's also used for [changelog/release notes](#include-in-changelog-and-release-notes). See [formatting guidelines](create-pull-request.md#formatting-guidelines) for more information. ### Assign a milestone A milestone **should** be added to every pull request. Several things in the Grafana release process requires at least pull requests to be in a milestone, for example [generating changelog/release notes](#include-in-changelog-and-release-notes). This makes it easier to track what changes go into a certain release. Without this information, release managers have to go through git commits which is not an efficient process. ### Include in changelog and release notes? At Grafana we generate the [changelog](https://github.com/grafana/grafana/blob/main/CHANGELOG.md) and [release notes](https://grafana.com/docs/grafana/latest/release-notes/) based on merged pull requests. Including changes in the changelog/release notes is very important to provide a somewhat complete picture of what changes a Grafana release actually includes. Exactly what changes should be added to the changelog is hard to answer but some general guidance would be any change that you think would be interesting for the community as a whole. Use your best judgement and/or ask other maintainers for advice. There's a GitHub action available in the repository named [Update changelog](https://github.com/grafana/grafana/blob/main/.github/workflows/update-changelog.yml) that can manually be triggered to re-generate the changelog and release notes for any release. To include a pull request in the changelog/release notes the general rule of thumb is that a milestone should be assigned and labeled with `add to changelog`. The changelog/release notes are divided into sections and here's a description of how you make a pull request show up in a certain section. **Features and enhancements:** Milestone assigned and labeled with `add to changelog` and any of the other section rules don't apply. **Bug fixes:** Milestone assigned and labeled with `add to changelog` and either labeled with `type/bug` or the pull request title contains `fix` or `fixes`. **Plugin development fixes & changes:** Milestone assigned and labeled with `area/grafana/toolkit`, `area/grafana/ui` or `area/grafana/runtime`. **Deprecations:** In case the pull request introduces a deprecation you should document this. Label the pull request with `add to changelog` and use the following template at the end of the pull request description describing the deprecation change. ```md # Deprecation notice <Deprecation description> ``` **Breaking changes:** In case the pull request introduces a breaking change you should document this. Label the pull request with `add to changelog` and `breaking change` and use the following template at the end of the pull request description describing the breaking change. ```md # Release notice breaking change <Breaking change description> ``` ### Should the pull request be backported? An active decision of backporting needs to be taken for every pull request. There's a pull request check named **Backport Check** that will enforce this. By adding/removing labels on the pull request the check will be re-evaluated. #### No backport If you don't want to backport you need to add a label named **no-backport** to the pull request. #### Backport If your pull request has changes that need to go into one or several existing release branches you need to backport the changes. Please refer to [Backport PR](/.github/bot.md#backport-pr) for detailed instructions. The general rule of thumb regarding what changes goes into what release is: - bug fixes should be released in patch releases, e.g. v8.1.3, if the bug was introduced in the same major/minor or lower patch version. - new features should go into the next major/minor version, e.g. v8.0.0, v8.2.0. Some examples when backport is required: - The change needs to be released in the next upcoming patch release, e.g. v8.1.3, so you have to backport it, e.g. into the v8.1.x release branch. - You have a change to be released in the next major/minor release, e.g. v8.0.0, and there's already a release branch, e.g. v8.0.x, you have to backport it, e.g. into the v8.0.x release branch. - The change includes documentation changes that needs to be updated for one or multiple older versions, then you have to backport it to each release branch. Some examples when backport is not required: - The change is supposed to be released in the next major/minor release, e.g. v8.0.0, but the release branch, e.g. v8.0.x, has not yet been created. > **Note:** You can still backport a pull request after it's been merged. ## Doing the actual merge Time to actually merge the pull request changes. All commits in a pull request are squashed, hence the GitHub `Squash and merge` button is used to initialize the merge. This will present you with options allowing you to optionally change the commit message before merging. Please remember that developers might use the commit information when reviewing changes of files, doing git blame and resolving merge conflicts etc., trying to quickly figure out what the actual change was. But there's not really any best practices around this, the following is an attempt to bring some guidance. Do: - Make sure the pull request title is formatted properly before merging, this will automatically give you a good and short summary of the commit/change. - Leave `Co-authored-by:` lines as is so that co-authors will be accounted for the contribution. - Remove any commit information that doesn't bring any context to the change. Consider: - Add any references to issues that the pull request fixes/closes/references to ease giving quick context to things. Doing this allows cross-reference between the commit and referenced issue(s). Finalize the merge by clicking on the `Confirm squash and merge` button. ## After the merge Make sure to close any referenced/related issues. It's recommended to assign the same milestone on the issues that the pull request fixes/closes, but not required.
contribute/merge-pull-request.md
0
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.00017127567843999714, 0.00016721324936952442, 0.00016415445134043694, 0.00016721172141842544, 0.0000017099731621783576 ]
{ "id": 2, "code_window": [ " };\n", "\n", " onRemove = (dashboard: PluginDashboard) => {\n", " this.props.removeDashboard(dashboard.importedUri);\n", " };\n", "\n", " render() {\n", " const { dashboards, navModel, isLoading } = this.props;\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.props.removeDashboard(dashboard.uid);\n" ], "file_path": "public/app/features/datasources/DataSourceDashboards.tsx", "type": "replace", "edit_start_line_idx": 73 }
// Copyright (c) 2017 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import cx from 'classnames'; import { css } from '@emotion/css'; import { groupBy as _groupBy } from 'lodash'; import React, { useState } from 'react'; import { GrafanaTheme2 } from '@grafana/data'; import { useStyles2 } from '@grafana/ui'; import { autoColor } from '../Theme'; import { TraceSpan } from '../types/trace'; import { TNil } from '../types'; import AccordianLogs from './SpanDetail/AccordianLogs'; import { ViewedBoundsFunctionType } from './utils'; import { Popover } from '../common/Popover'; const getStyles = (theme: GrafanaTheme2) => { return { wrapper: css` label: wrapper; bottom: 0; left: 0; position: absolute; right: 0; top: 0; overflow: hidden; z-index: 0; `, bar: css` label: bar; border-radius: 3px; min-width: 2px; position: absolute; height: 36%; top: 32%; `, rpc: css` label: rpc; position: absolute; top: 35%; bottom: 35%; z-index: 1; `, label: css` label: label; color: #aaa; font-size: 12px; font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; line-height: 1em; white-space: nowrap; padding: 0 0.5em; position: absolute; `, logMarker: css` label: logMarker; background-color: ${autoColor(theme, '#2c3235')}; cursor: pointer; height: 60%; min-width: 1px; position: absolute; top: 20%; &:hover { background-color: ${autoColor(theme, '#464c54')}; } &::before, &::after { content: ''; position: absolute; top: 0; bottom: 0; right: 0; border: 1px solid transparent; } &::after { left: 0; } `, }; }; type Props = { color: string; onClick?: (evt: React.MouseEvent<any>) => void; viewEnd: number; viewStart: number; getViewedBounds: ViewedBoundsFunctionType; rpc: | { viewStart: number; viewEnd: number; color: string; } | TNil; traceStartTime: number; span: TraceSpan; className?: string; labelClassName?: string; longLabel: string; shortLabel: string; }; function toPercent(value: number) { return `${(value * 100).toFixed(1)}%`; } function SpanBar({ viewEnd, viewStart, getViewedBounds, color, shortLabel, longLabel, onClick, rpc, traceStartTime, span, className, labelClassName, }: Props) { const [label, setLabel] = useState(shortLabel); const setShortLabel = () => setLabel(shortLabel); const setLongLabel = () => setLabel(longLabel); // group logs based on timestamps const logGroups = _groupBy(span.logs, (log) => { const posPercent = getViewedBounds(log.timestamp, log.timestamp).start; // round to the nearest 0.2% return toPercent(Math.round(posPercent * 500) / 500); }); const styles = useStyles2(getStyles); return ( <div className={cx(styles.wrapper, className)} onClick={onClick} onMouseLeave={setShortLabel} onMouseOver={setLongLabel} aria-hidden data-test-id="SpanBar--wrapper" > <div aria-label={label} className={styles.bar} style={{ background: color, left: toPercent(viewStart), width: toPercent(viewEnd - viewStart), }} > <div className={cx(styles.label, labelClassName)} data-test-id="SpanBar--label"> {label} </div> </div> <div> {Object.keys(logGroups).map((positionKey) => ( <Popover key={positionKey} content={ <AccordianLogs interactive={false} isOpen logs={logGroups[positionKey]} timestamp={traceStartTime} /> } > <div className={styles.logMarker} style={{ left: positionKey }} /> </Popover> ))} </div> {rpc && ( <div className={styles.rpc} style={{ background: rpc.color, left: toPercent(rpc.viewStart), width: toPercent(rpc.viewEnd - rpc.viewStart), }} /> )} </div> ); } export default React.memo(SpanBar);
packages/jaeger-ui-components/src/TraceTimelineViewer/SpanBar.tsx
0
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.004459998104721308, 0.0003879459691233933, 0.00016692266217432916, 0.00016997286002151668, 0.0009342955308966339 ]
{ "id": 2, "code_window": [ " };\n", "\n", " onRemove = (dashboard: PluginDashboard) => {\n", " this.props.removeDashboard(dashboard.importedUri);\n", " };\n", "\n", " render() {\n", " const { dashboards, navModel, isLoading } = this.props;\n", " return (\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " this.props.removeDashboard(dashboard.uid);\n" ], "file_path": "public/app/features/datasources/DataSourceDashboards.tsx", "type": "replace", "edit_start_line_idx": 73 }
import React, { ChangeEvent, FC, FormEvent, useEffect, useState } from 'react'; import { EventsWithValidation, LegacyForms, ValidationEvents, Button, Select, InlineField } from '@grafana/ui'; import { NewApiKey, OrgRole } from '../../types'; import { rangeUtil, SelectableValue } from '@grafana/data'; import { SlideDown } from '../../core/components/Animations/SlideDown'; import { CloseButton } from 'app/core/components/CloseButton/CloseButton'; const { Input } = LegacyForms; const ROLE_OPTIONS: Array<SelectableValue<OrgRole>> = Object.keys(OrgRole).map((role) => ({ label: role, value: role as OrgRole, })); interface Props { show: boolean; onClose: () => void; onKeyAdded: (apiKey: NewApiKey) => void; } function isValidInterval(value: string): boolean { if (!value) { return true; } try { rangeUtil.intervalToSeconds(value); return true; } catch {} return false; } const timeRangeValidationEvents: ValidationEvents = { [EventsWithValidation.onBlur]: [ { rule: isValidInterval, errorMessage: 'Not a valid duration', }, ], }; const tooltipText = 'The API key life duration. For example, 1d if your key is going to last for one day. Supported units are: s,m,h,d,w,M,y'; export const ApiKeysForm: FC<Props> = ({ show, onClose, onKeyAdded }) => { const [name, setName] = useState<string>(''); const [role, setRole] = useState<OrgRole>(OrgRole.Viewer); const [secondsToLive, setSecondsToLive] = useState<string>(''); useEffect(() => { setName(''); setRole(OrgRole.Viewer); setSecondsToLive(''); }, [show]); const onSubmit = (event: FormEvent) => { event.preventDefault(); if (isValidInterval(secondsToLive)) { onKeyAdded({ name, role, secondsToLive }); onClose(); } }; const onNameChange = (event: ChangeEvent<HTMLInputElement>) => { setName(event.currentTarget.value); }; const onRoleChange = (role: SelectableValue<OrgRole>) => { setRole(role.value!); }; const onSecondsToLiveChange = (event: ChangeEvent<HTMLInputElement>) => { setSecondsToLive(event.currentTarget.value); }; return ( <SlideDown in={show}> <div className="gf-form-inline cta-form"> <CloseButton onClick={onClose} /> <form className="gf-form-group" onSubmit={onSubmit}> <h5>Add API Key</h5> <div className="gf-form-inline"> <div className="gf-form max-width-21"> <span className="gf-form-label">Key name</span> <Input type="text" className="gf-form-input" value={name} placeholder="Name" onChange={onNameChange} /> </div> <div className="gf-form"> <InlineField label="Role"> <Select inputId="role-select" value={role} onChange={onRoleChange} options={ROLE_OPTIONS} menuShouldPortal /> </InlineField> </div> <div className="gf-form max-width-21"> <InlineField tooltip={tooltipText} label="Time to live"> <Input id="time-to-live-input" type="text" placeholder="1d" validationEvents={timeRangeValidationEvents} value={secondsToLive} onChange={onSecondsToLiveChange} /> </InlineField> </div> <div className="gf-form"> <Button>Add</Button> </div> </div> </form> </div> </SlideDown> ); };
public/app/features/api-keys/ApiKeysForm.tsx
0
https://github.com/grafana/grafana/commit/c3ee98a9b67cc8a571361ba5567d2a7536fbecd8
[ 0.002264412585645914, 0.0003596974129322916, 0.00016711742500774562, 0.0001702777954051271, 0.0005759908817708492 ]
{ "id": 0, "code_window": [ "export const RESPONSE_PASSTHROUGH_METADATA = '__responsePassthrough__';\n", "export const SSE_METADATA = '__sse__';\n", "export const VERSION_METADATA = '__version__';\n", "export const INJECTABLE_WATERMARK = '__injectable__';\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "export const CONTROLLER_WATERMARK = '__controller__';\n", "export const CATCH_WATERMARK = '__catch__';" ], "file_path": "packages/common/constants.ts", "type": "add", "edit_start_line_idx": 32 }
import { expect } from 'chai'; import { VERSION_METADATA } from '../../constants'; import { Controller } from '../../decorators/core/controller.decorator'; describe('@Controller', () => { const reflectedPath = 'test'; const reflectedHost = 'api.example.com'; const reflectedHostArray = ['api1.example.com', 'api2.example.com']; const reflectedVersion = '1'; @Controller(reflectedPath) class Test {} @Controller() class EmptyDecorator {} @Controller({ path: reflectedPath, host: reflectedHost }) class PathAndHostDecorator {} @Controller({ path: reflectedPath, host: reflectedHostArray }) class PathAndHostArrayDecorator {} @Controller({ host: reflectedHost }) class HostOnlyDecorator {} @Controller({ path: reflectedPath, host: reflectedHost, version: reflectedVersion, }) class PathAndHostAndVersionDecorator {} @Controller({ version: reflectedVersion }) class VersionOnlyDecorator {} it('should enhance controller with expected path metadata', () => { const path = Reflect.getMetadata('path', Test); expect(path).to.be.eql(reflectedPath); const path2 = Reflect.getMetadata('path', PathAndHostDecorator); expect(path2).to.be.eql(reflectedPath); const path3 = Reflect.getMetadata('path', PathAndHostAndVersionDecorator); expect(path3).to.be.eql(reflectedPath); }); it('should enhance controller with expected host metadata', () => { const host = Reflect.getMetadata('host', PathAndHostDecorator); expect(host).to.be.eql(reflectedHost); const host2 = Reflect.getMetadata('host', HostOnlyDecorator); expect(host2).to.be.eql(reflectedHost); const host3 = Reflect.getMetadata('host', PathAndHostArrayDecorator); expect(host3).to.be.eql(reflectedHostArray); const host4 = Reflect.getMetadata('host', PathAndHostAndVersionDecorator); expect(host4).to.be.eql(reflectedHost); }); it('should enhance controller with expected version metadata', () => { const version = Reflect.getMetadata( VERSION_METADATA, PathAndHostAndVersionDecorator, ); expect(version).to.be.eql(reflectedVersion); const version2 = Reflect.getMetadata( VERSION_METADATA, VersionOnlyDecorator, ); expect(version2).to.be.eql(reflectedVersion); }); it('should set default path when no object passed as param', () => { const path = Reflect.getMetadata('path', EmptyDecorator); expect(path).to.be.eql('/'); const path2 = Reflect.getMetadata('path', HostOnlyDecorator); expect(path2).to.be.eql('/'); const path3 = Reflect.getMetadata('path', VersionOnlyDecorator); expect(path3).to.be.eql('/'); }); it('should not set host when no host passed as param', () => { const host = Reflect.getMetadata('host', Test); expect(host).to.be.undefined; const host2 = Reflect.getMetadata('host', EmptyDecorator); expect(host2).to.be.undefined; }); it('should not set version when no version passed as param', () => { const version = Reflect.getMetadata(VERSION_METADATA, Test); expect(version).to.be.undefined; const version2 = Reflect.getMetadata(VERSION_METADATA, EmptyDecorator); expect(version2).to.be.undefined; }); });
packages/common/test/decorators/controller.decorator.spec.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.9991920590400696, 0.39972954988479614, 0.0001691762008704245, 0.00020194830722175539, 0.4893437623977661 ]
{ "id": 0, "code_window": [ "export const RESPONSE_PASSTHROUGH_METADATA = '__responsePassthrough__';\n", "export const SSE_METADATA = '__sse__';\n", "export const VERSION_METADATA = '__version__';\n", "export const INJECTABLE_WATERMARK = '__injectable__';\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "export const CONTROLLER_WATERMARK = '__controller__';\n", "export const CATCH_WATERMARK = '__catch__';" ], "file_path": "packages/common/constants.ts", "type": "add", "edit_start_line_idx": 32 }
export class CreateUserDto { firstName: string; lastName: string; }
sample/05-sql-typeorm/src/users/dto/create-user.dto.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00021366150758694857, 0.00021366150758694857, 0.00021366150758694857, 0.00021366150758694857, 0 ]
{ "id": 0, "code_window": [ "export const RESPONSE_PASSTHROUGH_METADATA = '__responsePassthrough__';\n", "export const SSE_METADATA = '__sse__';\n", "export const VERSION_METADATA = '__version__';\n", "export const INJECTABLE_WATERMARK = '__injectable__';\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "export const CONTROLLER_WATERMARK = '__controller__';\n", "export const CATCH_WATERMARK = '__catch__';" ], "file_path": "packages/common/constants.ts", "type": "add", "edit_start_line_idx": 32 }
import { Module } from '@nestjs/common'; import { EventsModule } from './events/events.module'; @Module({ imports: [EventsModule], }) export class AppModule {}
sample/02-gateways/src/app.module.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00016946841788012534, 0.00016946841788012534, 0.00016946841788012534, 0.00016946841788012534, 0 ]
{ "id": 0, "code_window": [ "export const RESPONSE_PASSTHROUGH_METADATA = '__responsePassthrough__';\n", "export const SSE_METADATA = '__sse__';\n", "export const VERSION_METADATA = '__version__';\n", "export const INJECTABLE_WATERMARK = '__injectable__';\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "export const CONTROLLER_WATERMARK = '__controller__';\n", "export const CATCH_WATERMARK = '__catch__';" ], "file_path": "packages/common/constants.ts", "type": "add", "edit_start_line_idx": 32 }
{ "name": "nest-typescript-starter", "version": "1.0.0", "description": "Nest TypeScript starter repository", "license": "MIT", "scripts": { "prebuild": "rimraf dist", "build": "nest build", "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", "start": "nest start", "start:dev": "nest start --watch", "start:debug": "nest start --debug --watch", "start:prod": "node dist/main", "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", "test": "jest", "test:watch": "jest --watch", "test:cov": "jest --coverage", "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", "test:e2e": "echo 'No e2e tests implemented yet.'" }, "dependencies": { "@nestjs/common": "8.2.3", "@nestjs/core": "8.2.3", "@nestjs/event-emitter": "1.0.0", "@nestjs/platform-express": "8.2.3", "reflect-metadata": "0.1.13", "rimraf": "3.0.2", "rxjs": "7.4.0" }, "devDependencies": { "@nestjs/cli": "8.1.5", "@nestjs/schematics": "8.0.5", "@nestjs/testing": "8.2.3", "@types/express": "4.17.13", "@types/jest": "27.0.3", "@types/node": "16.11.12", "@types/supertest": "2.0.11", "@typescript-eslint/eslint-plugin": "4.33.0", "@typescript-eslint/parser": "4.33.0", "eslint": "7.32.0", "eslint-config-prettier": "8.3.0", "eslint-plugin-import": "2.25.3", "jest": "27.3.1", "prettier": "2.5.1", "supertest": "6.1.6", "ts-jest": "27.0.7", "ts-loader": "9.2.6", "ts-node": "10.4.0", "tsconfig-paths": "3.11.0", "typescript": "4.3.5" }, "jest": { "moduleFileExtensions": [ "js", "json", "ts" ], "rootDir": "src", "testRegex": ".spec.ts$", "transform": { "^.+\\.(t|j)s$": "ts-jest" }, "coverageDirectory": "../coverage", "testEnvironment": "node" } }
sample/30-event-emitter/package.json
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017383611702825874, 0.00017008488066494465, 0.00016804822371341288, 0.0001694259262876585, 0.0000017782019767764723 ]
{ "id": 1, "code_window": [ "import { FILTER_CATCH_EXCEPTIONS } from '../../constants';\n", "import { Type } from '../../interfaces';\n", "\n", "/**\n", " * Decorator that marks a class as a Nest exception filter. An exception filter\n", " * handles exceptions thrown by or not handled by your application code.\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { CATCH_WATERMARK, FILTER_CATCH_EXCEPTIONS } from '../../constants';\n" ], "file_path": "packages/common/decorators/core/catch.decorator.ts", "type": "replace", "edit_start_line_idx": 0 }
export const MODULE_METADATA = { IMPORTS: 'imports', PROVIDERS: 'providers', CONTROLLERS: 'controllers', EXPORTS: 'exports', }; export const GLOBAL_MODULE_METADATA = '__module:global__'; export const HOST_METADATA = 'host'; export const PATH_METADATA = 'path'; export const PARAMTYPES_METADATA = 'design:paramtypes'; export const SELF_DECLARED_DEPS_METADATA = 'self:paramtypes'; export const OPTIONAL_DEPS_METADATA = 'optional:paramtypes'; export const PROPERTY_DEPS_METADATA = 'self:properties_metadata'; export const OPTIONAL_PROPERTY_DEPS_METADATA = 'optional:properties_metadata'; export const SCOPE_OPTIONS_METADATA = 'scope:options'; export const METHOD_METADATA = 'method'; export const ROUTE_ARGS_METADATA = '__routeArguments__'; export const CUSTOM_ROUTE_AGRS_METADATA = '__customRouteArgs__'; export const EXCEPTION_FILTERS_METADATA = '__exceptionFilters__'; export const FILTER_CATCH_EXCEPTIONS = '__filterCatchExceptions__'; export const PIPES_METADATA = '__pipes__'; export const GUARDS_METADATA = '__guards__'; export const RENDER_METADATA = '__renderTemplate__'; export const INTERCEPTORS_METADATA = '__interceptors__'; export const HTTP_CODE_METADATA = '__httpCode__'; export const MODULE_PATH = '__module_path__'; export const HEADERS_METADATA = '__headers__'; export const REDIRECT_METADATA = '__redirect__'; export const RESPONSE_PASSTHROUGH_METADATA = '__responsePassthrough__'; export const SSE_METADATA = '__sse__'; export const VERSION_METADATA = '__version__'; export const INJECTABLE_WATERMARK = '__injectable__';
packages/common/constants.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.007753955665975809, 0.002081893850117922, 0.00016642204718664289, 0.00020359849440865219, 0.0032749006059020758 ]
{ "id": 1, "code_window": [ "import { FILTER_CATCH_EXCEPTIONS } from '../../constants';\n", "import { Type } from '../../interfaces';\n", "\n", "/**\n", " * Decorator that marks a class as a Nest exception filter. An exception filter\n", " * handles exceptions thrown by or not handled by your application code.\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { CATCH_WATERMARK, FILTER_CATCH_EXCEPTIONS } from '../../constants';\n" ], "file_path": "packages/common/decorators/core/catch.decorator.ts", "type": "replace", "edit_start_line_idx": 0 }
import { HttpStatus } from '../enums/http-status.enum'; import { HttpException } from './http.exception'; /** * Defines an HTTP exception for *Bad Request* type errors. * * @see [Base Exceptions](https://docs.nestjs.com/exception-filters#base-exceptions) * * @publicApi */ export class BadRequestException extends HttpException { /** * Instantiate a `BadRequestException` Exception. * * @example * `throw new BadRequestException()` * * @usageNotes * The HTTP response status code will be 400. * - The `objectOrError` argument defines the JSON response body or the message string. * - The `description` argument contains a short description of the HTTP error. * * By default, the JSON response body contains two properties: * - `statusCode`: this will be the value 400. * - `message`: the string `'Bad Request'` by default; override this by supplying * a string in the `objectOrError` parameter. * * If the parameter `objectOrError` is a string, the response body will contain an * additional property, `error`, with a short description of the HTTP error. To override the * entire JSON response body, pass an object instead. Nest will serialize the object * and return it as the JSON response body. * * @param objectOrError string or object describing the error condition. * @param description a short description of the HTTP error. */ constructor( objectOrError?: string | object | any, description = 'Bad Request', ) { super( HttpException.createBody( objectOrError, description, HttpStatus.BAD_REQUEST, ), HttpStatus.BAD_REQUEST, ); } }
packages/common/exceptions/bad-request.exception.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00023723278718534857, 0.00018843557336367667, 0.00016603908443357795, 0.00017457646026741713, 0.000025842855393420905 ]
{ "id": 1, "code_window": [ "import { FILTER_CATCH_EXCEPTIONS } from '../../constants';\n", "import { Type } from '../../interfaces';\n", "\n", "/**\n", " * Decorator that marks a class as a Nest exception filter. An exception filter\n", " * handles exceptions thrown by or not handled by your application code.\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { CATCH_WATERMARK, FILTER_CATCH_EXCEPTIONS } from '../../constants';\n" ], "file_path": "packages/common/decorators/core/catch.decorator.ts", "type": "replace", "edit_start_line_idx": 0 }
import { flatten, RequestMethod, VersioningOptions, VersioningType, VERSION_NEUTRAL, } from '@nestjs/common'; import { addLeadingSlash, isUndefined, stripEndSlash, } from '@nestjs/common/utils/shared.utils'; import { ApplicationConfig } from '../application-config'; import { RoutePathMetadata } from './interfaces/route-path-metadata.interface'; import { isRouteExcluded } from './utils'; export class RoutePathFactory { constructor(private readonly applicationConfig: ApplicationConfig) {} public create( metadata: RoutePathMetadata, requestMethod?: RequestMethod, ): string[] { let paths = ['']; const version = this.getVersion(metadata); if (version && metadata.versioningOptions?.type === VersioningType.URI) { const versionPrefix = this.getVersionPrefix(metadata.versioningOptions); // Version Neutral - Do not include version in URL if (version !== VERSION_NEUTRAL) { if (Array.isArray(version)) { paths = flatten( paths.map(path => version.map(v => path + `/${versionPrefix}${v}`)), ); } else { paths = paths.map(path => path + `/${versionPrefix}${version}`); } } } paths = this.appendToAllIfDefined(paths, metadata.modulePath); paths = this.appendToAllIfDefined(paths, metadata.ctrlPath); paths = this.appendToAllIfDefined(paths, metadata.methodPath); if (metadata.globalPrefix) { paths = paths.map(path => { if (this.isExcludedFromGlobalPrefix(path, requestMethod)) { return path; } return stripEndSlash(metadata.globalPrefix || '') + path; }); } return paths .map(path => addLeadingSlash(path || '/')) .map(path => (path !== '/' ? stripEndSlash(path) : path)); } public getVersion(metadata: RoutePathMetadata) { // The version will be either the path version or the controller version, // with the pathVersion taking priority. return metadata.methodVersion || metadata.controllerVersion; } public getVersionPrefix(versioningOptions: VersioningOptions): string { const defaultPrefix = 'v'; if (versioningOptions.type === VersioningType.URI) { if (versioningOptions.prefix === false) { return ''; } else if (versioningOptions.prefix !== undefined) { return versioningOptions.prefix; } } return defaultPrefix; } public appendToAllIfDefined( paths: string[], fragmentToAppend: string | string[] | undefined, ): string[] { if (!fragmentToAppend) { return paths; } const concatPaths = (a: string, b: string) => stripEndSlash(a) + addLeadingSlash(b); if (Array.isArray(fragmentToAppend)) { const paths2dArray = paths.map(path => fragmentToAppend.map(fragment => concatPaths(path, fragment)), ); return flatten(paths2dArray); } return paths.map(path => concatPaths(path, fragmentToAppend)); } public isExcludedFromGlobalPrefix( path: string, requestMethod?: RequestMethod, ) { if (isUndefined(requestMethod)) { return false; } const options = this.applicationConfig.getGlobalPrefixOptions(); const excludedRoutes = options.exclude; return ( Array.isArray(excludedRoutes) && isRouteExcluded(excludedRoutes, path, requestMethod) ); } }
packages/core/router/route-path-factory.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00016941300418693572, 0.0001670803176239133, 0.00016539172793272883, 0.00016699032858014107, 0.0000013183891951484839 ]
{ "id": 1, "code_window": [ "import { FILTER_CATCH_EXCEPTIONS } from '../../constants';\n", "import { Type } from '../../interfaces';\n", "\n", "/**\n", " * Decorator that marks a class as a Nest exception filter. An exception filter\n", " * handles exceptions thrown by or not handled by your application code.\n" ], "labels": [ "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { CATCH_WATERMARK, FILTER_CATCH_EXCEPTIONS } from '../../constants';\n" ], "file_path": "packages/common/decorators/core/catch.decorator.ts", "type": "replace", "edit_start_line_idx": 0 }
module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], extends: [ 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'prettier', ], root: true, env: { node: true, jest: true, }, rules: { '@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/no-explicit-any': 'off', }, };
sample/07-sequelize/.eslintrc.js
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00016863731434568763, 0.00016778364079073071, 0.00016730556671973318, 0.00016740801220294088, 6.050923389011587e-7 ]
{ "id": 2, "code_window": [ " *\n", " * @publicApi\n", " */\n", "export function Catch(...exceptions: Type<any>[]): ClassDecorator {\n", " return (target: object) => {\n", " Reflect.defineMetadata(FILTER_CATCH_EXCEPTIONS, exceptions, target);\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " Reflect.defineMetadata(CATCH_WATERMARK, true, target);\n" ], "file_path": "packages/common/decorators/core/catch.decorator.ts", "type": "add", "edit_start_line_idx": 22 }
import { expect } from 'chai'; import { VERSION_METADATA } from '../../constants'; import { Controller } from '../../decorators/core/controller.decorator'; describe('@Controller', () => { const reflectedPath = 'test'; const reflectedHost = 'api.example.com'; const reflectedHostArray = ['api1.example.com', 'api2.example.com']; const reflectedVersion = '1'; @Controller(reflectedPath) class Test {} @Controller() class EmptyDecorator {} @Controller({ path: reflectedPath, host: reflectedHost }) class PathAndHostDecorator {} @Controller({ path: reflectedPath, host: reflectedHostArray }) class PathAndHostArrayDecorator {} @Controller({ host: reflectedHost }) class HostOnlyDecorator {} @Controller({ path: reflectedPath, host: reflectedHost, version: reflectedVersion, }) class PathAndHostAndVersionDecorator {} @Controller({ version: reflectedVersion }) class VersionOnlyDecorator {} it('should enhance controller with expected path metadata', () => { const path = Reflect.getMetadata('path', Test); expect(path).to.be.eql(reflectedPath); const path2 = Reflect.getMetadata('path', PathAndHostDecorator); expect(path2).to.be.eql(reflectedPath); const path3 = Reflect.getMetadata('path', PathAndHostAndVersionDecorator); expect(path3).to.be.eql(reflectedPath); }); it('should enhance controller with expected host metadata', () => { const host = Reflect.getMetadata('host', PathAndHostDecorator); expect(host).to.be.eql(reflectedHost); const host2 = Reflect.getMetadata('host', HostOnlyDecorator); expect(host2).to.be.eql(reflectedHost); const host3 = Reflect.getMetadata('host', PathAndHostArrayDecorator); expect(host3).to.be.eql(reflectedHostArray); const host4 = Reflect.getMetadata('host', PathAndHostAndVersionDecorator); expect(host4).to.be.eql(reflectedHost); }); it('should enhance controller with expected version metadata', () => { const version = Reflect.getMetadata( VERSION_METADATA, PathAndHostAndVersionDecorator, ); expect(version).to.be.eql(reflectedVersion); const version2 = Reflect.getMetadata( VERSION_METADATA, VersionOnlyDecorator, ); expect(version2).to.be.eql(reflectedVersion); }); it('should set default path when no object passed as param', () => { const path = Reflect.getMetadata('path', EmptyDecorator); expect(path).to.be.eql('/'); const path2 = Reflect.getMetadata('path', HostOnlyDecorator); expect(path2).to.be.eql('/'); const path3 = Reflect.getMetadata('path', VersionOnlyDecorator); expect(path3).to.be.eql('/'); }); it('should not set host when no host passed as param', () => { const host = Reflect.getMetadata('host', Test); expect(host).to.be.undefined; const host2 = Reflect.getMetadata('host', EmptyDecorator); expect(host2).to.be.undefined; }); it('should not set version when no version passed as param', () => { const version = Reflect.getMetadata(VERSION_METADATA, Test); expect(version).to.be.undefined; const version2 = Reflect.getMetadata(VERSION_METADATA, EmptyDecorator); expect(version2).to.be.undefined; }); });
packages/common/test/decorators/controller.decorator.spec.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0001827197556849569, 0.00017276935977861285, 0.00016850953397806734, 0.00017122547433245927, 0.000004191895186522743 ]
{ "id": 2, "code_window": [ " *\n", " * @publicApi\n", " */\n", "export function Catch(...exceptions: Type<any>[]): ClassDecorator {\n", " return (target: object) => {\n", " Reflect.defineMetadata(FILTER_CATCH_EXCEPTIONS, exceptions, target);\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " Reflect.defineMetadata(CATCH_WATERMARK, true, target);\n" ], "file_path": "packages/common/decorators/core/catch.decorator.ts", "type": "add", "edit_start_line_idx": 22 }
import { expect } from 'chai'; import * as sinon from 'sinon'; import { logLevel } from '../../external/kafka.interface'; import { KafkaLogger } from '../../helpers/kafka-logger'; const namespace = 'namespace'; const label = 'label'; const entry = { message: 'message', other: { stuff: 'here', }, }; describe('KafkaLogger', () => { let kafkaLogger: any; let error: sinon.SinonSpy; let warn: sinon.SinonSpy; let log: sinon.SinonSpy; let debug: sinon.SinonSpy; beforeEach(() => { // set error = sinon.spy(); warn = sinon.spy(); log = sinon.spy(); debug = sinon.spy(); kafkaLogger = KafkaLogger({ error, warn, log, debug, }); }); it('error', () => { kafkaLogger({ namespace, level: logLevel.ERROR, label, log: entry, }); expect(error.calledOnce).to.be.true; expect(error.args[0][0]).to.eq( 'label [namespace] message {"other":{"stuff":"here"}}', ); }); it('nothing', () => { kafkaLogger({ namespace, level: logLevel.NOTHING, label, log: entry, }); expect(error.calledOnce).to.be.true; }); it('warn', () => { kafkaLogger({ namespace, level: logLevel.WARN, label, log: entry, }); expect(warn.calledOnce).to.be.true; }); it('info', () => { kafkaLogger({ namespace, level: logLevel.INFO, label, log: entry, }); expect(log.calledOnce).to.be.true; }); it('debug', () => { kafkaLogger({ namespace, level: logLevel.DEBUG, label, log: entry, }); expect(debug.calledOnce).to.be.true; }); });
packages/microservices/test/helpers/kafka-logger.spec.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0001794639538275078, 0.00017512950580567122, 0.00016580162628088146, 0.00017570334603078663, 0.0000034866038731706794 ]
{ "id": 2, "code_window": [ " *\n", " * @publicApi\n", " */\n", "export function Catch(...exceptions: Type<any>[]): ClassDecorator {\n", " return (target: object) => {\n", " Reflect.defineMetadata(FILTER_CATCH_EXCEPTIONS, exceptions, target);\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " Reflect.defineMetadata(CATCH_WATERMARK, true, target);\n" ], "file_path": "packages/common/decorators/core/catch.decorator.ts", "type": "add", "edit_start_line_idx": 22 }
{ "moduleFileExtensions": [ "ts", "tsx", "js", "json" ], "transform": { "^.+\\.tsx?$": "ts-jest" }, "testRegex": "/src/.*\\.(test|spec).(ts|tsx|js)$", "collectCoverageFrom" : ["src/**/*.{js,jsx,tsx,ts}", "!**/node_modules/**", "!**/vendor/**"], "coverageReporters": ["json", "lcov"] }
sample/01-cats-app/jest.json
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0001787383371265605, 0.000177529058419168, 0.0001763197942636907, 0.000177529058419168, 0.0000012092714314348996 ]
{ "id": 2, "code_window": [ " *\n", " * @publicApi\n", " */\n", "export function Catch(...exceptions: Type<any>[]): ClassDecorator {\n", " return (target: object) => {\n", " Reflect.defineMetadata(FILTER_CATCH_EXCEPTIONS, exceptions, target);\n", " };\n", "}" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " Reflect.defineMetadata(CATCH_WATERMARK, true, target);\n" ], "file_path": "packages/common/decorators/core/catch.decorator.ts", "type": "add", "edit_start_line_idx": 22 }
import { INestApplication, VersioningType } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import * as request from 'supertest'; import { AppModule } from '../src/app.module'; describe('URI Versioning', () => { let app: INestApplication; // ======================================================================== // describe('without global default version', () => { before(async () => { const moduleRef = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleRef.createNestApplication(); app.enableVersioning({ type: VersioningType.URI, }); await app.init(); }); describe('GET /', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1/') .expect(200) .expect('Hello World V1!'); }); it('V2', () => { return request(app.getHttpServer()) .get('/v2/') .expect(200) .expect('Hello World V2!'); }); it('V3', () => { return request(app.getHttpServer()).get('/v3/').expect(404); }); it('No Version', () => { return request(app.getHttpServer()).get('/').expect(404); }); }); describe('GET /:param', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1/param/hello') .expect(200) .expect('Parameter V1!'); }); it('V2', () => { return request(app.getHttpServer()) .get('/v2/param/hello') .expect(200) .expect('Parameter V2!'); }); it('V3', () => { return request(app.getHttpServer()).get('/v3/param/hello').expect(404); }); it('No Version', () => { return request(app.getHttpServer()).get('/param/hello').expect(404); }); }); describe('GET /multiple', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1/multiple') .expect(200) .expect('Multiple Versions 1 or 2'); }); it('V2', () => { return request(app.getHttpServer()) .get('/v2/multiple') .expect(200) .expect('Multiple Versions 1 or 2'); }); it('V3', () => { return request(app.getHttpServer()).get('/v3/multiple').expect(404); }); it('No Version', () => { return request(app.getHttpServer()).get('/multiple').expect(404); }); }); describe('GET /neutral', () => { it('No Version', () => { return request(app.getHttpServer()) .get('/neutral') .expect(200) .expect('Neutral'); }); }); describe('GET /override', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1/override') .expect(200) .expect('Override Version 1'); }); it('V2', () => { return request(app.getHttpServer()) .get('/v2/override') .expect(200) .expect('Override Version 2'); }); it('V3', () => { return request(app.getHttpServer()).get('/v3/override').expect(404); }); it('No Version', () => { return request(app.getHttpServer()).get('/override').expect(404); }); }); describe('GET /override-partial', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1/override-partial') .expect(200) .expect('Override Partial Version 1'); }); it('V2', () => { return request(app.getHttpServer()) .get('/v2/override-partial') .expect(200) .expect('Override Partial Version 2'); }); it('V3', () => { return request(app.getHttpServer()) .get('/v3/override-partial') .expect(404); }); it('No Version', () => { return request(app.getHttpServer()) .get('/override-partial') .expect(404); }); }); describe('GET /foo/bar', () => { it('V1', () => { return request(app.getHttpServer()).get('/v1/foo/bar').expect(404); }); it('V2', () => { return request(app.getHttpServer()).get('/v2/foo/bar').expect(404); }); it('V3', () => { return request(app.getHttpServer()).get('/v3/foo/bar').expect(404); }); it('No Version', () => { return request(app.getHttpServer()) .get('/foo/bar') .expect(200) .expect('Hello FooBar!'); }); }); after(async () => { await app.close(); }); }); // ======================================================================== // describe('with the global default version: "1"', () => { before(async () => { const moduleRef = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleRef.createNestApplication(); app.enableVersioning({ type: VersioningType.URI, defaultVersion: '1', }); await app.init(); }); describe('GET /', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1') .expect(200) .expect('Hello World V1!'); }); it('V2', () => { return request(app.getHttpServer()) .get('/v2') .expect(200) .expect('Hello World V2!'); }); it('V3', () => { return request(app.getHttpServer()).get('/v3').expect(404); }); it('No Version', () => { return request(app.getHttpServer()).get('/').expect(404); }); }); describe('GET /:param', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1/param/hello') .expect(200) .expect('Parameter V1!'); }); it('V2', () => { return request(app.getHttpServer()) .get('/v2/param/hello') .expect(200) .expect('Parameter V2!'); }); it('V3', () => { return request(app.getHttpServer()).get('/v3/param/hello').expect(404); }); it('No Version', () => { return request(app.getHttpServer()).get('/param/hello').expect(404); }); }); describe('GET /multiple', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1/multiple') .expect(200) .expect('Multiple Versions 1 or 2'); }); it('V2', () => { return request(app.getHttpServer()) .get('/v2/multiple') .expect(200) .expect('Multiple Versions 1 or 2'); }); it('V3', () => { return request(app.getHttpServer()).get('/v3/multiple').expect(404); }); it('No Version', () => { return request(app.getHttpServer()).get('/multiple').expect(404); }); }); describe('GET /neutral', () => { it('No Version', () => { return request(app.getHttpServer()) .get('/neutral') .expect(200) .expect('Neutral'); }); }); describe('GET /override', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1/override') .expect(200) .expect('Override Version 1'); }); it('V2', () => { return request(app.getHttpServer()) .get('/v2/override') .expect(200) .expect('Override Version 2'); }); it('V3', () => { return request(app.getHttpServer()).get('/v3/override').expect(404); }); it('No Version', () => { return request(app.getHttpServer()).get('/override').expect(404); }); }); describe('GET /override-partial', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1/override-partial') .expect(200) .expect('Override Partial Version 1'); }); it('V2', () => { return request(app.getHttpServer()) .get('/v2/override-partial') .expect(200) .expect('Override Partial Version 2'); }); it('V3', () => { return request(app.getHttpServer()) .get('/v3/override-partial') .expect(404); }); it('No Version', () => { return request(app.getHttpServer()) .get('/override-partial') .expect(404); }); }); describe('GET /foo/bar', () => { it('V1', () => { return request(app.getHttpServer()) .get('/v1/foo/bar') .expect(200) .expect('Hello FooBar!'); }); it('V2', () => { return request(app.getHttpServer()).get('/v2/foo/bar').expect(404); }); it('V3', () => { return request(app.getHttpServer()).get('/v3/foo/bar').expect(404); }); it('No Version', () => { return request(app.getHttpServer()).get('/foo/bar').expect(404); }); }); after(async () => { await app.close(); }); }); });
integration/versioning/e2e/uri-versioning.spec.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017879391089081764, 0.00017567205941304564, 0.0001721012667985633, 0.00017564308654982597, 0.0000017451410485591623 ]
{ "id": 3, "code_window": [ "import {\n", " HOST_METADATA,\n", " PATH_METADATA,\n", " SCOPE_OPTIONS_METADATA,\n", " VERSION_METADATA,\n", "} from '../../constants';\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " CONTROLLER_WATERMARK,\n" ], "file_path": "packages/common/decorators/core/controller.decorator.ts", "type": "add", "edit_start_line_idx": 1 }
import { expect } from 'chai'; import { VERSION_METADATA } from '../../constants'; import { Controller } from '../../decorators/core/controller.decorator'; describe('@Controller', () => { const reflectedPath = 'test'; const reflectedHost = 'api.example.com'; const reflectedHostArray = ['api1.example.com', 'api2.example.com']; const reflectedVersion = '1'; @Controller(reflectedPath) class Test {} @Controller() class EmptyDecorator {} @Controller({ path: reflectedPath, host: reflectedHost }) class PathAndHostDecorator {} @Controller({ path: reflectedPath, host: reflectedHostArray }) class PathAndHostArrayDecorator {} @Controller({ host: reflectedHost }) class HostOnlyDecorator {} @Controller({ path: reflectedPath, host: reflectedHost, version: reflectedVersion, }) class PathAndHostAndVersionDecorator {} @Controller({ version: reflectedVersion }) class VersionOnlyDecorator {} it('should enhance controller with expected path metadata', () => { const path = Reflect.getMetadata('path', Test); expect(path).to.be.eql(reflectedPath); const path2 = Reflect.getMetadata('path', PathAndHostDecorator); expect(path2).to.be.eql(reflectedPath); const path3 = Reflect.getMetadata('path', PathAndHostAndVersionDecorator); expect(path3).to.be.eql(reflectedPath); }); it('should enhance controller with expected host metadata', () => { const host = Reflect.getMetadata('host', PathAndHostDecorator); expect(host).to.be.eql(reflectedHost); const host2 = Reflect.getMetadata('host', HostOnlyDecorator); expect(host2).to.be.eql(reflectedHost); const host3 = Reflect.getMetadata('host', PathAndHostArrayDecorator); expect(host3).to.be.eql(reflectedHostArray); const host4 = Reflect.getMetadata('host', PathAndHostAndVersionDecorator); expect(host4).to.be.eql(reflectedHost); }); it('should enhance controller with expected version metadata', () => { const version = Reflect.getMetadata( VERSION_METADATA, PathAndHostAndVersionDecorator, ); expect(version).to.be.eql(reflectedVersion); const version2 = Reflect.getMetadata( VERSION_METADATA, VersionOnlyDecorator, ); expect(version2).to.be.eql(reflectedVersion); }); it('should set default path when no object passed as param', () => { const path = Reflect.getMetadata('path', EmptyDecorator); expect(path).to.be.eql('/'); const path2 = Reflect.getMetadata('path', HostOnlyDecorator); expect(path2).to.be.eql('/'); const path3 = Reflect.getMetadata('path', VersionOnlyDecorator); expect(path3).to.be.eql('/'); }); it('should not set host when no host passed as param', () => { const host = Reflect.getMetadata('host', Test); expect(host).to.be.undefined; const host2 = Reflect.getMetadata('host', EmptyDecorator); expect(host2).to.be.undefined; }); it('should not set version when no version passed as param', () => { const version = Reflect.getMetadata(VERSION_METADATA, Test); expect(version).to.be.undefined; const version2 = Reflect.getMetadata(VERSION_METADATA, EmptyDecorator); expect(version2).to.be.undefined; }); });
packages/common/test/decorators/controller.decorator.spec.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.9958016276359558, 0.32391592860221863, 0.000182988093001768, 0.003380398964509368, 0.43894389271736145 ]
{ "id": 3, "code_window": [ "import {\n", " HOST_METADATA,\n", " PATH_METADATA,\n", " SCOPE_OPTIONS_METADATA,\n", " VERSION_METADATA,\n", "} from '../../constants';\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " CONTROLLER_WATERMARK,\n" ], "file_path": "packages/common/decorators/core/controller.decorator.ts", "type": "add", "edit_start_line_idx": 1 }
import * as mongoose from 'mongoose'; export const CatSchema = new mongoose.Schema({ name: String, age: Number, breed: String, });
integration/mongoose/src/cats/schemas/cat.schema.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0001733532699290663, 0.0001733532699290663, 0.0001733532699290663, 0.0001733532699290663, 0 ]
{ "id": 3, "code_window": [ "import {\n", " HOST_METADATA,\n", " PATH_METADATA,\n", " SCOPE_OPTIONS_METADATA,\n", " VERSION_METADATA,\n", "} from '../../constants';\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " CONTROLLER_WATERMARK,\n" ], "file_path": "packages/common/decorators/core/controller.decorator.ts", "type": "add", "edit_start_line_idx": 1 }
import { expect } from 'chai'; import * as sinon from 'sinon'; import { Catch } from '../../../common/decorators/core/catch.decorator'; import { UseFilters } from '../../../common/decorators/core/exception-filters.decorator'; import { ApplicationConfig } from '../../application-config'; import { NestContainer } from '../../injector/container'; import { InstanceWrapper } from '../../injector/instance-wrapper'; import { RouterExceptionFilters } from '../../router/router-exception-filters'; import { NoopHttpAdapter } from '../utils/noop-adapter.spec'; describe('RouterExceptionFilters', () => { let applicationConfig: ApplicationConfig; let exceptionFilter: RouterExceptionFilters; class CustomException {} @Catch(CustomException) class ExceptionFilter { public catch(exc, res) {} } beforeEach(() => { applicationConfig = new ApplicationConfig(); exceptionFilter = new RouterExceptionFilters( new NestContainer(), applicationConfig, new NoopHttpAdapter({}), ); }); describe('create', () => { describe('when filters metadata is empty', () => { class EmptyMetadata {} beforeEach(() => { sinon.stub(exceptionFilter, 'createContext').returns([]); }); it('should return plain ExceptionHandler object', () => { const filter = exceptionFilter.create( new EmptyMetadata(), () => ({} as any), undefined, ); expect((filter as any).filters).to.be.empty; }); }); describe('when filters metadata is not empty', () => { @UseFilters(new ExceptionFilter()) class WithMetadata {} it('should return ExceptionHandler object with exception filters', () => { const filter = exceptionFilter.create( new WithMetadata(), () => ({} as any), undefined, ); expect((filter as any).filters).to.not.be.empty; }); }); }); describe('reflectCatchExceptions', () => { it('should return FILTER_CATCH_EXCEPTIONS metadata', () => { expect( exceptionFilter.reflectCatchExceptions(new ExceptionFilter()), ).to.be.eql([CustomException]); }); }); describe('createConcreteContext', () => { class InvalidFilter {} const filters = [new ExceptionFilter(), new InvalidFilter(), 'test']; it('should return expected exception filters metadata', () => { const resolved = exceptionFilter.createConcreteContext(filters as any); expect(resolved).to.have.length(1); expect(resolved[0].exceptionMetatypes).to.be.deep.equal([ CustomException, ]); expect(resolved[0].func).to.be.a('function'); }); }); describe('getGlobalMetadata', () => { describe('when contextId is static and inquirerId is nil', () => { it('should return global filters', () => { const expectedResult = applicationConfig.getGlobalFilters(); expect(exceptionFilter.getGlobalMetadata()).to.be.equal(expectedResult); }); }); describe('otherwise', () => { it('should merge static global with request/transient scoped filters', () => { const globalFilters: any = ['test']; const instanceWrapper = new InstanceWrapper(); const instance = 'request-scoped'; const scopedFilterWrappers = [instanceWrapper]; sinon .stub(applicationConfig, 'getGlobalFilters') .callsFake(() => globalFilters); sinon .stub(applicationConfig, 'getGlobalRequestFilters') .callsFake(() => scopedFilterWrappers); sinon .stub(instanceWrapper, 'getInstanceByContextId') .callsFake(() => ({ instance } as any)); expect(exceptionFilter.getGlobalMetadata({ id: 3 })).to.contains( instance, ...globalFilters, ); }); }); }); });
packages/core/test/router/router-exception-filters.spec.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00019875702855642885, 0.00017373490845784545, 0.000168193771969527, 0.00017102062702178955, 0.000008124799933284521 ]
{ "id": 3, "code_window": [ "import {\n", " HOST_METADATA,\n", " PATH_METADATA,\n", " SCOPE_OPTIONS_METADATA,\n", " VERSION_METADATA,\n", "} from '../../constants';\n" ], "labels": [ "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " CONTROLLER_WATERMARK,\n" ], "file_path": "packages/common/decorators/core/controller.decorator.ts", "type": "add", "edit_start_line_idx": 1 }
import { expect } from 'chai'; import { Transport } from '../../enums/transport.enum'; import { ServerFactory } from '../../server/server-factory'; import { ServerGrpc } from '../../server/server-grpc'; import { ServerKafka } from '../../server/server-kafka'; import { ServerMqtt } from '../../server/server-mqtt'; import { ServerNats } from '../../server/server-nats'; import { ServerRedis } from '../../server/server-redis'; import { ServerRMQ } from '../../server/server-rmq'; import { ServerTCP } from '../../server/server-tcp'; describe('ServerFactory', () => { describe('create', () => { it(`should return tcp server by default`, () => { expect(ServerFactory.create({}) instanceof ServerTCP).to.be.true; }); it(`should return redis server`, () => { expect( ServerFactory.create({ transport: Transport.REDIS }) instanceof ServerRedis, ).to.be.true; }); it(`should return redis server`, () => { expect( ServerFactory.create({ transport: Transport.REDIS }) instanceof ServerRedis, ).to.be.true; }); it(`should return mqtt server`, () => { expect( ServerFactory.create({ transport: Transport.MQTT }) instanceof ServerMqtt, ).to.be.true; }); it(`should return nats server`, () => { expect( ServerFactory.create({ transport: Transport.NATS }) instanceof ServerNats, ).to.be.true; }); it(`should return rmq server`, () => { expect( ServerFactory.create({ transport: Transport.RMQ }) instanceof ServerRMQ, ).to.be.true; }); it(`should return kafka server`, () => { expect( ServerFactory.create({ transport: Transport.KAFKA }) instanceof ServerKafka, ).to.be.true; }); it(`should return grpc server`, () => { expect( ServerFactory.create({ transport: Transport.GRPC, options: { protoPath: '', package: '' }, }) instanceof ServerGrpc, ).to.be.true; }); }); });
packages/microservices/test/server/server-factory.spec.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0001748696668073535, 0.00017014962213579565, 0.00016818447329569608, 0.00016994206816889346, 0.0000020684949504357064 ]
{ "id": 4, "code_window": [ " prefixOrOptions.version,\n", " ];\n", "\n", " return (target: object) => {\n", " Reflect.defineMetadata(PATH_METADATA, path, target);\n", " Reflect.defineMetadata(HOST_METADATA, host, target);\n", " Reflect.defineMetadata(SCOPE_OPTIONS_METADATA, scopeOptions, target);\n", " Reflect.defineMetadata(VERSION_METADATA, versionOptions, target);\n", " };\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " Reflect.defineMetadata(CONTROLLER_WATERMARK, true, target);\n" ], "file_path": "packages/common/decorators/core/controller.decorator.ts", "type": "add", "edit_start_line_idx": 169 }
import { expect } from 'chai'; import { FILTER_CATCH_EXCEPTIONS } from '../../constants'; import { Catch } from '../../decorators/core/catch.decorator'; describe('@Catch', () => { const exceptions: any = ['exception', 'exception2']; @Catch(...exceptions) class Test {} it('should enhance class with expected exceptions array', () => { const metadata = Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, Test); expect(metadata).to.be.eql(exceptions); }); });
packages/common/test/decorators/catch.decorator.spec.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017587616457603872, 0.00016893510473892093, 0.00016199404490180314, 0.00016893510473892093, 0.000006941059837117791 ]
{ "id": 4, "code_window": [ " prefixOrOptions.version,\n", " ];\n", "\n", " return (target: object) => {\n", " Reflect.defineMetadata(PATH_METADATA, path, target);\n", " Reflect.defineMetadata(HOST_METADATA, host, target);\n", " Reflect.defineMetadata(SCOPE_OPTIONS_METADATA, scopeOptions, target);\n", " Reflect.defineMetadata(VERSION_METADATA, versionOptions, target);\n", " };\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " Reflect.defineMetadata(CONTROLLER_WATERMARK, true, target);\n" ], "file_path": "packages/common/decorators/core/controller.decorator.ts", "type": "add", "edit_start_line_idx": 169 }
module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], extends: [ 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'prettier', ], root: true, env: { node: true, jest: true, }, rules: { '@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/no-explicit-any': 'off', }, };
sample/14-mongoose-base/.eslintrc.js
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017358303011860698, 0.00017219521396327764, 0.0001695516548352316, 0.00017345100059174, 0.00000187006583018956 ]
{ "id": 4, "code_window": [ " prefixOrOptions.version,\n", " ];\n", "\n", " return (target: object) => {\n", " Reflect.defineMetadata(PATH_METADATA, path, target);\n", " Reflect.defineMetadata(HOST_METADATA, host, target);\n", " Reflect.defineMetadata(SCOPE_OPTIONS_METADATA, scopeOptions, target);\n", " Reflect.defineMetadata(VERSION_METADATA, versionOptions, target);\n", " };\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " Reflect.defineMetadata(CONTROLLER_WATERMARK, true, target);\n" ], "file_path": "packages/common/decorators/core/controller.decorator.ts", "type": "add", "edit_start_line_idx": 169 }
import { LogLevel } from '../logger.service'; const LOG_LEVEL_VALUES: Record<LogLevel, number> = { debug: 0, verbose: 1, log: 2, warn: 3, error: 4, }; /** * Checks if target level is enabled. * @param targetLevel target level * @param logLevels array of enabled log levels */ export function isLogLevelEnabled( targetLevel: LogLevel, logLevels: LogLevel[] | undefined, ): boolean { if (!logLevels || (Array.isArray(logLevels) && logLevels?.length === 0)) { return false; } if (logLevels.includes(targetLevel)) { return true; } const highestLogLevelValue = logLevels .map(level => LOG_LEVEL_VALUES[level]) .sort((a, b) => b - a)?.[0]; const targetLevelValue = LOG_LEVEL_VALUES[targetLevel]; return targetLevelValue >= highestLogLevelValue; }
packages/common/services/utils/is-log-level-enabled.util.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00020517349184956402, 0.0001780374877853319, 0.00016776914708316326, 0.00016960366338025779, 0.00001568624247738626 ]
{ "id": 4, "code_window": [ " prefixOrOptions.version,\n", " ];\n", "\n", " return (target: object) => {\n", " Reflect.defineMetadata(PATH_METADATA, path, target);\n", " Reflect.defineMetadata(HOST_METADATA, host, target);\n", " Reflect.defineMetadata(SCOPE_OPTIONS_METADATA, scopeOptions, target);\n", " Reflect.defineMetadata(VERSION_METADATA, versionOptions, target);\n", " };\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " Reflect.defineMetadata(CONTROLLER_WATERMARK, true, target);\n" ], "file_path": "packages/common/decorators/core/controller.decorator.ts", "type": "add", "edit_start_line_idx": 169 }
{ "collection": "@nestjs/schematics", "sourceRoot": "src" }
sample/31-graphql-federation-code-first/posts-application/nest-cli.json
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0001713434758130461, 0.0001713434758130461, 0.0001713434758130461, 0.0001713434758130461, 0 ]
{ "id": 5, "code_window": [ "import { expect } from 'chai';\n", "import { FILTER_CATCH_EXCEPTIONS } from '../../constants';\n", "import { Catch } from '../../decorators/core/catch.decorator';\n", "\n", "describe('@Catch', () => {\n", " const exceptions: any = ['exception', 'exception2'];\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { CATCH_WATERMARK, FILTER_CATCH_EXCEPTIONS } from '../../constants';\n" ], "file_path": "packages/common/test/decorators/catch.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 1 }
import { expect } from 'chai'; import { FILTER_CATCH_EXCEPTIONS } from '../../constants'; import { Catch } from '../../decorators/core/catch.decorator'; describe('@Catch', () => { const exceptions: any = ['exception', 'exception2']; @Catch(...exceptions) class Test {} it('should enhance class with expected exceptions array', () => { const metadata = Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, Test); expect(metadata).to.be.eql(exceptions); }); });
packages/common/test/decorators/catch.decorator.spec.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.9945645332336426, 0.9647539854049683, 0.934943437576294, 0.9647539854049683, 0.029810547828674316 ]
{ "id": 5, "code_window": [ "import { expect } from 'chai';\n", "import { FILTER_CATCH_EXCEPTIONS } from '../../constants';\n", "import { Catch } from '../../decorators/core/catch.decorator';\n", "\n", "describe('@Catch', () => {\n", " const exceptions: any = ['exception', 'exception2'];\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { CATCH_WATERMARK, FILTER_CATCH_EXCEPTIONS } from '../../constants';\n" ], "file_path": "packages/common/test/decorators/catch.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 1 }
import { ArgumentMetadata, Inject, Injectable, PipeTransform, } from '@nestjs/common'; import { UsersService } from './users.service'; @Injectable() export class UserByIdPipe implements PipeTransform<string> { static COUNTER = 0; static REQUEST_SCOPED_DATA = []; constructor( @Inject('REQUEST_ID') private readonly requestId: number, private readonly usersService: UsersService, ) { UserByIdPipe.COUNTER++; } transform(value: string, metadata: ArgumentMetadata) { UserByIdPipe.REQUEST_SCOPED_DATA.push(this.requestId); return this.usersService.findById(value); } }
integration/scopes/src/hello/users/user-by-id.pipe.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017648075299803168, 0.00017357109754811972, 0.00016788886568974704, 0.00017634364485275, 0.000004018327672383748 ]
{ "id": 5, "code_window": [ "import { expect } from 'chai';\n", "import { FILTER_CATCH_EXCEPTIONS } from '../../constants';\n", "import { Catch } from '../../decorators/core/catch.decorator';\n", "\n", "describe('@Catch', () => {\n", " const exceptions: any = ['exception', 'exception2'];\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { CATCH_WATERMARK, FILTER_CATCH_EXCEPTIONS } from '../../constants';\n" ], "file_path": "packages/common/test/decorators/catch.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 1 }
<p align="center"> <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a> </p> [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456 [circleci-url]: https://circleci.com/gh/nestjs/nest <p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p> <p align="center"> <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a> <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a> <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a> <a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a> <a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a> <a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a> <a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a> <a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a> <a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a> <a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a> <a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a> </p> <!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer) [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)--> ## Description Nest is a framework for building efficient, scalable <a href="http://nodejs.org" target="_blank">Node.js</a> server-side applications. It uses modern JavaScript, is built with <a href="http://www.typescriptlang.org" target="_blank">TypeScript</a> (preserves compatibility with pure JavaScript) and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Reactive Programming). <p>Under the hood, Nest makes use of <a href="https://expressjs.com/" target="_blank">Express</a>, but also, provides compatibility with a wide range of other libraries, like e.g. <a href="https://github.com/fastify/fastify" target="_blank">Fastify</a>, allowing for easy use of the myriad third-party plugins which are available.</p> ## Philosophy <p>In recent years, thanks to Node.js, JavaScript has become the “lingua franca” of the web for both front and backend applications, giving rise to awesome projects like <a href="https://angular.io/" target="_blank">Angular</a>, <a href="https://github.com/facebook/react" target="_blank">React</a> and <a href="https://github.com/vuejs/vue" target="_blank">Vue</a> which improve developer productivity and enable the construction of fast, testable, extensible frontend applications. However, on the server-side, while there are a lot of superb libraries, helpers and tools for Node, none of them effectively solve the main problem - the architecture.</p> <p>Nest aims to provide an application architecture out of the box which allows for effortless creation of highly testable, scalable, loosely coupled and easily maintainable applications. The architecture is heavily inspired by Angular.</p> ## Getting started * To check out the [guide](https://docs.nestjs.com), visit [docs.nestjs.com](https://docs.nestjs.com). :books: * 要查看中文 [指南](readme_zh.md), 请访问 [docs.nestjs.cn](https://docs.nestjs.cn). :books: * [가이드](readme_kr.md)를 확인하려면, [docs.nestjs.com](https://docs.nestjs.com)를 방문하세요.:books: * チェックするには [ガイド](readme_jp.md), 詳しくは [docs.nestjs.com](https://docs.nestjs.com). :books: ## Questions For questions and support please use the official [Discord channel](https://discord.gg/G7Qnnhy). The issue list of this repo is **exclusively** for bug reports and feature requests. ## Issues Please make sure to read the [Issue Reporting Checklist](https://github.com/nestjs/nest/blob/master/CONTRIBUTING.md#-submitting-an-issue) before opening an issue. Issues not conforming to the guidelines may be closed immediately. ## Consulting With official support, you can get expert help straight from Nest core team. We provide dedicated technical support, migration strategies, advice on best practices (and design decisions), PR reviews, and team augmentation. Read more about [support here](https://enterprise.nestjs.com). ## Support Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support). #### Principal Sponsors <table style="text-align:center;"><tr> <td><a href="https://trilon.io" target="_blank"><img src="https://nestjs.com/img/trilon.svg" width="200" valign="middle" /></a></td> <td> <a href="https://github.com/Sanofi-IADC" target="_blank"><img src="https://docs.nestjs.com/assets/sponsors/sanofi.png" width="180" valign="middle" /></a></td> <td> <a href="https://nx.dev" target="_blank"><img src="https://nestjs.com/img/nx-logo.png" height="45" valign="middle" /></a></td> </tr></table> #### Gold Sponsors <table style="text-align:center;"><tr><td> <a href="https://careers.labster.com/departments/platform" target="_blank"><img src="https://nestjs.com/img/labster-logo.png" width="170" valign="middle" /></a></td><td> <a href="https://weld.app/" target="_blank"><img src="https://nestjs.com/img/weld-logo.svg" width="150" valign="middle" /></a></td> <td> <a href="https://valor-software.com/" target="_blank"><img src="https://docs.nestjs.com/assets/sponsors/valor-software.png" width="170" valign="middle" /></a></td> <td> <a href="https://intrinsic.ventures/" target="_blank"><img src="https://nestjs.com/img/intrinisic-logo.png" width="210" valign="middle" /></a></td></</tr></table> #### Silver Sponsors <table style="text-align:center;"><tr><td> <a href="https://neoteric.eu/" target="_blank"><img src="https://nestjs.com/img/neoteric-cut.png" width="120" valign="middle" /></a> </td><td> <a href="http://gojob.com" target="_blank"><img src="http://nestjs.com/img/gojob-logo.png" valign="middle" width="100" /></a> </td><td> <a href="http://www.leogistics.com" target="_blank"><img src="https://nestjs.com/img/leogistics-logo.jpeg" width="150" valign="middle" /></td><td> <a href="https://careers.meetdandy.com/?gh_src=063ba61e3us" target="_blank"><img src="https://nestjs.com/img/dandy-roles-logo.svg" width="150" valign="middle" /></td><td> <a href="https://www.castlecraft.in" target="_blank"><img src="https://nestjs.com/img/castlecraft-logo.png" width="150" valign="middle" /></td> <td><a href="https://www.tinystacks.com" target="_blank"><img src="https://nestjs.com/img/tinystacks-logo.png#1" width="140" valign="middle" /></td></tr></table> #### Sponsors <table><tr><td align="center" valign="middle"> <a href="https://www.swingdev.io" target="_blank"><img src="https://nestjs.com/img/swingdev-logo.svg#1" width="110" valign="middle" /> </a></td><td align="center" valign="middle"> <a href="https://www.novologic.com/" target="_blank"><img src="https://nestjs.com/img/novologic.png" width="110" valign="middle" /></a> </td><td align="center" valign="middle"> <a href="https://ever.co/" target="_blank"><img src="https://nestjs.com/img/ever-logo.png" width="72" valign="middle" /></a> </td><td align="center" valign="middle"> <a href="https://blokt.com" target="_blank"><img src="https://nestjs.com/img/blokt-logo.png" width="120" valign="middle" /></a> </td><td align="center" valign="middle"> <a href="http://architectnow.net/" target="_blank"><img src="https://nestjs.com/img/architectnow.png" width="125" valign="middle" /></a> </td><td align="center" valign="middle"> <a href="https://quander.io/" target="_blank"><img src="https://nestjs.com/img/quander.png" width="100" valign="middle" /></a> </td></tr><tr><td align="center" valign="middle"> <a href="https://mantro.net/" target="_blank"><img src="https://nestjs.com/img/mantro-logo.svg" width="95" valign="middle" /></a> </td><td align="center" valign="middle"> <a href="https://triplebyte.com/" target="_blank"><img src="https://nestjs.com/img/triplebyte.png" width="107" valign="middle" /></a> </td><td align="center" valign="middle"> <a href="https://reposit.co.uk/" target="_blank"><img src="https://nestjs.com/img/reposit-logo.png" width="71" valign="middle" /></a></td><td align="center" valign="middle"> <a href="https://nearpod.com/" target="_blank"><img src="https://nestjs.com/img/nearpod-logo.svg" width="100" valign="middle" /></a> </td><td align="center" valign="middle"> <a href="https://clay.global/" target="_blank"><img src="https://nestjs.com/img/clay-logo.svg" width="75" valign="middle" /></a> </td><td align="center" valign="middle"> <a href="https://firesticktricks.com" target="_blank"><img src="https://nestjs.com/img/firesticktricks-logo.png" width="120" valign="middle" /></a></td></tr><tr><td align="center" valign="middle"> <a href="https://www.codeguesser.co.uk" target="_blank"><img src="https://nestjs.com/img/codeguesser-logo.svg" width="120" valign="middle" /></a> </td><td align="center" valign="middle"> <a href="https://f-a.nz/" target="_blank"><img src="https://nestjs.com/img/franz.svg" width="80" valign="middle" /></a> </td><td align="center" valign="middle"> <a href="https://sparkfabrik.com/" target="_blank"><img src="https://nestjs.com/img/sparkfabrik-logo.png" width="120" valign="middle" /></a></td><td align="center" valign="middle"><a href="https://www.thebigphonestore.co.uk/" target="_blank"><img src="https://nestjs.com/img/the-big-phone-store-logo.png" width="65" valign="middle" /></a></td> <td align="center" valign="middle"> <a href="https://genuinebee.com/" target="_blank"><img src="https://nestjs.com/img/genuinebee.svg" width="97" valign="middle" /></a> </td> <td align="center" valign="middle"><a href="https://sanyodigital.com/" target="_blank"><img src="https://nestjs.com/img/sanyo-digital.png" width="130" valign="middle" /></a></td></tr><tr><td align="center" valign="middle"><a href="https://vpn-review.com/vpn-for-torrenting" target="_blank"><img src="https://nestjs.com/img/vpn-review-logo.png" width="85" valign="middle" /></a></td><td align="center" valign="middle"><a href="https://lambda-it.ch/" target="_blank"><img src="https://nestjs.com/img/lambda-it-logo.svg" width="115" valign="middle" /></a></td><td align="center" valign="middle"><a href="https://pickwriters.com/top-10-translation-services" target="_blank"><img src="https://nestjs.com/img/pickwriters-logo.png" width="40" valign="middle" /></a></td><td align="center" valign="middle"><a href="https://thewordpoint.com/services/localization" target="_blank"><img src="https://nestjs.com/img/thewordpoint-logo.png" width="40" valign="middle" /></a></td> <td align="center" valign="middle"><a href="https://meercode.io/" target="_blank"><img src="https://nestjs.com/img/meercode-logo.png" width="60" valign="middle" /></a></td> <td align="center" valign="middle"><a href="https://www.najlepszeplatformyforex.pl/blog/broker-xtb/" target="_blank"><img src="https://nestjs.com/img/npf-logo.jpg" width="200" valign="middle" /></a></td></tr><tr> <td align="center" valign="middle"><a href="https://thestandarddaily.com/" target="_blank"><img src="https://nestjs.com/img/the-standard-daily-logo.png" width="180" valign="middle" /></a></td> <td align="center" valign="middle"><a href="https://houseofangular.io/" target="_blank"><img src="https://nestjs.com/img/house-of-angular.png" width="100" valign="middle" /></a></td> <td align="center" valign="middle"><a href="https://rocketech.it/cases/?utm_source=google&utm_medium=badge&utm_campaign=nestjs" target="_blank"><img src="https://nestjs.com/img/rocketech-logo.svg" width="110" valign="middle" /></a></td> <td align="center" valign="middle"><a href="https://www.bystored.com/" target="_blank"><img src="https://nestjs.com/img/stored-logo.svg" width="110" valign="middle" /></a></td> <td align="center" valign="middle"><a href="https://studyclerk.com/pay-for-research-paper" target="_blank"><img src="https://nestjs.com/img/studyclerk-logo.png" width="125" valign="middle" /></a></td><td align="center" valign="middle"><a href="https://xyndata.com" target="_blank"><img src="https://nestjs.com/img/xyndata-logo.png" width="125" valign="middle" /></a></td></tr><tr> <td align="center" valign="middle"><a href="https://www.anonymistic.com/" target="_blank"><img src="https://nestjs.com/img/anonymistic-logo.png" width="125" valign="middle" /></a></td> <td align="center" valign="middle"><a href="https://www.naologic.com/" target="_blank"><img src="https://nestjs.com/img/naologic-logo.svg" width="125" valign="middle" /></a></td> <td align="center" valign="middle"><a href="https://messaged.com/" target="_blank"><img src="https://nestjs.com/img/messaged-logo.png" width="50" valign="middle" /></a></td> <td align="center" valign="middle"><a href="https://triplecore.io" target="_blank"><img src="https://nestjs.com/img/triplecore-logo.svg" width="50" valign="middle" /></a></td> </tr></table> ## Backers <a href="https://opencollective.com/nest" target="_blank"><img src="https://opencollective.com/nest/backers.svg?width=1000"></a> ## Stay in touch * Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec) * Website - [https://nestjs.com](https://nestjs.com/) * Twitter - [@nestframework](https://twitter.com/nestframework) ## License Nest is [MIT licensed](LICENSE).
packages/websockets/Readme.md
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0001807900407584384, 0.00017353401926811785, 0.00016657666128594428, 0.00017248510266654193, 0.000003992488018411677 ]
{ "id": 5, "code_window": [ "import { expect } from 'chai';\n", "import { FILTER_CATCH_EXCEPTIONS } from '../../constants';\n", "import { Catch } from '../../decorators/core/catch.decorator';\n", "\n", "describe('@Catch', () => {\n", " const exceptions: any = ['exception', 'exception2'];\n", "\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { CATCH_WATERMARK, FILTER_CATCH_EXCEPTIONS } from '../../constants';\n" ], "file_path": "packages/common/test/decorators/catch.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 1 }
import { v4 as uuid } from 'uuid'; import { INJECTABLE_WATERMARK, SCOPE_OPTIONS_METADATA } from '../../constants'; import { ScopeOptions } from '../../interfaces/scope-options.interface'; import { Type } from '../../interfaces/type.interface'; /** * Defines the injection scope. * * @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes) * * @publicApi */ export type InjectableOptions = ScopeOptions; /** * Decorator that marks a class as a [provider](https://docs.nestjs.com/providers). * Providers can be injected into other classes via constructor parameter injection * using Nest's built-in [Dependency Injection (DI)](https://docs.nestjs.com/providers#dependency-injection) * system. * * When injecting a provider, it must be visible within the module scope (loosely * speaking, the containing module) of the class it is being injected into. This * can be done by: * * - defining the provider in the same module scope * - exporting the provider from one module scope and importing that module into the * module scope of the class being injected into * - exporting the provider from a module that is marked as global using the * `@Global()` decorator * * Providers can also be defined in a more explicit and imperative form using * various [custom provider](https://docs.nestjs.com/fundamentals/custom-providers) techniques that expose * more capabilities of the DI system. * * @param options options specifying scope of injectable * * @see [Providers](https://docs.nestjs.com/providers) * @see [Custom Providers](https://docs.nestjs.com/fundamentals/custom-providers) * @see [Injection Scopes](https://docs.nestjs.com/fundamentals/injection-scopes) * * @publicApi */ export function Injectable(options?: InjectableOptions): ClassDecorator { return (target: object) => { Reflect.defineMetadata(INJECTABLE_WATERMARK, true, target); Reflect.defineMetadata(SCOPE_OPTIONS_METADATA, options, target); }; } export function mixin<T>(mixinClass: Type<T>) { Object.defineProperty(mixinClass, 'name', { value: uuid(), }); Injectable()(mixinClass); return mixinClass; }
packages/common/decorators/core/injectable.decorator.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017839270003605634, 0.0001685445458861068, 0.00016151067393366247, 0.00016791143571026623, 0.000005978663011774188 ]
{ "id": 6, "code_window": [ " @Catch(...exceptions)\n", " class Test {}\n", "\n", " it('should enhance class with expected exceptions array', () => {\n", " const metadata = Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, Test);\n", " expect(metadata).to.be.eql(exceptions);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it(`should enhance component with \"${CATCH_WATERMARK}\" metadata`, () => {\n", " const catchWatermark = Reflect.getMetadata(CATCH_WATERMARK, Test);\n", "\n", " expect(catchWatermark).to.be.true;\n", " });\n", "\n" ], "file_path": "packages/common/test/decorators/catch.decorator.spec.ts", "type": "add", "edit_start_line_idx": 10 }
import { expect } from 'chai'; import { VERSION_METADATA } from '../../constants'; import { Controller } from '../../decorators/core/controller.decorator'; describe('@Controller', () => { const reflectedPath = 'test'; const reflectedHost = 'api.example.com'; const reflectedHostArray = ['api1.example.com', 'api2.example.com']; const reflectedVersion = '1'; @Controller(reflectedPath) class Test {} @Controller() class EmptyDecorator {} @Controller({ path: reflectedPath, host: reflectedHost }) class PathAndHostDecorator {} @Controller({ path: reflectedPath, host: reflectedHostArray }) class PathAndHostArrayDecorator {} @Controller({ host: reflectedHost }) class HostOnlyDecorator {} @Controller({ path: reflectedPath, host: reflectedHost, version: reflectedVersion, }) class PathAndHostAndVersionDecorator {} @Controller({ version: reflectedVersion }) class VersionOnlyDecorator {} it('should enhance controller with expected path metadata', () => { const path = Reflect.getMetadata('path', Test); expect(path).to.be.eql(reflectedPath); const path2 = Reflect.getMetadata('path', PathAndHostDecorator); expect(path2).to.be.eql(reflectedPath); const path3 = Reflect.getMetadata('path', PathAndHostAndVersionDecorator); expect(path3).to.be.eql(reflectedPath); }); it('should enhance controller with expected host metadata', () => { const host = Reflect.getMetadata('host', PathAndHostDecorator); expect(host).to.be.eql(reflectedHost); const host2 = Reflect.getMetadata('host', HostOnlyDecorator); expect(host2).to.be.eql(reflectedHost); const host3 = Reflect.getMetadata('host', PathAndHostArrayDecorator); expect(host3).to.be.eql(reflectedHostArray); const host4 = Reflect.getMetadata('host', PathAndHostAndVersionDecorator); expect(host4).to.be.eql(reflectedHost); }); it('should enhance controller with expected version metadata', () => { const version = Reflect.getMetadata( VERSION_METADATA, PathAndHostAndVersionDecorator, ); expect(version).to.be.eql(reflectedVersion); const version2 = Reflect.getMetadata( VERSION_METADATA, VersionOnlyDecorator, ); expect(version2).to.be.eql(reflectedVersion); }); it('should set default path when no object passed as param', () => { const path = Reflect.getMetadata('path', EmptyDecorator); expect(path).to.be.eql('/'); const path2 = Reflect.getMetadata('path', HostOnlyDecorator); expect(path2).to.be.eql('/'); const path3 = Reflect.getMetadata('path', VersionOnlyDecorator); expect(path3).to.be.eql('/'); }); it('should not set host when no host passed as param', () => { const host = Reflect.getMetadata('host', Test); expect(host).to.be.undefined; const host2 = Reflect.getMetadata('host', EmptyDecorator); expect(host2).to.be.undefined; }); it('should not set version when no version passed as param', () => { const version = Reflect.getMetadata(VERSION_METADATA, Test); expect(version).to.be.undefined; const version2 = Reflect.getMetadata(VERSION_METADATA, EmptyDecorator); expect(version2).to.be.undefined; }); });
packages/common/test/decorators/controller.decorator.spec.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.9981083869934082, 0.2984270751476288, 0.0001679545093793422, 0.00017654382099863142, 0.45552191138267517 ]
{ "id": 6, "code_window": [ " @Catch(...exceptions)\n", " class Test {}\n", "\n", " it('should enhance class with expected exceptions array', () => {\n", " const metadata = Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, Test);\n", " expect(metadata).to.be.eql(exceptions);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it(`should enhance component with \"${CATCH_WATERMARK}\" metadata`, () => {\n", " const catchWatermark = Reflect.getMetadata(CATCH_WATERMARK, Test);\n", "\n", " expect(catchWatermark).to.be.true;\n", " });\n", "\n" ], "file_path": "packages/common/test/decorators/catch.decorator.spec.ts", "type": "add", "edit_start_line_idx": 10 }
import { HttpStatus } from '../enums/http-status.enum'; import { HttpException } from './http.exception'; /** * Defines an HTTP exception for *Internal Server Error* type errors. * * @see [Base Exceptions](https://docs.nestjs.com/exception-filters#base-exceptions) * * @publicApi */ export class InternalServerErrorException extends HttpException { /** * Instantiate an `InternalServerErrorException` Exception. * * @example * `throw new InternalServerErrorException()` * * @usageNotes * The HTTP response status code will be 500. * - The `objectOrError` argument defines the JSON response body or the message string. * - The `description` argument contains a short description of the HTTP error. * * By default, the JSON response body contains two properties: * - `statusCode`: this will be the value 500. * - `message`: the string `'Internal Server Error'` by default; override this by supplying * a string in the `objectOrError` parameter. * * If the parameter `objectOrError` is a string, the response body will contain an * additional property, `error`, with a short description of the HTTP error. To override the * entire JSON response body, pass an object instead. Nest will serialize the object * and return it as the JSON response body. * * @param objectOrError string or object describing the error condition. * @param description a short description of the HTTP error. */ constructor( objectOrError?: string | object | any, description = 'Internal Server Error', ) { super( HttpException.createBody( objectOrError, description, HttpStatus.INTERNAL_SERVER_ERROR, ), HttpStatus.INTERNAL_SERVER_ERROR, ); } }
packages/common/exceptions/internal-server-error.exception.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017409272550139576, 0.00016931374557316303, 0.0001648145989747718, 0.0001706384791759774, 0.000003370455942786066 ]
{ "id": 6, "code_window": [ " @Catch(...exceptions)\n", " class Test {}\n", "\n", " it('should enhance class with expected exceptions array', () => {\n", " const metadata = Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, Test);\n", " expect(metadata).to.be.eql(exceptions);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it(`should enhance component with \"${CATCH_WATERMARK}\" metadata`, () => {\n", " const catchWatermark = Reflect.getMetadata(CATCH_WATERMARK, Test);\n", "\n", " expect(catchWatermark).to.be.true;\n", " });\n", "\n" ], "file_path": "packages/common/test/decorators/catch.decorator.spec.ts", "type": "add", "edit_start_line_idx": 10 }
name: "\U0001F41B Bug Report" description: "If something isn't working as expected \U0001F914" labels: ["needs triage"] body: - type: markdown attributes: value: | ## :warning: We use GitHub Issues to track bug reports, feature requests and regressions If you are not sure that your issue is a bug, you could: - use our [Discord community](https://discord.gg/NestJS) - use [StackOverflow using the tag `nestjs`](https://stackoverflow.com/questions/tagged/nestjs) - If it's just a quick question you can ping [our Twitter](https://twitter.com/nestframework) **NOTE:** You don't need to answer questions that you know that aren't relevant. --- - type: checkboxes attributes: label: "Is there an existing issue for this?" description: "Please search [here](https://github.com/nestjs/nest/issues?q=is%3Aissue) to see if an issue already exists for the bug you encountered" options: - label: "I have searched the existing issues" required: true - type: textarea validations: required: true attributes: label: "Current behavior" description: "How the issue manifests?" - type: input validations: required: true attributes: label: "Minimum reproduction code" description: "An URL to some git repository that reproduces this issue. [Wtf is a minimum reproduction?](https://jmcdo29.github.io/wtf-is-a-minimum-reproduction)" placeholder: "https://github.com/..." - type: textarea attributes: label: "Steps to reproduce" description: | How the issue manifests? You could leave this blank if you alread write this in your reproduction code placeholder: | 1. `npm i` 2. `npm start:dev` 3. See error... - type: textarea validations: required: true attributes: label: "Expected behavior" description: "A clear and concise description of what you expected to happend (or code)" - type: markdown attributes: value: | --- - type: checkboxes validations: required: true attributes: label: "Package" description: | Which package (or packages) do you think your issue is related to? **Tip**: The first line of the stack trace can help you to figure out this The package isn't listed below? Try to find its repository [here](https://github.com/orgs/nestjs/repositories) and open the issue there instead options: - label: "I don't know. Or some 3rd-party package" - label: "<code>@nestjs/common</code>" - label: "<code>@nestjs/core</code>" - label: "<code>@nestjs/microservices</code>" - label: "<code>@nestjs/platform-express</code>" - label: "<code>@nestjs/platform-fastify</code>" - label: "<code>@nestjs/platform-socket.io</code>" - label: "<code>@nestjs/platform-ws</code>" - label: "<code>@nestjs/testing</code>" - label: "<code>@nestjs/websockets</code>" - label: "Other (see below)" - type: input attributes: label: "Other package" description: "If your issue is related to some package that is not listed above nor under @nestjs org, write its name here" - type: input attributes: label: "NestJS version" description: | Which version of `@nestjs/core` are you using? **Tip**: Make sure that all of yours `@nestjs/*` dependencies are in sync! placeholder: "8.1.3" - type: textarea validations: required: true attributes: label: "Packages versions" description: "You could leave your whole `package.json` dependencies list here, or just indicates which version of `@nestjs/*` are you using" placeholder: | - `@nestjs/common`: 8.1.3 - `@nestjs/platform-express`: 8.1.3 - type: input attributes: label: "Node.js version" description: "Which version of Node.js are you using?" placeholder: "14.17.6" - type: checkboxes validations: required: true attributes: label: "In which operating systems have you tested?" options: - label: macOS - label: Windows - label: Linux - type: markdown attributes: value: | --- - type: textarea attributes: label: "Other" description: | Anything else relevant? eg: Logs, OS version, IDE, package manager, etc. **Tip:** You can attach images, recordings or log files by clicking this area to highlight it and then dragging files in
.github/ISSUE_TEMPLATE/Bug_report.yml
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017830869182944298, 0.00017571169883012772, 0.00017170132196042687, 0.00017553375801071525, 0.0000016330018297594506 ]
{ "id": 6, "code_window": [ " @Catch(...exceptions)\n", " class Test {}\n", "\n", " it('should enhance class with expected exceptions array', () => {\n", " const metadata = Reflect.getMetadata(FILTER_CATCH_EXCEPTIONS, Test);\n", " expect(metadata).to.be.eql(exceptions);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " it(`should enhance component with \"${CATCH_WATERMARK}\" metadata`, () => {\n", " const catchWatermark = Reflect.getMetadata(CATCH_WATERMARK, Test);\n", "\n", " expect(catchWatermark).to.be.true;\n", " });\n", "\n" ], "file_path": "packages/common/test/decorators/catch.decorator.spec.ts", "type": "add", "edit_start_line_idx": 10 }
{ "extends": "./tsconfig.json", "exclude": ["node_modules", "dist", "test", "**/*spec.ts"] }
sample/15-mvc/tsconfig.build.json
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017183806630782783, 0.00017183806630782783, 0.00017183806630782783, 0.00017183806630782783, 0 ]
{ "id": 7, "code_window": [ "import { expect } from 'chai';\n", "import { VERSION_METADATA } from '../../constants';\n", "import { Controller } from '../../decorators/core/controller.decorator';\n", "\n", "describe('@Controller', () => {\n", " const reflectedPath = 'test';\n", " const reflectedHost = 'api.example.com';\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { VERSION_METADATA, CONTROLLER_WATERMARK } from '../../constants';\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 1 }
import { FILTER_CATCH_EXCEPTIONS } from '../../constants'; import { Type } from '../../interfaces'; /** * Decorator that marks a class as a Nest exception filter. An exception filter * handles exceptions thrown by or not handled by your application code. * * The decorated class must implement the `ExceptionFilter` interface. * * @param exceptions one or more exception *types* specifying * the exceptions to be caught and handled by this filter. * * @see [Exception Filters](https://docs.nestjs.com/exception-filters) * * @usageNotes * Exception filters are applied using the `@UseFilters()` decorator, or (globally) * with `app.useGlobalFilters()`. * * @publicApi */ export function Catch(...exceptions: Type<any>[]): ClassDecorator { return (target: object) => { Reflect.defineMetadata(FILTER_CATCH_EXCEPTIONS, exceptions, target); }; }
packages/common/decorators/core/catch.decorator.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00018240712233819067, 0.00017360628407914191, 0.00016794521070551127, 0.0001704665774013847, 0.000006307674084382597 ]
{ "id": 7, "code_window": [ "import { expect } from 'chai';\n", "import { VERSION_METADATA } from '../../constants';\n", "import { Controller } from '../../decorators/core/controller.decorator';\n", "\n", "describe('@Controller', () => {\n", " const reflectedPath = 'test';\n", " const reflectedHost = 'api.example.com';\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { VERSION_METADATA, CONTROLLER_WATERMARK } from '../../constants';\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 1 }
module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], extends: [ 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'prettier', ], root: true, env: { node: true, jest: true, }, rules: { '@typescript-eslint/interface-name-prefix': 'off', '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/no-explicit-any': 'off', }, };
sample/13-mongo-typeorm/.eslintrc.js
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0001764736807672307, 0.0001750433730194345, 0.0001742307358654216, 0.00017442570242565125, 0.0000010145074611500604 ]
{ "id": 7, "code_window": [ "import { expect } from 'chai';\n", "import { VERSION_METADATA } from '../../constants';\n", "import { Controller } from '../../decorators/core/controller.decorator';\n", "\n", "describe('@Controller', () => {\n", " const reflectedPath = 'test';\n", " const reflectedHost = 'api.example.com';\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { VERSION_METADATA, CONTROLLER_WATERMARK } from '../../constants';\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 1 }
import { CanActivate, ExceptionFilter, NestInterceptor, PipeTransform, VersioningOptions, WebSocketAdapter, } from '@nestjs/common'; import { GlobalPrefixOptions } from '@nestjs/common/interfaces'; import { InstanceWrapper } from './injector/instance-wrapper'; import { ExcludeRouteMetadata } from './router/interfaces/exclude-route-metadata.interface'; export class ApplicationConfig { private globalPrefix = ''; private globalPrefixOptions: GlobalPrefixOptions<ExcludeRouteMetadata> = {}; private globalPipes: Array<PipeTransform> = []; private globalFilters: Array<ExceptionFilter> = []; private globalInterceptors: Array<NestInterceptor> = []; private globalGuards: Array<CanActivate> = []; private versioningOptions: VersioningOptions; private readonly globalRequestPipes: InstanceWrapper<PipeTransform>[] = []; private readonly globalRequestFilters: InstanceWrapper<ExceptionFilter>[] = []; private readonly globalRequestInterceptors: InstanceWrapper<NestInterceptor>[] = []; private readonly globalRequestGuards: InstanceWrapper<CanActivate>[] = []; constructor(private ioAdapter: WebSocketAdapter | null = null) {} public setGlobalPrefix(prefix: string) { this.globalPrefix = prefix; } public getGlobalPrefix() { return this.globalPrefix; } public setGlobalPrefixOptions( options: GlobalPrefixOptions<ExcludeRouteMetadata>, ) { this.globalPrefixOptions = options; } public getGlobalPrefixOptions(): GlobalPrefixOptions<ExcludeRouteMetadata> { return this.globalPrefixOptions; } public setIoAdapter(ioAdapter: WebSocketAdapter) { this.ioAdapter = ioAdapter; } public getIoAdapter(): WebSocketAdapter { return this.ioAdapter; } public addGlobalPipe(pipe: PipeTransform<any>) { this.globalPipes.push(pipe); } public useGlobalPipes(...pipes: PipeTransform<any>[]) { this.globalPipes = this.globalPipes.concat(pipes); } public getGlobalFilters(): ExceptionFilter[] { return this.globalFilters; } public addGlobalFilter(filter: ExceptionFilter) { this.globalFilters.push(filter); } public useGlobalFilters(...filters: ExceptionFilter[]) { this.globalFilters = this.globalFilters.concat(filters); } public getGlobalPipes(): PipeTransform<any>[] { return this.globalPipes; } public getGlobalInterceptors(): NestInterceptor[] { return this.globalInterceptors; } public addGlobalInterceptor(interceptor: NestInterceptor) { this.globalInterceptors.push(interceptor); } public useGlobalInterceptors(...interceptors: NestInterceptor[]) { this.globalInterceptors = this.globalInterceptors.concat(interceptors); } public getGlobalGuards(): CanActivate[] { return this.globalGuards; } public addGlobalGuard(guard: CanActivate) { this.globalGuards.push(guard); } public useGlobalGuards(...guards: CanActivate[]) { this.globalGuards = this.globalGuards.concat(guards); } public addGlobalRequestInterceptor( wrapper: InstanceWrapper<NestInterceptor>, ) { this.globalRequestInterceptors.push(wrapper); } public getGlobalRequestInterceptors(): InstanceWrapper<NestInterceptor>[] { return this.globalRequestInterceptors; } public addGlobalRequestPipe(wrapper: InstanceWrapper<PipeTransform>) { this.globalRequestPipes.push(wrapper); } public getGlobalRequestPipes(): InstanceWrapper<PipeTransform>[] { return this.globalRequestPipes; } public addGlobalRequestFilter(wrapper: InstanceWrapper<ExceptionFilter>) { this.globalRequestFilters.push(wrapper); } public getGlobalRequestFilters(): InstanceWrapper<ExceptionFilter>[] { return this.globalRequestFilters; } public addGlobalRequestGuard(wrapper: InstanceWrapper<CanActivate>) { this.globalRequestGuards.push(wrapper); } public getGlobalRequestGuards(): InstanceWrapper<CanActivate>[] { return this.globalRequestGuards; } public enableVersioning(options: VersioningOptions): void { this.versioningOptions = options; } public getVersioning(): VersioningOptions | undefined { return this.versioningOptions; } }
packages/core/application-config.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017841329099610448, 0.00017476125503890216, 0.00016963138477876782, 0.0001752275275066495, 0.0000024144874259945937 ]
{ "id": 7, "code_window": [ "import { expect } from 'chai';\n", "import { VERSION_METADATA } from '../../constants';\n", "import { Controller } from '../../decorators/core/controller.decorator';\n", "\n", "describe('@Controller', () => {\n", " const reflectedPath = 'test';\n", " const reflectedHost = 'api.example.com';\n" ], "labels": [ "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { VERSION_METADATA, CONTROLLER_WATERMARK } from '../../constants';\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 1 }
import { Controller, Scope } from '@nestjs/common'; @Controller({ path: 'test', scope: Scope.REQUEST, }) export class ScopedController {}
integration/injector/src/scoped/scoped.controller.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017903307161759585, 0.00017903307161759585, 0.00017903307161759585, 0.00017903307161759585, 0 ]
{ "id": 8, "code_window": [ " const reflectedHostArray = ['api1.example.com', 'api2.example.com'];\n", " const reflectedVersion = '1';\n", "\n", " @Controller(reflectedPath)\n", " class Test {}\n", "\n", " @Controller()\n", " class EmptyDecorator {}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 10 }
export const MODULE_METADATA = { IMPORTS: 'imports', PROVIDERS: 'providers', CONTROLLERS: 'controllers', EXPORTS: 'exports', }; export const GLOBAL_MODULE_METADATA = '__module:global__'; export const HOST_METADATA = 'host'; export const PATH_METADATA = 'path'; export const PARAMTYPES_METADATA = 'design:paramtypes'; export const SELF_DECLARED_DEPS_METADATA = 'self:paramtypes'; export const OPTIONAL_DEPS_METADATA = 'optional:paramtypes'; export const PROPERTY_DEPS_METADATA = 'self:properties_metadata'; export const OPTIONAL_PROPERTY_DEPS_METADATA = 'optional:properties_metadata'; export const SCOPE_OPTIONS_METADATA = 'scope:options'; export const METHOD_METADATA = 'method'; export const ROUTE_ARGS_METADATA = '__routeArguments__'; export const CUSTOM_ROUTE_AGRS_METADATA = '__customRouteArgs__'; export const EXCEPTION_FILTERS_METADATA = '__exceptionFilters__'; export const FILTER_CATCH_EXCEPTIONS = '__filterCatchExceptions__'; export const PIPES_METADATA = '__pipes__'; export const GUARDS_METADATA = '__guards__'; export const RENDER_METADATA = '__renderTemplate__'; export const INTERCEPTORS_METADATA = '__interceptors__'; export const HTTP_CODE_METADATA = '__httpCode__'; export const MODULE_PATH = '__module_path__'; export const HEADERS_METADATA = '__headers__'; export const REDIRECT_METADATA = '__redirect__'; export const RESPONSE_PASSTHROUGH_METADATA = '__responsePassthrough__'; export const SSE_METADATA = '__sse__'; export const VERSION_METADATA = '__version__'; export const INJECTABLE_WATERMARK = '__injectable__';
packages/common/constants.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0003983881324529648, 0.00024087404017336667, 0.0001723025634419173, 0.00019640271784737706, 0.00009153255086857826 ]
{ "id": 8, "code_window": [ " const reflectedHostArray = ['api1.example.com', 'api2.example.com'];\n", " const reflectedVersion = '1';\n", "\n", " @Controller(reflectedPath)\n", " class Test {}\n", "\n", " @Controller()\n", " class EmptyDecorator {}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 10 }
{ "singleQuote": true, "trailingComma": "all" }
sample/28-sse/.prettierrc
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017467803263571113, 0.00017467803263571113, 0.00017467803263571113, 0.00017467803263571113, 0 ]
{ "id": 8, "code_window": [ " const reflectedHostArray = ['api1.example.com', 'api2.example.com'];\n", " const reflectedVersion = '1';\n", "\n", " @Controller(reflectedPath)\n", " class Test {}\n", "\n", " @Controller()\n", " class EmptyDecorator {}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 10 }
import { ExecutionContextHost } from '@nestjs/core/helpers/execution-context-host'; import { expect } from 'chai'; import * as sinon from 'sinon'; import { WsException } from '../../errors/ws-exception'; import { WsExceptionsHandler } from '../../exceptions/ws-exceptions-handler'; describe('WsExceptionsHandler', () => { let handler: WsExceptionsHandler; let emitStub: sinon.SinonStub; let client; beforeEach(() => { handler = new WsExceptionsHandler(); emitStub = sinon.stub(); client = { emit: emitStub, }; client.emit.returns(client); }); describe('handle', () => { it('should method emit expected status code message when exception is unknown', () => { handler.handle(new Error(), new ExecutionContextHost([client])); expect( emitStub.calledWith('exception', { status: 'error', message: 'Internal server error', }), ).to.be.true; }); describe('when exception is instance of WsException', () => { it('should method emit expected status and json object', () => { const message = { custom: 'Unauthorized', }; handler.handle( new WsException(message), new ExecutionContextHost([client]), ); expect(emitStub.calledWith('exception', message)).to.be.true; }); it('should method emit expected status and transform message to json', () => { const message = 'Unauthorized'; handler.handle( new WsException(message), new ExecutionContextHost([client]), ); expect(emitStub.calledWith('exception', { message, status: 'error' })) .to.be.true; }); }); describe('when "invokeCustomFilters" returns true', () => { beforeEach(() => { sinon.stub(handler, 'invokeCustomFilters').returns(true); }); it('should not call `emit`', () => { handler.handle(new WsException(''), new ExecutionContextHost([client])); expect(emitStub.notCalled).to.be.true; }); }); }); describe('setCustomFilters', () => { const filters = ['test', 'test2']; it('should set custom filters', () => { handler.setCustomFilters(filters as any); expect((handler as any).filters).to.be.eql(filters); }); it('should throws exception when passed argument is not an array', () => { expect(() => handler.setCustomFilters(null)).to.throw(); }); }); describe('invokeCustomFilters', () => { describe('when filters array is empty', () => { it('should return false', () => { expect(handler.invokeCustomFilters(null, null)).to.be.false; }); }); describe('when filters array is not empty', () => { let filters, funcSpy; class TestException {} beforeEach(() => { funcSpy = sinon.spy(); }); describe('when filter exists in filters array', () => { beforeEach(() => { filters = [{ exceptionMetatypes: [TestException], func: funcSpy }]; (handler as any).filters = filters; }); it('should call funcSpy', () => { handler.invokeCustomFilters(new TestException(), null); expect(funcSpy.notCalled).to.be.false; }); it('should call funcSpy with exception and response passed as an arguments', () => { const exception = new TestException(); const res = { foo: 'bar' }; handler.invokeCustomFilters(exception, res as any); expect(funcSpy.calledWith(exception, res)).to.be.true; }); it('should return true', () => { expect(handler.invokeCustomFilters(new TestException(), null)).to.be .true; }); }); describe('when filter does not exists in filters array', () => { it('should not call funcSpy', () => { handler.invokeCustomFilters(new TestException(), null); expect(funcSpy.notCalled).to.be.true; }); it('should return false', () => { expect(handler.invokeCustomFilters(new TestException(), null)).to.be .false; }); }); }); }); });
packages/websockets/test/exceptions/ws-exceptions-handler.spec.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0003704612608999014, 0.0001884079974843189, 0.00016821846656966954, 0.00017175168613903224, 0.000054942047427175567 ]
{ "id": 8, "code_window": [ " const reflectedHostArray = ['api1.example.com', 'api2.example.com'];\n", " const reflectedVersion = '1';\n", "\n", " @Controller(reflectedPath)\n", " class Test {}\n", "\n", " @Controller()\n", " class EmptyDecorator {}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "replace", "edit_start_line_idx": 10 }
import { iterate } from 'iterare'; import { Optional } from '../decorators'; import { Injectable } from '../decorators/core'; import { HttpStatus } from '../enums/http-status.enum'; import { ClassTransformOptions } from '../interfaces/external/class-transform-options.interface'; import { TransformerPackage } from '../interfaces/external/transformer-package.interface'; import { ValidationError } from '../interfaces/external/validation-error.interface'; import { ValidatorOptions } from '../interfaces/external/validator-options.interface'; import { ValidatorPackage } from '../interfaces/external/validator-package.interface'; import { ArgumentMetadata, PipeTransform, } from '../interfaces/features/pipe-transform.interface'; import { Type } from '../interfaces/type.interface'; import { ErrorHttpStatusCode, HttpErrorByCode, } from '../utils/http-error-by-code.util'; import { loadPackage } from '../utils/load-package.util'; import { isNil } from '../utils/shared.utils'; export interface ValidationPipeOptions extends ValidatorOptions { transform?: boolean; disableErrorMessages?: boolean; transformOptions?: ClassTransformOptions; errorHttpStatusCode?: ErrorHttpStatusCode; exceptionFactory?: (errors: ValidationError[]) => any; validateCustomDecorators?: boolean; expectedType?: Type<any>; validatorPackage?: ValidatorPackage; transformerPackage?: TransformerPackage; } let classValidator: ValidatorPackage = {} as any; let classTransformer: TransformerPackage = {} as any; @Injectable() export class ValidationPipe implements PipeTransform<any> { protected isTransformEnabled: boolean; protected isDetailedOutputDisabled?: boolean; protected validatorOptions: ValidatorOptions; protected transformOptions: ClassTransformOptions; protected errorHttpStatusCode: ErrorHttpStatusCode; protected expectedType: Type<any>; protected exceptionFactory: (errors: ValidationError[]) => any; protected validateCustomDecorators: boolean; constructor(@Optional() options?: ValidationPipeOptions) { options = options || {}; const { transform, disableErrorMessages, errorHttpStatusCode, expectedType, transformOptions, validateCustomDecorators, ...validatorOptions } = options; this.isTransformEnabled = !!transform; this.validatorOptions = validatorOptions; this.transformOptions = transformOptions; this.isDetailedOutputDisabled = disableErrorMessages; this.validateCustomDecorators = validateCustomDecorators || false; this.errorHttpStatusCode = errorHttpStatusCode || HttpStatus.BAD_REQUEST; this.expectedType = expectedType; this.exceptionFactory = options.exceptionFactory || this.createExceptionFactory(); classValidator = this.loadValidator(options.validatorPackage); classTransformer = this.loadTransformer(options.transformerPackage); } protected loadValidator( validatorPackage?: ValidatorPackage, ): ValidatorPackage { return ( validatorPackage ?? loadPackage('class-validator', 'ValidationPipe', () => require('class-validator'), ) ); } protected loadTransformer( transformerPackage?: TransformerPackage, ): TransformerPackage { return ( transformerPackage ?? loadPackage('class-transformer', 'ValidationPipe', () => require('class-transformer'), ) ); } public async transform(value: any, metadata: ArgumentMetadata) { if (this.expectedType) { metadata = { ...metadata, metatype: this.expectedType }; } const metatype = metadata.metatype; if (!metatype || !this.toValidate(metadata)) { return this.isTransformEnabled ? this.transformPrimitive(value, metadata) : value; } const originalValue = value; value = this.toEmptyIfNil(value); const isNil = value !== originalValue; const isPrimitive = this.isPrimitive(value); this.stripProtoKeys(value); let entity = classTransformer.plainToClass( metatype, value, this.transformOptions, ); const originalEntity = entity; const isCtorNotEqual = entity.constructor !== metatype; if (isCtorNotEqual && !isPrimitive) { entity.constructor = metatype; } else if (isCtorNotEqual) { // when "entity" is a primitive value, we have to temporarily // replace the entity to perform the validation against the original // metatype defined inside the handler entity = { constructor: metatype }; } const errors = await this.validate(entity, this.validatorOptions); if (errors.length > 0) { throw await this.exceptionFactory(errors); } if (isPrimitive) { // if the value is a primitive value and the validation process has been successfully completed // we have to revert the original value passed through the pipe entity = originalEntity; } if (this.isTransformEnabled) { return entity; } if (isNil) { // if the value was originally undefined or null, revert it back return originalValue; } return Object.keys(this.validatorOptions).length > 0 ? classTransformer.classToPlain(entity, this.transformOptions) : value; } public createExceptionFactory() { return (validationErrors: ValidationError[] = []) => { if (this.isDetailedOutputDisabled) { return new HttpErrorByCode[this.errorHttpStatusCode](); } const errors = this.flattenValidationErrors(validationErrors); return new HttpErrorByCode[this.errorHttpStatusCode](errors); }; } protected toValidate(metadata: ArgumentMetadata): boolean { const { metatype, type } = metadata; if (type === 'custom' && !this.validateCustomDecorators) { return false; } const types = [String, Boolean, Number, Array, Object, Buffer]; return !types.some(t => metatype === t) && !isNil(metatype); } protected transformPrimitive(value: any, metadata: ArgumentMetadata) { if (!metadata.data) { // leave top-level query/param objects unmodified return value; } const { type, metatype } = metadata; if (type !== 'param' && type !== 'query') { return value; } if (metatype === Boolean) { return value === true || value === 'true'; } if (metatype === Number) { return +value; } return value; } protected toEmptyIfNil<T = any, R = any>(value: T): R | {} { return isNil(value) ? {} : value; } protected stripProtoKeys(value: Record<string, any>) { delete value.__proto__; const keys = Object.keys(value); iterate(keys) .filter(key => typeof value[key] === 'object' && value[key]) .forEach(key => this.stripProtoKeys(value[key])); } protected isPrimitive(value: unknown): boolean { return ['number', 'boolean', 'string'].includes(typeof value); } protected validate( object: object, validatorOptions?: ValidatorOptions, ): Promise<ValidationError[]> | ValidationError[] { return classValidator.validate(object, validatorOptions); } protected flattenValidationErrors( validationErrors: ValidationError[], ): string[] { return iterate(validationErrors) .map(error => this.mapChildrenToValidationErrors(error)) .flatten() .filter(item => !!item.constraints) .map(item => Object.values(item.constraints)) .flatten() .toArray(); } protected mapChildrenToValidationErrors( error: ValidationError, parentPath?: string, ): ValidationError[] { if (!(error.children && error.children.length)) { return [error]; } const validationErrors = []; parentPath = parentPath ? `${parentPath}.${error.property}` : error.property; for (const item of error.children) { if (item.children && item.children.length) { validationErrors.push( ...this.mapChildrenToValidationErrors(item, parentPath), ); } validationErrors.push( this.prependConstraintsWithParentProp(parentPath, item), ); } return validationErrors; } protected prependConstraintsWithParentProp( parentPath: string, error: ValidationError, ): ValidationError { const constraints = {}; for (const key in error.constraints) { constraints[key] = `${parentPath}.${error.constraints[key]}`; } return { ...error, constraints, }; } }
packages/common/pipes/validation.pipe.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00022371477098204195, 0.00017484539421275258, 0.00016555060574319214, 0.00017294350254815072, 0.000010352015124226455 ]
{ "id": 9, "code_window": [ " @Controller()\n", " class EmptyDecorator {}\n", "\n", " @Controller({ path: reflectedPath, host: reflectedHost })\n", " class PathAndHostDecorator {}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @Controller(reflectedPath)\n", " class Test {}\n", "\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "add", "edit_start_line_idx": 16 }
import { HOST_METADATA, PATH_METADATA, SCOPE_OPTIONS_METADATA, VERSION_METADATA, } from '../../constants'; import { ScopeOptions } from '../../interfaces/scope-options.interface'; import { VersionOptions } from '../../interfaces/version-options.interface'; import { isString, isUndefined } from '../../utils/shared.utils'; /** * Interface defining options that can be passed to `@Controller()` decorator * * @publicApi */ export interface ControllerOptions extends ScopeOptions, VersionOptions { /** * Specifies an optional `route path prefix`. The prefix is pre-pended to the * path specified in any request decorator in the class. * * Supported only by HTTP-based applications (does not apply to non-HTTP microservices). * * @see [Routing](https://docs.nestjs.com/controllers#routing) */ path?: string | string[]; /** * Specifies an optional HTTP Request host filter. When configured, methods * within the controller will only be routed if the request host matches the * specified value. * * @see [Routing](https://docs.nestjs.com/controllers#routing) */ host?: string | RegExp | Array<string | RegExp>; } /** * Decorator that marks a class as a Nest controller that can receive inbound * requests and produce responses. * * An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. * It defines a class that provides the context for one or more related route * handlers that correspond to HTTP request methods and associated routes * for example `GET /api/profile`, `POST /users/resume`. * * A Microservice Controller responds to requests as well as events, running over * a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). * It defines a class that provides a context for one or more message or event * handlers. * * @see [Controllers](https://docs.nestjs.com/controllers) * @see [Microservices](https://docs.nestjs.com/microservices/basics#request-response) * * @publicApi */ export function Controller(): ClassDecorator; /** * Decorator that marks a class as a Nest controller that can receive inbound * requests and produce responses. * * An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. * It defines a class that provides the context for one or more related route * handlers that correspond to HTTP request methods and associated routes * for example `GET /api/profile`, `POST /users/resume`. * * A Microservice Controller responds to requests as well as events, running over * a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). * It defines a class that provides a context for one or more message or event * handlers. * * @param {string, Array} prefix string that defines a `route path prefix`. The prefix * is pre-pended to the path specified in any request decorator in the class. * * @see [Routing](https://docs.nestjs.com/controllers#routing) * @see [Controllers](https://docs.nestjs.com/controllers) * @see [Microservices](https://docs.nestjs.com/microservices/basics#request-response) * * @publicApi */ export function Controller(prefix: string | string[]): ClassDecorator; /** * Decorator that marks a class as a Nest controller that can receive inbound * requests and produce responses. * * An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. * It defines a class that provides the context for one or more related route * handlers that correspond to HTTP request methods and associated routes * for example `GET /api/profile`, `POST /users/resume`. * * A Microservice Controller responds to requests as well as events, running over * a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). * It defines a class that provides a context for one or more message or event * handlers. * * @param {object} options configuration object specifying: * * - `scope` - symbol that determines the lifetime of a Controller instance. * [See Scope](https://docs.nestjs.com/fundamentals/injection-scopes#usage) for * more details. * - `prefix` - string that defines a `route path prefix`. The prefix * is pre-pended to the path specified in any request decorator in the class. * - `version` - string, array of strings, or Symbol that defines the version * of all routes in the class. [See Versioning](https://docs.nestjs.com/techniques/versioning) * for more details. * * @see [Routing](https://docs.nestjs.com/controllers#routing) * @see [Controllers](https://docs.nestjs.com/controllers) * @see [Microservices](https://docs.nestjs.com/microservices/basics#request-response) * @see [Versioning](https://docs.nestjs.com/techniques/versioning) * * @publicApi */ export function Controller(options: ControllerOptions): ClassDecorator; /** * Decorator that marks a class as a Nest controller that can receive inbound * requests and produce responses. * * An HTTP Controller responds to inbound HTTP Requests and produces HTTP Responses. * It defines a class that provides the context for one or more related route * handlers that correspond to HTTP request methods and associated routes * for example `GET /api/profile`, `POST /users/resume` * * A Microservice Controller responds to requests as well as events, running over * a variety of transports [(read more here)](https://docs.nestjs.com/microservices/basics). * It defines a class that provides a context for one or more message or event * handlers. * * @param prefixOrOptions a `route path prefix` or a `ControllerOptions` object. * A `route path prefix` is pre-pended to the path specified in any request decorator * in the class. `ControllerOptions` is an options configuration object specifying: * - `scope` - symbol that determines the lifetime of a Controller instance. * [See Scope](https://docs.nestjs.com/fundamentals/injection-scopes#usage) for * more details. * - `prefix` - string that defines a `route path prefix`. The prefix * is pre-pended to the path specified in any request decorator in the class. * - `version` - string, array of strings, or Symbol that defines the version * of all routes in the class. [See Versioning](https://docs.nestjs.com/techniques/versioning) * for more details. * * @see [Routing](https://docs.nestjs.com/controllers#routing) * @see [Controllers](https://docs.nestjs.com/controllers) * @see [Microservices](https://docs.nestjs.com/microservices/basics#request-response) * @see [Scope](https://docs.nestjs.com/fundamentals/injection-scopes#usage) * @see [Versioning](https://docs.nestjs.com/techniques/versioning) * * @publicApi */ export function Controller( prefixOrOptions?: string | string[] | ControllerOptions, ): ClassDecorator { const defaultPath = '/'; const [path, host, scopeOptions, versionOptions] = isUndefined( prefixOrOptions, ) ? [defaultPath, undefined, undefined, undefined] : isString(prefixOrOptions) || Array.isArray(prefixOrOptions) ? [prefixOrOptions, undefined, undefined, undefined] : [ prefixOrOptions.path || defaultPath, prefixOrOptions.host, { scope: prefixOrOptions.scope }, prefixOrOptions.version, ]; return (target: object) => { Reflect.defineMetadata(PATH_METADATA, path, target); Reflect.defineMetadata(HOST_METADATA, host, target); Reflect.defineMetadata(SCOPE_OPTIONS_METADATA, scopeOptions, target); Reflect.defineMetadata(VERSION_METADATA, versionOptions, target); }; }
packages/common/decorators/core/controller.decorator.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.002864195266738534, 0.0006924306508153677, 0.00016370616503991187, 0.000224004324991256, 0.000829237571451813 ]
{ "id": 9, "code_window": [ " @Controller()\n", " class EmptyDecorator {}\n", "\n", " @Controller({ path: reflectedPath, host: reflectedHost })\n", " class PathAndHostDecorator {}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @Controller(reflectedPath)\n", " class Test {}\n", "\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "add", "edit_start_line_idx": 16 }
export * from './cache-key.decorator'; export * from './cache-ttl.decorator';
packages/common/cache/decorators/index.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00016939928173087537, 0.00016939928173087537, 0.00016939928173087537, 0.00016939928173087537, 0 ]
{ "id": 9, "code_window": [ " @Controller()\n", " class EmptyDecorator {}\n", "\n", " @Controller({ path: reflectedPath, host: reflectedHost })\n", " class PathAndHostDecorator {}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @Controller(reflectedPath)\n", " class Test {}\n", "\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "add", "edit_start_line_idx": 16 }
import { isUndefined } from '@nestjs/common/utils/shared.utils'; import { IncomingResponse, ProducerDeserializer } from '../interfaces'; export class IncomingResponseDeserializer implements ProducerDeserializer { deserialize(value: any, options?: Record<string, any>): IncomingResponse { return this.isExternal(value) ? this.mapToSchema(value) : value; } isExternal(value: any): boolean { if (!value) { return true; } if ( !isUndefined((value as IncomingResponse).err) || !isUndefined((value as IncomingResponse).response) || !isUndefined((value as IncomingResponse).isDisposed) ) { return false; } return true; } mapToSchema(value: any): IncomingResponse { return { id: value && value.id, response: value, isDisposed: true, }; } }
packages/microservices/deserializers/incoming-response.deserializer.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00018053165695164353, 0.00017467275029048324, 0.00017184167518280447, 0.0001731588417897001, 0.0000034252389014000073 ]
{ "id": 9, "code_window": [ " @Controller()\n", " class EmptyDecorator {}\n", "\n", " @Controller({ path: reflectedPath, host: reflectedHost })\n", " class PathAndHostDecorator {}\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " @Controller(reflectedPath)\n", " class Test {}\n", "\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "add", "edit_start_line_idx": 16 }
export const CONFIG_OPTIONS = 'CONFIG_OPTIONS';
sample/25-dynamic-modules/src/config/constants.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00018758820078801364, 0.00018758820078801364, 0.00018758820078801364, 0.00018758820078801364, 0 ]
{ "id": 10, "code_window": [ " @Controller({ version: reflectedVersion })\n", " class VersionOnlyDecorator {}\n", "\n", " it('should enhance controller with expected path metadata', () => {\n", " const path = Reflect.getMetadata('path', Test);\n", " expect(path).to.be.eql(reflectedPath);\n", " const path2 = Reflect.getMetadata('path', PathAndHostDecorator);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it(`should enhance component with \"${CONTROLLER_WATERMARK}\" metadata`, () => {\n", " const controllerWatermark = Reflect.getMetadata(\n", " CONTROLLER_WATERMARK,\n", " EmptyDecorator,\n", " );\n", "\n", " expect(controllerWatermark).to.be.true;\n", " });\n", "\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "add", "edit_start_line_idx": 35 }
import { FILTER_CATCH_EXCEPTIONS } from '../../constants'; import { Type } from '../../interfaces'; /** * Decorator that marks a class as a Nest exception filter. An exception filter * handles exceptions thrown by or not handled by your application code. * * The decorated class must implement the `ExceptionFilter` interface. * * @param exceptions one or more exception *types* specifying * the exceptions to be caught and handled by this filter. * * @see [Exception Filters](https://docs.nestjs.com/exception-filters) * * @usageNotes * Exception filters are applied using the `@UseFilters()` decorator, or (globally) * with `app.useGlobalFilters()`. * * @publicApi */ export function Catch(...exceptions: Type<any>[]): ClassDecorator { return (target: object) => { Reflect.defineMetadata(FILTER_CATCH_EXCEPTIONS, exceptions, target); }; }
packages/common/decorators/core/catch.decorator.ts
1
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00018085383635479957, 0.00017266366921830922, 0.0001673234364716336, 0.00016981377848424017, 0.000005879875061509665 ]
{ "id": 10, "code_window": [ " @Controller({ version: reflectedVersion })\n", " class VersionOnlyDecorator {}\n", "\n", " it('should enhance controller with expected path metadata', () => {\n", " const path = Reflect.getMetadata('path', Test);\n", " expect(path).to.be.eql(reflectedPath);\n", " const path2 = Reflect.getMetadata('path', PathAndHostDecorator);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it(`should enhance component with \"${CONTROLLER_WATERMARK}\" metadata`, () => {\n", " const controllerWatermark = Reflect.getMetadata(\n", " CONTROLLER_WATERMARK,\n", " EmptyDecorator,\n", " );\n", "\n", " expect(controllerWatermark).to.be.true;\n", " });\n", "\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "add", "edit_start_line_idx": 35 }
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3001); } bootstrap();
sample/32-graphql-federation-schema-first/posts-application/src/main.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017556134844198823, 0.00017556134844198823, 0.00017556134844198823, 0.00017556134844198823, 0 ]
{ "id": 10, "code_window": [ " @Controller({ version: reflectedVersion })\n", " class VersionOnlyDecorator {}\n", "\n", " it('should enhance controller with expected path metadata', () => {\n", " const path = Reflect.getMetadata('path', Test);\n", " expect(path).to.be.eql(reflectedPath);\n", " const path2 = Reflect.getMetadata('path', PathAndHostDecorator);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it(`should enhance component with \"${CONTROLLER_WATERMARK}\" metadata`, () => {\n", " const controllerWatermark = Reflect.getMetadata(\n", " CONTROLLER_WATERMARK,\n", " EmptyDecorator,\n", " );\n", "\n", " expect(controllerWatermark).to.be.true;\n", " });\n", "\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "add", "edit_start_line_idx": 35 }
import { Type } from '@nestjs/common'; import { isEmpty, isObject } from '@nestjs/common/utils/shared.utils'; /** * Helper class providing Nest reflection capabilities. * * @see [Reflection](https://docs.nestjs.com/guards#putting-it-all-together) * * @publicApi */ export class Reflector { /** * Retrieve metadata for a specified key for a specified target. * * @example * `const roles = this.reflector.get<string[]>('roles', context.getHandler());` * * @param metadataKey lookup key for metadata to retrieve * @param target context (decorated object) to retrieve metadata from * */ public get<TResult = any, TKey = any>( metadataKey: TKey, target: Type<any> | Function, ): TResult { return Reflect.getMetadata(metadataKey, target) as TResult; } /** * Retrieve metadata for a specified key for a specified set of targets. * * @param metadataKey lookup key for metadata to retrieve * @param targets context (decorated objects) to retrieve metadata from * */ public getAll<TResult extends any[] = any[], TKey = any>( metadataKey: TKey, targets: (Type<any> | Function)[], ): TResult { return (targets || []).map(target => Reflect.getMetadata(metadataKey, target), ) as TResult; } /** * Retrieve metadata for a specified key for a specified set of targets and merge results. * * @param metadataKey lookup key for metadata to retrieve * @param targets context (decorated objects) to retrieve metadata from * */ public getAllAndMerge<TResult extends any[] = any[], TKey = any>( metadataKey: TKey, targets: (Type<any> | Function)[], ): TResult { const metadataCollection = this.getAll<TResult, TKey>( metadataKey, targets, ).filter(item => item !== undefined); if (isEmpty(metadataCollection)) { return metadataCollection as TResult; } return metadataCollection.reduce((a, b) => { if (Array.isArray(a)) { return a.concat(b); } if (isObject(a) && isObject(b)) { return { ...a, ...b, }; } return [a, b]; }); } /** * Retrieve metadata for a specified key for a specified set of targets and return a first not undefined value. * * @param metadataKey lookup key for metadata to retrieve * @param targets context (decorated objects) to retrieve metadata from * */ public getAllAndOverride<TResult = any, TKey = any>( metadataKey: TKey, targets: (Type<any> | Function)[], ): TResult { const metadataCollection = this.getAll(metadataKey, targets).filter( item => item !== undefined, ); return metadataCollection[0]; } }
packages/core/services/reflector.service.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.0002021437103394419, 0.00017334744916297495, 0.00016500077617820352, 0.00017224060138687491, 0.000010224630386801437 ]
{ "id": 10, "code_window": [ " @Controller({ version: reflectedVersion })\n", " class VersionOnlyDecorator {}\n", "\n", " it('should enhance controller with expected path metadata', () => {\n", " const path = Reflect.getMetadata('path', Test);\n", " expect(path).to.be.eql(reflectedPath);\n", " const path2 = Reflect.getMetadata('path', PathAndHostDecorator);\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " it(`should enhance component with \"${CONTROLLER_WATERMARK}\" metadata`, () => {\n", " const controllerWatermark = Reflect.getMetadata(\n", " CONTROLLER_WATERMARK,\n", " EmptyDecorator,\n", " );\n", "\n", " expect(controllerWatermark).to.be.true;\n", " });\n", "\n" ], "file_path": "packages/common/test/decorators/controller.decorator.spec.ts", "type": "add", "edit_start_line_idx": 35 }
import { Injectable, StreamableFile } from '@nestjs/common'; import { createReadStream, readFileSync } from 'fs'; import { join } from 'path'; import { Observable, of } from 'rxjs'; import { NonFile } from './non-file'; @Injectable() export class AppService { getReadStream(): StreamableFile { return new StreamableFile( createReadStream(join(process.cwd(), 'Readme.md')), ); } getBuffer(): StreamableFile { return new StreamableFile(readFileSync(join(process.cwd(), 'Readme.md'))); } getNonFile(): NonFile { return new NonFile('Hello world'); } getRxJSFile(): Observable<StreamableFile> { return of(this.getReadStream()); } getFileWithHeaders(): StreamableFile { return new StreamableFile( createReadStream(join(process.cwd(), 'Readme.md')), { type: 'text/markdown', disposition: 'attachment; filename="Readme.md"', }, ); } }
integration/send-files/src/app.service.ts
0
https://github.com/nestjs/nest/commit/0f99d70f09a4089025e822b3b42f9f5f1a0dd361
[ 0.00017828133422881365, 0.00017618350102566183, 0.0001740907464409247, 0.0001761809689924121, 0.0000015300549875973957 ]
{ "id": 0, "code_window": [ "on how to do so.\n", "\n", "## SVG Icons\n", "\n", "In order to use prebuilt SVG Material icons, such as those found in the [component demos](/component-demos)\n", "you must first install the [material-ui-icons](https://www.npmjs.org/package/material-ui-icons) package:\n", "\n", "```\n", "npm install material-ui-icons\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "In order to use prebuilt SVG Material icons, such as those found in the [component demos](/demos/app-bar/)\n" ], "file_path": "docs/src/pages/getting-started/installation.md", "type": "replace", "edit_start_line_idx": 26 }
// @flow // @inheritedComponent TableRow import React from 'react'; import type { Node } from 'react'; import withStyles from '../styles/withStyles'; import IconButton from '../IconButton'; import Input from '../Input'; import { MenuItem } from '../Menu'; import Select from '../Select'; import TableCell from './TableCell'; import TableRow from './TableRow'; import Toolbar from '../Toolbar'; import Typography from '../Typography'; import KeyboardArrowLeft from '../svg-icons/KeyboardArrowLeft'; import KeyboardArrowRight from '../svg-icons/KeyboardArrowRight'; export const styles = (theme: Object) => ({ cell: { // Increase the specificity to override TableCell. '&:last-child': { padding: '0', }, }, toolbar: { height: 56, minHeight: 56, paddingRight: 2, }, spacer: { flex: '1 1 100%', }, select: { marginLeft: theme.spacing.unit, width: 34, textAlign: 'right', paddingRight: 22, color: theme.palette.text.secondary, height: 32, lineHeight: '32px', }, selectRoot: { marginRight: theme.spacing.unit * 4, }, actions: { color: theme.palette.text.secondary, marginLeft: theme.spacing.unit * 2.5, }, }); export type LabelDisplayedRowsArgs = { from: number, to: number, count: number, page: number, }; type ProvidedProps = { classes: Object, labelRowsPerPage: string, labelDisplayedRows: (paginationInfo: LabelDisplayedRowsArgs) => string, rowsPerPageOptions: number[], }; export type Props = { /** * Useful to extend the style applied to components. */ classes?: Object, /** * @ignore */ className?: string, /** * The total number of rows. */ count: number, /** * Useful to customize the displayed rows label. */ labelDisplayedRows?: (paginationInfo: LabelDisplayedRowsArgs) => Node, /** * Useful to customize the rows per page label. Invoked with a `{ from, to, count, page }` * object. */ labelRowsPerPage?: Node, /** * Callback fired when the page is changed. Invoked with two arguments: the event and the * page to show. */ onChangePage: (event: SyntheticInputEvent<> | null, page: number) => void, /** * Callback fired when the number of rows per page is changed. Invoked with two arguments: the * event. */ onChangeRowsPerPage: (event: SyntheticInputEvent<>) => void, /** * The zero-based index of the current page. */ page: number, /** * The number of rows per page. */ rowsPerPage: number, /** * Customizes the options of the rows per page select field. */ rowsPerPageOptions?: number[], }; /** * A `TableRow` based component for placing inside `TableFooter` for pagination. */ class TablePagination extends React.Component<ProvidedProps & Props> { static defaultProps = { labelRowsPerPage: 'Rows per page:', labelDisplayedRows: ({ from, to, count }) => `${from}-${to} of ${count}`, rowsPerPageOptions: [5, 10, 25], }; componentWillReceiveProps({ count, onChangePage, rowsPerPage }) { const newLastPage = Math.max(0, Math.ceil(count / rowsPerPage) - 1); if (this.props.page > newLastPage) { onChangePage(null, newLastPage); } } handleBackButtonClick = event => { this.props.onChangePage(event, this.props.page - 1); }; handleNextButtonClick = event => { this.props.onChangePage(event, this.props.page + 1); }; render() { const { classes, className, count, labelDisplayedRows, labelRowsPerPage, onChangePage, onChangeRowsPerPage, page, rowsPerPage, rowsPerPageOptions, ...other } = this.props; return ( <TableRow className={className} {...other}> <TableCell className={classes.cell} colSpan={9001} // col-span over everything > <Toolbar className={classes.toolbar}> <div className={classes.spacer} /> <Typography type="caption">{labelRowsPerPage}</Typography> <Select classes={{ root: classes.selectRoot, select: classes.select }} input={<Input disableUnderline />} value={rowsPerPage} onChange={onChangeRowsPerPage} > {rowsPerPageOptions.map(rowsPerPageOption => ( <MenuItem key={rowsPerPageOption} value={rowsPerPageOption}> {rowsPerPageOption} </MenuItem> ))} </Select> <Typography type="caption"> {labelDisplayedRows({ from: count === 0 ? 0 : page * rowsPerPage + 1, to: Math.min(count, (page + 1) * rowsPerPage), count, page, })} </Typography> <div className={classes.actions}> <IconButton onClick={this.handleBackButtonClick} disabled={page === 0}> <KeyboardArrowLeft /> </IconButton> <IconButton onClick={this.handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} > <KeyboardArrowRight /> </IconButton> </div> </Toolbar> </TableCell> </TableRow> ); } } export default withStyles(styles, { name: 'MuiTablePagination' })(TablePagination);
src/Table/TablePagination.js
1
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00033322919625788927, 0.0001868045364972204, 0.00016532976587768644, 0.00016818425501696765, 0.00004749310028273612 ]
{ "id": 0, "code_window": [ "on how to do so.\n", "\n", "## SVG Icons\n", "\n", "In order to use prebuilt SVG Material icons, such as those found in the [component demos](/component-demos)\n", "you must first install the [material-ui-icons](https://www.npmjs.org/package/material-ui-icons) package:\n", "\n", "```\n", "npm install material-ui-icons\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "In order to use prebuilt SVG Material icons, such as those found in the [component demos](/demos/app-bar/)\n" ], "file_path": "docs/src/pages/getting-started/installation.md", "type": "replace", "edit_start_line_idx": 26 }
{ "projects": { "material-ui": "material-ui-1dab0" } }
.firebaserc
0
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00017399166245013475, 0.00017399166245013475, 0.00017399166245013475, 0.00017399166245013475, 0 ]
{ "id": 0, "code_window": [ "on how to do so.\n", "\n", "## SVG Icons\n", "\n", "In order to use prebuilt SVG Material icons, such as those found in the [component demos](/component-demos)\n", "you must first install the [material-ui-icons](https://www.npmjs.org/package/material-ui-icons) package:\n", "\n", "```\n", "npm install material-ui-icons\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "In order to use prebuilt SVG Material icons, such as those found in the [component demos](/demos/app-bar/)\n" ], "file_path": "docs/src/pages/getting-started/installation.md", "type": "replace", "edit_start_line_idx": 26 }
export function cloneChildrenWithClassName<T>( children: React.ReactNode, className: string ): T[];
src/utils/reactHelpers.d.ts
0
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00016790677909739316, 0.00016790677909739316, 0.00016790677909739316, 0.00016790677909739316, 0 ]
{ "id": 0, "code_window": [ "on how to do so.\n", "\n", "## SVG Icons\n", "\n", "In order to use prebuilt SVG Material icons, such as those found in the [component demos](/component-demos)\n", "you must first install the [material-ui-icons](https://www.npmjs.org/package/material-ui-icons) package:\n", "\n", "```\n", "npm install material-ui-icons\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ "In order to use prebuilt SVG Material icons, such as those found in the [component demos](/demos/app-bar/)\n" ], "file_path": "docs/src/pages/getting-started/installation.md", "type": "replace", "edit_start_line_idx": 26 }
import { StyledComponent } from '..'; export interface ListItemIconProps {} export type ListItemIconClassKey = | 'root' ; declare const ListItemIcon: StyledComponent<ListItemIconProps, ListItemIconClassKey>; export default ListItemIcon;
src/List/ListItemIcon.d.ts
0
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00022620779054705054, 0.00020142659195698798, 0.00017664539336692542, 0.00020142659195698798, 0.00002478119859006256 ]
{ "id": 1, "code_window": [ " render() {\n", " const {\n", " classes,\n", " className,\n", " count,\n", " labelDisplayedRows,\n", " labelRowsPerPage,\n", " onChangePage,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/Table/TablePagination.js", "type": "replace", "edit_start_line_idx": 138 }
// @flow // @inheritedComponent TableRow import React from 'react'; import type { Node } from 'react'; import withStyles from '../styles/withStyles'; import IconButton from '../IconButton'; import Input from '../Input'; import { MenuItem } from '../Menu'; import Select from '../Select'; import TableCell from './TableCell'; import TableRow from './TableRow'; import Toolbar from '../Toolbar'; import Typography from '../Typography'; import KeyboardArrowLeft from '../svg-icons/KeyboardArrowLeft'; import KeyboardArrowRight from '../svg-icons/KeyboardArrowRight'; export const styles = (theme: Object) => ({ cell: { // Increase the specificity to override TableCell. '&:last-child': { padding: '0', }, }, toolbar: { height: 56, minHeight: 56, paddingRight: 2, }, spacer: { flex: '1 1 100%', }, select: { marginLeft: theme.spacing.unit, width: 34, textAlign: 'right', paddingRight: 22, color: theme.palette.text.secondary, height: 32, lineHeight: '32px', }, selectRoot: { marginRight: theme.spacing.unit * 4, }, actions: { color: theme.palette.text.secondary, marginLeft: theme.spacing.unit * 2.5, }, }); export type LabelDisplayedRowsArgs = { from: number, to: number, count: number, page: number, }; type ProvidedProps = { classes: Object, labelRowsPerPage: string, labelDisplayedRows: (paginationInfo: LabelDisplayedRowsArgs) => string, rowsPerPageOptions: number[], }; export type Props = { /** * Useful to extend the style applied to components. */ classes?: Object, /** * @ignore */ className?: string, /** * The total number of rows. */ count: number, /** * Useful to customize the displayed rows label. */ labelDisplayedRows?: (paginationInfo: LabelDisplayedRowsArgs) => Node, /** * Useful to customize the rows per page label. Invoked with a `{ from, to, count, page }` * object. */ labelRowsPerPage?: Node, /** * Callback fired when the page is changed. Invoked with two arguments: the event and the * page to show. */ onChangePage: (event: SyntheticInputEvent<> | null, page: number) => void, /** * Callback fired when the number of rows per page is changed. Invoked with two arguments: the * event. */ onChangeRowsPerPage: (event: SyntheticInputEvent<>) => void, /** * The zero-based index of the current page. */ page: number, /** * The number of rows per page. */ rowsPerPage: number, /** * Customizes the options of the rows per page select field. */ rowsPerPageOptions?: number[], }; /** * A `TableRow` based component for placing inside `TableFooter` for pagination. */ class TablePagination extends React.Component<ProvidedProps & Props> { static defaultProps = { labelRowsPerPage: 'Rows per page:', labelDisplayedRows: ({ from, to, count }) => `${from}-${to} of ${count}`, rowsPerPageOptions: [5, 10, 25], }; componentWillReceiveProps({ count, onChangePage, rowsPerPage }) { const newLastPage = Math.max(0, Math.ceil(count / rowsPerPage) - 1); if (this.props.page > newLastPage) { onChangePage(null, newLastPage); } } handleBackButtonClick = event => { this.props.onChangePage(event, this.props.page - 1); }; handleNextButtonClick = event => { this.props.onChangePage(event, this.props.page + 1); }; render() { const { classes, className, count, labelDisplayedRows, labelRowsPerPage, onChangePage, onChangeRowsPerPage, page, rowsPerPage, rowsPerPageOptions, ...other } = this.props; return ( <TableRow className={className} {...other}> <TableCell className={classes.cell} colSpan={9001} // col-span over everything > <Toolbar className={classes.toolbar}> <div className={classes.spacer} /> <Typography type="caption">{labelRowsPerPage}</Typography> <Select classes={{ root: classes.selectRoot, select: classes.select }} input={<Input disableUnderline />} value={rowsPerPage} onChange={onChangeRowsPerPage} > {rowsPerPageOptions.map(rowsPerPageOption => ( <MenuItem key={rowsPerPageOption} value={rowsPerPageOption}> {rowsPerPageOption} </MenuItem> ))} </Select> <Typography type="caption"> {labelDisplayedRows({ from: count === 0 ? 0 : page * rowsPerPage + 1, to: Math.min(count, (page + 1) * rowsPerPage), count, page, })} </Typography> <div className={classes.actions}> <IconButton onClick={this.handleBackButtonClick} disabled={page === 0}> <KeyboardArrowLeft /> </IconButton> <IconButton onClick={this.handleNextButtonClick} disabled={page >= Math.ceil(count / rowsPerPage) - 1} > <KeyboardArrowRight /> </IconButton> </div> </Toolbar> </TableCell> </TableRow> ); } } export default withStyles(styles, { name: 'MuiTablePagination' })(TablePagination);
src/Table/TablePagination.js
1
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.9973993301391602, 0.18040600419044495, 0.00017301129992119968, 0.002412706147879362, 0.3619237542152405 ]
{ "id": 1, "code_window": [ " render() {\n", " const {\n", " classes,\n", " className,\n", " count,\n", " labelDisplayedRows,\n", " labelRowsPerPage,\n", " onChangePage,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/Table/TablePagination.js", "type": "replace", "edit_start_line_idx": 138 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let PanoramaFishEye = props => <SvgIconCustom {...props}> <path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" /> </SvgIconCustom>; PanoramaFishEye = pure(PanoramaFishEye); PanoramaFishEye.muiName = 'SvgIcon'; export default PanoramaFishEye;
packages/material-ui-icons/src/PanoramaFishEye.js
0
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00017375258903484792, 0.00017331061826553196, 0.000172868647496216, 0.00017331061826553196, 4.41970769315958e-7 ]
{ "id": 1, "code_window": [ " render() {\n", " const {\n", " classes,\n", " className,\n", " count,\n", " labelDisplayedRows,\n", " labelRowsPerPage,\n", " onChangePage,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/Table/TablePagination.js", "type": "replace", "edit_start_line_idx": 138 }
// @flow import React from 'react'; import TextField from 'material-ui/TextField'; export default function TextFieldMargin() { return ( <div style={{ display: 'flex' }}> <TextField label="Dense" defaultValue="Default Value" margin="dense" /> <TextField style={{ position: 'absolute ' }} label="Dense" margin="dense" /> </div> ); }
test/regressions/tests/TextField/TextFieldMargin.js
0
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00017726868099998683, 0.000175304536242038, 0.0001733403914840892, 0.000175304536242038, 0.000001964144757948816 ]
{ "id": 1, "code_window": [ " render() {\n", " const {\n", " classes,\n", " className,\n", " count,\n", " labelDisplayedRows,\n", " labelRowsPerPage,\n", " onChangePage,\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [], "file_path": "src/Table/TablePagination.js", "type": "replace", "edit_start_line_idx": 138 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let PauseCircleFilled = props => <SvgIconCustom {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 14H9V8h2v8zm4 0h-2V8h2v8z" /> </SvgIconCustom>; PauseCircleFilled = pure(PauseCircleFilled); PauseCircleFilled.muiName = 'SvgIcon'; export default PauseCircleFilled;
packages/material-ui-icons/src/PauseCircleFilled.js
0
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.0001735538971843198, 0.0001732788805384189, 0.0001730038784444332, 0.0001732788805384189, 2.7500936994329095e-7 ]
{ "id": 2, "code_window": [ " ...other\n", " } = this.props;\n", "\n", " return (\n", " <TableRow className={className} {...other}>\n", " <TableCell\n", " className={classes.cell}\n", " colSpan={9001} // col-span over everything\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <TableRow {...other}>\n" ], "file_path": "src/Table/TablePagination.js", "type": "replace", "edit_start_line_idx": 151 }
// @flow weak import { unmountComponentAtNode } from 'react-dom'; import { mount as enzymeMount } from 'enzyme'; // Generate an enhanced mount function. export default function createMount(options: Object = {}) { const { mount = enzymeMount } = options; const attachTo = window.document.createElement('div'); attachTo.className = 'app'; attachTo.setAttribute('id', 'app'); window.document.body.insertBefore(attachTo, window.document.body.firstChild); const mountWithContext = function mountWithContext( node: React$Element<any>, options2: Object = {}, ) { return mount(node, { attachTo, ...options2, }); }; mountWithContext.attachTo = attachTo; mountWithContext.cleanUp = () => { unmountComponentAtNode(attachTo); attachTo.parentNode.removeChild(attachTo); }; return mountWithContext; }
src/test-utils/createMount.js
1
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00017851777374744415, 0.00017325622320640832, 0.00016915217565838248, 0.00017267747898586094, 0.000003713125124704675 ]
{ "id": 2, "code_window": [ " ...other\n", " } = this.props;\n", "\n", " return (\n", " <TableRow className={className} {...other}>\n", " <TableCell\n", " className={classes.cell}\n", " colSpan={9001} // col-span over everything\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <TableRow {...other}>\n" ], "file_path": "src/Table/TablePagination.js", "type": "replace", "edit_start_line_idx": 151 }
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; const SvgIconCustom = global.__MUI_SvgIcon__ || SvgIcon; let BubbleChart = props => <SvgIconCustom {...props}> <circle cx="7.2" cy="14.4" r="3.2" /><circle cx="14.8" cy="18" r="2" /><circle cx="15.2" cy="8.8" r="4.8" /> </SvgIconCustom>; BubbleChart = pure(BubbleChart); BubbleChart.muiName = 'SvgIcon'; export default BubbleChart;
packages/material-ui-icons/src/BubbleChart.js
0
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00026171031640842557, 0.00021740206284448504, 0.00017309380928054452, 0.00021740206284448504, 0.000044308253563940525 ]
{ "id": 2, "code_window": [ " ...other\n", " } = this.props;\n", "\n", " return (\n", " <TableRow className={className} {...other}>\n", " <TableCell\n", " className={classes.cell}\n", " colSpan={9001} // col-span over everything\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <TableRow {...other}>\n" ], "file_path": "src/Table/TablePagination.js", "type": "replace", "edit_start_line_idx": 151 }
<!--- This documentation is automatically generated, do not try to edit it. --> --- filename: /src/MobileStepper/MobileStepper.js --- # MobileStepper ## Props | Name | Type | Default | Description | |:-----|:-----|:--------|:------------| | activeStep | number | 0 | Set the active step (zero based index). Defines which dot is highlighted when the type is 'dots'. | | <span style="color: #31a148">backButton *</span> | Element | | A back button element. For instance, it can be be a `Button` or a `IconButton`. | | classes | Object | | Useful to extend the style applied to components. | | <span style="color: #31a148">nextButton *</span> | Element | | A next button element. For instance, it can be be a `Button` or a `IconButton`. | | position | union:&nbsp;'bottom'<br>&nbsp;'top'<br>&nbsp;'static'<br> | 'bottom' | Set the positioning type. | | <span style="color: #31a148">steps *</span> | number | | The total steps. | | type | union:&nbsp;'text'<br>&nbsp;'dots'<br>&nbsp;'progress'<br> | 'dots' | The type of mobile stepper to use. | Any other properties supplied will be [spread to the root element](/customization/api#spread). ## CSS API You can override all the class names injected by Material-UI thanks to the `classes` property. This property accepts the following keys: - `root` - `positionBottom` - `positionTop` - `positionStatic` - `dots` - `dot` - `dotActive` - `progress` Have a look at [overriding with classes](/customization/overrides#overriding-with-classes) section and the [implementation of the component](https://github.com/callemall/material-ui/tree/v1-beta/src/MobileStepper/MobileStepper.js) for more detail. If using the `overrides` key of the theme as documented [here](/customization/themes#customizing-all-instances-of-a-component-type), you need to use the following style sheet name: `MuiMobileStepper`. ## Inheritance The properties of the [&lt;Paper /&gt;](/api/paper) component are also available. ## Demos - [Stepper](/demos/stepper)
pages/api/mobile-stepper.md
0
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00017056381329894066, 0.00016540098295081407, 0.00015917638665996492, 0.0001659105037106201, 0.000004265457391738892 ]
{ "id": 2, "code_window": [ " ...other\n", " } = this.props;\n", "\n", " return (\n", " <TableRow className={className} {...other}>\n", " <TableCell\n", " className={classes.cell}\n", " colSpan={9001} // col-span over everything\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <TableRow {...other}>\n" ], "file_path": "src/Table/TablePagination.js", "type": "replace", "edit_start_line_idx": 151 }
export { default } from './Divider'; export * from './Divider';
src/Divider/index.d.ts
0
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00017278642917517573, 0.00017278642917517573, 0.00017278642917517573, 0.00017278642917517573, 0 ]
{ "id": 3, "code_window": [ "import { unmountComponentAtNode } from 'react-dom';\n", "import { mount as enzymeMount } from 'enzyme';\n", "\n", "// Generate an enhanced mount function.\n", "export default function createMount(options: Object = {}) {\n", " const { mount = enzymeMount } = options;\n", "\n", " const attachTo = window.document.createElement('div');\n", " attachTo.className = 'app';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "export default function createMount(options1: Object = {}) {\n", " const { mount = enzymeMount, ...other1 } = options1;\n" ], "file_path": "src/test-utils/createMount.js", "type": "replace", "edit_start_line_idx": 6 }
// @flow weak import { shallow as enzymeShallow } from 'enzyme'; import until from './until'; // Generate an enhanced shallow function. export default function createShallow(options: Object = {}) { const { shallow = enzymeShallow, context, dive = false, untilSelector = false } = options; const shallowWithContext = function shallowWithContext( node: React$Element<any>, options2: Object = {}, ) { const { context: context2, ...other } = options2; const wrapper = shallow(node, { ...other, context: { ...context, ...context2, }, }); if (dive) { return wrapper.dive(); } if (untilSelector) { return until.call(wrapper, untilSelector); } return wrapper; }; return shallowWithContext; }
src/test-utils/createShallow.js
1
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.0021944185718894005, 0.0006766139413230121, 0.00016701595450285822, 0.00017251056851819158, 0.000876308826263994 ]
{ "id": 3, "code_window": [ "import { unmountComponentAtNode } from 'react-dom';\n", "import { mount as enzymeMount } from 'enzyme';\n", "\n", "// Generate an enhanced mount function.\n", "export default function createMount(options: Object = {}) {\n", " const { mount = enzymeMount } = options;\n", "\n", " const attachTo = window.document.createElement('div');\n", " attachTo.className = 'app';\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ "export default function createMount(options1: Object = {}) {\n", " const { mount = enzymeMount, ...other1 } = options1;\n" ], "file_path": "src/test-utils/createMount.js", "type": "replace", "edit_start_line_idx": 6 }
# Supported Components The following is a list of Material Design components & features. Those currently supported by Material-UI are **highlighted ✓**. While we strive to follow the guidelines where practical (applying common sense where guidelines contradict - a more common occurence than one might expect), we do not expect to support every component, or every feature of every component, but rather to provide the building blocks to allow developers to create compelling user interfaces and experiences. If you wish to add support for a component or feature not highlighted here, please search for the relevant [GitHub Issue](https://github.com/callemall/material-ui/issues), or create a new one to discuss the approach before submitting a PR. - **[App Bar](https://material.io/guidelines/layout/structure.html#structure-app-bar) ✓** - [App shortcut icons](https://material.io/guidelines/style/icons.html#icons-app-shortcut-icons) - Icon - Avatar - Group avatar - **[Bottom navigation](https://material.io/guidelines/components/bottom-navigation.html) ✓** - [Bottom sheets](https://material.io/guidelines/components/bottom-sheets.html) - **[Buttons](https://material.io/guidelines/components/buttons.html) ✓** - **[Flat & raised buttons](https://material.io/guidelines/components/buttons.html#buttons-flat-raised-buttons) ✓** - [Toggle buttons](https://material.io/guidelines/components/buttons.html#buttons-toggle-buttons) - **[Icon toggles](https://material.io/guidelines/components/buttons.html#buttons-toggle-buttons) (Custom Checkbox) ✓** - [Dropdown: Mobile: Dropdown buttons](https://material.io/guidelines/components/buttons.html#buttons-dropdown-buttons) (DropDownMenu) - [Dropdown: Mobile: Generic overflow](https://material.io/guidelines/components/buttons.html#buttons-dropdown-buttons) - [Dropdown: Mobile: Segmented](https://material.io/guidelines/components/buttons.html#buttons-dropdown-buttons) - [Dropdown: Mobile: Editable segmented](https://material.io/guidelines/components/buttons.html#buttons-dropdown-buttons) - [Dropdown: Desktop: Dropdown buttons](https://material.io/guidelines/components/buttons.html#buttons-dropdown-buttons) - **[Buttons: Floating Action Button](https://material.io/guidelines/components/buttons-floating-action-button.html) ✓** - **[Trigger](https://material.io/guidelines/components/buttons-floating-action-button.html#buttons-floating-action-button-transitions) ✓** - [Toolbar](https://material.io/guidelines/components/buttons-floating-action-button.html#buttons-floating-action-button-transitions) - [Speed dial](https://material.io/guidelines/components/buttons-floating-action-button.html#buttons-floating-action-button-transitions) - [Morph](http://www.google.com/design/spec/components/buttons-floating-action-button.html#buttons-floating-action-button-transitions) - [Full screen](http://www.google.com/design/spec/components/buttons-floating-action-button.html#buttons-floating-action-button-transitions) - **[Cards](https://material.io/guidelines/components/cards.html) ✓** - **[Chips](https://material.io/guidelines/components/chips.html) ✓** - **[Standard](https://material.io/guidelines/components/chips.html) ✓** - **[Contact](https://material.io/guidelines/components/chips.html#chips-contact-chips) ✓** - **[Data tables](https://material.io/guidelines/components/data-tables.html) ✓** - **Sortable ✓** - **Selectable ✓** - **Pagination ✓** - **[Dialogs](https://material.io/guidelines/components/dialogs.html) ✓** - **[Alerts](https://material.io/guidelines/components/dialogs.html#dialogs-alerts) ✓** - **[Simple menus](https://material.io/guidelines/components/dialogs.html#dialogs-simple-menus) (Menu) ✓** - **[Simple dialogs](https://material.io/guidelines/components/dialogs.html#dialogs-simple-dialogs) (Can be constructed with Dialog and List.) ✓** - **[Confirmation dialogs](https://material.io/guidelines/components/dialogs.html#dialogs-confirmation-dialogs) ✓** - **[Full screen dialogs](https://material.io/guidelines/components/dialogs.html#dialogs-full-screen-dialogs) ✓** - **[Dividers](https://material.io/guidelines/components/dividers.html) ✓** - **[Full bleed](https://material.io/guidelines/components/dividers.html#dividers-types-of-dividers) ✓** - **[Inset](https://material.io/guidelines/components/dividers.html#dividers-types-of-dividers) ✓** - [Expansion Panels](https://material.io/guidelines/components/expansion-panels.html) - **[Grid lists](https://material.io/guidelines/components/grid-lists.html) ✓** - **[Lists](https://material.io/guidelines/components/lists.html) ✓** - **[Single line](https://material.io/guidelines/components/lists.html#lists-specs) ✓** - **[Two line](https://material.io/guidelines/components/lists.html#lists-specs) ✓** - [Three line](https://material.io/guidelines/components/lists.html#lists-specs) - **[Avatar](https://material.io/guidelines/components/lists.html#lists-specs) ✓** - **[Icon](https://material.io/guidelines/components/lists.html#lists-specs) ✓** - **[Lists: Controls](https://material.io/guidelines/components/lists-controls.html) ✓** - **[Checkbox](https://material.io/guidelines/components/lists-controls.html#lists-controls-types-of-list-controls) (Primary only) ✓** - **[Switch](https://material.io/guidelines/components/lists-controls.html#lists-controls-types-of-list-controls) (Toggle) ✓** - [Reorder](https://material.io/guidelines/components/lists-controls.html#lists-controls-types-of-list-controls) - [Expand/collapse](https://material.io/guidelines/components/lists-controls.html#lists-controls-types-of-list-controls) - [Leave-behinds](https://material.io/guidelines/components/lists-controls.html#lists-controls-types-of-list-controls) - **[Menus](https://material.io/guidelines/components/menus.html) ✓** - **[Button menu](https://material.io/guidelines/components/menus.html#menus-usage) (Can be constructed) ✓** - **[Scrollable](https://material.io/guidelines/components/menus.html#menus-usage) ✓** - [Cascade](https://material.io/guidelines/components/menus.html#menus-usage) - **[Textfield dropdown](https://material.io/guidelines/components/menus.html#menus-behavior) (Selet) ✓** - **[Contextual / App bar dropdown](https://material.io/guidelines/components/menus.html#menus-usage) (IconButton + Menu) ✓** - **[Simple menus](https://material.io/guidelines/components/menus.html#menus-simple-menus) (Menu) ✓** - [Pickers](https://material.io/guidelines/components/pickers.html) - [Date picker](https://material.io/guidelines/components/pickers.html#pickers-date-pickers) - [Time picker](https://material.io/guidelines/components/pickers.html#pickers-time-pickers) - **[Progress & activity](https://material.io/guidelines/components/progress-activity.html) ✓** - **[Linear](https://material.io/guidelines/components/progress-activity.html#progress-activity-types-of-indicators) ✓** - **[Circular](https://material.io/guidelines/components/progress-activity.html#progress-activity-types-of-indicators) ✓** - **[Circular with integration](https://material.io/guidelines/components/progress-activity.html#progress-activity-types-of-indicators) ✓** - **[Loading](https://material.io/guidelines/components/progress-activity.html#progress-activity-types-of-indicators) ✓** - **[Selection controls](https://material.io/guidelines/components/selection-controls.html) ✓** - **[Checkbox](https://material.io/guidelines/components/selection-controls.html#selection-controls-checkbox) ✓** - **[Radio button](https://material.io/guidelines/components/selection-controls.html#selection-controls-radio-button) ✓** - **[Switch](https://material.io/guidelines/components/selection-controls.html#selection-controls-switch) ✓** - [Sliders](https://material.io/guidelines/components/sliders.html) - [Continuous](https://material.io/guidelines/components/sliders.html#sliders-continuous-slider) - [Discrete](https://material.io/guidelines/components/sliders.html#sliders-discrete-slider) - **[Snackbars](https://material.io/guidelines/components/snackbars-toasts.html) ✓** - **[Subheaders](https://material.io/guidelines/components/subheaders.html) ✓** - **[List](https://material.io/guidelines/components/subheaders.html#subheaders-list-subheaders) ✓** - **[Grid](https://material.io/guidelines/components/subheaders.html#subheaders-list-subheaders) ✓** - [Menu](https://material.io/guidelines/components/subheaders.html#subheaders-list-subheaders) - [Steppers](https://material.io/guidelines/components/steppers.html) - [Horizontal](https://material.io/guidelines/components/steppers.html#steppers-types-of-steppers) - [Vertical](https://material.io/guidelines/components/steppers.html#steppers-types-of-steppers) - **[Mobile steps](https://material.io/guidelines/components/steppers.html#steppers-types-of-steps) ✓** - **[Tabs](https://material.io/guidelines/components/tabs.html) ✓** - Usage - **[Mobile (Full width)](https://material.io/guidelines/components/tabs.html#tabs-usage) ✓** - **[Desktop (Left aligned AKA Basic)](https://material.io/guidelines/components/tabs.html#tabs-usage) ✓** - **[Centered](https://material.io/guidelines/components/tabs.html#tabs-usage) ✓** - **[Scrollable tab bar](https://material.io/guidelines/components/tabs.html#tabs-usage) ✓** - **[Overflow pagination](https://material.io/guidelines/components/tabs.html#tabs-usage) ✓** - [Dropdown](https://material.io/guidelines/components/tabs.html#tabs-usage) - Label - **[Text](https://material.io/guidelines/components/tabs.html#tabs-usage) ✓** - **[Icon](https://material.io/guidelines/components/tabs.html#tabs-usage) ✓** - **[Icon and text](https://material.io/guidelines/components/tabs.html#tabs-usage) ✓** - **[Text fields](https://material.io/guidelines/components/text-fields.html) ✓** - **[Single-line](https://material.io/guidelines/components/text-fields.html#text-fields-single-line-text-field) ✓** - [Multi-line](https://material.io/guidelines/components/text-fields.html#text-fields-field-types) - [Text-area](https://material.io/guidelines/components/text-fields.html#text-fields-field-types) - **[Full-width](https://material.io/guidelines/components/text-fields.html#text-fields-multi-line-text-field) ✓** - [Character counter](https://material.io/guidelines/components/text-fields.html#text-fields-character-counter) - **[Autocomplete](https://material.io/guidelines/components/text-fields.html#text-fields-auto-complete-text-field) (Can be done with external library such as [react-autosuggest](https://github.com/moroshko/react-autosuggest)) ✓** - [Search filter](https://material.io/guidelines/components/text-fields.html#text-fields-search-filter) - [Password](https://material.io/guidelines/components/text-fields.html#text-fields-password-input) - **[Toolbars](https://material.io/guidelines/components/toolbars.html) ✓** - **[Tooltips](https://material.io/guidelines/components/tooltips.html) ✓** - **[Desktop](https://material.io/guidelines/components/tooltips.html#tooltips-tooltips-desktop-) ✓** - **[Mobile](https://material.io/guidelines/components/tooltips.html#tooltips-tooltips-mobile-) ✓** - [Widgets](https://material.io/guidelines/components/widgets.html) - [Information widgets](https://material.io/guidelines/components/widgets.html#widgets-types-of-widgets) - [Collection widgets](https://material.io/guidelines/components/widgets.html#widgets-types-of-widgets) - [Control widgets](https://material.io/guidelines/components/widgets.html#widgets-types-of-widgets)
docs/src/pages/getting-started/supported-components.md
0
https://github.com/mui/material-ui/commit/8be0c2d933070e0f124841a2ed2c913314a73816
[ 0.00017014116747304797, 0.00016475153097417206, 0.0001619736576685682, 0.00016429524112027138, 0.000002412808498775121 ]