Codebase analysis · CoreStory V3

Contoso Real Estate

A reference rental-listing application written in TypeScript: an Angular portal, a Node API, a Stripe payment service and a blog CMS. It covers listings, reservations, checkout and payments, favorites and user roles. A sample published by Microsoft Azure Samples; this page is not affiliated with or endorsed by Microsoft.

Maintained by
Microsoft (Azure Samples)
License
MIT
Commit analyzed
e4c3bd81aca873673fbf24352ed0ede6bc363443
Rules extracted
2026-11-15
Extracted by CoreStory V3
1533
accepted rules, each with a cited source quote
22
capabilities
120
features
01 · Rules

Business rules, traced to source lines.

These 12 rules are a sample of the 1,533 CoreStory V3 extracted from Contoso Real Estate. Each one links to the exact lines on GitHub at commit e4c3bd8. The statement is CoreStory V3’s wording; the code excerpt is the source it cites.

calculation
packages/api/src/functions/checkout.ts

The number of months for a reservation is computed as the difference in milliseconds between to and from divided by 1000, 60, 60, and 24 to yield days, then divided by 30 and rounded to 2 decimal places; if either date is missing, the result is 0.

  • 1000 — milliseconds per second divisor
  • 60 — seconds per minute and minutes per hour divisor
  • 24 — hours per day divisor
  • 30 — days per month divisor
  • 2 — decimal places used in toFixed for month calculation
  • 0 — months returned when from or to is missing
function getMonths(from: Date, to: Date) { if (!from || !to) { return 0; } const days = (to.getTime() - from.getTime()) / 1000 / 60 / 60 / 24; return +(days / 30).toFixed(2); }
validation
packages/api/src/functions/checkout.ts

A new reservation must not overlap existing reservations for the same listing over the [from, to] range; if findReservationsByListingIdAndDateRange returns one or more overlaps, the request is rejected with HTTP 400 and an error listing the overlapping reservation ids.

  • 400 — HTTP status returned when overlaps exist
const overlaps = await findReservationsByListingIdAndDateRange(listing.id, from.toISOString(), to.toISOString()); if (overlaps.length > 0) { return { status: 400, jsonBody: { error: `Reservation overlaps with existing reservation(s): ${overlaps .map(o => o.id) .join(", ")} (from: ${from.toISOString()}, to: ${to.toISOString()})`, }, }; }
query
packages/api/src/models/reservation.ts

findReservationsByListingIdAndDateRange queries reservations matching the given listingId whose status is in ["pending", "active"], whose `from` is strictly less than the ISO string of `to`, and whose `to` is strictly greater than the ISO string of `from` (an overlap condition).

  • pending — allowed status in the query
  • active — allowed status in the query
return await ReservationModel.find({ listingId, status: { $in: ["pending", "active"] }, from: { $lt: new Date(to).toISOString() }, to: { $gt: new Date(from).toISOString() }, });
state transition
packages/api/src/models/reservation.ts

Updating a reservation's status to "active" or "cancelled" is only permitted when the reservation's current status is "pending"; otherwise an error is thrown with the message `Invalid reservation status transition: ${reservation.status} -> ${status}`.

  • active — target status permitted only from pending
  • cancelled — target status permitted only from pending
  • pending — required current status for active or cancelled transitions
if ( (status === "active" && reservation.status !== "pending") || (status === "cancelled" && reservation.status !== "pending") ) { throw new Error(`Invalid reservation status transition: ${reservation.status} -> ${status}`); }

Also cited: L10

authorization
packages/portal/src/app/shared/booking-form/booking-form.component.ts

The rent operation only emits an onRent event when the current user is not a guest; otherwise no reservation request is emitted.

async rent() { if (!this.isGuest()) { const user = await this.userService.currentUser(); this.onRent.emit({ userId: user.id, listingId: this.listing?.id, guests: this.guests.value, from: this.localeDateToUTCDateString(this.rentingPeriod.value.start), to: this.localeDateToUTCDateString(this.rentingPeriod.value.end), }); } }
role assignment
packages/portal/src/app/shared/user/user.service.ts

An authenticated user is assigned UserRole.Admin if clientPrincipal.userRoles includes the literal `admin`; otherwise the role is UserRole.Renter.

  • admin — role string checked in userRoles to grant Admin
  • admin — assigned UserRole.Admin value
  • renter — assigned UserRole.Renter value when not admin
const isAdmin = clientPrincipal.userRoles.includes("admin"); return { id: clientPrincipal.userId, name: clientPrincipal.userDetails, photo: "account_circle", role: isAdmin ? UserRole.Admin : UserRole.Renter,

Also cited: L6–L10

validation
packages/api/src/models/user.schema.ts

User.role is a required string restricted to one of "guest", "renter", or "admin", and defaults to "guest" when not supplied.

  • guest — permitted role and default value
  • renter — permitted role
  • admin — permitted role
  • true — required flag on role
role: { type: String, required: true, enum: ["guest", "renter", "admin"], default: "guest", },

Also cited: L8

schema field enum constraint
packages/api/src/models/reservation.schema.ts

A reservation must have a status of type String; it is required and its value must be one of "pending", "active", "cancelled", or "archived".

  • String — field type
  • true — required flag
  • pending — allowed enum member
  • active — allowed enum member
  • cancelled — allowed enum member
  • archived — allowed enum member
status: { type: String, required: true, enum: ["pending", "active", "cancelled", "archived"], },
validation
packages/portal/src/app/shared/booking-form/booking-form.component.ts

The renting period end date must not be the same as the start date; if the start and end timestamps are equal, the end control returns the validation error { sameDate: { value: <end value> } }; otherwise no error is returned.

const differentThanStartDateValidator = (): ValidatorFn => { return (control: AbstractControl): ValidationErrors | null => { const startDate = new Date(this.rentingPeriod?.value.start).getTime(); const endDate = new Date(control.value).getTime(); const sameDate = startDate === endDate; return sameDate ? { sameDate: { value: control.value } } : null; }; };

Also cited: L75–L78

validation
packages/api/src/models/payment.ts

isValidPayment returns false if payment.amount is not of type "number" or is less than or equal to 0; the amount must be a positive number.

  • 0 — upper bound of the invalid amount range (amount <= 0 is invalid)
  • number — required primitive type for amount
// Check if the amount is a positive number if (typeof payment.amount !== "number" || payment.amount <= 0) { return false; }
idempotency
packages/api/src/models/favorite.ts

When saving a favorite, if a favorite with the same userId and listingId already exists, the existing record is returned and no new record is created; otherwise a new favorite is created from the supplied favorite.

export async function saveFavorite(fav: Favorite): Promise<Favorite | null> { const recordFavorite = await findFavorite(fav); return recordFavorite || (await FavoriteModel.create(fav)); }

Also cited: L12–L14

validation
packages/stripe/src/models/checkout.ts

The numeric guests value must not be NaN and must be at least 1; otherwise validation throws Error("Invalid guests number").

  • 1 — minimum permitted guests value
const guests = Number(checkout.guests); if (isNaN(guests) || guests < 1) { throw new Error("Invalid guests number"); }
02 · Capabilities

What the application does

22 capabilities identified, grouping 112 of the 112 distinct features extracted. These are descriptions, not the cited rules above.

Cloud Resource Modeling

Declarative modeling of Azure resource types across compute, networking, storage, data, security, and management domains.

  • AI and Machine Learning Modeling: Capability to represent and model Azure cognitive services and machine learning resources.
  • API and Integration Modeling: Capability to represent and model Azure API management and integration resources.
  • Application and Container Hosting: Capability to represent and model Azure application hosting, container, and web resources.
  • Compute Resource Modeling: Capability to represent and model Azure compute resources and their supporting services.
  • Data Analytics and Big Data Modeling: Capability to represent and model Azure analytics, big data, and data integration resources.
  • Database Resource Modeling: Capability to represent and model Azure SQL, NoSQL, and relational database services.
  • Enterprise Data and Power BI Modeling: Capability to represent and model enterprise analytics and dedicated capacity resources.
  • Governance and Management Modeling: Capability to represent and model Azure governance, management, and organizational resources.
  • Identity and Security Modeling: Capability to represent and model Azure identity, key vault, and security resources.
  • IoT Resource Modeling: Capability to represent and model Azure IoT hubs, provisioning, and connected device resources.
  • Load Balancing and Traffic Modeling: Capability to represent and model Azure load balancing, DNS, and traffic routing resources.
  • Media and CDN Modeling: Capability to represent and model Azure CDN and content delivery resources.
  • Messaging and Event Modeling: Capability to represent and model Azure messaging, eventing, and notification resources.
  • Monitoring and Observability Modeling: Capability to represent and model Azure monitoring, logging, and alerting resources.
  • Network Security Modeling: Capability to represent and model Azure network security resources such as security groups and firewall policies.
  • Networking Connectivity Modeling: Capability to represent and model Azure connectivity, route, and watcher resources.
  • Networking Resource Modeling: Capability to represent and model Azure virtual networks, gateways, and related networking resources.
  • Storage Account Modeling: Capability to represent and model Azure storage and file/account resources.

Marketplace Browsing and Bookings

Browsing listings and properties, viewing details and recommendations, and creating reservations and bookings.

  • Booking: Users can book a listing through the booking flow.
  • Favorites Management: Adding, listing, and removing listings that a user has marked as favorites.
  • Featured and Recommended Listings Display: Listings can be surfaced as featured or recommended to help users discover highlighted properties.
  • Listing Browsing: Browsing and retrieval of rental listings with their descriptive details, amenities, photos and ratings.
  • Listing Details Browsing: Users can view detailed information about a rental listing, including its address, amenities, capacity, bedrooms, bathrooms, photos, fees, and review statistics.
  • Listing Display: Users can view a lodging listing's details, description, photos, amenities, and reviews.
  • Listing Recommendations: Surfacing featured and recommended listings to users.
  • Property Attribute Summary: Expose the key property attributes such as bedrooms, bathrooms, and quantity/amount with min/max bounds and array values.
  • Property Listing Display: Present a rental/property listing with its title, description, location, images, and amenity details to the user.
  • Reservation Management: Creating and viewing reservations for a listing with guest, date and occupancy details.

Application Build and Run

Builds application artifacts and starts the application locally or in development and production modes.

  • Application Build: Builds the Angular application via the ng build command through the configured builder.
  • Application Build and Run: Build and start the Next.js application in development and production modes.
  • Application Start / Dev Server: Starts the application development server for local development and preview.
  • Build: Build the application artifacts from source prior to deployment.
  • Generate Angular Bundles: Generate Angular bundles, including a test bundle, for the web app.
  • Local Preview Server: Serves the built site locally so users can preview it in a browser.
  • Restore Dependencies: Restore dependencies for the API and Web projects.
  • Start API and Web: Start the API and web frontends together or individually via npm start.
  • Static Site Build: Compiles source content into a deployable static site via a build command.

Browser Automation and Element Interaction

Resolves locators, parses selector syntax, enforces actionability and strictness, and performs user-like element interactions.

  • Actionability and Strictness Enforcement: Waits for element states and performs actions only when targets are actionable (hit-target checks, stability) while enforcing strict single-element matching.
  • Element Highlighting: Visually highlights and masks target elements in the browser (with action-point markers) so users can see which elements an action targets.
  • Element Query and Locator Resolution: Resolves selectors/locators to DOM elements, supporting the full selector engine (CSS, text, role, attribute, nth, visibility engines) used to find and match page elements.
  • Element State Checking: Determines an element's state — visibility, enabled/disabled, checked, focused/active — used to assert and wait on conditions.
  • Interactive Element Actions: Performs user-like interactions on page elements — click, fill, select options, select text, set input files, focus/blur — as actions a test author directly invokes.
  • Locator Generation: Generates human-readable locator expressions (with text, test-id, exact-match and regex helpers) that describe how to find an element, exposed to users via codegen and error reporting.
  • Locator Source Realization: Provides source/serialization representation of locators and selectors, exposing human-readable source strings for them.
  • Playwright Selector Syntax Parsing: Parses Playwright selector strings into structured selector ASTs (including layout selectors and scope expansion) consumed by the query engine.

Cloud Infrastructure Provisioning

Provisions and configures Azure infrastructure and environments, then deploys application containers and static assets into them.

  • Application Deployment: Deploy the built application to the provisioned Azure infrastructure.
  • Azure Environment Provisioning: Provision Azure development infrastructure and environment configuration for the application.
  • Azure Infrastructure Provisioning: Defines the deployment parameters that provision the containerized application infrastructure, including the container apps environment, container registry, storage, and CMS database.
  • Container Host Requirements: Specifies the host resources (CPU, memory, storage) required to run the container.
  • Container Image Deployment: Configures and deploys the individual application container images (blog, CMS, Stripe) into the hosted environment.
  • Environment URI Replacement: Replaces environment-specific placeholder URIs in configuration with actual environment values.
  • Infrastructure Provisioning: Provision the target Azure infrastructure for the application environment.
  • Static Web App Deployment: Invokes the Azure Static Web Apps CLI to build and deploy the app as a static web app.

Containerization and Dev Environment

Defines and runs Docker-based and dev container environments with port forwarding and post-create setup.

  • Automated Test Execution: Executes the project's test suite using Jest.
  • Build Execution: Runs the project's build process in a container.
  • Code Linting: Runs static analysis/linting over the codebase in a container.
  • Dev Container Configuration: Defines a development container environment with a base image, features, and VS Code customizations.
  • Docker Containerization: Build and run the application as a Docker container for deployment.
  • Port Forwarding: Configures ports to be forwarded from the container to the host with auto-forward behavior.
  • Post-Create Setup: Runs setup commands automatically after the container is created to provision tooling.
  • Test Execution: Runs the project's test suite in a container.

Automated Testing

Discovers, executes, merges, and reports automated test suites and their results.

  • Automated Test Execution: Executes the project's test suite using Jest.
  • Reporter Configuration: Reads and applies reporter configuration and project settings for the test run.
  • Test Discovery and Project Model: Enumerates all tests and exposes the project structure and title paths for the run.
  • Test Execution: Runs the project's test suite in a container.
  • Test Reporting: Collects and publishes test run results, including per-test begin/end, errors, steps, and attachments, to an external reporter.
  • Test Result Management: Maintains test results, outcomes, and title paths, allowing results to be queried and cleared.
  • Test Suite Merging: Merges suites and tests into a unified view for reporting.

API Gateway Policy Processing

Routes HTTP requests through policy chains with validation, conditional execution, error handling, rate limiting, and CORS.

  • Concurrency Limiting: Restricts the number of concurrent requests handled by the gateway.
  • Conditional Policy Execution: Evaluates conditions to decide whether a policy branch or step should run.
  • Cross-Origin Resource Sharing: Applies CORS policy so browser clients from other origins can call the API.
  • Error Handling: Handles failures during request processing through a dedicated error policy flow.
  • HTTP Request Forwarding: Routes an inbound HTTP request through a chain of policies to the backend and returns the response to the caller.
  • Request Validation: Validates incoming request headers and content before the request is forwarded.

Content and Site Experience

Delivers homepage content, articles, and site-level SEO, favicon, and search appearance metadata.

  • Article Content Browsing: Users can browse articles along with their authors, categories, and article details such as title and description.
  • Homepage Content Display: The homepage presents structured content including a hero section and global site information.
  • Homepage Features Display: Surfaces a set of homepage feature highlights as a user-facing capability.
  • SEO Metadata Management: Site pages expose SEO metadata such as meta title, meta description, share image, and favicon for search and social presentation.
  • Search Engine Metadata: Configures SEO-related metadata such as the site name and default search engine description for pages.
  • Site Favicon: Associates a favicon with the site so browsers and clients can display the site icon.

Web Frontend Application

Component-based Angular/Next.js UI delivering routing, forms, animations, icons, GraphQL, realtime, and content rendering.

  • Angular UI Application: Delivers the component-based user interface with routing, forms, animations, and Material components.
  • GraphQL API Integration: Provides GraphQL client capabilities and Angular integration for querying remote APIs.
  • Iconography: Renders Font Awesome icons in the Angular UI using bundled icon sets.
  • Markdown Rendering: Render and sanitize raw Markdown content for display in the application.
  • Metadata Management: Allows users or systems to specify and store page metadata such as titles, descriptions, and share images for a data element.
  • Realtime Communication: Enables realtime bidirectional communication with a server via Socket.IO client.

Snapshot Capture and Serving

Records, stores, queries, renders, and serves page snapshots for test replay and inspection.

  • Snapshot HTTP Serving: Serves recorded snapshots and their metadata over HTTP for clients to consume.
  • Snapshot Querying: Provides read access to snapshot entries, entry names, liveness, blobs, text, and trace URLs.
  • Snapshot Recording: Records page snapshots for a running test by adding frames and resources and finalizing them into named snapshots.
  • Snapshot Rendering: Renders a snapshot into a view with viewport control and resource-by-URL resolution.
  • Snapshot Storage: Persists and loads snapshot entries and their resources, resolving resources by SHA-1 and appending events.

Payments and Checkout

Initiates Stripe checkout sessions, processes payment webhooks, and configures Stripe credentials.

  • Checkout and Payment: Processing a checkout session and recording payments for reservations with amounts and currency.
  • Stripe Checkout: Enables a user to initiate a payment checkout session for a reservation via Stripe and receive a session URL.
  • Stripe Payment Integration: Configure and connect Stripe payment capabilities via public, secret, and webhook keys.
  • Stripe Webhook Handling: Receives and processes Stripe webhook events to confirm payment outcomes for a checkout.

CI/CD Pipeline

Pipeline workflows that check out source, trigger on branches or manual dispatch, and run security and validation steps.

  • CI/CD Checkout: Check out the repository source as the first step of the pipeline.
  • CI/CD Workflow Triggering: Trigger the pipeline on pushes to main/master branches or via manual dispatch.
  • Microsoft Security DevOps Analysis: Runs the Microsoft Security DevOps analysis to scan and surface security findings.

Code Quality Tooling

Enforces consistent formatting and static analysis across the codebase.

  • Code Formatting: Format source code consistently using Prettier.
  • Code Linting: Provide linting and auto-fixing of source code via ESLint.
  • Internationalization Extraction: Extracts translatable strings to support localization workflows.

Deployment Authentication and Tooling

Authorizes deployments to Azure and manages toolchain setup and template validation for provisioning.

  • AZD Template Validation: Builds and validates the AZD template to verify it is well-formed.
  • Azure Deployment Authentication: Log in to Azure using either client credentials or federated (OIDC) credentials to authorize subsequent deployments.
  • azd Installation: Install the Azure Developer CLI tooling required to run provisioning and deployment commands.

Project Configuration Discovery

Discovers main entry files and supports TypeScript compilation configuration.

  • Main File Discovery: Locates and identifies the main entry file for a project or configuration.
  • TypeScript Compilation: Compiles TypeScript sources using the Angular compiler tooling and runtime support libraries.
  • TypeScript Compilation Configuration: Supports configuring a TypeScript compilation with compiler options, included files, output directory, and type definitions.

CMS and Content Platform

Strapi-based content runtime and project tooling providing GraphQL, internationalization, and permission-backed APIs.

  • Strapi Application Project Tooling: Provides project lifecycle commands for building, developing, and running a Strapi application, including Docker-based build and run workflows.
  • Strapi Application Runtime: Delivers the Strapi content platform runtime with GraphQL, internationalization, and user-permission plugins for the application's core API and admin capabilities.

Serverless Functions

Builds, maintains, and hosts serverless functions exposing HTTP-triggered endpoints.

  • Functions Build and Maintenance: Build, clean, install, and prune dependencies for the serverless functions, and run the functions host.
  • HTTP Trigger Endpoint: Exposes an HTTP endpoint that invokes a script when an incoming request is received.

Key-Value Data Store

Provides an iterable in-memory key/value map with core collection operations.

  • Key-Value Collection: Provides an iterable key/value map with set, get, has, delete, clear, and size operations.

Monitoring and Telemetry

Enables application telemetry and observability through configured monitoring resources.

  • Application Monitoring: Enables application telemetry and monitoring through the Application Insights instance and its configuration.

Storage and Media Uploads

Provides file and media upload backends backed by Azure Storage.

  • Azure Storage Upload Provider: Enables media and file uploads to Azure Storage as the application's upload backend.

User and Account Management

Creates and looks up user accounts and their profile details.

  • User Account Management: Creation and lookup of user accounts with profile details such as name, email, and role.
03 · Size

What was analyzed

  • JSON · 71 files · 59,978 lines
  • JavaScript · 16 files · 35,902 lines
  • HTML · 24 files · 19,783 lines
  • TypeScript · 199 files · 6,999 lines
  • CSS · 8 files · 5,576 lines
  • Markdown · 73 files · 2,876 lines
  • YAML · 9 files · 1,919 lines
  • SCSS · 15 files · 799 lines
  • XML · 1 file · 84 lines
  • Dockerfile · 4 files · 73 lines
  • Bourne Shell · 3 files · 71 lines
  • Other (3 languages) · 9 files · 46 lines

Whole repository: 623 files. cloc 2.06 counts 134,106 lines of code in 432 of them (138,022 lines with comments and blanks).

04 · Source

Where this came from

Extracted by CoreStory V3 (build 4470 with two small engine fixes) using DeepSeek-V4.1-Flash from the public repository at commit e4c3bd8 on 2026-11-15. Capability descriptions are from the same run.

Code excerpts are from the upstream repository and remain under its MIT license. CoreStory is not affiliated with or endorsed by Microsoft (Azure Samples).

Want this for your own codebase?

Talk to us about mapping the business rules in your repositories.

Talk to an expert